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:io.github.retz.inttest.RetzIntTest.java

protected void verifyCommand(String[] command) throws Exception {
    String result = container.system(command);
    System.err.println(String.join(" ", command) + " => " + result);
    assertFalse(result, result.contains("ERROR"));
    assertFalse(result, result.contains("Error"));
    assertFalse(result, result.contains("Exception"));
}

From source file:io.github.retz.inttest.RetzIntTest.java

protected void verifyCommandFails(String[] command, String word) throws Exception {
    String result = container.system(command);
    System.err.println(String.join(" ", command) + " => " + result);
    assertTrue(result, result.contains(word));
}

From source file:com.orange.ngsi2.client.Ngsi2Client.java

private void addParam(UriComponentsBuilder builder, String key, Collection<? extends CharSequence> value) {
    if (!nullOrEmpty(value)) {
        builder.queryParam(key, String.join(",", value));
    }//from   w  ww . j a  v a 2  s.  c  o  m
}

From source file:org.graylog2.indexer.indices.Indices.java

/**
 * Retrieve the response for the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-indices.html">cat indices</a> request from Elasticsearch.
 *
 * @param fields The fields to show, see <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-indices.html">cat indices API</a>.
 * @return A {@link JsonArray} with the result of the cat indices request.
 *///from   w ww .  ja v a 2 s .c  om
private JsonArray catIndices(Collection<String> indices, String... fields) {
    final String fieldNames = String.join(",", fields);
    final Cat request = new Cat.IndicesBuilder().addIndex(indices).setParameter("h", fieldNames).build();
    final CatResult response = JestUtils.execute(jestClient, request,
            () -> "Unable to read information for indices " + indices);
    return Optional.of(response.getJsonObject()).map(json -> GsonUtils.asJsonArray(json.get("result")))
            .orElse(new JsonArray());
}

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

public void testOpenIndex() {
    String[] indices = randomIndicesNames(1, 5);
    OpenIndexRequest openIndexRequest = new OpenIndexRequest(indices);
    openIndexRequest.indices(indices);//  ww  w  . j a v  a2 s.  c  om

    Map<String, String> expectedParams = new HashMap<>();
    setRandomTimeout(openIndexRequest::timeout, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams);
    setRandomMasterTimeout(openIndexRequest, expectedParams);
    setRandomIndicesOptions(openIndexRequest::indicesOptions, openIndexRequest::indicesOptions, expectedParams);
    setRandomWaitForActiveShards(openIndexRequest::waitForActiveShards, expectedParams);

    Request request = RequestConverters.openIndex(openIndexRequest);
    StringJoiner endpoint = new StringJoiner("/", "/", "").add(String.join(",", indices)).add("_open");
    assertThat(endpoint.toString(), equalTo(request.getEndpoint()));
    assertThat(expectedParams, equalTo(request.getParameters()));
    assertThat(request.getMethod(), equalTo(HttpPost.METHOD_NAME));
    assertThat(request.getEntity(), nullValue());
}

From source file:org.graylog2.indexer.indices.Indices.java

public Set<String> getReopenedIndices(final Collection<String> indices) {
    final String indexList = String.join(",", indices);
    final State request = new State.Builder().withMetadata().indices(indexList).build();

    final JestResult jestResult = JestUtils.execute(jestClient, request,
            () -> "Couldn't read cluster state for reopened indices " + indices);
    final JsonObject indicesJson = getClusterStateIndicesMetadata(jestResult.getJsonObject());
    final ImmutableSet.Builder<String> reopenedIndices = ImmutableSet.builder();

    for (Map.Entry<String, JsonElement> entry : indicesJson.entrySet()) {
        final String indexName = entry.getKey();
        final JsonElement value = entry.getValue();
        if (value.isJsonObject()) {
            final JsonObject indexSettingsJson = value.getAsJsonObject();
            final JsonObject indexSettings = getIndexSettings(indexSettingsJson, indexName);
            if (checkForReopened(indexSettings)) {
                reopenedIndices.add(indexName);
            }//ww w  .j a  v a2 s.  c  om
        }
    }

    return reopenedIndices.build();
}

From source file:com.oneops.inductor.WorkOrderExecutor.java

/**
 * Calls local or remote chef to do recipe [ciClassname::wo.getRfcCi().rfcAction]
 *
 * @param wo CmsWorkOrderSimple//from w w  w  .  j av  a 2  s  .  c  om
 */
private void runWorkOrder(CmsWorkOrderSimple wo) {

    // check to see if should be remote by looking at proxy
    Boolean isRemote = isRemoteChefCall(wo);

    // file-based request keyed by deployment record id - remotely by
    // class.ciName for ease of debug
    String remoteFileName = getRemoteFileName(wo);
    String fileName = config.getDataDir() + "/" + wo.getDpmtRecordId() + ".json";
    logger.info("writing config to: " + fileName + " remote: " + remoteFileName);
    // assume failed; gets set to COMPLETE at the end
    wo.setDpmtRecordState(FAILED);
    String appName = normalizeClassName(wo);
    String logKey = getLogKey(wo);
    logger.info(logKey + " Inductor: " + config.getIpAddr());
    wo.putSearchTag("inductor", config.getIpAddr());

    writeChefRequest(wo, fileName);

    String cookbookPath = getCookbookPath(wo.getRfcCi().getCiClassName());
    logger.info("cookbookPath: " + cookbookPath);

    Set<String> serviceCookbookPaths = null;

    // sync cookbook and chef json request to remote site
    String host = null;
    String user = "oneops";

    String keyFile = null;
    String port = "22";

    if (isRemote) {

        host = getWorkOrderHost(wo, logKey);

        try {
            keyFile = writePrivateKey(wo);
        } catch (KeyNotFoundException e) {
            logger.error(e.getMessage());
            return;
        }
        if (host.contains(":")) {
            String[] parts = host.split(":");
            host = parts[0];
            port = parts[1];
            logger.info("using port from " + config.getIpAttribute());
        }

        long rsyncStartTime = System.currentTimeMillis();
        String[] rsyncCmdLineWithKey = rsyncCmdLine.clone();
        rsyncCmdLineWithKey[4] += "-p " + port + " -qi " + keyFile;

        // return with failure if empty
        if (host == null || host.isEmpty()) {
            wo.setComments("failed : missing host/ip cannot connect");
            removeFile(wo, keyFile);
            return;
        }

        String rfcAction = wo.getRfcCi().getRfcAction();

        logger.info("rfc: " + wo.getRfcCi().getRfcId() + ", appName: " + appName + ", rfcAction: " + rfcAction);

        // v2 install base done via compute cookbook
        // compute::remote logic can be removed once v1 packs are decommed
        //skip base install for propagation updates
        if (appName.equalsIgnoreCase(COMPUTE) && rfcAction.equalsIgnoreCase(REMOTE)
                && !isPropagationUpdate(wo)) {

            logger.info(logKey + " ### BASE INSTALL");
            wo.setComments("");
            runBaseInstall(processRunner, wo, host, port, logKey, keyFile);
            if (!wo.getComments().isEmpty()) {
                logger.info(logKey + " failed base install.");
                return;
            }
        }
        String baseDir = config.getCircuitDir().replace("packer", cookbookPath);
        String components = baseDir + "/components";
        String destination = "/home/" + user + "/" + cookbookPath;

        // always sync base cookbooks/modules
        String[] cmdLine = (String[]) ArrayUtils.addAll(rsyncCmdLineWithKey,
                new String[] { components, user + "@" + host + ":" + destination });
        logger.info(logKey + " ### SYNC BASE: " + components);

        if (!host.equals(TEST_HOST)) {
            ProcessResult result = processRunner
                    .executeProcessRetry(new ExecutionContext(wo, cmdLine, logKey, retryCount));
            if (result.getResultCode() > 0) {
                if (DELETE.equals(wo.getRfcCi().getRfcAction())) {
                    List<CmsRfcCISimple> managedViaRfcs = wo.getPayLoad().get(MANAGED_VIA);
                    if (managedViaRfcs != null && managedViaRfcs.size() > 0
                            && DELETE.equals(managedViaRfcs.get(0).getRfcAction())) {
                        if (failOnDeleteFailure(wo)) {
                            logger.info(logKey
                                    + "wo failed due to unreachable compute, this component is set to fail on delete failures");
                        } else {
                            logger.warn(logKey
                                    + "wo failed due to unreachable compute, but marking ok due to ManagedVia rfcAction==delete");
                            wo.setDpmtRecordState(COMPLETE);
                        }
                    } else {
                        wo.setComments("FATAL: "
                                + generateRsyncErrorMessage(result.getResultCode(), host + ":" + port));
                    }
                } else {
                    wo.setComments(
                            "FATAL: " + generateRsyncErrorMessage(result.getResultCode(), host + ":" + port));
                }

                handleRsyncFailure(wo, keyFile);
                return;
            }
        }

        // rsync exec-order shared
        String sharedComponents = config.getCircuitDir().replace("packer", "shared/");
        destination = "/home/" + user + "/shared/";
        cmdLine = (String[]) ArrayUtils.addAll(rsyncCmdLineWithKey,
                new String[] { sharedComponents, user + "@" + host + ":" + destination });
        logger.info(logKey + " ### SYNC SHARED: " + sharedComponents);

        if (!host.equals(TEST_HOST)) {
            ProcessResult result = processRunner
                    .executeProcessRetry(new ExecutionContext(wo, cmdLine, logKey, retryCount));
            if (result.getResultCode() > 0) {
                inductorStat.addRsyncFailed();
                wo.setComments(
                        "FATAL: " + generateRsyncErrorMessage(result.getResultCode(), host + ":" + port));
                handleRsyncFailure(wo, keyFile);
                return;
            }
        }

        serviceCookbookPaths = syncServiceCookbooks(wo, cookbookPath, user, rsyncCmdLineWithKey, host, port,
                logKey, keyFile);

        // put workorder
        cmdLine = (String[]) ArrayUtils.addAll(rsyncCmdLineWithKey,
                new String[] { fileName, user + "@" + host + ":" + remoteFileName });
        logger.info(logKey + " ### SYNC: " + remoteFileName);
        if (!host.equals(TEST_HOST)) {
            ProcessResult result = processRunner
                    .executeProcessRetry(new ExecutionContext(wo, cmdLine, logKey, retryCount));
            if (result.getResultCode() > 0) {
                wo.setComments(
                        "FATAL: " + generateRsyncErrorMessage(result.getResultCode(), host + ":" + port));
                handleRsyncFailure(wo, keyFile);
                return;
            }
        }
        wo.putSearchTag(CmsConstants.INDUCTOR_RSYNC_TIME,
                Long.toString(System.currentTimeMillis() - rsyncStartTime));
    }

    // run the chef command
    String[] cmd = null;
    if (isRemote) {
        String vars = getProxyEnvVars(wo);
        // exec-order.rb takes -d switch and 3 args: impl, json node
        // structure w/ work/actionorder, and cookbook path
        String debugFlag = "";
        if (isDebugEnabled(wo)) {
            debugFlag = "-d";
        }

        String additionalCookbookPaths = "";
        if (serviceCookbookPaths != null && serviceCookbookPaths.size() > 0) {
            additionalCookbookPaths = String.join(",", serviceCookbookPaths);
        }

        String remoteCmd = "sudo " + vars + " shared/exec-order.rb " + wo.getRfcCi().getImpl() + " "
                + remoteFileName + " " + cookbookPath + " " + additionalCookbookPaths + " " + debugFlag;

        cmd = (String[]) ArrayUtils.addAll(sshCmdLine,
                new String[] { keyFile, "-p " + port, user + "@" + host, remoteCmd });
        logger.info(logKey + " ### EXEC: " + user + "@" + host + " " + remoteCmd);
        int woRetryCount = getRetryCountForWorkOrder(wo);
        if (!host.equals(TEST_HOST)) {
            ProcessResult result = processRunner
                    .executeProcessRetry(new ExecutionContext(wo, cmd, logKey, woRetryCount));

            // set the result status
            if (result.getResultCode() != 0) {
                inductorStat.addWoFailed();
                // mark as complete when rfc and managed_via is DELETE
                if (DELETE.equals(wo.getRfcCi().getRfcAction())) {
                    List<CmsRfcCISimple> managedViaRfcs = wo.getPayLoad().get(MANAGED_VIA);
                    if (managedViaRfcs != null && managedViaRfcs.size() > 0
                            && DELETE.equals(managedViaRfcs.get(0).getRfcAction())) {
                        if (failOnDeleteFailure(wo)) {
                            logger.info(logKey + "wo failed, this component is set to fail on delete failures");
                        } else {
                            logger.warn(
                                    logKey + "wo failed, but marking ok due to ManagedVia rfcAction==delete");
                            wo.setDpmtRecordState(COMPLETE);
                        }
                    }
                } else {
                    String comments = getCommentsFromResult(result);
                    logger.error(logKey + comments);
                    wo.setComments(comments);
                }

                removeRemoteWorkOrder(wo, keyFile, processRunner);
                removeFile(wo, keyFile);
                copySearchTagsFromResult(wo, result);
                return;
            }
            // remove remote workorder for success and failure.
            removeRemoteWorkOrder(wo, keyFile, processRunner);
            setResultCi(result, wo);
        }

        wo.setDpmtRecordState(COMPLETE);
        removeFile(wo, keyFile);

    } else {
        runLocalWorkOrder(processRunner, wo, appName, logKey, fileName, cookbookPath);
    }
    if (!isDebugEnabled(wo))
        removeFile(fileName);
}

From source file:controllers.nwbib.Application.java

/**
 * @param q Query to search in all fields
 * @param person Query for a person associated with the resource
 * @param name Query for the resource name (title)
 * @param subject Query for the resource subject
 * @param id Query for the resource id/*  ww w .  j  av  a2s. c  om*/
 * @param publisher Query for the resource publisher
 * @param issued Query for the resource issued year
 * @param medium Query for the resource medium
 * @param nwbibspatial Query for the resource nwbibspatial classification
 * @param nwbibsubject Query for the resource nwbibsubject classification
 * @param from The page start (offset of page of resource to return)
 * @param size The page size (size of page of resource to return)
 * @param owner Owner filter for resource queries
 * @param t Type filter for resource queries
 * @param field The facet field (the field to facet over)
 * @param sort Sorting order for results ("newest", "oldest", "" -> relevance)
 * @param set The set, overrides the default NWBib set if not empty
 * @param location A polygon describing the subject area of the resources
 * @param word A word, a concept from the hbz union catalog
 * @param corporation A corporation associated with the resource
 * @param raw A query string that's directly (unprocessed) passed to ES
 * @return The search results
 */
public static Promise<Result> facets(String q, String person, String name, String subject, String id,
        String publisher, String issued, String medium, String nwbibspatial, String nwbibsubject, int from,
        int size, String owner, String t, String field, String sort, String set, String location, String word,
        String corporation, String raw) {

    String key = String.format("facets.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s", field, q, person,
            name, id, publisher, set, location, word, corporation, raw, subject, issued, medium, nwbibspatial,
            nwbibsubject, owner, t);
    Result cachedResult = (Result) Cache.get(key);
    if (cachedResult != null) {
        return Promise.promise(() -> cachedResult);
    }

    String labelTemplate = "<span class='%s'/>&nbsp;%s (%s)";

    Function<JsonNode, Pair<JsonNode, String>> toLabel = json -> {
        String term = json.get("term").asText();
        int count = json.get("count").asInt();
        String icon = Lobid.facetIcon(Arrays.asList(term), field);
        String label = Lobid.facetLabel(Arrays.asList(term), field, "");
        String fullLabel = String.format(labelTemplate, icon, label, count);
        return Pair.of(json, fullLabel);
    };

    Predicate<Pair<JsonNode, String>> labelled = pair -> {
        JsonNode json = pair.getLeft();
        String label = pair.getRight();
        int count = json.get("count").asInt();
        return (!label.contains("http") || label.contains("nwbib"))
                && label.length() > String.format(labelTemplate, "", "", count).length();
    };

    Collator collator = Collator.getInstance(Locale.GERMAN);
    Comparator<Pair<JsonNode, String>> sorter = (p1, p2) -> {
        String t1 = p1.getLeft().get("term").asText();
        String t2 = p2.getLeft().get("term").asText();
        boolean t1Current = current(subject, medium, nwbibspatial, nwbibsubject, owner, t, field, t1, raw);
        boolean t2Current = current(subject, medium, nwbibspatial, nwbibsubject, owner, t, field, t2, raw);
        if (t1Current == t2Current) {
            if (!field.equals(ISSUED_FIELD)) {
                Integer c1 = p1.getLeft().get("count").asInt();
                Integer c2 = p2.getLeft().get("count").asInt();
                return c2.compareTo(c1);
            }
            String l1 = p1.getRight().substring(p1.getRight().lastIndexOf('>') + 1);
            String l2 = p2.getRight().substring(p2.getRight().lastIndexOf('>') + 1);
            return collator.compare(l1, l2);
        }
        return t1Current ? -1 : t2Current ? 1 : 0;
    };

    Function<Pair<JsonNode, String>, String> toHtml = pair -> {
        JsonNode json = pair.getLeft();
        String fullLabel = pair.getRight();
        String term = json.get("term").asText();
        if (field.equals(SUBJECT_LOCATION_FIELD)) {
            GeoPoint point = new GeoPoint(term);
            term = String.format("%s,%s", point.getLat(), point.getLon());
        }
        String mediumQuery = !field.equals(MEDIUM_FIELD) //
                ? medium
                : queryParam(medium, term);
        String typeQuery = !field.equals(TYPE_FIELD) //
                ? t
                : queryParam(t, term);
        String ownerQuery = !field.equals(ITEM_FIELD) //
                ? owner
                : withoutAndOperator(queryParam(owner, term));
        String nwbibsubjectQuery = !field.equals(NWBIB_SUBJECT_FIELD) //
                ? nwbibsubject
                : queryParam(nwbibsubject, term);
        String nwbibspatialQuery = !field.equals(NWBIB_SPATIAL_FIELD) //
                ? nwbibspatial
                : queryParam(nwbibspatial, term);
        String rawQuery = !field.equals(COVERAGE_FIELD) //
                ? raw
                : rawQueryParam(raw, term);
        String locationQuery = !field.equals(SUBJECT_LOCATION_FIELD) //
                ? location
                : term;
        String subjectQuery = !field.equals(SUBJECT_FIELD) //
                ? subject
                : queryParam(subject, term);
        String issuedQuery = !field.equals(ISSUED_FIELD) //
                ? issued
                : queryParam(issued, term);

        boolean current = current(subject, medium, nwbibspatial, nwbibsubject, owner, t, field, term, raw);

        String routeUrl = routes.Application.search(q, person, name, subjectQuery, id, publisher, issuedQuery,
                mediumQuery, nwbibspatialQuery, nwbibsubjectQuery, from, size, ownerQuery, typeQuery,
                sort(sort, nwbibspatialQuery, nwbibsubjectQuery, subjectQuery), false, set, locationQuery, word,
                corporation, rawQuery).url();

        String result = String.format(
                "<li " + (current ? "class=\"active\"" : "") + "><a class=\"%s-facet-link\" href='%s'>"
                        + "<input onclick=\"location.href='%s'\" class=\"facet-checkbox\" "
                        + "type=\"checkbox\" %s>&nbsp;%s</input>" + "</a></li>",
                Math.abs(field.hashCode()), routeUrl, routeUrl, current ? "checked" : "", fullLabel);

        return result;
    };

    Promise<Result> promise = Lobid.getFacets(q, person, name, subject, id, publisher, issued, medium,
            nwbibspatial, nwbibsubject, owner, field, t, set, location, word, corporation, raw).map(json -> {
                Stream<JsonNode> stream = StreamSupport.stream(
                        Spliterators.spliteratorUnknownSize(json.findValue("entries").elements(), 0), false);
                if (field.equals(ITEM_FIELD)) {
                    stream = preprocess(stream);
                }
                String labelKey = String.format(
                        "facets-labels.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s.%s", field, raw, q,
                        person, name, id, publisher, set, word, corporation, subject, issued, medium,
                        nwbibspatial, nwbibsubject, raw, field.equals(ITEM_FIELD) ? "" : owner, t, location);

                @SuppressWarnings("unchecked")
                List<Pair<JsonNode, String>> labelledFacets = (List<Pair<JsonNode, String>>) Cache
                        .get(labelKey);
                if (labelledFacets == null) {
                    labelledFacets = stream.map(toLabel).filter(labelled).collect(Collectors.toList());
                    Cache.set(labelKey, labelledFacets, ONE_DAY);
                }
                return labelledFacets.stream().sorted(sorter).map(toHtml).collect(Collectors.toList());
            }).map(lis -> ok(String.join("\n", lis)));
    promise.onRedeem(r -> Cache.set(key, r, ONE_DAY));
    return promise;
}

From source file:com.spankingrpgs.model.characters.GameCharacter.java

/**
 * Returns a description of the character. If no description was provided at construction, builds a simple
 * description based on the values in appearance
 *
 * @return A description of the character
 *//*from w w  w  . j av  a2s.  c  o  m*/
@JsonIgnore
public String getDescription() {
    if (description == null) {
        return String.join("\n", appearance.entrySet().stream()
                .map(entry -> entry.getKey() + ": " + entry.getValue()).collect(Collectors.toList()));
    } else {
        return description;
    }
}

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

public void testCloseIndex() {
    String[] indices = randomIndicesNames(1, 5);
    CloseIndexRequest closeIndexRequest = new CloseIndexRequest(indices);

    Map<String, String> expectedParams = new HashMap<>();
    setRandomTimeout(closeIndexRequest::timeout, AcknowledgedRequest.DEFAULT_ACK_TIMEOUT, expectedParams);
    setRandomMasterTimeout(closeIndexRequest, expectedParams);
    setRandomIndicesOptions(closeIndexRequest::indicesOptions, closeIndexRequest::indicesOptions,
            expectedParams);//from w  w  w .  j  av a 2  s .  co  m

    Request request = RequestConverters.closeIndex(closeIndexRequest);
    StringJoiner endpoint = new StringJoiner("/", "/", "").add(String.join(",", indices)).add("_close");
    assertThat(endpoint.toString(), equalTo(request.getEndpoint()));
    assertThat(expectedParams, equalTo(request.getParameters()));
    assertThat(request.getMethod(), equalTo(HttpPost.METHOD_NAME));
    assertThat(request.getEntity(), nullValue());
}