Example usage for java.util StringJoiner toString

List of usage examples for java.util StringJoiner toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns the current value, consisting of the prefix , the values added so far separated by the delimiter , and the suffix , unless no elements have been added in which case, the prefix + suffix or the emptyValue characters are returned.

Usage

From source file:com.google.gerrit.server.mail.send.OutgoingEmail.java

/**
 * Format and enqueue the message for delivery.
 *
 * @throws EmailException/*from w  w  w. ja v a  2 s.  c om*/
 */
public void send() throws EmailException {
    if (NotifyHandling.NONE.equals(notify) && accountsToNotify.isEmpty()) {
        return;
    }

    if (!args.emailSender.isEnabled()) {
        // Server has explicitly disabled email sending.
        //
        return;
    }

    init();
    if (useHtml()) {
        appendHtml(soyHtmlTemplate("HeaderHtml"));
    }
    format();
    appendText(textTemplate("Footer"));
    if (useHtml()) {
        appendHtml(soyHtmlTemplate("FooterHtml"));
    }

    Set<Address> smtpRcptToPlaintextOnly = new HashSet<>();
    if (shouldSendMessage()) {
        if (fromId != null) {
            final Account fromUser = args.accountCache.get(fromId).getAccount();
            GeneralPreferencesInfo senderPrefs = fromUser.getGeneralPreferencesInfo();

            if (senderPrefs != null && senderPrefs.getEmailStrategy() == CC_ON_OWN_COMMENTS) {
                // If we are impersonating a user, make sure they receive a CC of
                // this message so they can always review and audit what we sent
                // on their behalf to others.
                //
                add(RecipientType.CC, fromId);
            } else if (!accountsToNotify.containsValue(fromId) && rcptTo.remove(fromId)) {
                // If they don't want a copy, but we queued one up anyway,
                // drop them from the recipient lists.
                //
                removeUser(fromUser);
            }
        }
        // Check the preferences of all recipients. If any user has disabled
        // his email notifications then drop him from recipients' list.
        // In addition, check if users only want to receive plaintext email.
        for (Account.Id id : rcptTo) {
            Account thisUser = args.accountCache.get(id).getAccount();
            GeneralPreferencesInfo prefs = thisUser.getGeneralPreferencesInfo();
            if (prefs == null || prefs.getEmailStrategy() == DISABLED) {
                removeUser(thisUser);
            } else if (useHtml() && prefs.getEmailFormat() == EmailFormat.PLAINTEXT) {
                removeUser(thisUser);
                smtpRcptToPlaintextOnly.add(new Address(thisUser.getFullName(), thisUser.getPreferredEmail()));
            }
            if (smtpRcptTo.isEmpty() && smtpRcptToPlaintextOnly.isEmpty()) {
                return;
            }
        }

        // Set Reply-To only if it hasn't been set by a child class
        // Reply-To will already be populated for the message types where Gerrit supports
        // inbound email replies.
        if (!headers.containsKey("Reply-To")) {
            StringJoiner j = new StringJoiner(", ");
            if (fromId != null) {
                Address address = toAddress(fromId);
                if (address != null) {
                    j.add(address.getEmail());
                }
            }
            smtpRcptTo.stream().forEach(a -> j.add(a.getEmail()));
            smtpRcptToPlaintextOnly.stream().forEach(a -> j.add(a.getEmail()));
            setHeader("Reply-To", j.toString());
        }

        String textPart = textBody.toString();
        OutgoingEmailValidationListener.Args va = new OutgoingEmailValidationListener.Args();
        va.messageClass = messageClass;
        va.smtpFromAddress = smtpFromAddress;
        va.smtpRcptTo = smtpRcptTo;
        va.headers = headers;
        va.body = textPart;

        if (useHtml()) {
            va.htmlBody = htmlBody.toString();
        } else {
            va.htmlBody = null;
        }

        for (OutgoingEmailValidationListener validator : args.outgoingEmailValidationListeners) {
            try {
                validator.validateOutgoingEmail(va);
            } catch (ValidationException e) {
                return;
            }
        }

        if (!smtpRcptTo.isEmpty()) {
            // Send multipart message
            args.emailSender.send(va.smtpFromAddress, va.smtpRcptTo, va.headers, va.body, va.htmlBody);
        }

        if (!smtpRcptToPlaintextOnly.isEmpty()) {
            // Send plaintext message
            Map<String, EmailHeader> shallowCopy = new HashMap<>();
            shallowCopy.putAll(headers);
            // Remove To and Cc
            shallowCopy.remove(HDR_TO);
            shallowCopy.remove(HDR_CC);
            for (Address a : smtpRcptToPlaintextOnly) {
                // Add new To
                EmailHeader.AddressList to = new EmailHeader.AddressList();
                to.add(a);
                shallowCopy.put(HDR_TO, to);
            }
            args.emailSender.send(va.smtpFromAddress, smtpRcptToPlaintextOnly, shallowCopy, va.body);
        }
    }
}

From source file:io.mapzone.arena.share.content.ImagePngContentProvider.java

@Override
public ImagePngContent get() {
    ImagePngContent content = new ImagePngContent();

    StringJoiner layers = new StringJoiner(",");
    for (SelectionDescriptor selection : context.selectionDescriptors.get()) {
        layers.add(GeoServerUtils.simpleName(selection.layer.get().label.get()));
        // FIXME, if multilayers are working, remove this break!!!
        //break;/*from www  .  j  a  va  2 s.c  o  m*/
    }
    Envelope bbox = context.boundingBox.get();
    String extent = Joiner.on(",").join((int) bbox.getMinX(), (int) bbox.getMinY(), (int) bbox.getMaxX(),
            (int) bbox.getMaxY());

    String imageUrl = ArenaPlugin.instance().config().getProxyUrl() + GeoServerStarter.ALIAS;
    List<NameValuePair> params = new ArrayList() {
        {
            add(nameValue("SERVICE", "WMS"));
            add(nameValue("VERSION", "1.3.0"));
            add(nameValue("REQUEST", "GetMap"));
            add(nameValue("FORMAT", "image/png"));
            add(nameValue("CRS", "EPSG:3857"));
            add(nameValue("BBOX", extent.toString()));
            add(nameValue("LAYERS", layers.toString()));
        }
    };
    if (!StringUtils.isBlank(ArenaPlugin.instance().config().getServiceAuthToken())) {
        params.add(nameValue("authToken", ArenaPlugin.instance().config().getServiceAuthToken()));
    }
    content.imgWidth = context.displaySize.get().x;
    content.imgHeight = context.displaySize.get().y;

    content.previewWidth = 320;
    content.previewHeight = content.previewWidth * content.imgHeight / content.imgWidth;

    ArrayList previewParams = new ArrayList(params) {
        {
            add(nameValue("WIDTH", content.previewWidth));
            add(nameValue("HEIGHT", content.previewHeight));
        }
    };
    content.previewResource = imageUrl + "?" + URLEncodedUtils.format(previewParams, "UTF-8");

    ArrayList imgParams = new ArrayList(params) {
        {
            add(nameValue("WIDTH", content.imgWidth));
            add(nameValue("HEIGHT", content.imgHeight));
        }
    };
    content.imgResource = imageUrl + "?" + URLEncodedUtils.format(imgParams, "UTF-8");
    return content;
}

From source file:info.archinnov.achilles.internals.codegen.meta.EntityMetaCodeGen.java

private MethodSpec buildStaticColumns(List<FieldMetaSignature> parsingResults, TypeName rawClassType) {
    StringJoiner joiner = new StringJoiner(",");
    parsingResults.stream()/*from   w  w  w .j  ava2  s  .  c om*/
            .filter(x -> (x.context.columnType == ColumnType.STATIC
                    || x.context.columnType == ColumnType.STATIC_COUNTER))
            .map(x -> Tuple2.of(x.context.cqlColumn, x.context.fieldName)).sorted(BY_CQL_NAME_COLUMN_SORTER)
            .map(x -> x._2()).forEach(x -> joiner.add(x));

    return MethodSpec.methodBuilder("getStaticColumns").addAnnotation(Override.class)
            .addModifiers(Modifier.PROTECTED).returns(propertyListType(rawClassType))
            .addStatement("return $T.asList($L)", ARRAYS, joiner.toString()).build();
}

From source file:org.eclipse.winery.tools.copybaragenerator.CopybaraGenerator.java

public String generateCopybaraConfigFile() {
    StringJoiner copybaraConfig = new StringJoiner("\n");
    copybaraConfig.add("urlOrigin = \"https://github.com/OpenTOSCA/tosca-definitions-internal.git\"");
    copybaraConfig.add("urlDestination = \"file:///tmp/copybara/tosca-definitions-public\"");
    copybaraConfig.add("core.workflow(");
    copybaraConfig.add("    name = \"default\",");
    copybaraConfig.add("    origin = git.origin(");
    copybaraConfig.add("        url = urlOrigin,");
    copybaraConfig.add("        ref = \"master\",");
    copybaraConfig.add("    ),");
    copybaraConfig.add("    destination = git.destination(");
    copybaraConfig.add("        url = urlDestination,");
    copybaraConfig.add("        fetch = \"master\",");
    copybaraConfig.add("        push = \"master\",");
    copybaraConfig.add("    ),");
    copybaraConfig// w  ww  .j  a  v  a 2s  .c o  m
            .add("    authoring = authoring.pass_thru(\"OpenTOSCA Bot <opentosca@iaas.uni-stuttgart.de>\"),");
    copybaraConfig.add("    " + generateOriginFilesConfig());
    copybaraConfig.add("    destination_files = glob([\"**\"], exclude = [\"README_INTERNAL.md\"]),");
    copybaraConfig.add(")");
    return copybaraConfig.toString();
}

From source file:ca.osmcanada.osvuploadr.JPMain.java

private void SendAuthTokens(String accessToken, String accessSecret) {
    try {/* www  .j  a va  2  s.  co  m*/
        URL url = new URL(URL_ACCESS);
        URLConnection con = url.openConnection();
        HttpURLConnection http = (HttpURLConnection) con;
        http.setRequestMethod("POST"); // PUT is another valid option
        http.setDoOutput(true);

        Map<String, String> arguments = new HashMap<>();
        arguments.put("request_token", accessToken);
        arguments.put("secret_token", accessSecret);
        System.out.println("accessToken:" + accessToken + "|secret token:" + accessSecret);

        StringJoiner sj = new StringJoiner("&");
        for (Map.Entry<String, String> entry : arguments.entrySet())
            sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
                    + URLEncoder.encode(entry.getValue(), "UTF-8"));
        byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
        int length = out.length;

        http.setFixedLengthStreamingMode(length);
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        http.connect();
        try (OutputStream os = http.getOutputStream()) {
            os.write(out);
            os.close();
        }
        InputStream is = http.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int letti;

        while ((letti = is.read(buf)) > 0)
            baos.write(buf, 0, letti);

        String data = new String(baos.toByteArray());
        http.disconnect();

    } catch (Exception ex) {
        Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ca.osmcanada.osvuploadr.JPMain.java

private void SendFinished(long Sequence_id, String accessToken) {
    try {/*from  w  ww.  ja v a 2s.c om*/
        URL url = new URL(URL_FINISH);
        URLConnection con = url.openConnection();
        HttpURLConnection http = (HttpURLConnection) con;
        http.setRequestMethod("POST"); // PUT is another valid option
        http.setDoOutput(true);

        Map<String, String> arguments = new HashMap<>();
        arguments.put("access_token", accessToken);
        arguments.put("sequenceId", Long.toString(Sequence_id));
        System.out.println("accessToken:" + accessToken + "|sequenceId:" + Long.toString(Sequence_id));

        StringJoiner sj = new StringJoiner("&");
        for (Map.Entry<String, String> entry : arguments.entrySet())
            sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
                    + URLEncoder.encode(entry.getValue(), "UTF-8"));
        byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
        int length = out.length;

        http.setFixedLengthStreamingMode(length);
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        http.connect();
        try (OutputStream os = http.getOutputStream()) {
            os.write(out);
            os.close();
        }
        InputStream is = http.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int letti;

        while ((letti = is.read(buf)) > 0)
            baos.write(buf, 0, letti);

        String data = new String(baos.toByteArray());
        http.disconnect();

    } catch (Exception ex) {
        Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ca.osmcanada.osvuploadr.JPMain.java

private long getSequence(ImageProperties imp, String accessToken) {
    try {/*from  w  ww  . j av a2 s  . co  m*/
        URL url = new URL(URL_SEQUENCE);
        URLConnection con = url.openConnection();
        HttpURLConnection http = (HttpURLConnection) con;
        http.setRequestMethod("POST"); // PUT is another valid option
        http.setDoOutput(true);

        DecimalFormat df = new DecimalFormat("#.##############");
        df.setRoundingMode(RoundingMode.CEILING);
        System.out.println("Getting Sequence ID..");
        Map<String, String> arguments = new HashMap<>();
        arguments.put("uploadSource", "OSVUploadr");
        arguments.put("access_token", accessToken);
        arguments.put("currentCoordinate", df.format(imp.getLatitude()) + "," + df.format(imp.getLongitude()));
        System.out.println(
                "currentCoordinate:" + df.format(imp.getLatitude()) + "," + df.format(imp.getLongitude()));
        StringJoiner sj = new StringJoiner("&");
        for (Map.Entry<String, String> entry : arguments.entrySet())
            sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
                    + URLEncoder.encode(entry.getValue(), "UTF-8"));
        byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
        int length = out.length;
        System.out.println("Sending request:" + sj.toString());

        http.setFixedLengthStreamingMode(length);
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        http.connect();
        try (OutputStream os = http.getOutputStream()) {
            os.write(out);
            os.close();
        }
        System.out.println("Request Sent getting sequence response...");
        InputStream is = http.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int letti;

        while ((letti = is.read(buf)) > 0)
            baos.write(buf, 0, letti);

        String data = new String(baos.toByteArray());
        int start = data.indexOf("\"osv\":{\"sequence\":{\"id\":\"");
        int end = data.indexOf("\"", start + 25);
        System.out.println("Received request:" + data);
        String sequence_id = data.substring(start + 25, end);
        System.out.println("Obtained Sequence ID: sequence_id");
        http.disconnect();
        return Long.parseLong(sequence_id);

    } catch (Exception ex) {
        System.out.println(ex.toString());
        Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex);
    }
    return -1;
}

From source file:ca.osmcanada.osvuploadr.JPMain.java

private String sendForm(String target_url, Map<String, String> arguments, String method,
        List<Cookie> cookielist) {
    try {/*from w  w  w . j  av  a2s  .  c  om*/
        URL url = new URL(target_url);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        //HttpURLConnection http = (HttpURLConnection)con;
        con.setRequestMethod(method); // PUT is another valid option
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        String cookiestr = "";
        if (cookielist != null) {
            if (cookielist.size() > 0) {
                for (Cookie cookie : cookielist) {
                    if (!cookiestr.equals("")) {
                        cookiestr += ";" + cookie.getName() + "=" + cookie.getValue();
                    } else {
                        cookiestr += cookie.getName() + "=" + cookie.getValue();
                    }
                }
                con.setRequestProperty("Cookie", cookiestr);
            }
        }

        con.setReadTimeout(5000);

        StringJoiner sj = new StringJoiner("&");
        for (Map.Entry<String, String> entry : arguments.entrySet())
            sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
                    + URLEncoder.encode(entry.getValue(), "UTF-8"));
        byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
        int length = out.length;

        con.setFixedLengthStreamingMode(length);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        con.setRequestProperty("Accept-Language", "en-us;");
        con.connect();
        try (OutputStream os = con.getOutputStream()) {
            os.write(out);
            os.close();
        }

        boolean redirect = false;
        int status = con.getResponseCode();

        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        if (redirect) {
            String newURL = con.getHeaderField("Location");
            String cookies = con.getHeaderField("Set-Cookie");
            if (cookies == null) {
                cookies = cookiestr;
            }
            con = (HttpURLConnection) new URL(newURL).openConnection();
            con.setRequestProperty("Cookie", cookies);
        }

        InputStream is = con.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int letti;

        while ((letti = is.read(buf)) > 0)
            baos.write(buf, 0, letti);

        String data = new String(baos.toByteArray(), Charset.forName("UTF-8"));
        con.disconnect();

        return data;

    } catch (Exception ex) {
        Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

From source file:io.mapzone.arena.share.content.OpenLayersContentProvider.java

@Override
public OpenLayersContent get() {

    OpenLayersContent content = new OpenLayersContent();
    content.jsressource = JSRESOURCE;/*  ww  w .ja  v  a 2 s  .c  om*/
    content.cssressource = CSSRESOURCE;
    content.body = BODY;

    StringBuffer js = new StringBuffer(MAPJSSTART);

    StringJoiner layers = new StringJoiner(",\n");
    for (SelectionDescriptor selection : context.selectionDescriptors.get()) {
        String layer = replace(LAYERJS, "WMSURL", ArenaPlugin.instance().config().getProxyUrl() + "/ows");
        layer = replace(layer, "LAYER", GeoServerUtils.simpleName(selection.layer.get().label.get()));
        if (!StringUtils.isBlank(ArenaPlugin.instance().config().getServiceAuthToken())) {
            layer = replace(layer, "AUTH",
                    ", 'authToken': '" + ArenaPlugin.instance().config().getServiceAuthToken() + "'");
        } else {
            layer = replace(layer, "AUTH", "");
        }
        //            Envelope envelope = context.boundingBox.get();
        //            StringBuffer extent = new StringBuffer().append( (int)envelope.getMinX() ).append( "," ).append( (int)envelope.getMinY() ).append( "," ).append( (int)envelope.getMaxX() ).append( "," ).append( (int)envelope.getMaxY() );
        //            layer = replace( layer, "EXTENT", extent.toString() );
        layer = replace(layer, "CRS", context.crs.get().getIdentifiers().iterator().next().toString());
        layers.add(layer);
    }
    js.append(layers.toString());

    Coordinate centreCoordinate = context.boundingBox.get().centre();
    StringBuffer centre = new StringBuffer().append((int) centreCoordinate.x).append(",")
            .append((int) centreCoordinate.y);
    String jsend = replace(MAPJSEND, "CENTER", centre.toString());
    jsend = replace(jsend, "RESOLUTION", "" + context.resolution.get().intValue());
    js.append(jsend);

    content.js = js.toString();

    StringBuffer complete = new StringBuffer();
    complete.append("<!DOCTYPE html>\n");
    complete.append("<html>\n");
    complete.append("  <head>\n");
    complete.append("    <title>").append(ArenaConfig.getAppTitle()).append("</title>\n");
    complete.append("    <link rel='stylesheet' href='").append(content.cssressource)
            .append("' type='text/css'>\n");
    complete.append("    <script src='").append(content.jsressource).append("'></script>\n");
    complete.append("  </head>\n");
    complete.append("  <body>\n");
    complete.append("    ").append(content.body).append("\n");
    complete.append("    <script>\n");
    complete.append(content.js);
    complete.append("    </script>\n");
    complete.append("  </body>\n");
    complete.append("</html>\n");

    content.complete = complete.toString();

    return content;
}

From source file:com.microsoft.sqlserver.testframework.DBTable.java

String createTableSql() {
    StringJoiner sb = new StringJoiner(SPACE_CHAR);

    sb.add(CREATE_TABLE);/*from   ww w.  j a v a2s.  c o  m*/
    sb.add(escapedTableName);
    sb.add(OPEN_BRACKET);
    for (int i = 0; i < totalColumns; i++) {
        DBColumn column = getColumn(i);
        sb.add(escapeIdentifier(column.getColumnName()));
        sb.add(column.getSqlType().getName());
        // add precision and scale
        if (VariableLengthType.Precision == column.getSqlType().getVariableLengthType()) {
            sb.add(OPEN_BRACKET);
            sb.add("" + column.getSqlType().getPrecision());
            sb.add(CLOSE_BRACKET);
        } else if (VariableLengthType.Scale == column.getSqlType().getVariableLengthType()) {
            sb.add(OPEN_BRACKET);
            sb.add("" + column.getSqlType().getPrecision());
            sb.add(COMMA);
            sb.add("" + column.getSqlType().getScale());
            sb.add(CLOSE_BRACKET);
        }

        sb.add(COMMA);
    }
    sb.add(CLOSE_BRACKET);
    return sb.toString();
}