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:com.viettel.util.StringUtils.java

public static void buidQuery(String name, HashMap<String, Object> searchParams, StringBuilder strQuery,
         Map<String, Object> params, String... prefix) {
     ArrayList<String> arrQuery = new ArrayList<String>();
     SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
     HashMap<String, Object> searchParamsCopy = new HashMap<>(searchParams);
     for (Map.Entry<String, Object> entry : searchParams.entrySet()) {
         String key = entry.getKey();
         Object value = entry.getValue();
         if (value == null || value.toString().equals("")) {
             searchParamsCopy.remove(key);
         }/*from  www . j a va 2  s . c o  m*/
     }
     String pref = prefix != null && prefix.length > 0 ? prefix[0] + "." : "";
     for (Map.Entry<String, Object> entry : searchParamsCopy.entrySet()) {
         String key = entry.getKey();

         Object value = entry.getValue();
         /*
          * if (value == null || value.toString().equals("") || (value
          * instanceof Long && 0 >= (int) value)) { continue; }
          */
         if (arrQuery.size() > 0) {
             arrQuery.add(" AND  ");
         }
         if (value instanceof Date || DateUtil.isValidDateWithFormat(value.toString(), "yyyy-MM-dd")) {
             try {
                 if (key.startsWith("from")) {
                     String cl = key.replace("from", "");
                     if (searchParamsCopy.containsKey("to" + cl)) {
                         arrQuery.add(String.format("%1$s BETWEEN :%2$s", pref + cl, key));
                         params.put(key, formatter.parse(value.toString()));

                         Object objTo = searchParamsCopy.get("to" + cl);
                         if (objTo != null) {
                             arrQuery.add(String.format(" AND :%s", "to" + cl));
                             params.put("to" + cl, formatter.parse(objTo.toString()));
                         }
                     } else {
                         arrQuery.add(String.format("%1$s >= :%2$s", pref + cl, key));
                         params.put(key, formatter.parse(value.toString()));
                     }
                 } else if (key.startsWith("to")) {
                     String cl = key.replace("to", "");
                     if (!searchParamsCopy.containsKey("from" + cl)) {
                         arrQuery.add(String.format("%1$s <= :%2$s", pref + cl, key));
                         params.put(key, formatter.parse(value.toString()));
                     } else {
                         if (arrQuery.size() > 0) {
                             arrQuery.remove(arrQuery.size() - 1);
                         }
                     }
                 } else {
                     arrQuery.add(String.format("DATE(%1$s) = DATE(:%2$s)", pref + key, key));
                     params.put(key, value + "%");
                 }
             } catch (ParseException ex) {

             }
         } else if (value instanceof Number) {
             if (key.startsWith("and_")) {
                 if (searchParamsCopy.containsKey(key.replace("and_", ""))) {
                     if (!CollectionUtils.isEmpty(arrQuery)) {
                         arrQuery.remove(arrQuery.size() - 1);
                     }
                 }
             } else if (searchParamsCopy.containsKey("and_" + key)) {
                 arrQuery.add(String.format("(%1$s = :%2$s", pref + key, key));
                 if (value instanceof Integer) {
                     params.put(key, Integer.parseInt(value.toString()));
                 } else if (value instanceof Long) {
                     params.put(key, Long.parseLong(value.toString()));
                 } else if (value instanceof Float) {
                     params.put(key, Float.parseFloat(value.toString()));
                 } else if (value instanceof Double) {
                     params.put(key, Double.parseDouble(value.toString()));
                 }

                 Object obj = searchParamsCopy.get("and_" + key);
                 if (obj != null) {
                     arrQuery.add(String.format(" OR %1$s = :%2$s)", pref + key, "and_" + key));
                     if (value instanceof Integer) {
                         params.put("and_" + key, Integer.parseInt(obj.toString()));
                     } else if (value instanceof Long) {
                         params.put("and_" + key, Long.parseLong(obj.toString()));
                     } else if (value instanceof Float) {
                         params.put("and_" + key, Float.parseFloat(obj.toString()));
                     } else if (value instanceof Double) {
                         params.put("and_" + key, Double.parseDouble(obj.toString()));
                     }
                 }
             } else {
                 arrQuery.add(String.format("%1$s = :%2$s", pref + key, key));
                 if (value instanceof Integer) {
                     params.put(key, Integer.parseInt(value.toString()));
                 } else if (value instanceof Long) {
                     params.put(key, Long.parseLong(value.toString()));
                 } else if (value instanceof Float) {
                     params.put(key, Float.parseFloat(value.toString()));
                 } else if (value instanceof Double) {
                     params.put(key, Double.parseDouble(value.toString()));
                 }
             }
         } else if (value instanceof String) {
             if (key.startsWith("and_")) {
                 if (searchParamsCopy.containsKey(key.replace("and_", ""))) {
                     if (arrQuery.size() > 0) {
                         arrQuery.remove(arrQuery.size() - 1);
                     }
                 }
             } else if (searchParamsCopy.containsKey("and_" + key)) {
                 arrQuery.add(String.format("(LOWER(%1$s) like LOWER(:%2$s)", pref + key, key));
                 params.put(key, "%" + value + "%");

                 Object obj = searchParamsCopy.get("and_" + key);
                 if (obj != null) {
                     arrQuery.add(String.format(" OR LOWER(%1$s) LIKE LOWER(:%2$s))", pref + key, "and_" + key));
                     params.put("and_" + key, "%" + obj + "%");
                 }
             } else if (key.startsWith("in_cond_")) {
                 String cl = key.replace("in_cond_", "");
                 arrQuery.add(String.format("%1$s IN (%2$s)", pref + cl, value.toString()));
                 params.remove(key);
             } else if (key.startsWith("not_in_cond_")) {
                 String cl = key.replace("not_in_cond_", "");
                 arrQuery.add(String.format("%1$s NOT IN (%2$s)", pref + cl, value.toString()));
                 params.remove(key);
             } else {
                 arrQuery.add(String.format("LOWER(%1$s) LIKE LOWER(:%2$s)", pref + key, key));
                 params.put(key, "%" + value + "%");
             }
         }
     }
     strQuery.append(String.join("", arrQuery));
 }

From source file:com.spotify.styx.cli.Main.java

private String apiUrl(CharSequence... parts) {
    return "http://" + apiHost + STYX_API_ENDPOINT + "/" + String.join("/", parts);
}

From source file:com.netflix.spinnaker.clouddriver.cloudfoundry.client.ServiceInstances.java

private static List<String> getServiceQueryParams(List<String> serviceNames, CloudFoundrySpace space) {
    return Arrays.asList(
            serviceNames.size() == 1 ? "name:" + serviceNames.get(0)
                    : "name IN " + String.join(",", serviceNames),
            "organization_guid:" + space.getOrganization().getId(), "space_guid:" + space.getId());
}

From source file:com.formkiq.core.service.workflow.WorkflowEditorServiceImplTest.java

/**
 * testEventStepup05().// w ww  .  j  a v a  2s .co m
 * _eventId_stepup item 1.
 * @throws IOException IOException
 */
@Test
public void testEventStepup05() throws IOException {
    // given
    Workflow wf = expectAction();

    // when
    replayAll();
    this.ws.eventIdstepup(this.flow, this.request, new String[] { "1" });

    // then
    verifyAll();

    assertEquals("2,1,3", String.join(",", wf.getSteps()));
    assertEquals("1,2,3", String.join(",", wf.getPrintsteps()));
}

From source file:io.github.retz.db.Database.java

public List<Job> findFit(List<String> orderBy, int cpu, int memMB) throws IOException {
    List<Job> ret = new LinkedList<>();
    String orders = String.join(", ", orderBy.stream().map(s -> s + " ASC").collect(Collectors.toList()));
    try (Connection conn = dataSource.getConnection(); //pool.getConnection();
            PreparedStatement p = conn
                    .prepareStatement("SELECT * FROM jobs WHERE state='QUEUED' ORDER BY " + orders)) {
        conn.setAutoCommit(true);//from   w w  w  .j a va 2s . c o m

        try (ResultSet res = p.executeQuery()) {
            int totalCpu = 0;
            int totalMem = 0;

            while (res.next() && totalCpu <= cpu && totalMem <= memMB) {
                String json = res.getString("json");
                Job job = MAPPER.readValue(json, Job.class);

                if (job == null) {
                    throw new AssertionError("Cannot be null!!");
                } else if (totalCpu + job.resources().getCpu() <= cpu
                        && totalMem + job.resources().getMemMB() <= memMB) {
                    ret.add(job);
                    totalCpu += job.resources().getCpu();
                    totalMem += job.resources().getMemMB();
                } else {
                    break;
                }
            }
        }
    } catch (SQLException e) {
        LOG.error(e.toString());
        e.printStackTrace();
    }
    return ret;
}

From source file:com.formkiq.core.service.workflow.WorkflowEditorServiceImplTest.java

/**
 * testPrintStepdown01()./*w w  w .j  a  va 2 s. c  o  m*/
 * _eventId_printstepup up.
 * @throws IOException IOException
 */
@Test
public void testPrintStepdown01() throws IOException {
    // given
    Workflow wf = expectAction();

    // when
    replayAll();
    this.ws.eventIdprintstepdown(this.flow, this.request, new String[] { "0" });

    // then
    verifyAll();

    assertEquals("1,2,3", String.join(",", wf.getSteps()));
    assertEquals("2,1,3", String.join(",", wf.getPrintsteps()));
}

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

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

    try {
        // -w is to ignore whitespace bug
        ProcessBuilder processBuilder = new ProcessBuilder(this.GITBINARYPATH, "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 = processBuilder.start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = 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 = br.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()
                + "\n with message: " + ex.getMessage());
    }

    return codeOwners;
}

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);
    }//from   w  w w.j  a va  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()));
}

From source file:com.formkiq.core.service.workflow.WorkflowEditorServiceImplTest.java

/**
 * testPrintStepup01()./*w w  w.  j  av a  2s  .c  o m*/
 * _eventId_printstepup last item of list.
 * @throws IOException IOException
 */
@Test
public void testPrintStepup01() throws IOException {
    // given
    Workflow wf = expectAction();

    // when
    replayAll();
    this.ws.eventIdprintstepup(this.flow, this.request, new String[] { "2" });

    // then
    verifyAll();

    assertEquals("1,2,3", String.join(",", wf.getSteps()));
    assertEquals("1,3,2", String.join(",", wf.getPrintsteps()));
}

From source file:it.unibas.spicy.persistence.sql.DAOSql.java

private void loadPrimaryAndForeignKeys(List<net.sf.jsqlparser.statement.Statement> stmtss,
        IDataSourceProxy dataSource, Statement statement, boolean source, int scenarioNo, boolean web)
        throws SQLException {
    for (net.sf.jsqlparser.statement.Statement stmt : stmtss) {
        if (stmt instanceof CreateTable) {
            CreateTable createStmt = (CreateTable) stmt;
            List<String> PKcolumnNames = new ArrayList<String>();
            String tableName = createStmt.getTable().getName();
            //trim and remove quotes
            tableName = tableName.trim().replace("\"", "");
            //there are two ways that Primary Keys and Foreign can be declared
            //1)at the end of the column definitions as indexes
            List<Index> indexes = createStmt.getIndexes();
            if (indexes != null && !indexes.isEmpty()) {
                for (Index index : indexes) {
                    String indexType = index.getType();
                    //PRIMARY KEY
                    if (indexType.equalsIgnoreCase("PRIMARY KEY")) {
                        for (String columnName : index.getColumnsNames()) {
                            //trim and remove quotes                
                            columnName = columnName.trim().replace("\"", "");
                            String keyPrimary = tableName + "." + columnName;
                            getNode(keyPrimary).setNotNull(true);
                            KeyConstraint keyConstraint = new KeyConstraint(
                                    DAORelationalUtility.generatePath(keyPrimary), true);
                            dataSource.addKeyConstraint(keyConstraint);
                            PKcolumnNames.add("\"" + columnName + "\"");
                        }//from  ww  w  . ja v  a 2  s . c  o  m
                    }
                    //FOREIGN KEY
                    //Auto-detection of foreign keys disabled
                    else if (indexType.equalsIgnoreCase("FOREIGN KEY")) {
                        ForeignKeyIndex fkIndex = (ForeignKeyIndex) index;
                        List<String> fkColumns = fkIndex.getColumnsNames();
                        List<String> refColumns = fkIndex.getReferencedColumnNames();
                        for (int i = 0; i < fkColumns.size(); i++) {
                            String columnName = fkColumns.get(i).trim().replace("\"", "");
                            String keyForeign = tableName + "." + columnName;
                            String referencedColumn = refColumns.get(i).trim().replace("\"", "");
                            String referencedTable = fkIndex.getTable().getName().trim().replace("\"", "");
                            String keyReferenced = referencedTable + "." + referencedColumn;
                            DAORelationalUtility.generateConstraint(keyForeign, keyReferenced, dataSource);
                        }
                    }
                }
            }
            //2)in the column definitions themselves
            List<ColumnDefinition> columns = createStmt.getColumnDefinitions();
            for (ColumnDefinition column : columns) {
                List<String> columnSpecs = column.getColumnSpecStrings();
                if (columnSpecs != null && !columnSpecs.isEmpty()) {
                    for (int i = 0; i < columnSpecs.size(); i++) {
                        //PRIMARY KEY
                        if (columnSpecs.get(i).equalsIgnoreCase("PRIMARY")
                                && columnSpecs.get(i + 1).equalsIgnoreCase("KEY")) {
                            String columnName = column.getColumnName();
                            //trim and remove quotes                
                            columnName = columnName.trim().replace("\"", "");
                            String keyPrimary = tableName + "." + columnName;
                            getNode(keyPrimary).setNotNull(true);
                            KeyConstraint keyConstraint = new KeyConstraint(
                                    DAORelationalUtility.generatePath(keyPrimary), true);
                            dataSource.addKeyConstraint(keyConstraint);
                            PKcolumnNames.add("\"" + columnName + "\"");
                        }
                        //FOREIGN KEY
                        //Auto-detection of foreign keys disabled
                        if (columnSpecs.get(i).equalsIgnoreCase("REFERENCES")) {
                            //trim and remove quotes 
                            String columnName = column.getColumnName().trim().replace("\"", "");
                            String referencedTable = columnSpecs.get(i + 1).trim().replace("\"", "");
                            //remove quotes and parenthesis from referenced column
                            String referencedColumn = columnSpecs.get(i + 2).trim().replace("\"", "")
                                    .replace("(", "").replace(")", "");
                            String keyForeign = tableName + "." + columnName;
                            String keyReferenced = referencedTable + "." + referencedColumn;
                            DAORelationalUtility.generateConstraint(keyForeign, keyReferenced, dataSource);
                        }
                    }
                }
            }
            //un-comment the following if Primary Key Constraints are to be considered
            /////
            if (!web && !PKcolumnNames.isEmpty()) {
                String table;
                if (source) {
                    table = SpicyEngineConstants.SOURCE_SCHEMA_NAME + scenarioNo + ".\"" + tableName + "\"";
                } else {
                    String newSchemaName = SpicyEngineConstants.TARGET_SCHEMA_NAME + scenarioNo;
                    table = newSchemaName + ".\"" + tableName + "\"";
                    statement.execute(
                            GenerateSQL.createTriggerFunction(table, newSchemaName, tableName, PKcolumnNames));
                    statement.execute(GenerateSQL.createTriggerBeforeInsert(table, newSchemaName, tableName));
                }
                String primaryKeys = String.join(",", PKcolumnNames);
                statement.executeUpdate("ALTER TABLE " + table + " ADD PRIMARY KEY (" + primaryKeys + ");");
            }
            /////
        }
        /********************ALTER Statement**********************/
        else if (stmt instanceof Alter) {
            Alter alterStmt = (Alter) stmt;
            String tableName = alterStmt.getTable().getName();
            //trim and remove quotes
            tableName = tableName.trim().replace("\"", "");
        }
    }
}