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.thoughtworks.go.apiv2.dashboard.DashboardControllerDelegate.java

public Object index(Request request, Response response) throws IOException {
    if (goDashboardService.isFeatureToggleDisabled()) {
        response.status(424);//ww  w .  ja va 2  s  .c o m
        return FEATURE_NOT_ENABLED;
    }
    if (!goDashboardService.hasEverLoadedCurrentState()) {
        response.status(202);
        return BEING_PROCESSED;
    }

    String selectedPipelinesCookie = request.cookie("selected_pipelines");
    Long userId = currentUserId(request);
    Username userName = currentUsername();

    PipelineSelections selectedPipelines = pipelineSelectionsService
            .getPersistedSelectedPipelines(selectedPipelinesCookie, userId);
    List<GoDashboardPipelineGroup> pipelineGroups = goDashboardService
            .allPipelineGroupsForDashboard(selectedPipelines, userName);
    String etag = DigestUtils.md5Hex(
            pipelineGroups.stream().map(GoDashboardPipelineGroup::etag).collect(Collectors.joining("/")));

    if (fresh(request, etag)) {
        return notModified(response);
    }

    setEtagHeader(response, etag);

    return writerForTopLevelObject(request, response, outputWriter -> PipelineGroupsRepresenter
            .toJSON(outputWriter, new DashboardFor(pipelineGroups, userName)));
}

From source file:dk.dma.msinm.common.time.TimeParser.java

/**
 * Parse the time description into its XML representation
 * @param time the time description to parse
 * @return the result// w  w  w. j a va 2  s.  com
 */
protected String parse(String time) throws TimeException {
    String monthMatch = "(" + Arrays.asList(months).stream().collect(Collectors.joining("|")) + ")";
    String seasonMatch = "(" + Arrays.asList(seasons).stream().collect(Collectors.joining("|")) + ")";
    String dayMatch = "(\\\\d{1,2})";
    String yearMatch = "(\\\\d{4})";
    String hourMatch = "(\\\\d{4})";
    String weekMatch = "(\\\\d{1,2})";

    BufferedReader reader = new BufferedReader(new StringReader(time));
    String line;
    StringBuilder result = new StringBuilder();
    try {
        while ((line = reader.readLine()) != null) {
            line = line.trim().toLowerCase();

            // Replace according to replace rules
            for (String key : rewriteRules.keySet()) {
                String value = rewriteRules.get(key);

                String from = key;
                from = from.replaceAll("\\$month", monthMatch);
                from = from.replaceAll("\\$season", seasonMatch);
                from = from.replaceAll("\\$date", dayMatch);
                from = from.replaceAll("\\$year", yearMatch);
                from = from.replaceAll("\\$hour", hourMatch);
                from = from.replaceAll("\\$week", weekMatch);

                Matcher m = Pattern.compile(from).matcher(line);
                StringBuffer sb = new StringBuffer();
                while (m.find()) {
                    String text = m.group();
                    m.appendReplacement(sb, value);
                }
                m.appendTail(sb);
                line = sb.toString();
            }
            result.append(line + "\n");
        }
    } catch (Exception e) {
        throw new TimeException("Failed converting time description into XML", e);
    }
    return "<time-result>" + result.toString() + "</time-result>";
}

From source file:io.mindmaps.loader.DistributedLoader.java

public void submitBatch(Collection<Var> batch) {
    String batchedString = batch.stream().map(Object::toString).collect(Collectors.joining(";"));

    if (batchedString.length() == 0) {
        return;/*from  w w w  . j  av  a  2  s  .c o m*/
    }

    HttpURLConnection currentConn = acquireNextHost();
    String query = RESTUtil.HttpConn.INSERT_PREFIX + batchedString;

    executePost(currentConn, query);

    int responseCode = getResponseCode(currentConn);
    if (responseCode != RESTUtil.HttpConn.HTTP_TRANSACTION_CREATED) {
        throw new HTTPException(responseCode);
    }

    markAsLoading(getResponseBody(currentConn));
    LOG.info("Transaction sent to host: " + hostsArray[currentHost]);

    if (future == null) {
        startCheckingStatus();
    }

    currentConn.disconnect();
}

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

String joined(String... list) {
    return list == null ? "" : Arrays.asList(list).stream().collect(Collectors.joining(" "));
}

From source file:com.gitpitch.models.MarkdownModel.java

@Inject
public MarkdownModel(ImageService imageService, VideoService videoService, GISTService gistService,
        @Nullable @Assisted MarkdownRenderer mrndr) {

    this.imageService = imageService;
    this.videoService = videoService;
    this.gistService = gistService;
    this.mrndr = mrndr;

    String consumed = null;//from   w  w w  .  jav a 2s .  c  o  m

    if (mrndr != null) {

        String gitRawBase = mrndr.gitRawBase();
        Path mdPath = mrndr.filePath(PITCHME_MD);

        File mdFile = mdPath.toFile();

        if (mdFile.exists()) {

            Optional<SlideshowModel> ssmo = mrndr.ssm();

            final PitchParams pp = ssmo.isPresent() ? ssmo.get().params() : null;
            final YAMLOptions yOpts = ssmo.isPresent() ? ssmo.get().options() : null;

            if (yOpts != null) {
                hSlideDelim = yOpts.hasHorzDelim(pp) ? yOpts.fetchHorzDelim(pp) : HSLIDE_DELIM_DEFAULT;
                vSlideDelim = yOpts.hasVertDelim(pp) ? yOpts.fetchVertDelim(pp) : VSLIDE_DELIM_DEFAULT;
            }

            try (Stream<String> stream = Files.lines(mdPath)) {

                consumed = stream.map(md -> {
                    return process(md, pp, yOpts, gitRawBase);
                }).collect(Collectors.joining("\n"));

                consumed = postProcess(consumed, pp, yOpts, gitRawBase);

            } catch (Exception mex) {
                log.warn("Markdown processing ex={}", mex);
                consumed = "PITCHME.md could not be parsed.";
            }

        } else {
            log.warn("Markdown file does not exist, {}", mdFile);
        }

    }

    this.markdown = consumed;
}

From source file:com.blackducksoftware.integration.hub.detect.configuration.DetectConfiguration.java

private void init() {
    Arrays.stream(DetectProperty.values()).forEach(currentProperty -> {
        final DetectProperty override = fromDeprecatedToOverride(currentProperty);
        final DetectProperty deprecated = fromOverrideToDeprecated(currentProperty);
        if (override == null && deprecated == null) {
            handleStandardProperty(currentProperty);
        } else if (override != null) {
            handleDeprecatedProperty(currentProperty, override);// a deprecated property has an override
        } else if (deprecated != null) {
            handleOverrideProperty(currentProperty, deprecated);// an override property has a deprecated property
        }/*from   ww  w  . j a  v a 2s. c  o  m*/
    });
    //TODO: Find a better way to do this - or - hopefully remove this if the scan cli gets better.
    String bdScanPaths = detectPropertySource.getProperty("BD_HUB_SCAN_PATH");
    if (StringUtils.isNotBlank(bdScanPaths)) {
        logger.warn("The environment variable BD_HUB_SCAN_PATH was set but you should use --"
                + DetectProperty.DETECT_BLACKDUCK_SIGNATURE_SCANNER_PATHS.getPropertyKey() + " instead.");
        List<String> values = new ArrayList<>();
        values.addAll(Arrays.asList(getStringArrayProperty(
                DetectProperty.DETECT_BLACKDUCK_SIGNATURE_SCANNER_PATHS, PropertyAuthority.None)));
        values.addAll(Arrays.asList(bdScanPaths.split(",")));
        setDetectProperty(DetectProperty.DETECT_BLACKDUCK_SIGNATURE_SCANNER_PATHS,
                values.stream().collect(Collectors.joining(",")));
    }
}

From source file:eu.crydee.alignment.aligner.cr.BritannicaCR.java

@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);
    corpus = new File(corpusPath);
    anns = new File(annsPath);
    List<String> errs = new ArrayList<>();
    if (!corpus.isDirectory()) {
        errs.add("The Britannica ccorpus folder path doesn't resolve to " + "a folder.");
    } else if (!corpus.canRead()) {
        errs.add("The Britannica corpus folder can't be read.");
    } else if (!anns.isDirectory()) {
        errs.add("The Britannica annotations folder path doesn't resolve " + "to a folder.");
    } else if (!anns.canRead()) {
        errs.add("The Britannica annotations folder can't be read.");
    }/*www .  j  a va 2s.c o m*/
    if (!errs.isEmpty()) {
        logger.error(errs.stream().collect(Collectors.joining("\n")));
        throw new ResourceInitializationException();
    }
    Pattern eleAdaFile = Pattern.compile(".*-ele\\.ada");
    Set<String> fileNames = new HashSet<>(Arrays.asList(corpus.list())),
            annsNames = new HashSet<>(Arrays.asList(anns.list()));
    filesNames = corpus.list(
            (d, n) -> eleAdaFile.matcher(n).matches() && fileNames.contains(n.replace("-ele.ada", "-bri.ada"))
                    && annsNames.contains(n.replace("-ele.ada", "-hum.txt")));
    currentIndex = 0;
    max = filesNames.length;
}

From source file:io.github.carlomicieli.footballdb.starter.pages.Table.java

private String headersToString() {
    if (tableWithoutHeader())
        return "";
    return "Header(" + headers.stream().collect(Collectors.joining(", ")) + "), ";
}

From source file:io.spotnext.maven.mojo.TransformTypesMojo.java

/** {@inheritDoc} */
@Override//from w w  w  .  j  ava2  s. c  o m
public void execute() throws MojoExecutionException {
    if (skip) {
        getLog().info("Skipping type transformation!");
        return;
    }

    trackExecution("start");

    final ClassLoader classLoader = getClassloader();
    final List<ClassFileTransformer> transformers = getClassFileTransformers(classLoader);

    List<File> classFiles = FileUtils.getFiles(project.getBuild().getOutputDirectory(),
            f -> f.getAbsolutePath().endsWith(".class"));
    getLog().debug("Found class files for processing: "
            + classFiles.stream().map(f -> f.getName()).collect(Collectors.joining(", ")));

    if (CollectionUtils.isNotEmpty(transformers)) {
        if (CollectionUtils.isNotEmpty(classFiles)) {
            getLog().info(String.format("Transforming %s classes", classFiles.size()));

            for (final File f : classFiles) {
                if (f.getName().endsWith(Constants.CLASS_EXTENSION)) {
                    String relativeClassFilePath = StringUtils.remove(f.getPath(),
                            project.getBuild().getOutputDirectory());
                    relativeClassFilePath = StringUtils.removeStart(relativeClassFilePath, "/");
                    final String className = relativeClassFilePath.substring(0,
                            relativeClassFilePath.length() - Constants.CLASS_EXTENSION.length());

                    trackExecution("Loading class: " + f.getAbsolutePath());

                    byte[] byteCode;
                    try {
                        byteCode = Files.readAllBytes(f.toPath());
                    } catch (final IOException e) {
                        String message = String.format("Can't read bytecode for class %s", className);
                        buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e);
                        throw new IllegalStateException(message, e);
                    }

                    trackExecution("Loaded class: " + f.getAbsolutePath());

                    for (final ClassFileTransformer t : transformers) {
                        try {

                            // log exceptions into separate folder, to be able to inspect them even if Eclipse swallows them ...
                            if (t instanceof AbstractBaseClassTransformer) {
                                ((AbstractBaseClassTransformer) t).setErrorLogger(this::logError);
                            }

                            // returns null if nothing has been transformed
                            byteCode = t.transform(classLoader, className, null, null, byteCode);
                        } catch (final Exception e) {
                            String exception = "Exception during transformation of class: "
                                    + f.getAbsolutePath() + "\n" + e.getMessage();
                            trackExecution(exception);
                            String message = String.format("Can't transform class %s, transformer %s: %s",
                                    className, t.getClass().getSimpleName(), ExceptionUtils.getStackTrace(e));
                            buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e);
                            throw new MojoExecutionException(exception, e);
                        }
                    }

                    if (byteCode != null && byteCode.length > 0) {
                        try {
                            Files.write(f.toPath(), byteCode, StandardOpenOption.CREATE,
                                    StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

                            trackExecution("Saved transformed class: " + f.getAbsolutePath());
                        } catch (final IOException e) {
                            String message = "Could not write modified class: " + relativeClassFilePath;
                            buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e);
                            throw new IllegalStateException(message);
                        } finally {
                            buildContext.refresh(f);
                            getLog().info("Applied transformation to type: " + f.getAbsolutePath());
                        }
                    } else {
                        trackExecution("No changes made for class: " + f.getAbsolutePath());
                        getLog().debug("No transformation was applied to type: " + f.getAbsolutePath());
                    }
                }
            }
        } else {
            getLog().info("No class files found");
        }

        trackExecution("All classes in build output folder transformed");

        if (includeJars) {
            final String packaging = project.getPackaging();
            final Artifact artifact = project.getArtifact();

            if ("jar".equals(packaging) && artifact != null) {
                try {
                    final File source = artifact.getFile();

                    if (source.isFile()) {
                        final File destination = new File(source.getParent(), "instrument.jar");

                        final JarTransformer transformer = new JarTransformer(getLog(), classLoader,
                                Arrays.asList(source), transformers);
                        transformer.transform(destination);

                        final File sourceRename = new File(source.getParent(),
                                "notransform-" + source.getName());

                        if (source.renameTo(sourceRename)) {
                            throw new MojoExecutionException(String.format("Could not move %s to %s",
                                    source.toString(), sourceRename.toString()));
                        }

                        if (destination.renameTo(sourceRename)) {
                            throw new MojoExecutionException(String.format("Could not move %s to %s",
                                    destination.toString(), sourceRename.toString()));
                        }

                        buildContext.refresh(destination);
                    }
                } catch (final Exception e) {
                    buildContext.addMessage(artifact.getFile(), 0, 0, e.getMessage(),
                            BuildContext.SEVERITY_ERROR, e);
                    throw new MojoExecutionException(e.getMessage(), e);
                }
            } else {
                getLog().debug(String.format("Artifact %s not a jar file",
                        artifact != null ? (artifact.getGroupId() + ":" + artifact.getArtifactId())
                                : "<null>"));
            }
        }
    } else {
        getLog().info("No class transformers configured");
    }
}

From source file:defaultmethods.StandardDeck.java

public String deckToString() {
    return this.entireDeck.stream().map(Card::toString).collect(Collectors.joining("\n"));
}