Example usage for java.lang String join

List of usage examples for java.lang String join

Introduction

In this page you can find the example usage for java.lang String join.

Prototype

public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) 

Source Link

Document

Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter .

Usage

From source file:cop.maven.plugins.AbstractRestToRamlMojo.java

private String buildCompileClasspath() {
    Set<String> elements = new LinkedHashSet<>();

    if (CollectionUtils.isNotEmpty(pluginArtifacts))
        elements.addAll(pluginArtifacts.stream()
                .filter(artifact -> Artifact.SCOPE_COMPILE.equalsIgnoreCase(artifact.getScope())
                        || Artifact.SCOPE_RUNTIME.equalsIgnoreCase(artifact.getScope()))
                .map(Artifact::getFile).filter(Objects::nonNull).map(File::getAbsolutePath)
                .collect(Collectors.toList()));

    elements.addAll(getClasspathElements());

    return String.join(";", elements);
}

From source file:com.spotify.styx.api.BackfillResource.java

private String schedulerApiUrl(CharSequence... parts) {
    return schedulerServiceBaseUrl + SCHEDULER_BASE_PATH + "/" + String.join("/", parts);
}

From source file:com.amazon.alexa.avs.http.AVSClient.java

private void createNewHttpClient() throws Exception {

    if ((httpClient != null) && httpClient.isStarted()) {
        try {/*  www  . j a v  a 2  s  .c om*/
            httpClient.stop();
        } catch (Exception e) {
            log.error("There was a problem stopping the HTTP client", e);
            throw e;
        }
    }

    // Sets up an HttpClient that sends HTTP/1.1 requests over an HTTP/2 transport
    httpClient = new HttpClient(new PingSendingHttpClientTransportOverHTTP2(http2Client, this),
            sslContextFactory);
    httpClient.addLifeCycleListener(new Listener() {

        @Override
        public void lifeCycleFailure(LifeCycle arg0, Throwable arg1) {
            log.error("HttpClient failed", arg1);
            StackTraceElement st[] = Thread.currentThread().getStackTrace();
            log.info(String.join(System.lineSeparator(), Arrays.toString(st)));
        }

        @Override
        public void lifeCycleStarted(LifeCycle arg0) {
            log.info("HttpClient started");
        }

        @Override
        public void lifeCycleStarting(LifeCycle arg0) {
            log.info("HttpClient starting");
        }

        @Override
        public void lifeCycleStopped(LifeCycle arg0) {
            log.info("HttpClient stopped");
        }

        @Override
        public void lifeCycleStopping(LifeCycle arg0) {
            log.info("HttpClient stopping");
            StackTraceElement st[] = Thread.currentThread().getStackTrace();
            log.info(String.join(System.lineSeparator(), Arrays.toString(st)));
        }

    });
    httpClient.start();

}

From source file:de.fosd.jdime.config.CommandLineConfigSource.java

/**
 * Builds the <code>Options</code> instance describing the JDime command line configuration options.
 *
 * @return the <code>Options</code> instance
 */// w w  w  .  ja  v  a2 s  .  co  m
private Options buildCliOptions() {
    Options options = new Options();
    Option o;

    o = Option.builder(CLI_LOG_LEVEL).longOpt("log-level").desc(
            "Set the logging level to one of (OFF, SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST, ALL).")
            .hasArg().argName("level").build();

    options.addOption(o);

    o = Option.builder(CLI_CONSECUTIVE).longOpt("consecutive")
            .desc("Requires diffonly mode. Treats versions as consecutive versions.").hasArg(false).build();

    options.addOption(o);

    o = Option.builder(CLI_DIFFONLY).longOpt("diffonly").desc("Only perform the diff stage.").hasArg(false)
            .build();

    options.addOption(o);

    o = Option.builder(CLI_FORCE_OVERWRITE).longOpt("force-overwrite")
            .desc("Force overwriting of output files.").hasArg(false).build();

    options.addOption(o);

    o = Option.builder(CLI_HELP).longOpt("help").desc("Print this message.").hasArg(false).build();

    options.addOption(o);

    o = Option.builder(CLI_KEEPGOING).longOpt("keep-going")
            .desc("Whether to skip a set of files if there is an exception merging them.").hasArg(false)
            .build();

    options.addOption(o);

    o = Option.builder(CLI_LOOKAHEAD).longOpt("lookahead").desc(
            "Use heuristics for matching. Supply 'off', 'full', or a non-negative integer as the argument.")
            .hasArg().argName("level").build();

    options.addOption(o);

    o = Option.builder(CLI_INSPECT_ELEMENT).longOpt("inspect-element")
            .desc("Inspect an AST element. Supply number of element.").hasArg().argName("element").build();

    options.addOption(o);

    o = Option.builder(CLI_INSPECT_METHOD).longOpt("inspect-method")
            .desc("Inspect the method of an AST element. Supply number of element.").hasArg().argName("element")
            .build();

    options.addOption(o);

    {
        String strategies = String.join(", ", MergeStrategy.listStrategies());

        o = Option.builder(CLI_MODE).longOpt("mode")
                .desc("Set the mode to one of (" + strategies + ") or a comma separated combination "
                        + "thereof. In the latter case the strategies will be executed in order until one "
                        + "does not produce conflicts.")
                .hasArg().argName("mode").build();

        options.addOption(o);
    }

    {
        String formats = Arrays.stream(DumpMode.values()).map(DumpMode::name).reduce("",
                (s, s2) -> s + " " + s2);

        o = Option.builder(CLI_DUMP).longOpt("dump")
                .desc("Dumps the inputs using one of the formats: " + formats).hasArg().argName("format")
                .build();

        options.addOption(o);
    }

    o = Option.builder(CLI_OUTPUT).longOpt("output").desc("Set the output directory/file.").hasArg()
            .argName("file").build();

    options.addOption(o);

    o = Option.builder(CLI_OPTIMIZE_MULTI_CONFLICTS).longOpt("optimize-multi-conflicts")
            .desc("Merge successive conflicts after running structured strategy.").hasArg(false).build();

    options.addOption(o);

    o = Option.builder(CLI_RECURSIVE).longOpt("recursive").desc("Merge directories recursively.").hasArg(false)
            .build();

    options.addOption(o);

    o = Option.builder(CLI_STATS).longOpt("stats").desc("Collect statistical data about the merge.")
            .hasArg(false).build();

    options.addOption(o);

    o = Option.builder(CLI_PRETEND).longOpt("pretend")
            .desc("Prints the merge result to stdout instead of an output file.").hasArg(false).build();

    options.addOption(o);

    o = Option.builder(CLI_QUIET).longOpt("quiet").desc("Do not print the merge result to stdout.")
            .hasArg(false).build();

    options.addOption(o);

    o = Option.builder(CLI_VERSION).longOpt("version").desc("Print the version information and exit.")
            .hasArg(false).build();

    options.addOption(o);

    o = Option.builder(CLI_PROP_FILE).longOpt("properties-file")
            .desc("Set the path to the properties file to use for additional configuration options.").hasArg()
            .argName("path").build();

    options.addOption(o);

    o = Option.builder(CLI_EXIT_ON_ERROR).longOpt("exit-on-error")
            .desc("Whether to end the merge if there is an exception merging a set of files. If neither this "
                    + "option nor keep-going is set the fallback line based strategy will be tried.")
            .hasArg(false).build();

    options.addOption(o);

    {
        String modes = Arrays.stream(CMMode.values()).map(CMMode::name).reduce("", (s, s2) -> s + " " + s2);

        o = Option.builder(CLI_CM).longOpt("cost-model-matcher")
                .desc("Sets the cost model matcher operation mode to one of " + modes).hasArg(true).build();

        options.addOption(o);
    }

    o = Option.builder(CLI_CM_REMATCH_BOUND).longOpt("cost-model-rematch-bound")
            .desc("If the cost model matcher operation mode is " + CMMode.INTEGRATED
                    + " the cost model matcher will "
                    + "be used to try and improve subtree matches with a percentage lower than this bound. "
                    + "Should be from (0, 1]. The default is 30%.")
            .hasArg(true).build();

    options.addOption(o);

    o = Option.builder(CLI_CM_OPTIONS).longOpt("cost-model-options")
            .desc("Accepts a comma separated list of parameters for the cost model matcher. The list must have "
                    + "the form: <int iterations>,<float pAssign>,<float wr>,<float wn>,<float wa>,<float ws>,<float wo>")
            .hasArg(true).build();

    options.addOption(o);

    o = Option.builder(CLI_CM_PARALLEL).longOpt("cost-model-parallel")
            .desc("Whether to speed up the cost model matcher by calculating the edge costs in parallel.")
            .hasArg(false).build();

    options.addOption(o);

    o = Option.builder(CLI_CM_FIX_PERCENTAGE).longOpt("cost-model-fix-percentage")
            .desc("Accepts a comma separated list of two percentages. <float fixLower>,<float fixUpper> both "
                    + "from the range [0, 1]. If these percentages are given, a random number (from the given range) "
                    + "of matchings from the previous iteration will be fixed for the next.")
            .hasArg(true).build();

    options.addOption(o);

    o = Option.builder(CLI_CM_SEED).longOpt("cost-model-seed")
            .desc("The seed for the PRNG used by the cost model matcher. If set to \"none\" a random seed will "
                    + "be used. Otherwise the default is 42.")
            .hasArg(true).build();

    options.addOption(o);

    return options;
}

From source file:com.wx3.galacdecks.Bootstrap.java

private void importDiscardValidators(GameDatastore datastore, String path) throws IOException {
    Files.walk(Paths.get(path)).forEach(filePath -> {
        if (Files.isRegularFile(filePath)) {
            try {
                if (FilenameUtils.getExtension(filePath.getFileName().toString()).toLowerCase().equals("js")) {
                    String id = FilenameUtils.removeExtension(filePath.getFileName().toString());
                    List<String> lines = Files.readAllLines(filePath);
                    if (lines.size() < 3) {
                        throw new RuntimeException(
                                "Script file should have at least 2 lines: description and code.");
                    }//from   ww w  .  j  a va  2  s.  c o  m
                    String description = lines.get(0).substring(2).trim();
                    String script = String.join("\n", lines);
                    ValidatorScript validator = ValidatorScript.createValidator(id, script, description);
                    discardValidatorCache.put(id, validator);
                    logger.info("Imported discard validator " + id);
                }
            } catch (Exception e) {
                throw new RuntimeException("Failed to parse " + filePath + ": " + e.getMessage());
            }
        }
    });
}

From source file:com.planet57.gshell.MainSupport.java

public void boot(final String... args) throws Exception {
    checkNotNull(args);// w  ww  . ja  va 2 s. c  om

    if (log.isDebugEnabled()) {
        log.debug("Booting w/args: {}", Arrays.toString(args));
    }

    // Register default handler for uncaught exceptions
    Thread.setDefaultUncaughtExceptionHandler(
            (thread, cause) -> log.warn("Unhandled exception occurred on thread: {}", thread, cause));

    // Prepare branding
    Branding branding = createBranding();

    // Process preferences
    PreferenceProcessor pp = new PreferenceProcessor();
    pp.setBasePath(branding.getPreferencesBasePath());
    pp.addBean(this);
    pp.process();

    // Process command line options & arguments
    CliProcessor clp = new CliProcessor();
    clp.addBean(this);
    clp.setStopAtNonOption(true);

    // cope with cli exceptions; which are expected
    try {
        clp.process(args);
    } catch (ParseException e) {
        e.printStackTrace(System.err);
        exit(2);
    }

    // once options are processed setup logging environment
    setupLogging(loggingLevel);

    // setup styling
    Styler.setSource(new MemoryStyleSource());

    // prepare terminal and I/O
    Terminal terminal = createTerminal(branding);
    IO io = StyledIO.create("shell", createStreamSet(terminal), terminal);

    if (help) {
        HelpPrinter printer = new HelpPrinter(clp, terminal.getWidth());
        printer.printUsage(io.out, branding.getProgramName());
        io.flush();
        exit(0);
    }

    if (version) {
        io.format("%s %s%n", branding.getDisplayName(), branding.getVersion());
        io.flush();
        exit(0);
    }

    // install thread-IO handler and attach streams
    threadIO.start();
    threadIO.setStreams(io.streams.in, io.streams.out, io.streams.err);

    Object result = null;
    try {
        variables.set(VariableNames.SHELL_ERRORS, showErrorTraces);

        Shell shell = createShell(io, variables, branding);
        shell.start();
        try {
            if (command != null) {
                result = shell.execute(command);
            } else if (appArgs != null) {
                result = shell.execute(String.join(" ", appArgs));
            } else {
                shell.run();
            }
        } finally {
            shell.stop();
        }
    } finally {
        io.flush();
        threadIO.stop();
        terminal.close();
    }

    if (result == null) {
        result = variables.get(VariableNames.LAST_RESULT);
    }

    exit(ExitCodeDecoder.decode(result));
}

From source file:com.netflix.spinnaker.halyard.cli.command.v1.NestableCommand.java

protected String translateFieldName(String fieldName) {
    if (fieldName == null || fieldName.isEmpty()) {
        throw new IllegalArgumentException("A field name must be supplied to translate.");
    }/*from  w  ww  .  j av  a 2 s  .  c o m*/

    int i = 0;
    char c = fieldName.charAt(i);
    while (c == '-') {
        i++;
        c = fieldName.charAt(i);
    }

    fieldName = fieldName.substring(i);
    String[] delimited = fieldName.split("-");

    if (delimited.length == 1) {
        return delimited[0];
    }

    for (i = 1; i < delimited.length; i++) {
        String token = delimited[i];
        if (token.length() == 0) {
            continue;
        }

        token = Character.toUpperCase(token.charAt(0)) + token.substring(1);
        delimited[i] = token;
    }

    return String.join("", delimited);
}

From source file:com.yahoo.parsec.filters.RequestResponeLoggingFilterTest.java

private String createLogStringPatternForError(String requestMethod, String url, String queryString,
        Map<String, Collection<String>> reqHeaders, String reqBodyJson, Object error)
        throws JsonProcessingException {

    Map<String, String> headers = reqHeaders.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, e -> String.join(",", e.getValue())));

    String reqHeaderString = _OBJECT_MAPPER.writeValueAsString(headers);
    String pattern = String.format(
            "{" + "\"time\":\"${json-unit.any-number}\"," + "\"request\": {" + "\"method\": \"%s\","
                    + "\"uri\": \"%s\"," + "\"query\": \"%s\"," + "\"headers\": %s," + "\"payload\": \"%s\""
                    + "}," + "\"response\": {}," + "\"response-error\": \"${json-unit.ignore}\", "
                    + "\"progress\": {" + "\"namelookup_time\": \"${json-unit.any-number}\","
                    + "\"connect_time\": \"${json-unit.any-number}\","
                    + "\"pretransfer_time\": \"${json-unit.any-number}\","
                    + "\"starttransfer_time\": \"${json-unit.any-number}\","
                    + "\"total_time\":\"${json-unit.any-number}\"" + "}" + "}",
            requestMethod, url, queryString, reqHeaderString, StringEscapeUtils.escapeJson(reqBodyJson));

    return pattern;

}

From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java

/**
 * Only works if we have path to GIT/*from   w w w .j a  va 2 s . com*/
 */
public List<CodeOwner> getBlameInfoExternal(int codeLinesSize, String repoName, String repoLocations,
        String fileName) {
    List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize);

    // -w is to ignore whitespace bug
    ProcessBuilder processBuilder = new ProcessBuilder(this.GIT_BINARY_PATH, "blame", "-c", "-w", fileName);
    // The / part is required due to centos bug for version 1.1.1
    processBuilder.directory(new File(repoLocations + "/" + repoName));

    Process process = null;
    BufferedReader bufferedReader = null;

    try {
        process = processBuilder.start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, Values.CHARSET_UTF8);
        bufferedReader = new BufferedReader(isr);
        String line;
        DateFormat df = new SimpleDateFormat("yyyy-mm-dd kk:mm:ss");

        HashMap<String, CodeOwner> owners = new HashMap<>();

        boolean foundSomething = false;

        while ((line = bufferedReader.readLine()) != null) {
            Singleton.getLogger().info("Blame line " + repoName + fileName + ": " + line);
            String[] split = line.split("\t");

            if (split.length > 2 && split[1].length() != 0) {
                foundSomething = true;
                String author = split[1].substring(1);
                int commitTime = (int) (System.currentTimeMillis() / 1000);
                try {
                    commitTime = (int) (df.parse(split[2]).getTime() / 1000);
                } catch (ParseException ex) {
                    Singleton.getLogger().info("time parse expection for " + repoName + fileName);
                }

                if (owners.containsKey(author)) {
                    CodeOwner codeOwner = owners.get(author);
                    codeOwner.incrementLines();

                    int timestamp = codeOwner.getMostRecentUnixCommitTimestamp();

                    if (commitTime > timestamp) {
                        codeOwner.setMostRecentUnixCommitTimestamp(commitTime);
                    }
                    owners.put(author, codeOwner);
                } else {
                    owners.put(author, new CodeOwner(author, 1, commitTime));
                }
            }
        }

        if (foundSomething == false) {
            // External call for CentOS issue
            String[] split = fileName.split("/");

            if (split.length != 1) {
                codeOwners = getBlameInfoExternal(codeLinesSize, repoName, repoLocations,
                        String.join("/", Arrays.asList(split).subList(1, split.length)));
            }

        } else {
            codeOwners = new ArrayList<>(owners.values());
        }

    } catch (IOException | StringIndexOutOfBoundsException ex) {
        Singleton.getLogger().info("getBlameInfoExternal repoloc: " + repoLocations + "/" + repoName);
        Singleton.getLogger().info("getBlameInfoExternal fileName: " + fileName);
        Singleton.getLogger()
                .warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                        + " getBlameInfoExternal for " + repoName + " " + fileName + "\n with message: "
                        + ex.getMessage());
    } finally {
        Singleton.getHelpers().closeQuietly(process);
        Singleton.getHelpers().closeQuietly(bufferedReader);
    }

    return codeOwners;
}