Example usage for java.util StringJoiner toString

List of usage examples for java.util StringJoiner toString

Introduction

In this page you can find the example usage for java.util StringJoiner toString.

Prototype

@Override
public String toString() 

Source Link

Document

Returns the current value, consisting of the prefix , the values added so far separated by the delimiter , and the suffix , unless no elements have been added in which case, the prefix + suffix or the emptyValue characters are returned.

Usage

From source file:org.polymap.p4.data.importer.prompts.CharsetPrompt.java

private String displayName(Charset charset) {
    StringBuffer name = new StringBuffer(charset.displayName(Polymap.getSessionLocale()));
    if (!charset.aliases().isEmpty()) {
        name.append(" ( ");
        StringJoiner joiner = new StringJoiner(", ");
        for (String alias : charset.aliases()) {
            joiner.add(alias);//from  www.  j  a v  a 2  s .c o m
        }
        name.append(joiner.toString());
        name.append(" )");
    }
    return name.toString();
}

From source file:com.teradata.benchto.driver.execution.QueryExecutionDriver.java

private void logRow(int rowNumber, ResultSet resultSet) throws SQLException {
    ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
    StringJoiner joiner = new StringJoiner("; ", "[", "]");
    for (int i = 1; i <= resultSetMetaData.getColumnCount(); ++i) {
        joiner.add(resultSetMetaData.getColumnName(i) + ": " + resultSet.getObject(i));
    }//from  w  w  w  . j av  a2 s . com

    LOG.info("Row: " + rowNumber + ", column values: " + joiner.toString());
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.StatsTest.java

@Test
public void itGetsApplicationStats() throws Exception {
    HttpGet httpGet = new HttpGet("http://localhost:3333/crs/stats");

    CloseableHttpResponse httpResponse = null;

    try {//from   w  ww . j av a 2 s .  c om

        httpResponse = httpClient.execute(httpGet);
        String responseContent = EntityUtils.toString(httpResponse.getEntity());

        ObjectMapper objectMapper = new ObjectMapper();

        Map<String, Object> data = objectMapper.readValue(responseContent,
                new TypeReference<HashMap<String, Object>>() {
                });

        assertThat(data.keySet(), containsInAnyOrder("app", "stats"));

        Map<String, Object> appData = (Map<String, Object>) data.get("app");
        assertThat(appData.keySet(),
                containsInAnyOrder("buildTimestamp", "name", "deploy-dir", "git-revision", "version"));

        Map<String, Object> statsData = (Map<String, Object>) data.get("stats");
        assertThat(statsData.keySet(),
                containsInAnyOrder("dnsMap", "httpMap", "totalDnsCount", "totalHttpCount", "totalDsMissCount",
                        "appStartTime", "averageDnsTime", "averageHttpTime", "updateTracker"));

        Map<String, Object> dnsStats = (Map<String, Object>) statsData.get("dnsMap");
        Map<String, Object> cacheDnsStats = (Map<String, Object>) dnsStats.values().iterator().next();
        assertThat(cacheDnsStats.keySet(),
                containsInAnyOrder("czCount", "geoCount", "missCount", "dsrCount", "errCount", "deepCzCount",
                        "staticRouteCount", "fedCount", "regionalDeniedCount", "regionalAlternateCount"));

        Map<String, Object> httpStats = (Map<String, Object>) statsData.get("httpMap");
        Map<String, Object> cacheHttpStats = (Map<String, Object>) httpStats.values().iterator().next();
        assertThat(cacheHttpStats.keySet(),
                containsInAnyOrder("czCount", "geoCount", "missCount", "dsrCount", "errCount", "deepCzCount",
                        "staticRouteCount", "fedCount", "regionalDeniedCount", "regionalAlternateCount"));

        Map<String, Object> updateTracker = (Map<String, Object>) statsData.get("updateTracker");
        Set<String> keys = updateTracker.keySet();
        List<String> expectedStats = Arrays.asList("lastCacheStateCheck", "lastCacheStateChange",
                "lastConfigCheck", "lastConfigChange");

        if (!keys.containsAll(expectedStats)) {

            StringJoiner joiner = new StringJoiner(",");
            for (String stat : expectedStats) {
                joiner.add(stat);
            }

            fail("Missing at least one of the following keys '" + joiner.toString() + "'");
        }

    } finally {
        if (httpResponse != null)
            httpResponse.close();
    }
}

From source file:edu.emory.mathcs.nlp.zzz.CSVRadiology.java

public void categorize(String inputFile) throws Exception {
    CSVParser parser = new CSVParser(IOUtils.createBufferedReader(inputFile), CSVFormat.DEFAULT);
    List<CSVRecord> records = parser.getRecords();
    StringJoiner join;
    CSVRecord record;//from w ww . j  a  v  a 2 s  .  c o  m

    for (int i = 0; i <= 500; i++) {
        if (i == 0)
            continue;
        record = records.get(i);
        join = new StringJoiner(" ");

        for (int j = 2; j < 7; j++)
            join.add(record.get(j));

        System.out.println(join.toString());
    }

    parser.close();
}

From source file:org.jhk.pulsing.sandbox.timeline.cli.CommandCli.java

private void processCommandLine(String command) {
    try {//  ww w .j  av  a2  s.  c o m
        // only support 3 args max
        String[] split = command.split(" ");
        if (split.length > 2) {
            // hacky for now...
            String[] temp = new String[3];
            temp[0] = split[0];
            temp[1] = split[1];

            StringJoiner joiner = new StringJoiner(" ");
            for (int loop = 2; loop < split.length; loop++) {
                joiner.add(split[loop]); // seriously why doesn't StringJoiner accept a List or Array...
            }
            temp[2] = joiner.toString();
            split = temp;
        }
        CommandLine commandLine = cliParser.parse(cliOptions, split);
        if (commandLine.hasOption("help")) {
            cliFormatter.printHelp("timeline", cliOptions);
        } else if (commandLine.hasOption("getTimeline")) {
            long timeLineId = Long.valueOf(commandLine.getOptionValue("getTimeline"));
            Optional<List<String>> tweets = timeLine.getTweets(timeLineId);

            if (tweets.isPresent()) {
                LOGGER.info("Tweets => {}", tweets.get());
            } else {
                LOGGER.info("Unable to retrieve tweets with id => {}", timeLineId);
            }

        } else if (commandLine.hasOption("tweet")) {
            String tweet = commandLine.getOptionValue("tweet");
            queue.publish(tweet);
        } else if (commandLine.hasOption("getUser")) {
            long userId = Long.valueOf(commandLine.getOptionValue("getUser"));
            Optional<User> user = userCache.getUser(userId);

            if (user.isPresent()) {
                LOGGER.info("Retrieved user => {}", user.get());
            } else {
                LOGGER.info("Unable to retrieve user with id => {}", userId);
            }
        } else if (commandLine.hasOption("getFollowers")) {
            long userId = Long.valueOf(commandLine.getOptionValue("getFollowers"));
            String userScreeNames = userCache.getFollowers(userId).stream().map(user -> user.getScreenName())
                    .collect(Collectors.joining(","));

            LOGGER.info("Retrieved followers => {}", userScreeNames);
        }

    } catch (Exception exp) {
        LOGGER.error(exp.getMessage(), exp);
    }
}

From source file:info.archinnov.achilles.internals.codegen.meta.UDTMetaCodeGen.java

private MethodSpec buildComponentsProperty(TypeName rawBeanType, List<FieldMetaSignature> parsingResults) {
    TypeName returnType = genericType(LIST, genericType(ABSTRACT_PROPERTY, rawBeanType, WILDCARD, WILDCARD));
    final StringJoiner allFields = new StringJoiner(", ");
    parsingResults.stream().map(x -> x.context.fieldName).forEach(x -> allFields.add(x));

    StringBuilder fieldList = new StringBuilder();
    fieldList.append("return $T.asList(").append(allFields.toString()).append(")");

    return MethodSpec.methodBuilder("getComponentsProperty").addAnnotation(Override.class)
            .addModifiers(Modifier.PROTECTED).returns(returnType).addStatement(fieldList.toString(), ARRAYS)
            .build();//from ww  w .  ja  v  a2s. c  om

}

From source file:info.archinnov.achilles.internals.statements.StatementWrapper.java

default void appendRowDataToBuilder(Row row, List<ColumnDefinitions.Definition> columnsDef,
        StringBuilder builder) {/*from ww  w  .  ja  v a 2  s .com*/
    StringJoiner joiner = new StringJoiner(", ", "\t", "\n");
    IntStream.range(0, columnsDef.size()).forEach(index -> {
        final ColumnDefinitions.Definition def = columnsDef.get(index);
        final Object value = extractValueFromRow(row, index, def.getType());
        joiner.add(format("%s: %s", def.getName(), value));
    });
    builder.append(joiner.toString());
}

From source file:info.archinnov.achilles.internals.metamodel.AbstractEntityProperty.java

public String generateSchema(SchemaContext context) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(format("Generating DDL script for entity of type %s", entityClass.getCanonicalName()));
    }//from   w w  w . ja  va2 s. com
    StringJoiner joiner = new StringJoiner("\n\n");
    SchemaCreator.generateTable_And_Indices(context, this).forEach(joiner::add);
    return joiner.toString();
}

From source file:info.archinnov.achilles.internals.parser.FieldInfoParser.java

protected Tuple2<CodeBlock, ColumnInfo> buildColumnInfo(AnnotationTree annotationTree, VariableElement elm,
        String fieldName, TypeName rawEntityClass) {
    final CodeBlock.Builder builder = CodeBlock.builder();
    final boolean isFrozen = containsAnnotation(annotationTree, Frozen.class);
    final Optional<TypedMap> partitionKey = extractTypedMap(annotationTree, PartitionKey.class);
    final Optional<TypedMap> clusteringColumn = extractTypedMap(annotationTree, ClusteringColumn.class);
    final Optional<TypedMap> computed = extractTypedMap(annotationTree, Computed.class);

    validateAllowedFrozen(isFrozen, aptUtils, elm, fieldName, rawEntityClass);

    if (partitionKey.isPresent()) {
        final int order = partitionKey.get().getTyped("order");
        aptUtils.validateTrue(order > 0,
                "@PartitionKey order on field '%s' of class '%s' should be > 0, the ordering starts at 1",
                fieldName, rawEntityClass);
        builder.add("new $T($L, $L)", PARTITION_KEY_INFO, order, isFrozen);
        return Tuple2.of(builder.build(), new PartitionKeyInfo(order, isFrozen));

    } else if (clusteringColumn.isPresent()) {
        final int order = clusteringColumn.get().getTyped("order");
        final ClusteringOrder clusteringOrder = clusteringColumn.get().<Boolean>getTyped("asc") ? ASC : DESC;
        aptUtils.validateTrue(order > 0,
                "@ClusteringColumn order on field '%s' of class '%s' should be > 0, the ordering starts at 1",
                fieldName, rawEntityClass);
        builder.add("new $T($L, $L, $T.$L)", CLUSTERING_COLUMN_INFO, order, isFrozen, CLUSTERING_ORDER,
                clusteringOrder.name());
        return Tuple2.of(builder.build(), new ClusteringColumnInfo(order, isFrozen, clusteringOrder));

    } else if (computed.isPresent()) {
        final TypedMap typedMap = computed.get();
        final String function = typedMap.getTyped("function");
        final String alias = typedMap.getTyped("alias");
        final List<String> targetColumns = typedMap.getTyped("targetColumns");
        final Class<?> cqlClass = typedMap.getTyped("cqlClass");
        final ClassName className = ClassName.get(cqlClass);
        final StringJoiner joiner = new StringJoiner(",");

        for (String x : targetColumns) {
            joiner.add("\"" + x + "\"");
        }/*from w  w w.  j  a  v  a  2s  .c om*/

        builder.add("new $T($S, $S, $T.asList(new String[]{$L}), $T.class)", COMPUTED_COLUMN_INFO, function,
                alias, ARRAYS, joiner.toString(), className);
        return Tuple2.of(builder.build(), new ComputedColumnInfo(function, alias, targetColumns, cqlClass));

    } else {
        builder.add("new $T($L)", COLUMN_INFO, isFrozen);
        return Tuple2.of(builder.build(), new ColumnInfo(isFrozen));
    }
}

From source file:org.springframework.cloud.gcp.data.spanner.core.SpannerTemplate.java

private StringBuilder logColumns(String tableName, KeySet keys, Iterable<String> columns) {
    StringBuilder logSb = new StringBuilder(
            "Executing read on table " + tableName + " with keys: " + keys + " and columns: ");
    StringJoiner sj = new StringJoiner(",");
    columns.forEach((col) -> sj.add(col));
    logSb.append(sj.toString());
    return logSb;
}