org.apache.maven.plugin.logging.Log Java Examples

The following examples show how to use org.apache.maven.plugin.logging.Log. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DocumentationUtils.java    From siddhi with Apache License 2.0 6 votes vote down vote up
/**
 * Remove the snapshot version documentation files from docs/api directory
 *
 * @param mkdocsConfigFile           The mkdocs configuration file
 * @param documentationBaseDirectory The path of the base directory in which the documentation will be generated
 * @param logger                     The maven plugin logger
 */
public static void removeSnapshotAPIDocs(File mkdocsConfigFile, String documentationBaseDirectory, Log logger) {
    // Retrieving the documentation file names
    File apiDocsDirectory = new File(documentationBaseDirectory
            + File.separator + Constants.API_SUB_DIRECTORY);
    String[] documentationFileNames = apiDocsDirectory.list(
            (directory, fileName) -> fileName.endsWith(Constants.MARKDOWN_FILE_EXTENSION)
    );

    if (documentationFileNames != null) {
        // Removing snapshot files and creating a list of the files that are left out
        for (String documentationFileName : documentationFileNames) {
            if (documentationFileName.endsWith(Constants.SNAPSHOT_VERSION_POSTFIX
                    + Constants.MARKDOWN_FILE_EXTENSION)) {
                // Removing the snapshot documentation file
                File documentationFile = new File(apiDocsDirectory.getAbsolutePath()
                        + File.separator + documentationFileName);
                if (!documentationFile.delete()) {
                    logger.warn("Failed to delete SNAPSHOT documentation file "
                            + documentationFile.getAbsolutePath());
                }
            }
        }

    }
}
 
Example #2
Source File: DocumentationUtils.java    From siddhi with Apache License 2.0 6 votes vote down vote up
/**
 * Build the mkdocs site using the mkdocs config file
 *
 * @param mkdocsConfigFile The mkdocs configuration file
 * @param logger           The maven logger
 * @return true if the documentation generation is successful
 */
public static boolean generateMkdocsSite(File mkdocsConfigFile, Log logger) {
    boolean isDocumentationGenerationSuccessful = false;
    try {
        // Building the mkdocs site
        executeCommand(new String[]{Constants.MKDOCS_COMMAND,
                Constants.MKDOCS_BUILD_COMMAND,
                Constants.MKDOCS_BUILD_COMMAND_CLEAN_ARGUEMENT,
                Constants.MKDOCS_BUILD_COMMAND_CONFIG_FILE_ARGUMENT,
                mkdocsConfigFile.getAbsolutePath(),
                Constants.MKDOCS_BUILD_COMMAND_SITE_DIRECTORY_ARGUMENT,
                Constants.MKDOCS_SITE_DIRECTORY}, logger);
        isDocumentationGenerationSuccessful = true;
    } catch (Throwable t) {
        logger.warn("Failed to generate the mkdocs site.", t);
    }
    return isDocumentationGenerationSuccessful;
}
 
Example #3
Source File: LocaleFacet.java    From jaxb2-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method used to parse a locale configuration string into a Locale instance.
 *
 * @param localeString A configuration string parameter on the form
 *                     {@code <language>[,<country>[,<variant>]]}
 * @param log          The active Maven Log. Cannot be null.
 * @return A fully constructed Locale.
 * @throws MojoExecutionException if the localeString was not supplied on the required form.
 */
public static LocaleFacet createFor(final String localeString, final Log log) throws MojoExecutionException {

    // Check sanity
    Validate.notNull(log, "log");
    Validate.notEmpty(localeString, "localeString");

    final StringTokenizer tok = new StringTokenizer(localeString, ",", false);
    final int numTokens = tok.countTokens();
    if (numTokens > 3 || numTokens == 0) {
        throw new MojoExecutionException("A localeString must consist of up to 3 comma-separated parts on the "
                + "form <language>[,<country>[,<variant>]]. Received incorrect value '" + localeString + "'");
    }

    // Extract the locale configuration data.
    final String language = tok.nextToken().trim();
    final String country = numTokens > 1 ? tok.nextToken().trim() : null;
    final String variant = numTokens > 2 ? tok.nextToken().trim() : null;

    // All done.
    return new LocaleFacet(log, findOptimumLocale(language, country, variant));
}
 
Example #4
Source File: BootstrapClusterStep.java    From elasticsearch-maven-plugin with Apache License 2.0 6 votes vote down vote up
protected void parseJson(ElasticsearchClient client, Log log, Path path)
{
    try
    {
        String json = new String(Files.readAllBytes(path));

        List<Map<String, Object>> commands = new ObjectMapper().readValue(
                json,
                new TypeReference<List<Map<String, Object>>>(){});
        commands.forEach(command ->
        {
            log.debug(String.format("Parsing command: %s", command));
            
            ElasticsearchCommand esCommand = parseMapCommand(command);
            executeInitCommand(client, log, esCommand);
        });
    }
    catch (IOException e)
    {
        throw new ElasticsearchSetupException("Cannot read the init json file", e);
    }
}
 
Example #5
Source File: MavenContractsDownloader.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
MavenContractsDownloader(MavenProject project, Dependency contractDependency,
		String contractsPath, String contractsRepositoryUrl,
		StubRunnerProperties.StubsMode stubsMode, Log log, String repositoryUsername,
		String repositoryPassword, String repositoryProxyHost,
		Integer repositoryProxyPort, boolean deleteStubsAfterTest,
		Map<String, String> contractsProperties, boolean failOnNoContracts) {
	this.project = project;
	this.contractDependency = contractDependency;
	this.contractsPath = contractsPath;
	this.contractsRepositoryUrl = contractsRepositoryUrl;
	this.stubsMode = stubsMode;
	this.log = log;
	this.repositoryUsername = repositoryUsername;
	this.repositoryPassword = repositoryPassword;
	this.repositoryProxyHost = repositoryProxyHost;
	this.repositoryProxyPort = repositoryProxyPort;
	this.stubDownloaderBuilderProvider = new StubDownloaderBuilderProvider();
	this.deleteStubsAfterTest = deleteStubsAfterTest;
	this.contractsProperties = contractsProperties;
	this.failOnNoStubs = failOnNoContracts;
}
 
Example #6
Source File: JaxrsReaderTest.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createCommonParameters() throws Exception {
    reader = new JaxrsReader(new Swagger(), Mockito.mock(Log.class));
    Swagger result = reader.read(CommonParametersApi.class);
    Parameter headerParam = result.getParameter("headerParam");
    assertTrue(headerParam instanceof HeaderParameter);
    Parameter queryParam = result.getParameter("queryParam");
    assertTrue(queryParam instanceof QueryParameter);

    result = reader.read(ReferenceCommonParametersApi.class);
    Operation get = result.getPath("/apath").getGet();
    List<Parameter> parameters = get.getParameters();
    for (Parameter parameter : parameters) {
        assertTrue(parameter instanceof RefParameter);
    }

    ObjectMapper mapper = Json.mapper();
    ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter());
    String json = jsonWriter.writeValueAsString(result);
    JsonNode expectJson = mapper.readTree(this.getClass().getResourceAsStream("/expectedOutput/swagger-common-parameters.json"));
    JsonAssert.assertJsonEquals(expectJson, json);
}
 
Example #7
Source File: ExecProcess.java    From maven-process-plugin with Apache License 2.0 6 votes vote down vote up
public void execute(File workingDirectory, Log log, String... args) {
    final ProcessBuilder pb = new ProcessBuilder();

    if(redirectErrorStream) {
        pb.redirectErrorStream(true);
        pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    }

    log.info("Using working directory for this process: " + workingDirectory);
    pb.directory(workingDirectory);
    pb.command(args);
    try {
        process = pb.start();
        pumpOutputToLog(process, log);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #8
Source File: TestInstrumentMojo.java    From coroutines with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    Log log = getLog();

    File testOutputFolder = new File(getProject().getBuild().getTestOutputDirectory());
    if (!testOutputFolder.isDirectory()) {
        log.warn("Test folder doesn't exist -- nothing to instrument");
        return;
    }
    
    List<String> classpath;
    try {
        classpath = getProject().getTestClasspathElements();
    } catch (DependencyResolutionRequiredException ex) {
        throw new MojoExecutionException("Dependency resolution problem", ex);
    }
    
    log.debug("Processing test output folder ... ");
    instrumentPath(log, classpath, testOutputFolder);
}
 
Example #9
Source File: Welcome.java    From carnotzet with Apache License 2.0 6 votes vote down vote up
public static void execute(ContainerOrchestrationRuntime runtime, Carnotzet carnotzet, Log log)
		throws MojoExecutionException, MojoFailureException {
	try {
		IpPlaceholderResolver ipPlaceholderResolver = new IpPlaceholderResolver(runtime);

		WelcomePageGenerator generator = new WelcomePageGenerator(Arrays.asList(ipPlaceholderResolver));

		Path moduleResources = carnotzet.getResourcesFolder().resolve("resolved");
		Path welcomePagePath = carnotzet.getResourcesFolder().resolve("welcome.html");

		generator.buildWelcomeHtmlFile(moduleResources, welcomePagePath);

		new ProcessBuilder("xdg-open", "file://" + welcomePagePath).start();
		log.info("********************************************************");
		log.info("*                                                      *");
		log.info("* The WELCOME page was opened in your default browser  *");
		log.info("*                                                      *");
		log.info("********************************************************");
	}
	catch (IOException e) {
		throw new MojoExecutionException("Cannot start browser:" + e, e);
	}
}
 
Example #10
Source File: CvsBZR.java    From mvn-golang with Apache License 2.0 6 votes vote down vote up
@Override
public boolean processCVSRequisites(
        @Nonnull final Log logger,
        @Nullable final ProxySettings proxy,
        @Nullable final String customCommand,
        @Nonnull final File cvsFolder,
        @Nullable final String branchId,
        @Nullable final String tagId,
        @Nullable final String revisionId
) {
    boolean noError = true;

    if (branchId != null) {
        noError &= upToBranch(logger, proxy, customCommand, cvsFolder, branchId);
    }

    if (noError && tagId != null) {
        noError &= upToTag(logger, proxy, customCommand, cvsFolder, tagId);
    }

    if (noError && revisionId != null) {
        noError &= upToRevision(logger, proxy, customCommand, cvsFolder, revisionId);
    }

    return noError;
}
 
Example #11
Source File: Util.java    From jax-maven-plugin with Apache License 2.0 6 votes vote down vote up
static Stream<String> getPluginRuntimeDependencyEntries(AbstractMojo mojo, MavenProject project, Log log,
        RepositorySystem repositorySystem, ArtifactRepository localRepository,
        List<ArtifactRepository> remoteRepositories) {
    PluginDescriptor pluginDescriptor = (PluginDescriptor) mojo.getPluginContext().get(PLUGIN_DESCRIPTOR);
    Plugin plugin = project.getBuild().getPluginsAsMap().get(pluginDescriptor.getPluginLookupKey());

    List<ArtifactResolutionResult> artifactResolutionResults = plugin //
            .getDependencies() //
            .stream() //
            .map(repositorySystem::createDependencyArtifact) //
            .map(a -> Util.resolve(log, a, repositorySystem, localRepository, remoteRepositories)) //
            .collect(Collectors.toList());

    Stream<Artifact> originalArtifacts = artifactResolutionResults.stream()
            .map(ArtifactResolutionResult::getOriginatingArtifact);

    Stream<Artifact> childArtifacts = artifactResolutionResults.stream()
            .flatMap(resolutionResult -> resolutionResult.getArtifactResolutionNodes().stream())
            .map(ResolutionNode::getArtifact);

    return Stream.concat(originalArtifacts, childArtifacts).map(Artifact::getFile).map(File::getAbsolutePath);
}
 
Example #12
Source File: Util.java    From jax-maven-plugin with Apache License 2.0 6 votes vote down vote up
static File createOutputDirectoryIfSpecifiedOrDefault(Log log, String param, List<String> arguments) {
    for (int i = 0; i < arguments.size(); i++) {
        if (isOptionParamSpecifiedAndNotEmpty(arguments, i, param)) {
            String path = arguments.get(i + 1);
            Preconditions.checkNotNull(path, "path for output directory not found, option="+ param);
            File outputDir = new File(path);
            if (!outputDir.exists()) {
                log.info("destination directory (" + param + " option) specified and does not exist, creating: "
                        + outputDir);
                outputDir.mkdirs();
            }
            return outputDir;
        }
    }
    log.warn("destination directory (" + param
            + " option) NOT specified. Generated source will be placed in project root if -keep argument is present.");
    return new File(".");
}
 
Example #13
Source File: InstallHooksMojo.java    From git-code-format-maven-plugin with MIT License 6 votes vote down vote up
public void execute() throws MojoExecutionException {
  if (!isExecutionRoot()) {
    getLog().debug("Not in execution root. Do not execute.");
    return;
  }
  if (skip) {
    Log log = getLog();
    if (log.isInfoEnabled()) {
      log.info("skipped");
    }
    return;
  }

  try {
    getLog().info("Installing git hooks");
    doExecute();
    getLog().info("Installed git hooks");
  } catch (Exception e) {
    throw new MojoExecutionException(e.getMessage(), e);
  }
}
 
Example #14
Source File: NPM.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to extract the version from a NPM by reading its 'package.json' file.
 *
 * @param npmDirectory the directory in which the NPM is installed
 * @param log          the logger object
 * @return the read version, "0.0.0" if there are not 'package.json' file, {@code null} if this file cannot be
 * read or does not contain the "version" metadata
 */
public static String getVersionFromNPM(File npmDirectory, Log log) {
    File packageFile = new File(npmDirectory, PACKAGE_JSON);
    if (!packageFile.isFile()) {
        return "0.0.0";
    }

    FileReader reader = null;
    try {
        reader = new FileReader(packageFile);  //NOSONAR
        JSONObject json = (JSONObject) JSONValue.parseWithException(reader);
        return (String) json.get("version");
    } catch (IOException | ParseException e) {
        log.error("Cannot extract version from " + packageFile.getAbsolutePath(), e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return null;
}
 
Example #15
Source File: DocumentationUtils.java    From siddhi with Apache License 2.0 6 votes vote down vote up
/**
 * Commit the documentation directory and the mkdocs config file
 *
 * @param docsDirectory    The docs drectory
 * @param mkdocsConfigFile The mkdocs configuration file
 * @param readmeFile       The read me file
 * @param version          The version of the documentation
 * @param logger           The maven logger
 */
public static void updateDocumentationOnGitHub(String docsDirectory, File mkdocsConfigFile, File readmeFile,
                                               String version, Log logger) {
    try {
        executeCommand(new String[]{Constants.GIT_COMMAND,
                Constants.GIT_ADD_COMMAND,
                docsDirectory, mkdocsConfigFile.getAbsolutePath(), readmeFile.getAbsolutePath()}, logger);
        executeCommand(new String[]{Constants.GIT_COMMAND,
                Constants.GIT_COMMIT_COMMAND,
                Constants.GIT_COMMIT_COMMAND_MESSAGE_ARGUMENT,
                String.format(Constants.GIT_COMMIT_COMMAND_MESSAGE_FORMAT, version, version),
                Constants.GIT_COMMIT_COMMAND_FILES_ARGUMENT,
                docsDirectory, mkdocsConfigFile.getAbsolutePath(), readmeFile.getAbsolutePath()}, logger);
    } catch (Throwable t) {
        logger.warn("Failed to update the documentation on GitHub repository", t);
    }
}
 
Example #16
Source File: FileSystemUtilities.java    From jaxb2-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves a List of Files containing all the existing files within the supplied files List, including all
 * files found in directories recursive to any directories provided in the files list. Each file included in the
 * result must pass an ExclusionRegExpFileFilter synthesized from the supplied exclusions pattern(s).
 *
 * @param files            The list of files to resolve, filter and return. If the {@code files} List
 *                         contains directories, they are searched for Files recursively. Any found Files in such
 *                         a search are included in the resulting File List if they do not match any of the
 *                         exclusionFilters supplied.
 * @param exclusionFilters A List of Filters which identify files to remove from the result - implying that any
 *                         File matched by any of these exclusionFilters will not be included in the result.
 * @param log              The active Maven Log.
 * @return All files in (or files in subdirectories of directories provided in) the files List, provided that each
 * file is accepted by an ExclusionRegExpFileFilter.
 */
public static List<File> resolveRecursively(final List<File> files,
                                            final List<Filter<File>> exclusionFilters,
                                            final Log log) {

    // Check sanity
    Validate.notNull(files, "files");

    final List<Filter<File>> effectiveExclusions = exclusionFilters == null
            ? new ArrayList<Filter<File>>()
            : exclusionFilters;

    final List<File> toReturn = new ArrayList<File>();

    if (files.size() > 0) {
        for (File current : files) {

            final boolean isAcceptedFile = EXISTING_FILE.accept(current)
                    && Filters.noFilterMatches(current, effectiveExclusions);
            final boolean isAcceptedDirectory = EXISTING_DIRECTORY.accept(current)
                    && Filters.noFilterMatches(current, effectiveExclusions);

            if (isAcceptedFile) {
                toReturn.add(current);
            } else if (isAcceptedDirectory) {
                recurseAndPopulate(toReturn, effectiveExclusions, current, true, log);
            }
        }
    }

    // All done
    return toReturn;
}
 
Example #17
Source File: LayzQueryCodeGenerator.java    From vaadinator with Apache License 2.0 5 votes vote down vote up
@Override
public void generateCode(VaadinatorConfig vaadinatorConfig) throws Exception {
	Log log = vaadinatorConfig.getLog();
	log.info("Generating lazy query containers");
	if (vaadinatorConfig.getGenTypeEn() == VaadinatorConfig.GenType.SOURCES
			|| vaadinatorConfig.getGenTypeEn() == VaadinatorConfig.GenType.ALL) {
		if (vaadinatorConfig.getGenTypeEn() == VaadinatorConfig.GenType.SOURCES
				|| vaadinatorConfig.getGenTypeEn() == VaadinatorConfig.GenType.ALL) {
			for (BeanDescription desc : vaadinatorConfig.getBeanDescriptions()) {
				if (desc.isDisplayed()) {
					for (DisplayProfileDescription p : desc.getDisplayProfiles()) {
						String componentPckg = desc.getViewPckg(p) + ".container";
						runVelocity(desc, vaadinatorConfig.getCommonMap(), componentPckg, desc.getPckg(),
								desc.getPresenterPckg(p), desc.getViewPckg(p), p.getProfileName(),
								"LazyQueryContainer.template",
								packageToFile(vaadinatorConfig.getTargetFolderSrcStart(), componentPckg,
										desc.getClassName(), "LazyQueryContainer.java"),
								TEMPLATE_PACKAGE, log);
						runVelocity(desc, vaadinatorConfig.getCommonMap(), componentPckg, desc.getPckg(),
								desc.getPresenterPckg(p), desc.getViewPckg(p), p.getProfileName(),
								"LazyQuery.template", packageToFile(vaadinatorConfig.getTargetFolderSrcStart(),
										componentPckg, desc.getClassName(), "LazyQuery.java"),
								TEMPLATE_PACKAGE, log);
						runVelocity(desc, vaadinatorConfig.getCommonMap(), componentPckg, desc.getPckg(),
								desc.getPresenterPckg(p), desc.getViewPckg(p), p.getProfileName(),
								"LazyQueryFactory.template",
								packageToFile(vaadinatorConfig.getTargetFolderSrcStart(), componentPckg,
										desc.getClassName(), "LazyQueryFactory.java"),
								TEMPLATE_PACKAGE, log);
					}

				}
			}
		}
	}
}
 
Example #18
Source File: AutoScalingPrePostFactory.java    From vertx-deploy-tools with Apache License 2.0 5 votes vote down vote up
public static AutoScalingPrePostHandler getPrePostHandler(DeployConfiguration activeConfiguration, AwsAutoScalingDeployUtils awsDeployUtils, Log log) {
    if (nl.jpoint.maven.vertx.utils.deploy.strategy.DeployStrategyType.SPIN_AND_REMOVE == activeConfiguration.getDeployStrategy()) {
        return new SpinAndRemovePrePostHandler(activeConfiguration, awsDeployUtils, log);
    } else {
        return new DefaultAutoScalingPrePostHandler(activeConfiguration, awsDeployUtils, log);
    }
}
 
Example #19
Source File: WebJars.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
private static File getOutput(Log log, File out, boolean stripVersion, String path) {
    if (stripVersion) {
        Matcher matcher = WEBJAR_INTERNAL_PATH_REGEX.matcher(path);
        if (matcher.matches()) {
            return new File(out, matcher.group(1) + "/" + matcher.group(3));
        } else {
            log.warn(path + " does not match the regex - did not strip the version for this file");
        }
    }
    return new File(out, path);
}
 
Example #20
Source File: DdlGeneratorHibernate50.java    From hibernate5-ddl-maven-plugin with GNU General Public License v3.0 5 votes vote down vote up
public PersistenceXmlHandler(
    final StandardServiceRegistryBuilder registryBuilder,
    final Log log,
    final Set<String> propertiesToUse) {

    this.registryBuilder = registryBuilder;
    this.log = log;
    this.propertiesToUse = propertiesToUse;
}
 
Example #21
Source File: BaseMojo.java    From multi-module-maven-release-plugin with MIT License 5 votes vote down vote up
protected CredentialsProvider getCredentialsProvider(final Log log) throws ValidationException {
    if (serverId != null) {
        Server server = settings.getServer(serverId);
        if (server == null) {
            log.warn(format("No server configuration in Maven settings found with id %s", serverId));
        }
        if (server.getUsername() != null && server.getPassword() != null) {
            return new UsernamePasswordCredentialsProvider(server.getUsername(), server.getPassword());
        }
    }
    return null;
}
 
Example #22
Source File: InstallPluginsStep.java    From elasticsearch-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(InstanceConfiguration config)
{
    if (config.getClusterConfiguration().getPlugins().size() > 0)
    {
        if (VersionUtil.isEqualOrGreater_6_4_0(config.getClusterConfiguration().getVersion()))
        {
            FilesystemUtil.setScriptPermission(config, "elasticsearch-cli");
        }
        FilesystemUtil.setScriptPermission(config, "elasticsearch-plugin");
    }

    Log log = config.getClusterConfiguration().getLog();
    
    for (PluginConfiguration plugin : config.getClusterConfiguration().getPlugins())
    {
        log.info(String.format(
                "Installing plugin '%s' with options '%s'",
                plugin.getUri(), plugin.getEsJavaOpts()));
        
        Map<String, String> environment = new HashMap<>(config.getEnvironmentVariables());
        
        if (StringUtils.isNotBlank(plugin.getEsJavaOpts()))
        {
            environment.put("ES_JAVA_OPTS", plugin.getEsJavaOpts());
        }

        CommandLine cmd = ProcessUtil.buildCommandLine("bin/elasticsearch-plugin")
                .addArgument("install")
                .addArgument("--batch")
                .addArgument(plugin.getUri());
        
        ProcessUtil.executeScript(config, cmd, environment, null);
    }
}
 
Example #23
Source File: AwsAutoScalingDeployUtils.java    From vertx-deploy-tools with Apache License 2.0 5 votes vote down vote up
public List<Ec2Instance> getInstancesForAutoScalingGroup(Log log, AutoScalingGroup autoScalingGroup) throws MojoFailureException {
    log.info("retrieving list of instanceId's for auto scaling group with id : " + activeConfiguration.getAutoScalingGroupId());

    activeConfiguration.getHosts().clear();

    log.debug("describing instances in auto scaling group");

    if (autoScalingGroup.getInstances().isEmpty()) {
        return new ArrayList<>();
    }

    Map<String, Instance> instanceMap = autoScalingGroup.getInstances().stream().collect(Collectors.toMap(Instance::getInstanceId, Function.identity()));

    try {
        DescribeInstancesResult instancesResult = awsEc2Client.describeInstances(new DescribeInstancesRequest().withInstanceIds(autoScalingGroup.getInstances().stream().map(Instance::getInstanceId).collect(Collectors.toList())));
        List<Ec2Instance> ec2Instances = instancesResult.getReservations().stream().flatMap(r -> r.getInstances().stream()).map(this::toEc2Instance).collect(Collectors.toList());
        log.debug("describing elb status");
        autoScalingGroup.getLoadBalancerNames().forEach(elb -> this.updateInstancesStateOnLoadBalancer(elb, ec2Instances));
        ec2Instances.forEach(i -> i.updateAsState(AwsState.map(instanceMap.get(i.getInstanceId()).getLifecycleState())));
        ec2Instances.sort((o1, o2) -> {

            int sComp = o1.getAsState().compareTo(o2.getAsState());

            if (sComp != 0) {
                return sComp;
            } else {
                return o1.getElbState().compareTo(o2.getElbState());
            }
        });
        if (activeConfiguration.isIgnoreInStandby()) {
            return ec2Instances.stream().filter(i -> i.getAsState() != AwsState.STANDBY).collect(Collectors.toList());
        }
        return ec2Instances;
    } catch (AmazonClientException e) {
        log.error(e.getMessage(), e);
        throw new MojoFailureException(e.getMessage());
    }

}
 
Example #24
Source File: ServiceFileCombinationImpl.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * The method to perform the service provider combining
 *
 * @param project      the Maven project
 * @param patterns     the set of patterns
 * @param logger       the logger
 * @param dependencies the dependencies
 */
private void combine(MavenProject project, List<String> patterns, Log logger, List<File> dependencies) {
    Map<String, List<String>> locals = findLocalDescriptors(project, patterns);
    Map<String, List<List<String>>> deps = findDescriptorsFromDependencies(dependencies, patterns);

    // Keys are path relative to the archive root.
    logger.debug("Descriptors declared in the project: " + locals.keySet());
    logger.debug("Descriptors declared in dependencies: " + deps.keySet());

    Set<String> descriptorsToMerge = new LinkedHashSet<>(locals.keySet());
    descriptorsToMerge.addAll(deps.keySet());

    Map<String, List<String>> descriptors = new HashMap<>();
    for (String spi : descriptorsToMerge) {
        descriptors.put(spi, merge(project, spi, locals.get(spi), deps.get(spi)));
    }

    // Write the new files in target/classes
    File out = new File(project.getBuild().getOutputDirectory());

    descriptors.forEach((name, content) -> {
        File merged = new File(out, name);
        try {
            org.apache.commons.io.FileUtils.writeLines(merged, content);
            logger.debug("Descriptor combined into " + merged.getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException("Cannot write combined Descriptor files", e);
        }
    });
}
 
Example #25
Source File: AwsAutoScalingDeployUtils.java    From vertx-deploy-tools with Apache License 2.0 5 votes vote down vote up
public AwsAutoScalingDeployUtils(String region, DeployConfiguration activeConfiguration, Log log) {
    this.activeConfiguration = activeConfiguration;
    this.log = log;

    awsAsClient = AmazonAutoScalingClientBuilder.standard().withRegion(region).build();
    awsElbClient = AmazonElasticLoadBalancingClientBuilder.standard().withRegion(region).build();
    awsEc2Client = AmazonEC2ClientBuilder.standard().withRegion(region).build();

    activeConfiguration.withAutoScalingGroup(matchAutoScalingGroupName(activeConfiguration.getAutoScalingGroupId()));

}
 
Example #26
Source File: DefinitionGenerator.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a Swagger definition generator which generates the definitions based on the specified parameters.
 *
 * @param log the log.
 * @param swagger the Swagger metadata.
 * @param exampleClassNames the example class names.
 * @param modelClasses the model classes.
 * @param xsdParser the XSD parser
 *
 * @throws MojoExecutionException if any problems were encountered.
 */
public DefinitionGenerator(Log log, Swagger swagger, Set<String> exampleClassNames, Set<Class<?>> modelClasses, XsdParser xsdParser)
    throws MojoExecutionException
{
    this.log = log;
    this.swagger = swagger;
    this.exampleClassNames = exampleClassNames;
    this.modelClasses = modelClasses;
    this.xsdParser = xsdParser;

    generateDefinitions();
}
 
Example #27
Source File: Slf4jAdapter.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
/**
 * Get Maven Log.
 * 
 * @return The log from Maven plugin
 */
private Log _log ()
{
  if (m_aMavenLog == null)
    throw new IllegalStateException ("initialize StaticLoggerBinder with #setMavenLog() first");
  return m_aMavenLog;
}
 
Example #28
Source File: SkipModuleStrategyTest.java    From japicmp with Apache License 2.0 5 votes vote down vote up
@Test
public void testModuleIsNotIncludedAndNoIncludesDefined() {
	PluginParameters pluginParameters = createPluginParameters();
	MavenParameters mavenParameters = createMavenParameters();
	mavenParameters.getMavenProject().setArtifactId("name-to-include");
	pluginParameters.getParameterParam().setIncludeModules(Collections.singletonList(".*test.*"));
	SkipModuleStrategy skipModuleStrategy = new SkipModuleStrategy(pluginParameters, mavenParameters, mock(Log.class));
	assertThat(skipModuleStrategy.skip(), is(true));
}
 
Example #29
Source File: ServiceUtils.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
public static Set<Artifact> filterArtifacts(Set<Artifact> artifacts, List<String> includes,
                                            List<String> excludes,
                                            boolean actTransitively, Log logger,
                                            ArtifactFilter... additionalFilters) {

    final AndArtifactFilter filter = new AndArtifactFilter();

    if (additionalFilters != null && additionalFilters.length > 0) {
        for (final ArtifactFilter additionalFilter : additionalFilters) {
            if (additionalFilter != null) {
                filter.add(additionalFilter);
            }
        }
    }

    if (!includes.isEmpty()) {
        final ArtifactFilter includeFilter = new PatternIncludesArtifactFilter(includes, actTransitively);
        filter.add(includeFilter);
    }

    if (!excludes.isEmpty()) {
        final ArtifactFilter excludeFilter = new PatternExcludesArtifactFilter(excludes, actTransitively);
        filter.add(excludeFilter);
    }

    Set<Artifact> copy = new LinkedHashSet<>(artifacts);
    for (final Iterator<Artifact> it = copy.iterator(); it.hasNext(); ) {

        final Artifact artifact = it.next();

        if (!filter.include(artifact)) {
            it.remove();
            if (logger.isDebugEnabled()) {
                logger.debug(artifact.getId() + " was removed by one or more filters.");
            }
        }
    }

    return copy;
}
 
Example #30
Source File: RequestExecutor.java    From vertx-deploy-tools with Apache License 2.0 5 votes vote down vote up
RequestExecutor(Log log, Integer requestTimeout, Integer port, String authToken) {
    this.log = log;
    this.port = port;
    this.authToken = authToken != null ? authToken : "";
    this.timeout = System.currentTimeMillis() + (60000L * requestTimeout);
    log.info("Setting timeout to : " + new Date(timeout));
}