Example usage for java.util.stream Collectors joining

List of usage examples for java.util.stream Collectors joining

Introduction

In this page you can find the example usage for java.util.stream Collectors joining.

Prototype

public static Collector<CharSequence, ?, String> joining(CharSequence delimiter) 

Source Link

Document

Returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.

Usage

From source file:com.hubrick.vertx.s3.signature.AWS4SignatureBuilder.java

public AWS4SignatureBuilder canonicalQueryString(final String canonicalQueryString) {
    final String defaultString = StringUtils.defaultString(canonicalQueryString);

    // this way of parsing the query string is the only way to satisfy the
    // test-suite, therefore we do it with a matcher:
    final Matcher matcher = QUERY_STRING_MATCHING_PATTERN.matcher(defaultString);
    final List<KeyValue<String, String>> parameters = Lists.newLinkedList();

    while (matcher.find()) {
        final String key = StringUtils.trim(matcher.group(1));
        final String value = StringUtils.trim(matcher.group(2));
        parameters.add(new DefaultKeyValue<>(key, value));
    }//from www  .j  av a2  s .com

    this.canonicalQueryString = parameters.stream().sorted(Comparator.comparing(KeyValue::getKey))
            .map(kv -> queryParameterEscape(kv.getKey()) + "=" + queryParameterEscape(kv.getValue()))
            .collect(Collectors.joining("&"));

    return this;
}

From source file:com.synopsys.detect.doctor.DoctorApplication.java

@Override
public void run(final ApplicationArguments applicationArguments) throws Exception {
    PropertyMap<DoctorProperty> doctorPropertyPropertyMap = new PropertyMap<>();
    SpringPropertySource springPropertySource = new SpringPropertySource(configurableEnvironment);
    DoctorConfiguration doctorConfiguration = new DoctorConfiguration(springPropertySource,
            doctorPropertyPropertyMap);//from  w  w  w . ja va 2s  .  c  o  m

    DoctorArgumentStateParser argumentStateParser = new DoctorArgumentStateParser();
    DoctorArgumentState state = argumentStateParser.parseArgs(applicationArguments.getSourceArgs());

    doctorConfiguration.init();

    DoctorRun doctorRun = DoctorRun.createDefault();

    logger.info("Doctor begin: " + doctorRun.getRunId());

    DoctorDirectoryManager doctorDirectoryManager = new DoctorDirectoryManager(doctorRun);

    logger.info("Doctor ready.");

    Optional<DetectRunInfo> detectRunInfo = Optional.empty();

    File diagnosticZip = new File(doctorConfiguration.getProperty(DoctorProperty.DETECT_DIAGNOSTIC_FILE));
    if (diagnosticZip.exists()) {
        logger.info("A diagnostic zip was found: " + diagnosticZip.getAbsolutePath());
        DiagnosticParser diagnosticParser = new DiagnosticParser();
        detectRunInfo = Optional
                .of(diagnosticParser.processDiagnosticZip(doctorDirectoryManager, diagnosticZip));
    } else {
        logger.info("No diagnostic zip provided, looking for the pieces.");
        File log = new File(doctorConfiguration.getProperty(DoctorProperty.DETECT_LOG_FILE));

        logger.info("Looking for log file at: " + log.getAbsolutePath());
        if (log.exists()) {
            logger.info("Found log file.");
            // detectRunInfo = Optional.of(new DetectRunInfo(log));
        } else {
            logger.info("No log file found.");
        }
    }

    if (detectRunInfo.isPresent()) {

        DetectLogParser logParser = new DetectLogParser();

        logger.info("Doctor can proceed, necessary pieces located.");

        File log = detectRunInfo.get().getLogFile();

        DetectLogParseResult result = logParser.parse(log);

        logger.info("Detect log parsed.");

        String extractionId = doctorConfiguration.getProperty(DoctorProperty.DETECT_EXTRACTION_ID);

        Set<String> extractions = new HashSet<>();

        LoggedDetectExtraction extraction = null;
        for (LoggedDetectExtraction possibleExtraction : result.loggedConfiguration.extractions) {
            extractions.add(possibleExtraction.extractionIdentifier);
            if (possibleExtraction.extractionIdentifier.equals(extractionId)) {
                extraction = possibleExtraction;
            }
        }

        if (StringUtils.isBlank(extractionId)) {
            quit("Doctor needs an extraction to work with, options are: "
                    + extractions.stream().collect(Collectors.joining(",")));
        }

        if (extraction == null) {
            quit("No extraction found for given id: " + extractionId);
        }

        logger.info("Found extraction with id: " + extractionId);
        logger.info("Doctor will attempt to diagnose!");

        logger.info("We begin by rebuilding the configuration.");
        Map<String, String> propertyMap = new HashMap<>();
        result.loggedConfiguration.loggedPropertyList.stream().forEach(it -> propertyMap.put(it.key, it.value));
        RehydratedPropertySource rehydratedPropertySource = new RehydratedPropertySource(propertyMap);
        DetectConfiguration detectConfiguration = new DetectConfiguration(
                new DetectPropertySource(rehydratedPropertySource), new DetectPropertyMap());

        ExtractionHandler extractionHandler = new ExtractionHandler();
        extractionHandler.processExtraction(extraction, detectRunInfo.get(), detectConfiguration);

    } else {
        quit("Neccessary pieces not found for doctor to proceed.");
    }

}

From source file:org.springframework.cloud.deployer.spi.cloudfoundry.CloudFoundry2630AndLaterTaskLauncher.java

private String getCommand(SummaryApplicationResponse application, AppDeploymentRequest request) {
    return Stream.concat(Stream.of(application.getDetectedStartCommand()),
            request.getCommandlineArguments().stream()).collect(Collectors.joining(" "));
}

From source file:com.github.horrorho.liquiddonkey.settings.commandline.CommandLineOptions.java

static String itemTypes(Properties properties) {
    Props<Property> props = Props.from(properties);

    String prefix = props.getProperty(CONFIG_PREFIX_ITEM_TYPE);
    if (prefix == null) {
        logger.warn("-- itemTypes() > no item type prefix: {}", CONFIG_PREFIX_ITEM_TYPE);
        return "";
    }//from  w  ww . j a  v  a 2s.  co m

    int substring = prefix.length();

    return Stream.of(Property.values()).filter(property -> property.name().startsWith(prefix))
            .filter(property -> !props.getProperty(property, props::asList).isEmpty()).map(property -> {
                String type = property.name().substring(substring);
                String paths = props.getProperty(property, props::asList).stream()
                        .collect(Collectors.joining(" "));
                return type + "(" + paths + ")";
            }).collect(Collectors.joining(" "));
}

From source file:com.marklogic.entityservices.e2e.ExamplesBase.java

public void importJSON(Path jsonDirectory, String toCollection) throws IOException {

    logger.info("job started.");

    WriteHostBatcher batcher = moveMgr.newWriteHostBatcher().withBatchSize(100).withThreadCount(5)
            .onBatchSuccess((client, batch) -> logger.info("Loaded batch of JSON documents"))
            .onBatchFailure((client, batch, throwable) -> {
                logger.error("FAILURE on batch:" + batch.toString() + "\n", throwable);
                System.err.println(throwable.getMessage());
                System.err.println(Arrays.stream(batch.getItems()).map(item -> item.getTargetUri())
                        .collect(Collectors.joining("\n")));
                // throwable.printStackTrace();
            });/*  w  w w  .j a  v  a 2  s  .  c om*/

    ticket = moveMgr.startJob(batcher);

    importOrDescend(jsonDirectory, batcher, toCollection, Format.JSON);

    batcher.flush();
}

From source file:io.pivotal.xd.chaoslemur.Destroyer.java

private String message(List<Member> members) {
    int size = members.size();

    String SPACE = "\u00A0";
    String BULLET = "\u2022";

    String s = "\n";
    s += size + English.plural(" VM", size) + " destroyed:\n";
    s += members.stream().sorted().map((member) -> SPACE + SPACE + BULLET + SPACE + member.getName())
            .collect(Collectors.joining("\n"));

    return s;//from   w w w.  j a  va2s. com
}

From source file:com.epam.catgenome.manager.reference.ReferenceGenomeManager.java

/**
 * Deletes a {@code Reference} instance from the server and database
 * @param reference an instnce to delete
 *//*from   w ww. j  a  va  2s. c  o  m*/
@Transactional(propagation = Propagation.REQUIRED)
public void unregister(final Reference reference) {
    Assert.notNull(reference, MessagesConstants.ERROR_INVALID_PARAM);
    Assert.notNull(reference.getId(), MessagesConstants.ERROR_INVALID_PARAM);

    if (reference.getType() != BiologicalDataItemResourceType.GA4GH) {
        List<Project> projectsWhereFileInUse = projectDao
                .loadProjectsByBioDataItemId(reference.getBioDataItemId());
        Assert.isTrue(projectsWhereFileInUse.isEmpty(), getMessage(MessagesConstants.ERROR_FILE_IN_USE,
                reference.getName(), reference.getId(),
                projectsWhereFileInUse.stream().map(BaseEntity::getName).collect(Collectors.joining(", "))));
        List<BaseEntity> fileList = loadAllFile(reference.getId());
        Assert.isTrue(fileList.isEmpty(),
                getMessage(MessagesConstants.ERROR_FILE_IN_LINK, reference.getName(), reference.getId(),
                        fileList.stream().map(BaseEntity::getName).collect(Collectors.joining(", "))));
    }
    referenceGenomeDao.unregisterReferenceGenome(reference.getId());
    biologicalDataItemDao.deleteBiologicalDataItem(reference.getBioDataItemId());
}

From source file:com.thinkbiganalytics.alerts.spi.defaults.KyloEntityAwareAlertCriteria.java

private String filterStringForFeedAlertEntities(String keyword) {
    return CommonFilterTranslations.feedFilters.keySet().stream().map(key -> key + "==" + keyword)
            .collect(Collectors.joining(","));
}

From source file:com.blackducksoftware.integration.hub.detect.lifecycle.shutdown.ShutdownManager.java

public void shutdown(Optional<RunResult> runResultOptional) {
    if (connectivityManager.getPhoneHomeManager().isPresent()) {
        try {/*w  ww  .ja  v a2  s. c  o  m*/
            logger.debug("Ending phone home.");
            connectivityManager.getPhoneHomeManager().get().endPhoneHome();
        } catch (final Exception e) {
            logger.debug(String.format("Error trying to end the phone home task: %s", e.getMessage()));
        }
    }

    try {
        if (diagnosticManager.getDiagnosticSystem().isPresent()) {
            logger.debug("Ending diagnostics.");
            diagnosticManager.getDiagnosticSystem().get().finish();
        }
    } catch (final Exception e) {
        logger.debug(String.format("Error trying to finish diagnostics: %s", e.getMessage()));
    }

    try {
        if (detectConfiguration.getBooleanProperty(DetectProperty.DETECT_CLEANUP, PropertyAuthority.None)) {
            logger.info("Detect will cleanup.");
            boolean dryRun = detectConfiguration.getBooleanProperty(
                    DetectProperty.DETECT_BLACKDUCK_SIGNATURE_SCANNER_DRY_RUN, PropertyAuthority.None);
            boolean offline = !connectivityManager.isDetectOnline();

            List<File> cleanupToSkip = new ArrayList<>();
            if (dryRun || offline) {
                logger.debug("Will not cleanup scan folder.");
                cleanupToSkip.add(directoryManager.getScanOutputDirectory());
            }
            if (offline) {
                logger.debug("Will not cleanup bdio folder.");
                cleanupToSkip.add(directoryManager.getBdioOutputDirectory());
            }
            logger.debug("Cleaning up directory: " + directoryManager.getRunHomeDirectory().getAbsolutePath());
            cleanup(directoryManager.getRunHomeDirectory(), cleanupToSkip);
        } else {
            logger.info("Skipping cleanup, it is disabled.");
        }
    } catch (final Exception e) {
        logger.debug(String.format("Error trying cleanup: %s", e.getMessage()));
    }

    Set<DetectorType> detectorTypes = new HashSet<>();
    if (runResultOptional.isPresent()) {
        detectorTypes.addAll(runResultOptional.get().getApplicableDetectors());
    }

    //Check required detector types
    String requiredDetectors = detectConfiguration.getProperty(DetectProperty.DETECT_REQUIRED_DETECTOR_TYPES,
            PropertyAuthority.None);
    RequiredDetectorChecker requiredDetectorChecker = new RequiredDetectorChecker();
    RequiredDetectorChecker.RequiredDetectorResult requiredDetectorResult = requiredDetectorChecker
            .checkForMissingDetectors(requiredDetectors, detectorTypes);
    if (requiredDetectorResult.wereDetectorsMissing()) {
        String missingDetectors = requiredDetectorResult.getMissingDetectors().stream().map(it -> it.toString())
                .collect(Collectors.joining(","));
        logger.error("One or more required detector types were not found: " + missingDetectors);
        exitCodeManager.requestExitCode(ExitCodeType.FAILURE_DETECTOR_REQUIRED);
    }
}

From source file:api.wiki.WikiGenerator.java

private String versionIndexPageLinks(List<String> versionsWithDocumentation) {
    return versionsWithDocumentation.stream().map(version -> hyperLink(version, version + "/index"))
            .collect(Collectors.joining("\n"));
}