Example usage for java.util StringJoiner StringJoiner

List of usage examples for java.util StringJoiner StringJoiner

Introduction

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

Prototype

public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix) 

Source Link

Document

Constructs a StringJoiner with no characters in it using copies of the supplied prefix , delimiter and suffix .

Usage

From source file:net.sf.jabref.sql.importer.DatabaseImporter.java

/**
 * Worker method to perform the import from a database
 *
 * @param dbs  The necessary database connection information
 * @param mode// w  w w . j a v a  2  s. c o m
 * @return An ArrayList containing pairs of Objects. Each position of the ArrayList stores three Objects: a
 * BibDatabase, a MetaData and a String with the bib database name stored in the DBMS
 * @throws SQLException
 * @throws ClassNotFoundException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws Exception
 */
public List<DBImporterResult> performImport(DBStrings dbs, List<String> listOfDBs, BibDatabaseMode mode)
        throws IllegalAccessException, InstantiationException, ClassNotFoundException, SQLException {
    List<DBImporterResult> result = new ArrayList<>();
    try (Connection conn = this.connectToDB(dbs)) {

        Iterator<String> itLista = listOfDBs.iterator();
        StringJoiner stringJoiner = new StringJoiner(",", "(", ")");

        while (itLista.hasNext()) {
            stringJoiner.add("'" + itLista.next() + "'");
        }

        String query = SQLUtil
                .queryAllFromTable("jabref_database WHERE database_name IN " + stringJoiner.toString());
        try (Statement statement = conn.createStatement();
                ResultSet rsDatabase = statement.executeQuery(query)) {
            while (rsDatabase.next()) {
                BibDatabase database = new BibDatabase();
                // Find entry type IDs and their mappings to type names:
                HashMap<String, EntryType> types = new HashMap<>();
                try (Statement entryTypes = conn.createStatement();
                        ResultSet rsEntryType = entryTypes
                                .executeQuery(SQLUtil.queryAllFromTable("entry_types"))) {
                    while (rsEntryType.next()) {
                        Optional<EntryType> entryType = EntryTypes.getType(rsEntryType.getString("label"),
                                mode);
                        if (entryType.isPresent()) {
                            types.put(rsEntryType.getString("entry_types_id"), entryType.get());
                        }
                    }
                }

                List<String> colNames = this.readColumnNames(conn).stream()
                        .filter(column -> !COLUMNS_NOT_CONSIDERED_FOR_ENTRIES.contains(column))
                        .collect(Collectors.toList());

                final String database_id = rsDatabase.getString("database_id");
                // Read the entries and create BibEntry instances:
                HashMap<String, BibEntry> entries = new HashMap<>();
                try (Statement entryStatement = conn.createStatement();
                        ResultSet rsEntries = entryStatement.executeQuery(SQLUtil
                                .queryAllFromTable("entries WHERE database_id= '" + database_id + "';"))) {
                    while (rsEntries.next()) {
                        String id = rsEntries.getString("entries_id");
                        BibEntry entry = new BibEntry(IdGenerator.next(),
                                types.get(rsEntries.getString("entry_types_id")).getName());
                        entry.setCiteKey(rsEntries.getString("cite_key"));
                        for (String col : colNames) {
                            String value = rsEntries.getString(col);
                            if (value != null) {
                                col = col.charAt(col.length() - 1) == '_' ? col.substring(0, col.length() - 1)
                                        : col;
                                entry.setField(col, value);
                            }
                        }
                        entries.put(id, entry);
                        database.insertEntry(entry);
                    }
                }
                // Import strings and preamble:
                try (Statement stringStatement = conn.createStatement();
                        ResultSet rsStrings = stringStatement.executeQuery(SQLUtil
                                .queryAllFromTable("strings WHERE database_id='" + database_id + '\''))) {
                    while (rsStrings.next()) {
                        String label = rsStrings.getString("label");
                        String content = rsStrings.getString("content");
                        if ("@PREAMBLE".equals(label)) {
                            database.setPreamble(content);
                        } else {
                            BibtexString string = new BibtexString(IdGenerator.next(), label, content);
                            database.addString(string);
                        }
                    }
                }
                MetaData metaData = new MetaData();
                metaData.initializeNewDatabase();
                // Read the groups tree:
                importGroupsTree(metaData, entries, conn, database_id);
                result.add(new DBImporterResult(database, metaData, rsDatabase.getString("database_name")));
            }
        }
    }

    return result;
}

From source file:com.sri.ai.praise.model.imports.church.ChurchToModelVisitor.java

@Override
public synchronized Expression visitParse(@NotNull ChurchParser.ParseContext ctx) {
    Expression result = null;//from  ww  w.  ja  v  a 2  s .co m

    // Clear down the working variables
    randoms.clear();
    knownConstants.clear();
    knownRandomVariableNames.clear();
    rules.clear();
    queries.clear();
    flipIdToValue.clear();

    visitChildren(ctx);

    // Construct the HOGM      
    StringBuilder hogm = new StringBuilder();
    hogm.append("\n");
    if (knownConstants.size() > 0) {
        StringJoiner knownConstantsCommaSeparatedList = new StringJoiner(", ", ", ", "");
        knownConstants.forEach(constant -> knownConstantsCommaSeparatedList.add(constant.toString()));
        hogm.append("sort " + CHURCH_VALUES_SORT + " : " + SortDeclaration.UNKNOWN_SIZE
                + knownConstantsCommaSeparatedList + ";\n\n");
    } else {
        boolean randomsReferToValuesSort = false;
        for (String randomDeclaration : randoms) {
            if (randomDeclaration.contains(CHURCH_VALUES_SORT)) {
                randomsReferToValuesSort = true;
                break;
            }
        }
        if (randomsReferToValuesSort) {
            hogm.append("sort " + CHURCH_VALUES_SORT + ";\n\n");
        }
    }

    for (String rv : randoms) {
        hogm.append(rv + ";\n");
    }
    hogm.append("\n");
    for (String r : rules) {
        if (Expressions.ZERO_POINT_FIVE.equals(r)) {
            continue; // simplified to know nothing about the random variable so skip it
        }
        hogm.append(r + ";\n");
    }

    Model m = RuleConverter.makeModel(churchProgramName, "\n" + churchProgram + "\n--->\n" + hogm.toString(),
            hogm.toString());

    result = Tuple.make(newSymbol(hogm.toString()), m.getModelDefinition(), ExtensionalSet.makeUniSet(queries));

    return result;
}

From source file:org.briljantframework.array.ArrayPrinter.java

/**
 * Format the {@link org.briljantframework.array.ArrayPrinter.ToStringArray}
 *
 * @param sb write resulting string representation to
 * @param arr the ToStringMatrix/*from   w  w w  .j  av a  2 s. c  om*/
 * @throws java.io.IOException if an IO error occurs
 */
public static void print(Appendable sb, ToStringArray arr, String startChar, String endChar, boolean truncate,
        int dims, IntArray maxWidth) throws IOException {
    if (arr.size() == 0) {
        sb.append(startChar).append(arr.get(0)).append(endChar);
        return;
    }
    if (arr.dims() == 1) {
        StringJoiner joiner = new StringJoiner(", ", startChar, endChar);
        int max = arr.size();
        if (truncate) {
            max = visiblePerSlice < 0 ? arr.size() : visiblePerSlice;
        }
        for (int i = 0; i < arr.size(); i++) {
            String value = pad(arr.get(i), maxWidth.get(i % max));
            joiner.add(value);
            if (i >= max) {
                int left = arr.size() - i - 1;
                if (left > max) {
                    i += left - max - 1;
                    joiner.add("...");
                }
            }
        }
        sb.append(joiner.toString());
    } else {
        int len = arr.size(0);
        sb.append("[");
        print(sb, arr.select(0), startChar, endChar, truncate, dims, maxWidth);
        for (int i = 1; i < len; i++) {
            if (arr.dims() > 2) {
                sb.append(",\n\n");
            } else {
                sb.append(",\n");
            }
            for (int j = 0; j < dims - arr.dims(); j++) {
                sb.append(" ");
            }
            print(sb, arr.select(i), startChar, endChar, truncate, dims, maxWidth);
            int max = len;
            if (truncate) {
                max = printSlices < 0 ? len : printSlices;
            }
            if (i >= max) {
                int left = len - i - 1;
                if (left > max) {
                    i += left - max - 1;
                    sb.append(",\n");
                    for (int j = 0; j < dims - arr.dims(); j++) {
                        sb.append(" ");
                    }
                    sb.append("...");
                }
            }
        }
        sb.append("]");
    }
}

From source file:info.archinnov.achilles.internals.codegen.dsl.select.SelectDSLCodeGen.java

private static MethodSpec buildSelectComputedColumnMethod(TypeName newTypeName,
        FieldMetaSignature parsingResult, String fieldName, ReturnType returnType) {

    final ComputedColumnInfo columnInfo = (ComputedColumnInfo) parsingResult.context.columnInfo;
    StringJoiner joiner = new StringJoiner(",", fieldName + ".fcall($S,", ").as($S)");
    columnInfo.functionArgs.forEach(x -> joiner.add("$L"));

    final Object[] functionName = new Object[] { columnInfo.functionName };
    final Object[] functionArgs = columnInfo.functionArgs.stream()
            .map(arg -> CodeBlock.builder().add("$T.column($S)", QUERY_BUILDER, arg).build()).toArray();
    final Object[] alias = new Object[] { columnInfo.alias };

    final Object[] varargs = ArrayUtils.addAll(functionName, ArrayUtils.addAll(functionArgs, alias));
    final MethodSpec.Builder builder = MethodSpec.methodBuilder(parsingResult.context.fieldName)
            .addJavadoc("Generate a SELECT ... <strong>$L($L) AS $L</strong> ...", varargs)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL).addStatement(joiner.toString(), varargs)
            .returns(newTypeName);/*  ww w  .  j a  v  a2s.  c om*/

    if (returnType == NEW) {
        return builder.addStatement("return new $T(select)", newTypeName).build();
    } else {
        return builder.addStatement("return this").build();
    }
}

From source file:com.netflix.imfutility.itunes.audio.AudioMapXmlProvider.java

/**
 * Gets pan parameter for track./*  w w  w .j  av a  2s  . c  om*/
 * <p></p>
 * Example: pan=4c|c0=c0|c1=c1|c2=c2|c3=c3,aformat=channel_layouts=FL+FR+FC+LFE
 *
 * @param track audio track
 * @return pan parameter for track
 */
private String getPanParameter(LinkedHashMap<String, ChannelType> track) {
    int[] i = { 0 };
    StringJoiner aformat = new StringJoiner("+", ",aformat=channel_layouts=", ""); // ,aformat=channel_layouts=
    StringBuilder panParameter = new StringBuilder("pan="); // pan=
    panParameter.append(track.size()).append("c"); // pan=4c
    track.forEach((chName, channel) -> {
        panParameter.append("|c").append(i[0]).append("="); // pan=4c|c0=

        // gets channel number in amerge channels sequence
        int sequencedChannel = sequencedTrackChannelNumbers.indexOf(
                getIntermediateKey(channel.getCPLVirtualTrackId(), channel.getCPLVirtualTrackChannel() - 1));
        if (sequencedChannel == -1) {
            throw new ConversionException(String.format(
                    "Audio Virtual TrackId \"%s\" with channel number \"%d\" was not found in CPL.",
                    channel.getCPLVirtualTrackId(), channel.getCPLVirtualTrackChannel()));
        }
        panParameter.append("c").append(sequencedChannel); // pan=4c|c0=c0

        aformat.add(chName); // ,aformat=channel_layouts=FL

        i[0]++;
    });
    panParameter.append(aformat); // pan=4c|c0=c0|c1=c1|c2=c2|c3=c3,aformat=channel_layouts=FL+FR+FC+LFE

    return panParameter.toString();
}

From source file:org.elasticsearch.client.Request.java

/**
 * Utility method to build request's endpoint.
 */// w  w w . j a  va2 s  . c  om
static String endpoint(String... parts) {
    if (parts == null || parts.length == 0) {
        return DELIMITER;
    }

    StringJoiner joiner = new StringJoiner(DELIMITER, DELIMITER, "");
    for (String part : parts) {
        if (part != null) {
            joiner.add(part);
        }
    }
    return joiner.toString();
}

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

CodeBlock buildJavaTypeForJackson(TypeName sourceType) {
    if (sourceType instanceof ClassName) {
        final ClassName className = (ClassName) sourceType;
        return CodeBlock.builder().add("$T.construct($T.class)", SIMPLE_TYPE, className.box()).build();

    } else if (sourceType instanceof ParameterizedTypeName) {
        final ParameterizedTypeName paramTypeName = (ParameterizedTypeName) sourceType;

        StringJoiner code = new StringJoiner(",", "$T.TYPE_FACTORY_INSTANCE.constructParametricType($T.class,",
                ")");

        for (TypeName x : paramTypeName.typeArguments) {
            code.add("$L");
        }/*  w  ww.j a v a 2  s .c  om*/

        final Object[] headTypes = new Object[] { JSON_CODEC, paramTypeName.rawType };
        final Object[] codeBlocks = paramTypeName.typeArguments.stream()
                .map(typeName -> (Object) buildJavaTypeForJackson(typeName)).toArray();

        return CodeBlock.builder().add(code.toString(), ArrayUtils.addAll(headTypes, codeBlocks)).build();

    } else if (sourceType instanceof ArrayTypeName) {
        final TypeName componentType = ((ArrayTypeName) sourceType).componentType;
        return CodeBlock.builder().add("$T.TYPE_FACTORY_INSTANCE.constructArrayType($L)", JSON_CODEC,
                buildJavaTypeForJackson(componentType.box())).build();

    } else if (sourceType instanceof WildcardTypeName) {
        aptUtils.printError("Cannot build Jackson Mapper JavaType for wildcard type " + sourceType.toString());
    } else {
        aptUtils.printError("Cannot build Jackson Mapper JavaType for type " + sourceType.toString());
    }

    return null;
}

From source file:com.sri.ai.praise.model.imports.church.ChurchToModelVisitor.java

protected Expression defineInHOGM(Expression name, List<Expression> params, Expression body) {
    Expression result = null;/*from  w w w .java 2 s. c  o m*/

    // Track the known random variable names
    knownRandomVariableNames.add(name);

    // Determine the correct argument names for any of the
    StringBuilder rArgs = new StringBuilder();
    final Map<Expression, Expression> paramVarNames = new HashMap<Expression, Expression>();
    boolean firstArg = true;
    int cnt = 0;
    Expression randomVariable = name;
    List<Expression> rvArgs = new ArrayList<Expression>();
    for (Expression arg : params) {
        if (firstArg) {
            firstArg = false;
            rArgs.append(" ");
        } else {
            rArgs.append(" x ");
        }
        // Ensure name is upper cased
        Expression logicalVariableArg = newLogicalVariable(arg.toString());
        rvArgs.add(logicalVariableArg);
        params.set(cnt, logicalVariableArg);
        paramVarNames.put(arg, params.get(cnt));
        // TODO - anything better?         
        rArgs.append(CHURCH_VALUES_SORT);
        cnt++;
    }
    randoms.add("random " + name + ":" + rArgs + (rArgs.length() > 0 ? " -> " : " ") + "Boolean");
    StringJoiner knownRandomVariablesHLM = new StringJoiner(";\n", "", ";");
    randoms.forEach(r -> knownRandomVariablesHLM.add(r));
    RewritingProcess processForRV = LBPFactory.newLBPProcessWithHighLevelModel(
            "sort " + CHURCH_VALUES_SORT + ";\n\n" + knownRandomVariablesHLM.toString());
    if (rvArgs.size() > 0) {
        randomVariable = Expressions.apply(randomVariable, rvArgs);
        processForRV = LPIUtil
                .extendContextualSymbolsWithFreeVariablesInferringDomainsFromUsageInRandomVariables(
                        randomVariable, processForRV);
    }

    final List<List<Boolean>> flipValues = new ArrayList<List<Boolean>>();
    final List<Boolean> trueFalseValues = new ArrayList<Boolean>();
    final Map<Expression, Integer> flipMarkerToId = new LinkedHashMap<Expression, Integer>();
    final Map<Expression, Integer> flipMarkerToFlipValuesIdx = new LinkedHashMap<Expression, Integer>();
    // Flips <- array of flip applications in body
    trueFalseValues.add(Boolean.FALSE);
    trueFalseValues.add(Boolean.TRUE);

    for (Integer flipId : flipIdToValue.keySet()) {
        Expression flipMarker = newSymbol(FLIP_ID_PREFIX + flipId);
        if (!flipMarkerToId.containsKey(flipMarker) && Expressions.isSubExpressionOf(flipMarker, body)) {
            flipMarkerToId.put(flipMarker, flipId);
            flipMarkerToFlipValuesIdx.put(flipMarker, flipMarkerToFlipValuesIdx.size());
            flipValues.add(trueFalseValues);
        }
    }

    if (flipValues.size() == 0) {
        Expression potentialRule = createPotentialRule(randomVariable,
                deterministicChurch2HOGM(body, paramVarNames, processForRV), Expressions.ONE, Expressions.ZERO);
        result = rNormalize.rewrite(potentialRule, processForRV);
    } else {
        // H <- empty list
        List<Expression> h = new ArrayList<Expression>();
        // for all assignments of FlipsValues to Flips do
        CartesianProductEnumeration<Boolean> cpe = new CartesianProductEnumeration<Boolean>(flipValues);
        while (cpe.hasMoreElements()) {
            final List<Boolean> values = cpe.nextElement();

            // caseC <- subsitute FlipsValues for Flips in body
            Expression caseC = body
                    .replaceAllOccurrences(new AbstractReplacementFunctionWithContextuallyUpdatedProcess() {
                        @Override
                        public Expression apply(Expression expression, RewritingProcess process) {
                            Expression result = expression;
                            if (Expressions.isSymbol(expression)) {
                                Integer idx = flipMarkerToFlipValuesIdx.get(expression);
                                if (idx != null) {
                                    result = values.get(idx) ? Expressions.TRUE : Expressions.FALSE;
                                }
                            }
                            return result;
                        }
                    }, LBPFactory.newLBPProcess());
            // caseH <- deterministicChurch2HOGM(caseC)
            Expression caseH = deterministicChurch2HOGM(caseC, paramVarNames, processForRV);

            // Calculate q
            Rational q = Rational.ONE;
            for (Map.Entry<Expression, Integer> flipMarkerToIdEntry : flipMarkerToId.entrySet()) {
                Rational pi = flipIdToValue.get(flipMarkerToIdEntry.getValue());
                if (!values.get(flipMarkerToFlipValuesIdx.get(flipMarkerToIdEntry.getKey()))) {
                    pi = Rational.ONE.subtract(pi);
                }

                q = q.multiply(pi);
            }

            h.add(createPotentialRule(randomVariable, caseH, Expressions.makeSymbol(q), Expressions.ZERO));
        }
        Expression plusH = Plus.make(h);
        List<Expression> constants = new ArrayList<>(FormulaUtil.getConstants(plusH, processForRV));
        // Ensure we exclude known random variable names
        constants.removeAll(knownRandomVariableNames);
        // And also ensure we remove these known constants as well.
        constants.remove(Expressions.TRUE);
        constants.remove(Expressions.FALSE);
        if (constants.size() > 0) {
            knownConstants.addAll(constants);
            Model model = Model.getRewritingProcessesModel(processForRV);
            Set<Expression> sortDeclarationExpressions = new LinkedHashSet<>();
            sortDeclarationExpressions.add(new SortDeclaration(Expressions.makeSymbol(CHURCH_VALUES_SORT),
                    SortDeclaration.UNKNOWN_SIZE, ExtensionalSet.makeUniSet(constants)).getSortDeclaration());
            Set<Expression> randomVariableDeclarationExpressions = new LinkedHashSet<>();
            model.getRandomVariableDeclarations()
                    .forEach(randomVariableDeclaration -> randomVariableDeclarationExpressions
                            .add(randomVariableDeclaration.getRandomVariableDeclaration()));
            processForRV = Model.setKnownSortsAndRandomVariables(sortDeclarationExpressions,
                    randomVariableDeclarationExpressions, processForRV);
        }

        result = SimplifyWithRelationsAtBottom.simplify(plusH, name, processForRV);
    }

    rules.add(result.toString());

    return result;
}

From source file:org.elasticsearch.client.RequestConvertersTests.java

public void testPutMapping() throws IOException {
    PutMappingRequest putMappingRequest = new PutMappingRequest();

    String[] indices = randomIndicesNames(0, 5);
    putMappingRequest.indices(indices);/*from  w ww  .j av  a  2  s. co  m*/

    String type = randomAlphaOfLengthBetween(3, 10);
    putMappingRequest.type(type);

    Map<String, String> expectedParams = new HashMap<>();

    setRandomTimeout(putMappingRequest::timeout, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams);
    setRandomMasterTimeout(putMappingRequest, expectedParams);

    Request request = RequestConverters.putMapping(putMappingRequest);
    StringJoiner endpoint = new StringJoiner("/", "/", "");
    String index = String.join(",", indices);
    if (Strings.hasLength(index)) {
        endpoint.add(index);
    }
    endpoint.add("_mapping");
    endpoint.add(type);
    assertEquals(endpoint.toString(), request.getEndpoint());

    assertEquals(expectedParams, request.getParameters());
    assertEquals(HttpPut.METHOD_NAME, request.getMethod());
    assertToXContentBody(putMappingRequest, request.getEntity());
}

From source file:org.elasticsearch.client.RequestConvertersTests.java

public void testGetMapping() throws IOException {
    GetMappingsRequest getMappingRequest = new GetMappingsRequest();

    String[] indices = Strings.EMPTY_ARRAY;
    if (randomBoolean()) {
        indices = randomIndicesNames(0, 5);
        getMappingRequest.indices(indices);
    } else if (randomBoolean()) {
        getMappingRequest.indices((String[]) null);
    }//w  ww .  j  a  v a 2  s .  c  o  m

    String type = null;
    if (randomBoolean()) {
        type = randomAlphaOfLengthBetween(3, 10);
        getMappingRequest.types(type);
    } else if (randomBoolean()) {
        getMappingRequest.types((String[]) null);
    }

    Map<String, String> expectedParams = new HashMap<>();

    setRandomIndicesOptions(getMappingRequest::indicesOptions, getMappingRequest::indicesOptions,
            expectedParams);
    setRandomMasterTimeout(getMappingRequest, expectedParams);
    setRandomLocal(getMappingRequest, expectedParams);

    Request request = RequestConverters.getMappings(getMappingRequest);
    StringJoiner endpoint = new StringJoiner("/", "/", "");
    String index = String.join(",", indices);
    if (Strings.hasLength(index)) {
        endpoint.add(index);
    }
    endpoint.add("_mapping");
    if (type != null) {
        endpoint.add(type);
    }
    assertThat(endpoint.toString(), equalTo(request.getEndpoint()));

    assertThat(expectedParams, equalTo(request.getParameters()));
    assertThat(HttpGet.METHOD_NAME, equalTo(request.getMethod()));
}