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:io.github.felsenhower.stine_calendar_bot.main.CallLevelWrapper.java

public CallLevelWrapper(String[] args) throws IOException {
    String username = null;//w  ww .java 2  s .c  o  m
    String password = null;
    boolean echoPages = false;
    Path calendarCache = null;
    Path outputFile = null;
    boolean echoCalendar = false;

    // These temporary options don't have descriptions and have their
    // required-value all set to false
    final Options tempOptions = getOptions();

    final CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    StringProvider strings = null;

    // Get the StringProvider
    try {
        cmd = parser.parse(tempOptions, args, true);
        if (cmd.hasOption("language")) {
            String lang = cmd.getOptionValue("language").toLowerCase();
            if (lang.equals("de")) {
                strings = new StringProvider(Locale.GERMAN);
            } else {
                strings = new StringProvider(Locale.ENGLISH);
                if (!lang.equals("en")) {
                    System.err.println(strings.get("HumanReadable.CallLevel.LangNotRecognised", lang));
                }
            }
        } else {
            strings = new StringProvider(new Locale(Locale.getDefault().getLanguage()));
        }
    } catch (Exception e) {
        strings = new StringProvider(Locale.ENGLISH);
    }

    this.strings = strings;
    this.cliStrings = strings.from("HumanReadable.CallLevel");
    this.messages = strings.from("HumanReadable.Messages");
    this.appInfo = strings.from("MachineReadable.App");

    // Get the localised options, with all required fields enabled as well.
    // Note that we are not yet applying the options to any command line,
    // because we still want to exit if only the help screen shall be
    // displayed first, but of course, we do need the localised options
    // here.
    this.isLangInitialised = true;
    this.options = getOptions();

    try {
        // If no arguments are supplied, or --help is used, we will exit
        // after printing the help screen
        if (cmd.hasOption("help") || (cmd.hasOption("language") && cmd.getOptions().length == 1)) {
            printHelp();
        }

        cmd = parser.parse(this.options, args, false);

        username = cmd.getOptionValue("user");

        // URL-decode the password (STiNE doesn't actually allow special
        // chars in passwords, but meh...)
        password = URLDecoder.decode(cmd.getOptionValue("pass"), "UTF-8");
        // Double-dash signals that the password shall be read from stdin
        if (password.equals("--")) {
            password = readPassword(messages.get("PasswordQuery"), messages.get("PasswordFallbackMsg"));
        }

        echoPages = cmd.hasOption("echo");

        // the cache-dir argument is optional, so we read it with a default
        // value
        calendarCache = Paths
                .get(cmd.getOptionValue("cache-dir", strings.get("MachineReadable.Paths.CalendarCache")))
                .toAbsolutePath();

        // output-argument is optional as well, but this time we check if
        // double-dash is specified (for echo to stdout)
        String outputStr = cmd.getOptionValue("output", strings.get("MachineReadable.Paths.OutputFile"));
        if (outputStr.equals("--")) {
            echoCalendar = true;
            outputFile = null;
        } else {
            echoCalendar = false;
            outputFile = Paths.get(outputStr).toAbsolutePath();
        }

    } catch (UnrecognizedOptionException e) {
        System.err.println(messages.get("UnrecognisedOption", e.getOption().toString()));
        this.printHelp();
    } catch (MissingOptionException e) {
        // e.getMissingOptions() is just extremely horribly designed and
        // here is why:
        //
        // It returns an unparametrised list, to make your job especially
        // hard, whose elements may be:
        // - String-instances, if there are single independent options
        // missing (NOT the stupid Option itself, just why????)
        // - OptionGroup-instances, if there are whole OptionGroups missing
        // (This time the actual OptionGroup and not an unparametrised Set
        // that may or may not contain an Option, how inconsequential).
        // - Basically anything because the programmer who wrote that
        // function was clearly high and is most probably not to be trusted.
        //
        // This makes the job of actually displaying all the options as a
        // comma-separated list unnecessarily hard and hence leads to this
        // ugly contraption of Java-8-statements. But hey, at least it's not
        // as ugly as the Java 7 version (for me at least).
        // Sorry!
        // TODO: Write better code.
        // TODO: Write my own command line interpreter, with blackjack and
        // hookers.
        try {
            System.err.println(messages.get("MissingRequiredOption", ((List<?>) (e.getMissingOptions()))
                    .stream().filter(Object.class::isInstance).map(Object.class::cast).map(o -> {
                        if (o instanceof String) {
                            return Collections.singletonList(options.getOption((String) o));
                        } else {
                            return ((OptionGroup) o).getOptions();
                        }
                    }).flatMap(o -> o.stream()).filter(Option.class::isInstance).map(Option.class::cast)
                    .map(o -> o.getLongOpt()).collect(Collectors.joining(", "))));
            this.printHelp();
        } catch (Exception totallyMoronicException) {
            throw new RuntimeException("I hate 3rd party libraries!", totallyMoronicException);
        }
    } catch (MissingArgumentException e) {
        System.err.println(messages.get("MissingRequiredArgument", e.getOption().getLongOpt()));
        this.printHelp();
    } catch (ParseException e) {
        System.err.println(messages.get("CallLevelParsingException", e.getMessage()));
    }

    this.username = username;
    this.password = password;
    this.echoPages = echoPages;
    this.calendarCache = calendarCache;
    this.outputFile = outputFile;
    this.echoCalendar = echoCalendar;
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.TestIkanowV1SyncService_LibraryJars.java

public static JsonNode getLibraryMetadata(Object resource, List<String> desc) throws Exception {
    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());
    final JsonNode v1_bean = ((ObjectNode) mapper
            .readTree(resource.getClass().getResourceAsStream("test_v1_sync_sample_share.json")))
                    .put("description", desc.stream().collect(Collectors.joining("\n")));

    return v1_bean;
}

From source file:com.ikanow.aleph2.graph.titan.services.TestTitanGraphService.java

@Test
public void test_onPublishOrUpdate() {

    final DataBucketBean bucket = BeanTemplateUtils.build(DataBucketBean.class)
            .with(DataBucketBean::full_name, "/test/validate/schema").done().get();

    // do nothing
    {//from ww  w .ja v  a2  s  .  co m
        CompletableFuture<Collection<BasicMessageBean>> ret_val = _mock_graph_db_service.onPublishOrUpdate(
                bucket, Optional.empty(), false, Collections.emptySet(), Collections.emptySet());

        assertEquals(Collections.emptyList(), ret_val.join());
    }
    // create all the indexes
    {
        CompletableFuture<Collection<BasicMessageBean>> ret_val = _mock_graph_db_service.onPublishOrUpdate(
                bucket, Optional.empty(), false, ImmutableSet.of(GraphSchemaBean.name), Collections.emptySet());

        assertEquals("" + ret_val.join().stream().map(b -> b.message()).collect(Collectors.joining(" // ")),
                Collections.emptyList(), ret_val.join());

        // But also now check the Titan indexes have all been created:

        final TitanManagement mgmt = _titan.openManagement();
        Stream<TitanGraphIndex> v_indexes = StreamUtils.stream(mgmt.getGraphIndexes(Vertex.class));
        Stream<TitanGraphIndex> e_indexes = StreamUtils.stream(mgmt.getGraphIndexes(Edge.class));
        assertEquals(4L, v_indexes.count());
        assertEquals(1L, e_indexes.count());
    }
    // rerun to check it all works second+ time round
    {
        CompletableFuture<Collection<BasicMessageBean>> ret_val = _mock_graph_db_service.onPublishOrUpdate(
                bucket, Optional.empty(), false, ImmutableSet.of(GraphSchemaBean.name), Collections.emptySet());

        assertEquals(
                "Should return no errors: "
                        + ret_val.join().stream().map(b -> b.message()).collect(Collectors.joining(";")),
                Collections.emptyList(), ret_val.join());

        // But also now check the Titan indexes have all been created:

        final TitanManagement mgmt = _titan.openManagement();
        Stream<TitanGraphIndex> v_indexes = StreamUtils.stream(mgmt.getGraphIndexes(Vertex.class));
        Stream<TitanGraphIndex> e_indexes = StreamUtils.stream(mgmt.getGraphIndexes(Edge.class));
        assertEquals(4L, v_indexes.count());
        assertEquals(1L, e_indexes.count());
    }
    // Error if specifying deduplication fields
    {
        final GraphSchemaBean graph_schema = BeanTemplateUtils.build(GraphSchemaBean.class)
                .with(GraphSchemaBean::custom_decomposition_configs, Arrays.asList())
                .with(GraphSchemaBean::deduplication_fields, Arrays.asList("nonempty")).done().get();

        final DataBucketBean dedup_fields_bucket = BeanTemplateUtils.build(DataBucketBean.class)
                .with(DataBucketBean::full_name, "/test/on/publish")
                .with(DataBucketBean::data_schema, BeanTemplateUtils.build(DataSchemaBean.class)
                        .with(DataSchemaBean::graph_schema, graph_schema).done().get())
                .done().get();

        CompletableFuture<Collection<BasicMessageBean>> ret_val = _mock_graph_db_service.onPublishOrUpdate(
                dedup_fields_bucket, Optional.empty(), false, ImmutableSet.of(GraphSchemaBean.name),
                Collections.emptySet());

        assertEquals(1, ret_val.join().size());
        assertEquals(1, ret_val.join().stream().filter(b -> !b.success()).count());
    }

    //(See also test_handleBucketDeletionRequest, for some coverage testing of onPublishOrUpdate)
}

From source file:de.themoep.simpleteampvp.TeamInfo.java

public boolean setColor(String colorStr) {
    if (colorStr.isEmpty())
        return false;
    try {//  w ww  . j a  va  2  s .  co  m
        color = ChatColor.valueOf(colorStr.toUpperCase());
    } catch (IllegalArgumentException e) {
        if (colorStr.length() == 1) {
            color = ChatColor.getByChar(colorStr.toLowerCase().charAt(0));
        } else if (colorStr.length() == 2 && (colorStr.charAt(0) == ChatColor.COLOR_CHAR
                || colorStr.charAt(0) == '&' || colorStr.charAt(0) == '#')) {
            color = ChatColor.getByChar(colorStr.toLowerCase().charAt(1));
        }
    }
    if (color == null) {
        List<String> colorList = new ArrayList<>();
        for (ChatColor color : ChatColor.values()) {
            colorList.add(color.name());
        }
        Bukkit.getLogger().log(Level.WARNING,
                "[SimpleTeamPvP] " + colorStr + " is not a valid color name! (Available are "
                        + colorList.stream().collect(Collectors.joining(", ")) + ")");
        return false;
    }
    if (scoreboardTeam != null) {
        scoreboardTeam.setPrefix("" + color);
        scoreboardTeam.setSuffix("" + ChatColor.RESET);
    }
    return true;

}

From source file:org.hawkular.apm.client.api.rest.AbstractRESTClient.java

public String getResponse(HttpURLConnection connection) throws IOException {
    InputStream is = connection.getInputStream();
    String response;//from  w w  w  .jav  a 2s  .c o m
    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(is))) {
        response = buffer.lines().collect(Collectors.joining("\n"));
    }
    return response;
}

From source file:ca.polymtl.dorsal.libdelorean.statedump.Statedump.java

/**
 * Retrieve a previously-saved statedump.
 *
 * @param parentPath//from ww  w .j ava 2 s . co  m
 *            The expected location of the statedump file. Like the
 *            corresponding parameter in {@link #dumpState}, this is the
 *            parent path of the TC-specific subdirectory.
 * @param ssid
 *            The ID of the state system to retrieve
 * @return The corresponding de-serialized statedump. Returns null if there
 *         are no statedump for this state system ID (or no statedump
 *         directory at all).
 */
public static @Nullable Statedump loadState(Path parentPath, String ssid) {
    /* Find the state dump directory */
    Path sdPath = parentPath.resolve(STATEDUMP_DIRECTORY);
    if (!Files.isDirectory(sdPath)) {
        return null;
    }

    /* Find the state dump file */
    String fileName = ssid + FILE_SUFFIX;
    Path filePath = sdPath.resolve(fileName);
    if (!Files.exists(filePath)) {
        return null;
    }

    try (InputStreamReader in = new InputStreamReader(
            Files.newInputStream(filePath, StandardOpenOption.READ))) {
        BufferedReader bufReader = new BufferedReader(in);
        String json = bufReader.lines().collect(Collectors.joining("\n")); //$NON-NLS-1$
        JSONObject root = new JSONObject(json);

        return Serialization.stateDumpFromJsonObject(root, ssid);
    } catch (IOException | JSONException e) {
        return null;
    }
}

From source file:es.uvigo.ei.sing.adops.datatypes.Project.java

public void addSequences(File fastaFile) throws IllegalArgumentException {
    try {//from  w ww. j a va 2 s.c  o m
        final int numSequences = this.listSequenceNames().size();

        writeSequences(this.originalFastaFile, loadAndCheckSequences(fastaFile), true);

        this.createNamesFile();

        final String inputSequences = IntStream.rangeClosed(1, numSequences).mapToObj(Integer::toString)
                .collect(Collectors.joining(" "));

        for (ProjectExperiment experiment : this.getExperiments()) {
            final Configuration configuration = experiment.getConfiguration();

            if (configuration.getInputSequences().isEmpty()) {
                configuration.setInputSequences(inputSequences);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalArgumentException(
                String.format("File %s is not a valid Fasta file", fastaFile.getAbsolutePath()), e);
    }

}

From source file:majordodo.client.http.HTTPClientConnection.java

private Map<String, Object> request(String method, Map<String, Object> data) throws ClientException {

    try {//w w  w .  ja  v  a  2 s.co m
        final int MAX_RETRIES = this.configuration.getBrokerNotAvailableRetries();
        for (int i = 0; i < MAX_RETRIES; i++) {
            try {
                String s = MAPPER.writeValueAsString(data);
                byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
                Map<String, Object> rr;
                if (method.equals("POST")) {
                    rr = post("application/json;charset=utf-8", bytes);
                } else if (method.equals("GET")) {
                    String path = data.entrySet().stream().map((entry) -> {
                        try {
                            return entry.getKey() + "="
                                    + URLEncoder.encode(entry.getValue().toString(), "utf-8");
                        } catch (UnsupportedEncodingException err) {
                            return "";
                        }
                    }).collect(Collectors.joining("&"));
                    rr = get("?" + path);
                } else {
                    throw new IllegalStateException(method);
                }
                if (!"true".equals(rr.get("ok") + "")) {
                    LOGGER.log(Level.SEVERE, "error from {0}: {1}", new Object[] { _broker, rr });
                    brokerFailed();
                    String error = rr.get("error") + "";
                    if (error.contains("broker_not_started") // broker does not exist on JVM
                            || error.contains("recovery_in_progress") // broker is in recovery mode, maybe it would become leader
                            || error.contains("broker_not_leader")) // broker is not leader
                    {
                        throw new RetryableError(rr + "");
                    } else {
                        throw new IOException("error from broker: " + rr);
                    }

                }
                return rr;
            } catch (RetryableError retry) {
                int interval = this.configuration.getBrokerNotAvailableRetryInterval() * (i + 1);
                LOGGER.log(Level.SEVERE, "retry on #{0}error from {1}: {2}: sleep {3} ms",
                        new Object[] { i + 1, _broker, retry, interval });
                Thread.sleep(interval);
            }
        }
        throw new IOException("could not issue request after " + MAX_RETRIES + " trials");
    } catch (InterruptedException err) {
        Thread.currentThread().interrupt();
        brokerFailed();
        throw new ClientException(err);
    } catch (Exception err) {
        brokerFailed();
        throw new ClientException(err);
    }
}

From source file:com.diversityarrays.kdxplore.ttools.shared.PlotTableModel.java

@Override
public Object getValueAt(int rowIndex, int columnIndex) {

    Plot plot = plots.get(rowIndex);/*from w w  w  .  jav  a 2  s. com*/

    if (!plot.isActivated()) {
        return null;
    }

    int index = columnIndex;
    if (showSelectedColumn) {
        if (index == 0) {
            return harvestedPlots.contains(plot);
        }
        index = index - 1;
    }

    if (index < plotIdentifiers.size()) {
        return plotIdentifiers.get(index).getDisplayValue(plot);
    }

    index = index - plotIdentifiers.size();

    if (plotAttributeProvider != null && index < PLANTED_SPECIMENS_COLUMNS.length) {
        return plotAttributeProvider.getPlotAttributeValue(plot, PLANTED_SPECIMENS_COLUMNS[index]);
    }
    if (this.needNewSpecimensColumn) {

        List<DalSpecimen> specimens = new ArrayList<>();
        if (trialDesignEditorMode) {
            specimens = editedSpecimenByplot.get(plot);
        } else if (specimens == null || specimens.isEmpty()) {
            if (plotToSpecimens != null) {
                specimens = plotToSpecimens.get(plot);
            }
        }

        String specimenNames = specimens.stream().map(DalSpecimen::getSpecimenName)
                .collect(Collectors.joining(", "));
        return specimenNames;
    }
    return null;

}

From source file:com.jaredjstewart.SampleSecurityManager.java

private Map<String, Role> readRoles(final JsonNode jsonNode) {
    if (jsonNode.get("roles") == null) {
        return Collections.EMPTY_MAP;
    }//from  w  ww .  j  av  a  2  s. c  o m
    Map<String, Role> roleMap = new HashMap<>();
    for (JsonNode rolesNode : jsonNode.get("roles")) {
        Role role = new Role();
        role.name = rolesNode.get("name").asText();
        String regionNames = null;
        String keys = null;

        JsonNode regionsNode = rolesNode.get("regions");
        if (regionsNode != null) {
            if (regionsNode.isArray()) {
                regionNames = StreamSupport.stream(regionsNode.spliterator(), false).map(JsonNode::asText)
                        .collect(Collectors.joining(","));
            } else {
                regionNames = regionsNode.asText();
            }
        }

        for (JsonNode operationsAllowedNode : rolesNode.get("operationsAllowed")) {
            String[] parts = operationsAllowedNode.asText().split(":");
            String resourcePart = (parts.length > 0) ? parts[0] : null;
            String operationPart = (parts.length > 1) ? parts[1] : null;

            if (parts.length > 2) {
                regionNames = parts[2];
            }
            if (parts.length > 3) {
                keys = parts[3];
            }

            String regionPart = (regionNames != null) ? regionNames : "*";
            String keyPart = (keys != null) ? keys : "*";

            role.permissions.add(new ResourcePermission(resourcePart, operationPart, regionPart, keyPart));
        }

        roleMap.put(role.name, role);

        if (rolesNode.has("serverGroup")) {
            role.serverGroup = rolesNode.get("serverGroup").asText();
        }
    }

    return roleMap;
}