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.wx3.galacdecks.Bootstrap.java

private void importPlayValidators(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 w w  w .ja v a  2s .  c  om*/
                    String description = lines.get(0).substring(2).trim();
                    String script = String.join("\n", lines);
                    ValidatorScript validator = ValidatorScript.createValidator(id, script, description);
                    //datastore.createValidator(validator);
                    playValidatorCache.put(id, validator);
                    logger.info("Imported play validator " + id);
                }
            } catch (Exception e) {
                throw new RuntimeException("Failed to parse " + filePath + ": " + e.getMessage());
            }
        }
    });
}

From source file:com.jci.utils.CommonUtils.java

/**
 * Gets the header string.//w ww.j a v a 2  s. co m
 *
 * @param mapping the mapping
 * @return the header string
 */
public String getHeaderString(HashMap<Integer, String> mapping) {
    StringBuilder line = new StringBuilder();
    for (int i = 0; i < mapping.size(); i++) {
        String str = StringUtils.capitalize(mapping.get(i));
        str = str.substring(0, 1).toUpperCase() + str.substring(1);
        String[] upperStr = str.split("(?<=[a-z])(?=[A-Z])");
        String joined = "#" + String.join(" ", upperStr);
        line.append(joined + "\t");
    }

    return line.toString();
}

From source file:com.yahoo.elide.extensions.JsonApiPatch.java

/**
 * Handle a patch action.// w w  w .  j a  va 2 s  .c o m
 *
 * @param requestScope outer request scope
 * @return List of responders
 */
private List<Supplier<Pair<Integer, JsonNode>>> handleActions(PatchRequestScope requestScope) {
    return actions.stream().map(action -> {
        Supplier<Pair<Integer, JsonNode>> result;
        try {
            String[] combined = ArrayUtils.addAll(rootUri.split("/"), action.patch.getPath().split("/"));
            String fullPath = String.join("/", combined).replace("/-", "");
            switch (action.patch.getOperation()) {
            case ADD:
                result = handleAddOp(fullPath, action.patch.getValue(), requestScope, action);
                break;
            case REPLACE:
                result = handleReplaceOp(fullPath, action.patch.getValue(), requestScope);
                break;
            case REMOVE:
                result = handleRemoveOp(fullPath, action.patch.getValue(), requestScope);
                break;
            default:
                throw new InvalidEntityBodyException(
                        "Could not parse patch extension operation:" + action.patch.getOperation());
            }
            return result;
        } catch (HttpStatusException e) {
            action.cause = e;
            throw e;
        }
    }).collect(Collectors.toList());
}

From source file:org.createnet.raptor.db.mapdb.MapDBConnection.java

@Override
public List<JsonNode> list(ListQuery query) {

    List<JsonNode> results = new ArrayList();

    List<ListQuery.QueryParam> params = query.getParams();

    if (params.size() > 0) {

        List<String> keys = new ArrayList();
        Map<String, String> values = new HashMap();

        for (ListQuery.QueryParam param : params) {
            keys.add(param.key);/*w  ww  . ja  v a  2s  .  c o  m*/
            values.put(param.key, param.value.toString());
        }

        String key = getIndexKey(keys);

        String[] arrKeys = new String[keys.size()];
        arrKeys = keys.toArray(arrKeys);
        Arrays.sort(arrKeys);

        String[] keyVal = new String[arrKeys.length];
        int i = 0;
        for (String arrKey : arrKeys) {
            keyVal[i] = values.get(arrKey);
            i++;
        }

        String valuesKey = String.join(keySeparator, keyVal);

        BTreeMap<String, String> idx = indexMap.get(key);

        if (idx == null) {
            logger.debug("Missing index for {}", key);
            throw new Storage.StorageException("Missing index " + key);
        }

        String json = idx.get(valuesKey);

        // no results
        if (json == null) {
            return results;
        }

        try {

            String[] ids = Storage.mapper.readValue(json, String[].class);

            for (String id1 : ids) {
                JsonNode row = get(id1);
                if (row != null) {
                    results.add(row);
                }
            }

        } catch (IOException ex) {
            throw new Storage.StorageException(ex);
        }

    }

    if (query.getLimit() > 0) {
    }

    if (query.getOffset() > 0) {
    }

    return results;
}

From source file:com.yahoo.egads.models.adm.AdaptiveKernelDensityChangePointDetector.java

@Override
public IntervalSequence detect(DataSequence observedSeries, DataSequence expectedSeries) throws Exception {

    if (observedSeries.size() != expectedSeries.size()) {
        throw new Exception("The observed time-series must have the same length as the expected time-series.");
    }//from w  ww. ja va2s.c o  m
    long unixTime = System.currentTimeMillis() / 1000L;

    IntervalSequence result = new IntervalSequence();
    int n = observedSeries.size();
    float[] residuals = new float[n];

    // Computing the residuals
    for (int i = 0; i < n; ++i) {
        residuals[i] = observedSeries.get(i).value - expectedSeries.get(i).value;
    }

    // Detecting change points
    ArrayList<Integer> changePoints = detectChangePoints(residuals, this.preWindowSize, this.postWindowSize,
            this.confidence);

    // Preparing the output
    if (this.outputDest.equals("STD_OUT_ALL")) {
        int j = 0;
        for (int i = 0; i < n; ++i) {
            boolean isCP = false;

            if (!changePoints.isEmpty()) {
                isCP = (changePoints.get(j) == i);
            }

            if (isCP && j < (changePoints.size() - 1)) {
                j++;
            }
            logger.debug("TS:" + observedSeries.get(i).time + ",SC:"
                    + String.join(":", arrayF2S(new Float[] { score[i] })) + ",LV:"
                    + arrayF2S(new Float[] { level[i] }) + ",OV:" + observedSeries.get(i).value + ",EV:"
                    + expectedSeries.get(i).value);

            result.add(new Interval(observedSeries.get(i).time, i, new Float[] { score[i] },
                    new Float[] { level[i] }, observedSeries.get(i).value, expectedSeries.get(i).value,
                    (isCP)));
        }
    } else {
        for (int index : changePoints) {
            if (((unixTime - observedSeries.get(index).time) / 3600) < maxHrsAgo) {
                result.add(new Interval(observedSeries.get(index).time, index, new Float[] { score[index] },
                        new Float[] { level[index] }, observedSeries.get(index).value,
                        expectedSeries.get(index).value));
            }
        }
    }

    return result;
}

From source file:edu.washington.gs.skyline.model.quantification.DesignMatrix.java

@Override
public String toString() {
    if (columnNames.length == 0) {
        return "";
    }//from ww w.j  a  v a  2s.  co m
    List<String> lines = new ArrayList<>();
    lines.add(String.join("\t", columnNames));
    for (int row = 0; row < matrixColumns[0].length; row++) {
        final int rowNumber = row;
        lines.add(String.join("\t", Arrays.stream(matrixColumns).map(col -> Double.toString(col[rowNumber]))
                .collect(Collectors.toList())));
    }

    return String.join("\n", lines);
}

From source file:com.baifendian.swordfish.dao.mapper.StreamingResultMapperProvider.java

/**
 * ???/* w  w  w . ja va2s . c om*/
 *
 * @param parameter
 * @return
 */
public String findLatestDetailByProjectAndNames(Map<String, Object> parameter) {
    List<String> nameList = (List<String>) parameter.get("nameList");

    String subSql = new SQL() {
        {
            SELECT("max(id)");

            FROM(TABLE_NAME);

            WHERE("p.id=#{projectId}");

            if (CollectionUtils.isNotEmpty(nameList)) {
                String names = "\"" + String.join("\", \"", nameList) + "\"";
                WHERE("s.name in (" + names + ")");
            }

            GROUP_BY("streaming_id");
        }
    }.toString();

    return constructCommonDetailSQL().WHERE("r.id in " + "(" + subSql + ")").toString();
}

From source file:io.rhiot.utils.install.DefaultInstaller.java

@Override
public boolean install(String packageNames) {
    if (!isPlatformSupported()) {
        throw new UnsupportedOperationException("DefaultInstaller does not support this platform");
    }/* w ww  .  j ava  2  s.  co  m*/

    if (StringUtils.isEmpty(packageNames)) {
        return true;
    }

    LOG.info("Installing [{}]", packageNames);
    String normalizedNames = packageNames.replaceAll(",", " ");

    if (isInstalled(Arrays.asList(normalizedNames.split(" ")))) {
        LOG.info("Already installed");
        return true;
    }

    List<String> output = getProcessManager()
            .executeAndJoinOutput((String.join(" ", (getInstallCommand() + " " + normalizedNames).split(" "))));

    LOG.info("Installation result : {}", output);
    if (isPermissionDenied(output)) {
        throw new PermissionDeniedException(
                "You must have sufficient privileges to install package/s [" + packageNames + "]");
    }

    return isInstalled(Arrays.asList(normalizedNames.split(" ")));
}

From source file:cd.go.contrib.elasticagents.marathon.MarathonInstance.java

public static MarathonInstance instanceFromApp(App app, PluginSettings settings) {
    Map<String, String> autoRegisterProperties = new HashMap<>();
    autoRegisterProperties.put("GO_EA_AUTO_REGISTER_KEY", app.getEnv().get("GO_EA_AUTO_REGISTER_KEY"));
    autoRegisterProperties.put("GO_EA_AUTO_REGISTER_ENVIRONMENT",
            app.getEnv().get("GO_EA_AUTO_REGISTER_ENVIRONMENT"));
    autoRegisterProperties.put("GO_EA_AUTO_REGISTER_ELASTIC_AGENT_ID",
            app.getEnv().get("GO_EA_AUTO_REGISTER_ELASTIC_AGENT_ID"));
    autoRegisterProperties.put("GO_EA_AUTO_REGISTER_ELASTIC_PLUGIN_ID",
            app.getEnv().get("GO_EA_AUTO_REGISTER_ELASTIC_PLUGIN_ID"));

    DateTime createdTime = new DateTime();

    if (app.getTasks() != null) {
        if (app.getTasks().size() > 0) {
            createdTime = new DateTime(Iterables.get(app.getTasks(), 0).getStagedAt());
        }//w  ww . j a v a2 s  .  co  m
    }

    Gson gson = new Gson();
    List<String> constraintList = new ArrayList<>();

    for (List<String> constraint : app.getConstraints()) {
        constraintList.add(gson.toJson(constraint));
    }
    String constraints = String.join("\n", constraintList);

    String uris = app.getUris() == null ? "" : String.join("\n", app.getUris());

    List<String> volumes = new ArrayList<>();
    if (app.getContainer().getVolumes() != null) {
        for (Volume volume : app.getContainer().getVolumes()) {
            volumes.add(volume.getContainerPath() + ":" + volume.getHostPath() + ":" + volume.getMode());
        }
    }
    String vols = String.join("\n", volumes);

    return new MarathonInstance(app.getId().substring(settings.getMarathonPrefix().length()), createdTime,
            app.getEnv().get("GO_EA_AUTO_REGISTER_ENVIRONMENT"), settings.getGoServerUrl(),
            settings.getMarathonPrefix(), app.getContainer().getDocker().getImage(), app.getMem(),
            app.getCpus(), app.getCmd(), app.getEnv().get("GO_EA_USER"), constraints, uris, vols,
            autoRegisterProperties);
}

From source file:edu.cmu.lti.oaqa.bioasq.concept.rerank.scorers.GoPubMedConceptRetrievalScorer.java

@Override
public void prepare(JCas jcas) throws AnalysisEngineProcessException {
    List<String> tokens = TypeUtil.getOrderedTokens(jcas).stream().map(Token::getCoveredText)
            .map(name -> name.replaceAll("[^A-Za-z0-9_\\-]+", " ").trim())
            .filter(name -> !name.isEmpty() && !stoplist.contains(name.toLowerCase())).collect(toList());
    List<String> wIdConceptNames = TypeUtil
            .getConcepts(jcas).stream().filter(concept -> !TypeUtil.getConceptIds(concept).isEmpty())
            .map(TypeUtil::getConceptNames).map(names -> names.stream()
                    .map(GoPubMedConceptRetrievalScorer::normalizeQuoteName).collect(joining(" ")))
            .collect(toList());//from w  w  w.  j a va2  s .c om
    List<String> woIdConceptNames = TypeUtil
            .getConcepts(jcas).stream().filter(concept -> TypeUtil.getConceptIds(concept).isEmpty())
            .map(TypeUtil::getConceptNames).map(names -> names.stream()
                    .map(GoPubMedConceptRetrievalScorer::normalizeQuoteName).collect(joining(" ")))
            .collect(toList());
    List<String> cmentionNames = TypeUtil.getConceptMentions(jcas).stream().map(ConceptMention::getMatchedName)
            .map(GoPubMedConceptRetrievalScorer::normalizeQuoteName).collect(toList());
    ExecutorService es = Executors.newCachedThreadPool();
    // execute against all tokens
    String concatenatedTokens = String.join(" ", tokens);
    LOG.debug("Query string: {}", concatenatedTokens);
    for (BioASQUtil.Ontology ontology : BioASQUtil.Ontology.values()) {
        es.execute(() -> {
            try {
                List<ConceptSearchResult> results = BioASQUtil.searchOntology(service, jcas, concatenatedTokens,
                        pages, hits, ontology);
                String conf = "tokens_concatenated@" + ontology.name();
                updateFeatureTable(results, conf);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
    // execute against concatenated concept names
    String concatenatedConceptNames = String.join(" ", Iterables.concat(wIdConceptNames, woIdConceptNames));
    LOG.debug("Query string: {}", concatenatedConceptNames);
    for (BioASQUtil.Ontology ontology : BioASQUtil.Ontology.values()) {
        es.execute(() -> {
            try {
                List<ConceptSearchResult> results = BioASQUtil.searchOntology(service, jcas,
                        concatenatedConceptNames, pages, hits, ontology);
                String conf = "concept_names_concatenated@" + ontology.name();
                updateFeatureTable(results, conf);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
    // execute against concatenated concept mentions
    String concatenatedCmentions = String.join(" ", cmentionNames);
    LOG.debug("Query string: {}", concatenatedCmentions);
    for (BioASQUtil.Ontology ontology : BioASQUtil.Ontology.values()) {
        es.execute(() -> {
            try {
                List<ConceptSearchResult> results = BioASQUtil.searchOntology(service, jcas,
                        concatenatedCmentions, pages, hits, ontology);
                String conf = "cmention_names_concatenated@" + ontology.name();
                updateFeatureTable(results, conf);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
    // execute against each concept name whose has an ID
    for (String conceptName : wIdConceptNames) {
        LOG.debug("Query string: {}", conceptName);
        for (BioASQUtil.Ontology ontology : BioASQUtil.Ontology.values()) {
            es.execute(() -> {
                try {
                    List<ConceptSearchResult> results = BioASQUtil.searchOntology(service, jcas, conceptName,
                            pages, hits, ontology);
                    String conf = "w_id_concept_names_individual@" + ontology.name();
                    updateFeatureTable(results, conf);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
    // execute against each concept name whose has no ID
    for (String conceptName : woIdConceptNames) {
        LOG.debug("Query string: {}", conceptName);
        for (BioASQUtil.Ontology ontology : BioASQUtil.Ontology.values()) {
            es.execute(() -> {
                try {
                    List<ConceptSearchResult> results = BioASQUtil.searchOntology(service, jcas, conceptName,
                            pages, hits, ontology);
                    String conf = "wo_id_concept_names_individual@" + ontology.name();
                    updateFeatureTable(results, conf);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
    // execute against each concept mention
    for (String cmentionName : cmentionNames) {
        LOG.debug("Query string: {}", cmentionName);
        for (BioASQUtil.Ontology ontology : BioASQUtil.Ontology.values()) {
            es.execute(() -> {
                try {
                    List<ConceptSearchResult> results = BioASQUtil.searchOntology(service, jcas, cmentionName,
                            pages, hits, ontology);
                    String conf = "cmention_names_individual@" + ontology.name();
                    updateFeatureTable(results, conf);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
    es.shutdown();
    try {
        if (!es.awaitTermination(timeout, TimeUnit.MINUTES)) {
            LOG.warn("Timeout occurs for one or some concept retrieval services.");
        }
    } catch (InterruptedException e) {
        throw new AnalysisEngineProcessException(e);
    }
    confs = uri2conf2score.columnKeySet();
}