Example usage for java.util.stream Collectors joining

List of usage examples for java.util.stream Collectors joining

Introduction

In this page you can find the example usage for java.util.stream Collectors joining.

Prototype

public static Collector<CharSequence, ?, String> joining(CharSequence delimiter) 

Source Link

Document

Returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.

Usage

From source file:io.mindmaps.graql.GraqlShell.java

private static String loadQuery(String filePath) throws IOException {
    List<String> lines = Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8);
    return lines.stream().collect(Collectors.joining("\n"));
}

From source file:com.thoughtworks.go.apiv1.securityauthconfig.SecurityAuthConfigControllerV1.java

private String etagFor(SecurityAuthConfigs securityAuthConfigs) {
    String md5OfAllAuthConfigs = securityAuthConfigs.stream().map(this::etagFor)
            .collect(Collectors.joining("/"));

    return CachedDigestUtils.md5Hex(md5OfAllAuthConfigs);
}

From source file:com.thinkbiganalytics.util.PartitionSpec.java

/**
 * Generates a select statement that will find all unique data partitions in the source table.
 *
 * @param sourceSchema       the schema or database name of the source table
 * @param sourceTable        the source table name
 * @param feedPartitionValue the source processing partition value
 *//*from ww  w.j  a va 2s .com*/
public String toDistinctSelectSQL(@Nonnull final String sourceSchema, @Nonnull final String sourceTable,
        @Nonnull final String feedPartitionValue) {
    final String keysWithAliases = keys.stream().map(PartitionKey::getFormulaWithAlias)
            .collect(Collectors.joining(", "));
    return "select " + keysWithAliases + ", count(0) as `tb_cnt` from "
            + HiveUtils.quoteIdentifier(sourceSchema, sourceTable) + " where `processing_dttm` = "
            + HiveUtils.quoteString(feedPartitionValue) + " group by " + keysWithAliases;
}

From source file:co.runrightfast.core.application.event.AppEvent.java

@Override
public String toString() {
    final MoreObjects.ToStringHelper toStringHelper = MoreObjects.toStringHelper(this)
            .add("timestamp", getTimestamp()).add("event", event).add("eventLevel", eventLevel);

    if (StringUtils.isNotBlank(message)) {
        toStringHelper.add("message", message);
    }//from   w  w  w  .j  a  v a2  s.c  o m

    if (CollectionUtils.isNotEmpty(tags)) {
        toStringHelper.add("tags", tags.stream().collect(Collectors.joining(",")));
    }

    if (data != null) {
        toStringHelper.add("data", data.getType());
    }

    if (exception != null) {
        toStringHelper.add("exception", ExceptionUtils.getStackTrace(exception));
    }

    return toStringHelper.toString();

}

From source file:com.linkedin.gradle.python.tasks.ParallelWheelGenerationTask.java

private void updateStatusLine(ProgressLogger progressLogger, int totalSize, int currentPackageCount) {
    String packagesBeingBuilt = currentPackages.stream().collect(Collectors.joining(", "));
    progressLogger.progress(String.format("Building wheel(s) [ %s ] %d of %d", packagesBeingBuilt,
            currentPackageCount, totalSize));
}

From source file:eu.itesla_project.modules.wca.WCATool.java

private static void writeClustersCsv(Map<String, Map<String, WCACluster>> clusterPerContingencyPerBaseCase,
        Set<String> contingencyIds, Path outputCsvFile) throws IOException {
    try (BufferedWriter writer = Files.newBufferedWriter(outputCsvFile, StandardCharsets.UTF_8)) {
        writer.write("base case");
        for (String contingencyId : contingencyIds) {
            writer.write(CSV_SEPARATOR);
            writer.write("cluster num " + contingencyId);
        }/*from w  ww. j  a v  a2 s  .  c o m*/
        for (String contingencyId : contingencyIds) {
            writer.write(CSV_SEPARATOR);
            writer.write("cluster cause " + contingencyId);
        }
        writer.newLine();
        for (Map.Entry<String, Map<String, WCACluster>> entry : clusterPerContingencyPerBaseCase.entrySet()) {
            String baseCaseName = entry.getKey();
            Map<String, WCACluster> clusterNumPerContingency = entry.getValue();
            writer.write(baseCaseName);
            for (String contingencyId : contingencyIds) {
                WCACluster cluster = clusterNumPerContingency.get(contingencyId);
                writer.write(CSV_SEPARATOR);
                if (cluster != null) {
                    writer.write(cluster.getNum().toIntValue() + " (" + cluster.getOrigin() + ")");
                } else {
                    writer.write("");
                }
            }
            for (String contingencyId : contingencyIds) {
                WCACluster cluster = clusterNumPerContingency.get(contingencyId);
                writer.write(CSV_SEPARATOR);
                if (cluster != null) {
                    writer.write(cluster.getCauses().stream().collect(Collectors.joining("|")));
                } else {
                    writer.write("");
                }
            }
            writer.newLine();
        }
    }
}

From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java

@Override
public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException {

    try {/*w w  w.j  a v  a2s. co m*/
        final GVBufferPropertyFormatter formatter = new GVBufferPropertyFormatter(gvBuffer);

        String expandedUrl = formatter.format(url);
        String querystring = "";

        if (!params.isEmpty()) {

            querystring = params.entrySet().stream().map(
                    e -> formatter.formatAndEncode(e.getKey()) + "=" + formatter.formatAndEncode(e.getValue()))
                    .collect(Collectors.joining("&"));

            expandedUrl = expandedUrl.concat("?").concat(querystring);
        }

        StringBuffer callDump = new StringBuffer();
        callDump.append("Performing RestCallOperation " + name).append("\n        ").append("URL: ")
                .append(expandedUrl);

        URL requestUrl = new URL(expandedUrl);

        HttpURLConnection httpURLConnection;
        if (truststorePath != null && expandedUrl.startsWith("https://")) {
            httpURLConnection = openSecureConnection(requestUrl);
        } else {
            httpURLConnection = (HttpURLConnection) requestUrl.openConnection();
        }
        callDump.append("\n        ").append("Method: " + method);

        callDump.append("\n        ").append("Connection timeout: " + connectionTimeout);
        callDump.append("\n        ").append("Read timeout: " + readTimeout);

        httpURLConnection.setRequestMethod(method);
        httpURLConnection.setConnectTimeout(connectionTimeout);
        httpURLConnection.setReadTimeout(readTimeout);

        for (Entry<String, String> header : headers.entrySet()) {
            String k = formatter.format(header.getKey());
            String v = formatter.format(header.getValue());
            httpURLConnection.setRequestProperty(k, v);
            callDump.append("\n        ").append("Header: " + k + "=" + v);
            if ("content-type".equalsIgnoreCase(k) && "application/x-www-form-urlencoded".equalsIgnoreCase(v)) {
                body = querystring;
            }

        }

        if (sendGVBufferObject && gvBuffer.getObject() != null) {
            byte[] requestData;
            if (gvBuffer.getObject() instanceof byte[]) {
                requestData = (byte[]) gvBuffer.getObject();
            } else {
                requestData = gvBuffer.getObject().toString().getBytes();

            }
            httpURLConnection.setRequestProperty("Content-Length", Integer.toString(requestData.length));
            callDump.append("\n        ").append("Content-Length: " + requestData.length);
            callDump.append("\n        ").append("Request body: binary");
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(requestData);

            dataOutputStream.flush();
            dataOutputStream.close();

        } else if (Objects.nonNull(body) && body.length() > 0) {

            String expandedBody = formatter.format(body);
            callDump.append("\n        ").append("Request body: " + expandedBody);
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
            outputStreamWriter.write(expandedBody);
            outputStreamWriter.flush();
            outputStreamWriter.close();

        }

        httpURLConnection.connect();

        InputStream responseStream = null;

        try {
            httpURLConnection.getResponseCode();
            responseStream = httpURLConnection.getInputStream();
        } catch (IOException connectionFail) {
            responseStream = httpURLConnection.getErrorStream();
        }

        for (Entry<String, List<String>> header : httpURLConnection.getHeaderFields().entrySet()) {
            if (Objects.nonNull(header.getKey()) && Objects.nonNull(header.getValue())) {
                gvBuffer.setProperty(RESPONSE_HEADER_PREFIX.concat(header.getKey().toUpperCase()),
                        header.getValue().stream().collect(Collectors.joining(";")));
            }
        }

        if (responseStream != null) {

            byte[] responseData = IOUtils.toByteArray(responseStream);
            String responseContentType = Optional
                    .ofNullable(gvBuffer.getProperty(RESPONSE_HEADER_PREFIX.concat("CONTENT-TYPE"))).orElse("");

            if (responseContentType.startsWith("application/json")
                    || responseContentType.startsWith("application/javascript")) {
                gvBuffer.setObject(new String(responseData, "UTF-8"));
            } else {
                gvBuffer.setObject(responseData);
            }

        } else { // No content
            gvBuffer.setObject(null);
        }

        gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(httpURLConnection.getResponseCode()));
        gvBuffer.setProperty(RESPONSE_MESSAGE,
                Optional.ofNullable(httpURLConnection.getResponseMessage()).orElse("NULL"));

        httpURLConnection.disconnect();

    } catch (Exception exc) {
        throw new CallException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                        { "tid", gvBuffer.getId().toString() }, { "message", exc.getMessage() } },
                exc);
    }
    return gvBuffer;
}

From source file:io.wcm.caconfig.extensions.references.impl.ConfigurationReferenceProvider.java

/**
 * Build reference display name from path with:
 * - translating configuration names to labels
 * - omitting configuration bucket names
 * - insert additional spaces so long paths may wrap on multiple lines
 *//*from  www.  jav a 2  s.c o m*/
private static String getReferenceName(Page configPage,
        Map<String, ConfigurationMetadata> configurationMetadatas, Set<String> configurationBuckets) {
    List<String> pathParts = Arrays.asList(StringUtils.split(configPage.getPath(), "/"));
    return pathParts.stream().filter(name -> !configurationBuckets.contains(name)).map(name -> {
        ConfigurationMetadata configMetadata = configurationMetadatas.get(name);
        if (configMetadata != null && configMetadata.getLabel() != null) {
            return configMetadata.getLabel();
        } else {
            return name;
        }
    }).collect(Collectors.joining(" / "));
}

From source file:com.intuit.wasabi.tests.service.priority.BasicPriorityTest.java

@Test(groups = { "priorityListChange" }, dependsOnGroups = { "setup",
        "priorityChange" }, dataProvider = "Application", dataProviderClass = PriorityDataProvider.class)
public void t_priorityListChange(String appName) {
    String exclusion = "{\"experimentIDs\": [\"89659e0b-2ee7-419d-8a4e-42938254d847\","
            + validExperimentsLists.stream().map(s -> "\"" + s.id + "\"").collect(Collectors.joining(","))
            + "]}";
    response = apiServerConnector.doPut("applications/" + appName + "/priorities", exclusion);
    assertReturnCode(response, HttpStatus.SC_NO_CONTENT);
    response = apiServerConnector.doGet("applications/" + appName + "/priorities");
    LOGGER.debug("output: " + response.asString());
    Type listType = new TypeToken<Map<String, ArrayList<Map<String, Object>>>>() {
    }.getType();//  www  . j a  va2  s .c  om
    Map<String, List<Map<String, Object>>> result = new Gson().fromJson(response.asString(), listType);
    List<Map<String, Object>> prioritizedExperiments = result.get("prioritizedExperiments");
    Assert.assertEquals(prioritizedExperiments.size(), 5);
}

From source file:it.greenvulcano.gvesb.adapter.http.mapping.ForwardHttpServletMapping.java

@SuppressWarnings("deprecation")
@Override//ww  w  .  j ava  2  s . co m
public void handleRequest(String methodName, HttpServletRequest req, HttpServletResponse resp)
        throws InboundHttpResponseException {

    logger.debug("BEGIN forward: " + req.getRequestURI());

    final HttpURLConnection httpConnection = (HttpURLConnection) connection;
    ;

    try {

        httpConnection.setRequestMethod(methodName);
        httpConnection.setReadTimeout(soTimeout);
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);

        if (dump) {
            StringBuffer sb = new StringBuffer();
            DumpUtils.dump(req, sb);
            logger.info(sb.toString());
        }

        String mapping = req.getPathInfo();
        if (mapping == null) {
            mapping = "/";
        }
        String destPath = contextPath + mapping;
        String queryString = req.getQueryString();
        if (queryString != null) {
            destPath += "?" + queryString;
        }
        if (!destPath.startsWith("/")) {
            destPath = "/" + destPath;
        }
        logger.info("Resulting QueryString: " + destPath);

        Collections.list(req.getHeaderNames()).forEach(headerName -> {
            httpConnection.setRequestProperty(headerName,
                    Collections.list(req.getHeaders(headerName)).stream().collect(Collectors.joining(";")));
        });

        if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
            httpConnection.setDoOutput(true);
            IOUtils.copy(req.getInputStream(), httpConnection.getOutputStream());

        }

        httpConnection.connect();
        int status = httpConnection.getResponseCode();

        resp.setStatus(status, httpConnection.getResponseMessage());

        httpConnection.getHeaderFields().entrySet().stream().forEach(header -> {
            resp.addHeader(header.getKey(), header.getValue().stream().collect(Collectors.joining(";")));
        });

        ByteArrayOutputStream bodyOut = new ByteArrayOutputStream();
        IOUtils.copy(httpConnection.getInputStream(), bodyOut);

        OutputStream out = resp.getOutputStream();
        out.write(bodyOut.toByteArray());
        //IOUtils.copy(method.getResponseBodyAsStream(), out);
        out.flush();
        out.close();

        if (dump) {
            StringBuffer sb = new StringBuffer();
            DumpUtils.dump(resp, bodyOut, sb);
            logger.info(sb.toString());
        }

    } catch (Exception exc) {
        logger.error("ERROR on forwarding: " + req.getRequestURI(), exc);
        throw new InboundHttpResponseException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "message", exc.getMessage() } }, exc);
    } finally {
        try {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
        } catch (Exception exc) {
            logger.warn("Error while releasing connection", exc);
        }
        logger.debug("END forward: " + req.getRequestURI());
    }
}