Example usage for com.google.common.base Joiner appendTo

List of usage examples for com.google.common.base Joiner appendTo

Introduction

In this page you can find the example usage for com.google.common.base Joiner appendTo.

Prototype

public final StringBuilder appendTo(StringBuilder builder, Object[] parts) 

Source Link

Document

Appends the string representation of each of parts , using the previously configured separator between each, to builder .

Usage

From source file:com.ut.tekir.contact.ContactCaption.java

public static String initCaption(ContactModel model) {
    StringBuilder sb = new StringBuilder();

    Joiner joiner = Joiner.on(" - ");
    joiner.appendTo(sb, typesAsList(model));

    model.setTypeCaption(sb.toString());

    return model.getTypeCaption();
}

From source file:com.google.devtools.build.lib.util.ShellEscaper.java

/**
 * Escapes all strings in {@code argv} individually and joins them into
 * {@code out} using the specified {@link Joiner}. The result is appended
 * directly into {@code out}, without adding a separator.
 *
 * <p>The resulting strings are the same as if escaped one by one using
 * {@link #escapeString(String)}.//www .  j  a v a2 s  .  c  om
 *
 * <p>Example: if the joiner is {@code Joiner.on('|')}, then the input
 * {@code ["abc", "de'f"]} will be escaped as "{@code abc|'de'\''f'}".
 * If {@code out} initially contains "{@code 123}", then the returned
 * {@code Appendable} will contain "{@code 123abc|'de'\''f'}".
 *
 * @param out what the result will be appended to
 * @param argv the strings to escape and join
 * @param joiner the {@link Joiner} to use to join the escaped strings
 * @return the same reference as {@code out}, now containing the the
 *     joined, escaped fragments
 * @throws IOException if an I/O error occurs while appending
 */
public static Appendable escapeJoinAll(Appendable out, Iterable<? extends String> argv, Joiner joiner)
        throws IOException {
    return joiner.appendTo(out, escapeAll(argv));
}

From source file:net.sf.sprockets.net.Uris.java

/**
 * Get a {@code mailto} Uri with the headers. Any null or empty parameters are skipped. The
 * subject and body will be encoded./*from   w ww .  j a  v a2  s .co m*/
 */
public static Uri mailto(List<String> to, List<String> cc, List<String> bcc, String subject, String body) {
    String encSubject = Uri.encode(subject);
    String encBody = Uri.encode(body);
    StringBuilder ssp = new StringBuilder((to != null ? to.size() * 34 : 0) + (cc != null ? cc.size() * 34 : 0)
            + (bcc != null ? bcc.size() * 34 : 0) + (encSubject != null ? encSubject.length() : 0)
            + (encBody != null ? encBody.length() : 0));
    Joiner joiner = Joiner.on(',');
    if (to != null && !to.isEmpty()) {
        joiner.appendTo(ssp, to);
    }
    boolean start = true;
    if (cc != null && !cc.isEmpty()) {
        joiner.appendTo(ssp.append(separator(start)).append("cc="), cc);
        start = false;
    }
    if (bcc != null && !bcc.isEmpty()) {
        joiner.appendTo(ssp.append(separator(start)).append("bcc="), bcc);
        start = false;
    }
    if (!TextUtils.isEmpty(encSubject)) {
        ssp.append(separator(start)).append("subject=").append(encSubject);
        start = false;
    }
    if (!TextUtils.isEmpty(encBody)) {
        ssp.append(separator(start)).append("body=").append(encBody);
        start = false;
    }
    return new Builder().scheme("mailto").encodedOpaquePart(ssp.toString()).build();
}

From source file:com.google.gcloud.examples.resourcemanager.ResourceManagerExample.java

private static void addUsage(String actionName, ResourceManagerAction action, StringBuilder usage) {
    usage.append(actionName);/*from  w w w. j ava  2  s  .  c om*/
    Joiner joiner = Joiner.on(" ");
    String[] requiredParams = action.getRequiredParams();
    if (requiredParams.length > 0) {
        usage.append(' ');
        joiner.appendTo(usage, requiredParams);
    }
    String[] optionalParams = action.getOptionalParams();
    if (optionalParams.length > 0) {
        usage.append(" [");
        joiner.appendTo(usage, optionalParams);
        usage.append(']');
    }
}

From source file:com.stratelia.silverpeas.silverstatistics.control.SilverStatisticsDAO.java

/**
 * Method declaration//from  w ww  .  j av a  2 s. c o m
 * @param con
 * @param type
 * @param valueKeys
 * @param conf
 * @return
 * @throws SQLException
 * @see
 */
static void insertDataStats(Connection con, StatType type, List<String> valueKeys, StatisticsConfig conf)
        throws SQLException {
    StringBuilder insertStatementBuf = new StringBuilder("INSERT INTO ");
    insertStatementBuf.append(conf.getTableName(type)).append("(");
    PreparedStatement prepStmt = null;
    int i = 0;

    Collection<String> theKeys = conf.getAllKeys(type);
    Joiner joiner = Joiner.on(",");
    joiner.appendTo(insertStatementBuf, theKeys);
    insertStatementBuf.append(") ");

    insertStatementBuf.append("VALUES(?");
    for (int j = 0; j < conf.getNumberOfKeys(type) - 1; j++) {
        insertStatementBuf.append(",?");
    }
    insertStatementBuf.append(")");
    String insertStatement = insertStatementBuf.toString();

    try {
        SilverTrace.info("silverstatistics", "SilverStatisticsDAO.insertDataStats", "root.MSG_GEN_PARAM_VALUE",
                "insertStatement=" + insertStatement);
        prepStmt = con.prepareStatement(insertStatement);
        for (String currentKey : theKeys) {
            i++;
            String currentType = conf.getKeyType(type, currentKey);
            if (currentType.equals("DECIMAL")) {
                long tmpLong;
                try {
                    String tmpString = valueKeys.get(i - 1);
                    if (!StringUtil.isDefined(tmpString)) {
                        if (!conf.isCumulKey(type, currentKey)) {
                            prepStmt.setNull(i, java.sql.Types.DECIMAL);
                        } else {
                            prepStmt.setLong(i, 0);
                        }
                    } else {
                        tmpLong = Long.parseLong(tmpString);
                        prepStmt.setLong(i, tmpLong);
                    }
                } catch (NumberFormatException e) {
                    prepStmt.setLong(i, 0);
                }
            }
            if (currentType.equals("INTEGER")) {
                int tmpInt;
                try {
                    String tmpString = valueKeys.get(i - 1);
                    if (!StringUtil.isDefined(tmpString)) {
                        if (!conf.isCumulKey(type, currentKey)) {
                            prepStmt.setNull(i, java.sql.Types.INTEGER);
                        } else {
                            prepStmt.setInt(i, 0);
                        }
                    } else {
                        tmpInt = Integer.parseInt(tmpString);
                        prepStmt.setInt(i, tmpInt);
                    }
                } catch (NumberFormatException e) {
                    prepStmt.setInt(i, 0);
                }
            }
            if (currentType.equals("VARCHAR")) {
                String tmpString = valueKeys.get(i - 1);
                if (!StringUtil.isDefined(tmpString)) {
                    prepStmt.setNull(i, java.sql.Types.VARCHAR);
                } else {
                    prepStmt.setString(i, valueKeys.get(i - 1));
                }
            }
        }
        prepStmt.executeUpdate();
    } finally {
        DBUtil.close(prepStmt);
    }
}

From source file:org.opendaylight.vpnservice.mdsalutil.MDSALUtil.java

public static String longToIp(long ip, long mask) {
    StringBuilder sb = new StringBuilder(15);
    Joiner joiner = Joiner.on('.');

    joiner.appendTo(sb, Bytes.asList(Ints.toByteArray((int) ip)));

    sb.append("/" + mask);

    return sb.toString();
}

From source file:com.stratelia.silverpeas.silverstatistics.control.SilverStatisticsManagerDAO.java

/**
 * Method declaration/* w  w  w .j a  v  a 2  s.  c om*/
 * @param con
 * @param statsType
 * @param valueKeys
 * @param conf
 * @throws SQLException
 * @see
 */
static void insertDataStatsCumul(Connection con, StatType statsType, List<String> valueKeys,
        StatisticsConfig conf) throws SQLException, IOException {
    StringBuilder insertStatementBuf = new StringBuilder("INSERT INTO ");
    insertStatementBuf.append(conf.getTableName(statsType)).append("Cumul" + "(");
    String insertStatement;
    PreparedStatement prepStmt = null;
    int i = 0;

    Collection<String> theKeys = conf.getAllKeys(statsType);
    Joiner joiner = Joiner.on(",");
    joiner.appendTo(insertStatementBuf, theKeys);
    insertStatementBuf.append(") ");

    insertStatementBuf.append("VALUES(?");
    for (int j = 0; j < conf.getNumberOfKeys(statsType) - 1; j++) {
        insertStatementBuf.append(",?");
    }
    insertStatementBuf.append(")");
    insertStatement = insertStatementBuf.toString();

    try {

        SilverTrace.info("silverstatistics", "SilverStatisticsManagerDAO.insertDataStatsCumul",
                "root.MSG_GEN_PARAM_VALUE", "insertStatement=" + insertStatement);
        prepStmt = con.prepareStatement(insertStatement);
        for (String currentKey : theKeys) {
            i++;
            String currentType = conf.getKeyType(statsType, currentKey);
            if ("DECIMAL".equals(currentType)) {
                long tmpLong;
                try {
                    String tmpString = valueKeys.get(i - 1);
                    if (!StringUtil.isDefined(tmpString)) {
                        if (!conf.isCumulKey(statsType, currentKey)) {
                            prepStmt.setNull(i, java.sql.Types.DECIMAL);
                        } else {
                            prepStmt.setLong(i, 0);
                        }
                    } else {
                        tmpLong = new Long(tmpString);
                        prepStmt.setLong(i, tmpLong);
                    }
                } catch (NumberFormatException e) {
                    prepStmt.setLong(i, 0);
                }
            }
            if ("INTEGER".equals(currentType)) {
                int tmpInt;

                try {
                    String tmpString = valueKeys.get(i - 1);

                    if (!StringUtil.isDefined(tmpString)) {
                        if (!conf.isCumulKey(statsType, currentKey)) {
                            prepStmt.setNull(i, java.sql.Types.INTEGER);
                        } else {
                            prepStmt.setInt(i, 0);
                        }
                    } else {
                        tmpInt = Integer.valueOf(tmpString);
                        prepStmt.setInt(i, tmpInt);
                    }
                } catch (NumberFormatException e) {
                    prepStmt.setInt(i, 0);
                }
            }
            if ("VARCHAR".equals(currentType)) {
                if ("dateStat".equals(currentKey)) {
                    String dateFirstDayOfMonth = valueKeys.get(i - 1).substring(0, 8);

                    dateFirstDayOfMonth = dateFirstDayOfMonth + "01";
                    prepStmt.setString(i, dateFirstDayOfMonth);
                } else {
                    String tmpString = valueKeys.get(i - 1);

                    if (!StringUtil.isDefined(tmpString)) {
                        prepStmt.setNull(i, java.sql.Types.VARCHAR);
                    } else {
                        prepStmt.setString(i, valueKeys.get(i - 1));
                    }
                }
            }
        }
        prepStmt.executeUpdate();
    } finally {
        DBUtil.close(prepStmt);
    }
}

From source file:org.openqa.selenium.remote.internal.HttpUrlBuilder.java

static URL toUrl(URL base, HttpRequest request) throws MalformedURLException {
    StringBuilder queryString = new StringBuilder();
    Joiner parameters = Joiner.on("&");

    List<String> allParams = StreamSupport.stream(request.getQueryParameterNames().spliterator(), false)
            .map(name -> {/*from w w  w . j  a  v  a2 s.  co m*/
                String encoded = QUERY_ENCODE.apply(name);
                return parameters.join(StreamSupport
                        .stream(request.getQueryParameters(name).spliterator(), false)
                        .map(value -> encoded + "=" + QUERY_ENCODE.apply(value)).collect(Collectors.toList()));
            }).collect(Collectors.toList());
    parameters.appendTo(queryString, allParams);

    String baseUrl;
    if (request.getUri().startsWith("http://") || request.getUri().startsWith("https://")) {
        baseUrl = request.getUri();
    } else {
        baseUrl = base.toExternalForm().replaceAll("/$", "") + request.getUri();
    }

    if (!queryString.toString().isEmpty()) {
        baseUrl += "?" + queryString.toString();
    }

    return new URL(baseUrl);
}

From source file:org.pentaho.cassandra.CassandraUtils.java

/**
 * converts a kettle row to CQL insert statement and adds it to the batch
 * //from  ww  w.j  a  va2 s.  co  m
 * @param batch
 *          StringBuilder for collecting the batch CQL
 * @param colFamilyName
 *          the name of the column family (table) to insert into
 * @param inputMeta
 *          Kettle input row meta data inserting
 * @param row
 *          the Kettle row
 * @param familyMeta
 *          meta data on the columns in the cassandra column family (table)
 * @param insertFieldsNotInMetaData
 *          true if any Kettle fields that are not in the Cassandra column family (table) meta data are to be
 *          inserted. This is irrelevant if the user has opted to have the step initially update the Cassandra meta
 *          data for incoming fields that are not known about.
 * @param cqlMajVersion
 *          the major version number of the cql version to use
 * @param additionalOpts
 *          additional options for the insert statement
 * @param log
 *          for logging
 * @return true if the row was added to the batch
 * @throws Exception
 *           if a problem occurs
 */
public static boolean addRowToCQLBatch(StringBuilder batch, String colFamilyName, RowMetaInterface inputMeta,
        Object[] row, ColumnFamilyMetaData familyMeta, boolean insertFieldsNotInMetaData, int cqlMajVersion,
        Map<String, String> additionalOpts, LogChannelInterface log) throws Exception {

    if (!preAddChecks(inputMeta, familyMeta.getKeyColumnNames(), row, log)) {
        return false;
    }

    // ValueMetaInterface keyMeta = inputMeta.getValueMeta(keyIndex);
    final String quoteChar = identifierQuoteChar(cqlMajVersion);
    List<String> keyColNames = familyMeta.getKeyColumnNames();

    Map<String, String> columnValues = new HashMap<String, String>();
    for (int i = 0; i < inputMeta.size(); i++) {
        ValueMetaInterface colMeta = inputMeta.getValueMeta(i);
        String colName = colMeta.getName();
        if (cqlMajVersion < 3 && colName.equals("KEY")) { //$NON-NLS-1$
            // key is a reserved work in CQL2 and is stored in lower case
            // in Cassandra's table metadata, but returned as upper case
            // in a thrift Column object. If our incoming Kettle field is
            // KEY then we need to lower case it or we won't find it in
            // our familyMeta
            if (keyColNames.get(0).equalsIgnoreCase("key")) {
                colName = "key";
            }
        }
        if (!familyMeta.columnExistsInSchema(colName) && !insertFieldsNotInMetaData) {
            continue;
        }
        // don't insert if null!
        if (colMeta.isNull(row[i])) {
            continue;
        }

        columnValues.put(colName, kettleValueToCQL(colMeta, row[i], cqlMajVersion));
    }

    Collection<String> columnOrder;
    if (cqlMajVersion >= 3) {
        // Quote column family name if version >=3 to enforce case sensitivity
        // http://www.datastax.com/documentation/cql/3.0/cql/cql_reference/ucase-lcase_r.html
        colFamilyName = cql3MixedCaseQuote(colFamilyName);
        // Column order does not matter
        columnOrder = columnValues.keySet();
    } else {
        // Key column has to be listed first for CQL 2
        columnOrder = new LinkedHashSet();
        for (String keyColName : keyColNames) {
            // Add keys in given order
            if (columnValues.containsKey(keyColName)) {
                columnOrder.add(keyColName);
            }
        }
        // Add remaining values
        columnOrder.addAll(columnValues.keySet());
    }

    List<String> columns = new ArrayList<String>(columnOrder.size());
    List<String> values = new ArrayList<String>(columnOrder.size());
    for (String column : columnOrder) {
        columns.add(quoteChar + column + quoteChar);
        values.add(columnValues.get(column));
    }

    Joiner joiner = Joiner.on(',').skipNulls();
    batch.append("INSERT INTO ").append(colFamilyName).append(" (");
    joiner.appendTo(batch, columns);
    batch.append(") VALUES ("); //$NON-NLS-1$
    joiner.appendTo(batch, values);
    batch.append(")"); //$NON-NLS-1$

    if (containsInsertOptions(additionalOpts)) {
        batch.append(" USING "); //$NON-NLS-1$

        boolean first = true;
        for (Map.Entry<String, String> o : additionalOpts.entrySet()) {
            if (validInsertOption(o.getKey())) {
                if (first) {
                    batch.append(o.getKey()).append(" ").append(o.getValue()); //$NON-NLS-1$
                    first = false;
                } else {
                    batch.append(" AND ").append(o.getKey()).append(" ") //$NON-NLS-1$ //$NON-NLS-2$
                            .append(o.getValue());
                }
            }
        }
    }

    batch.append("\n"); //$NON-NLS-1$

    return true;
}

From source file:org.dcache.utils.SubjectHolder.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("Subject: < ");
    Set<Principal> principals = _subject.getPrincipals();
    Joiner joiner = Joiner.on(',');
    synchronized (principals) {
        joiner.appendTo(sb, principals);
    }/*from   w  ww .  j a v  a  2 s  .c o m*/
    sb.append(" >");
    return sb.toString();
}