Example usage for java.lang StringBuilder lastIndexOf

List of usage examples for java.lang StringBuilder lastIndexOf

Introduction

In this page you can find the example usage for java.lang StringBuilder lastIndexOf.

Prototype

@Override
    public int lastIndexOf(String str) 

Source Link

Usage

From source file:io.anserini.doc.DataModel.java

public String generateRankingCommand(String collection) {
    Map<String, Object> config = this.collections.get(collection);
    StringBuilder builder = new StringBuilder();
    ObjectMapper oMapper = new ObjectMapper();
    List models = oMapper.convertValue((List) safeGet(config, "models"), List.class);
    List topics = oMapper.convertValue((List) safeGet(config, "topics"), List.class);
    for (Object modelObj : models) {
        Model model = oMapper.convertValue(modelObj, Model.class);
        for (Object topicObj : topics) {
            Topic topic = oMapper.convertValue(topicObj, Topic.class);
            builder.append("nohup ");
            builder.append(safeGet(config, "search_command"));
            builder.append(" ").append("-topicreader").append(" ").append(safeGet(config, "topic_reader"));
            builder.append(" ").append("-index").append(" ")
                    .append("lucene-index." + safeGet(config, "name") + ".pos+docvectors");
            builder.append(" ").append("-topic").append(" ")
                    .append(Paths.get((String) safeGet(config, "topic_root"), topic.getPath()).toString());
            builder.append(" ").append("-output").append(" ")
                    .append("run." + safeGet(config, "name") + "." + model.getName() + "." + topic.getPath());
            List modelParams = oMapper.convertValue(model.getParams(), List.class);
            if (modelParams != null) {
                for (Object option : modelParams) {
                    builder.append(" ").append(option);
                }//w ww .  j  a v a 2s  .co  m
            }
            builder.append(" &"); // nohup
            builder.append("\n");
        }
        builder.append("\n");
    }
    builder.delete(builder.lastIndexOf("\n"), builder.length());

    return builder.toString();
}

From source file:gov.nih.nci.nbia.customserieslist.FileGenerator.java

/**
 * generate comma separate string from the series instance uid list
 * @param seriesItems//from  w ww . j  a v a2s .c  om
*/
public String generateImageMetadata(List<BasketSeriesItemBean> seriesItems) {
    String[] csvHeaders = new String[] { "Collection", "Patient Id", "Study Date", "Study Description",
            "Modality", "Series Description", "Manufacturer", "Manufacturer Model", "Software Version",
            "Series UID" };
    StringBuilder sb = new StringBuilder();
    for (String csvHeader : csvHeaders) {
        sb.append(csvHeader);
        sb.append(",");
    }
    sb.append("\n");
    int size = seriesItems.size();
    List<Integer> seriesPKIdLst = new ArrayList<Integer>();
    for (int i = 0; i < size; i++) {
        BasketSeriesItemBean bsib = seriesItems.get(i);
        seriesPKIdLst.add(bsib.getSeriesPkId());
    }
    StudyDAO studyDAO = (StudyDAO) SpringApplicationContext.getBean("studyDAO");
    List<StudyDTO> studies = studyDAO.findStudiesBySeriesIdDBSorted(seriesPKIdLst);
    DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    for (StudyDTO study : studies) {
        List<SeriesDTO> seriesLst = study.getSeriesList();
        for (SeriesDTO series : seriesLst) {
            sb.append(series.getProject());
            sb.append(",");
            sb.append(series.getPatientId());
            sb.append(",");
            sb.append(df.format(study.getDate()));
            sb.append(",");
            sb.append(StringEscapeUtils.escapeCsv(study.getDescription()));
            sb.append(",");
            sb.append(series.getModality());
            sb.append(",");
            sb.append(StringEscapeUtils.escapeCsv(series.getDescription()));
            sb.append(",");
            sb.append(StringEscapeUtils.escapeCsv(series.getManufacturer()));
            sb.append(",");
            sb.append(StringEscapeUtils.escapeCsv(series.getManufacturerModelName()));
            sb.append(",");
            sb.append(StringEscapeUtils.escapeCsv(series.getSoftwareVersion()));
            sb.append(",");
            sb.append(series.getSeriesId());
            sb.append(",");
            sb.append("\n");
        }
    }
    int lastComma = sb.lastIndexOf(",");
    sb.replace(lastComma, lastComma, "");
    sb.trimToSize();
    return sb.toString();
}

From source file:org.vivoweb.harvester.fetch.JDBCFetch.java

/**
 * Builds a select statement against the table using configured fields
 * @param tableName the table to build the select statement for
 * @return the select statement/*from  w w  w  .ja  va  2s  .  co m*/
 * @throws SQLException error connecting to db
 */
private String buildSelect(String tableName) throws SQLException {
    if ((this.queryStrings != null) && this.queryStrings.containsKey(tableName)) {
        String query = this.queryStrings.get(tableName);
        log.trace("User defined SQL Query:\n" + query);
        return query;
    }
    boolean multiTable = (this.fromClauses != null) && this.fromClauses.containsKey(tableName);
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT ");
    for (String dataField : getDataFields(tableName)) {
        sb.append(getFieldPrefix());
        if (multiTable && (dataField.split("\\.").length <= 1)) {
            sb.append(tableName);
            sb.append(".");
        }
        sb.append(dataField);
        sb.append(getFieldSuffix());
        sb.append(", ");
    }
    for (String relField : getFkRelationFields(tableName).keySet()) {
        sb.append(getFieldPrefix());
        if (multiTable && (relField.split("\\.").length <= 1)) {
            sb.append(tableName);
            sb.append(".");
        }
        sb.append(relField);
        sb.append(getFieldSuffix());
        sb.append(", ");
    }
    for (String idField : getIDFields(tableName)) {
        sb.append(getFieldPrefix());
        if (multiTable && (idField.split("\\.").length <= 1)) {
            sb.append(tableName);
            sb.append(".");
        }
        sb.append(idField);
        sb.append(getFieldSuffix());
        sb.append(", ");
    }
    sb.delete(sb.lastIndexOf(", "), sb.length());
    sb.append(" FROM ");
    sb.append(tableName);
    if (multiTable) {
        sb.append(", ");
        sb.append(this.fromClauses.get(tableName));
    }

    if (getWhereClauses(tableName).size() > 0) {
        sb.append(" WHERE ");
        sb.append(StringUtils.join(getWhereClauses(tableName), " AND "));
    }
    log.trace("Generated SQL Query:\n" + sb.toString());
    return sb.toString();
}

From source file:org.silverpeas.components.yellowpages.control.YellowpagesSessionController.java

private List<StringBuilder> exportCurrentContactsAsCSV() {
    Collection<ContactFatherDetail> contacts = getCurrentContacts();
    List<StringBuilder> csvRows = new ArrayList<>();
    // Can't export all columns because data are heterogenous

    for (ContactFatherDetail contactFatherDetail : contacts) {
        ContactDetail contact = contactFatherDetail.getContactDetail();
        if (contact != null) {
            StringBuilder csvRow = new StringBuilder();
            addCSVValue(csvRow, contact.getLastName());
            addCSVValue(csvRow, contact.getFirstName());
            addCSVValue(csvRow, contact.getEmail());
            addCSVValue(csvRow, contact.getPhone());
            addCSVValue(csvRow, contact.getFax());

            // adding userFull data
            UserFull userFull = contact.getUserFull();
            if (userFull != null) {
                String[] properties = userFull.getPropertiesNames();
                for (String property : properties) {
                    if (!property.startsWith("password")) {
                        addCSVValue(csvRow, userFull.getValue(property));
                    }/*from  w  w  w . j  a  v a2s.c o  m*/
                }
            }

            // adding xml data
            exportFormData(contactFatherDetail, csvRow);

            // Remove final ","
            csvRow.deleteCharAt(csvRow.lastIndexOf(","));
            csvRows.add(csvRow);
        }
    }

    return csvRows;
}

From source file:Model.MHaze.java

public void addHazeInfo(String pStrString) throws ParseException {
    IDataStorage objDS = CDataStorageFactory.getMasterStorage();

    StringBuilder objSB = new StringBuilder();

    objSB.append("INSERT INTO `haze`(`region`, `psiValue`, `airQualityDescriptor`)" + " VALUES");

    JSONParser jsonParser = new JSONParser();

    JSONArray aryJSON = (JSONArray) jsonParser.parse(pStrString);

    for (Object objJson : aryJSON) {

        objSB.append("('");
        JSONObject objInnerObj = (JSONObject) objJson;

        int intPsi = Integer.parseInt(objInnerObj.get("psi").toString());
        String strRegionCode = objInnerObj.get("region").toString();

        switch (strRegionCode.toUpperCase()) {
        case "RNO":
            objSB.append("north");
            objSB.append("',");
            break;
        case "RSO":
            objSB.append("south");
            objSB.append("',");
            break;
        case "RCE":
            objSB.append("central");
            objSB.append("',");
            break;
        case "RWE":
            objSB.append("west");
            objSB.append("',");
            break;
        case "REA":
            objSB.append("east");
            objSB.append("',");
            break;
        default:/*from  w  ww. j a  v a 2s. c om*/
            objSB.append("national");
            objSB.append("',");
            break;

        }

        objSB.append(intPsi);
        objSB.append(",'");

        if (intPsi <= 50) {
            objSB.append("Good");
        } else if (intPsi <= 100) {
            objSB.append("Moderate");
        } else if (intPsi <= 200) {
            objSB.append("Unhealthy");
        } else if (intPsi <= 300) {
            objSB.append("Very unhealthy");
        } else {
            objSB.append("Hazardous");
        }
        objSB.append("'),");

    }
    objSB.deleteCharAt(objSB.lastIndexOf(","));

    objSB.append(";");

    System.out.println(objSB);

    objDS.openConnection();

    objDS.executeScalar("truncate table haze;");
    objDS.executeScalar(objSB.toString());

    objDS.closeConnection();

}

From source file:info.magnolia.ui.workbench.container.AbstractJcrContainer.java

/**
 * @param considerSorting an optional <code>ORDER BY</code> is added if this parameter is <code>true</code>.
 * @return a string representing a JCR statement to retrieve this container's items.
 * It creates a JCR query in the form {@code select * from [nt:base] as selectorName [WHERE] [ORDER BY]"}.
 * <p>//ww w  .  j a  v  a 2 s  .  c o m
 * Subclasses can customize the optional <code>WHERE</code> clause by overriding {@link #getQueryWhereClause()} or, at a more fine-grained level, {@link #getQueryWhereClauseNodeTypes()} and {@link #getQueryWhereClauseWorkspacePath()}.
 * <p>
 * A restriction on the node types to be searched for can be applied via {@link #getQueryWhereClauseNodeTypes()}.
 */
protected String constructJCRQuery(final boolean considerSorting) {
    final String select = getQuerySelectStatement();
    final StringBuilder stmt = new StringBuilder(select);
    // Return results only within the node configured in workbench/path
    stmt.append(getQueryWhereClause());

    if (considerSorting) {
        if (sorters.isEmpty()) {
            // no sorters set - use defaultOrder (always ascending)
            String defaultOrder = contentConnectorDefinition.getDefaultOrder();
            String[] defaultOrders = defaultOrder.split(",");
            for (String current : defaultOrders) {
                sorters.add(getDefaultOrderBy(current));
            }
        }
        stmt.append(ORDER_BY);
        String sortOrder;
        for (OrderBy orderBy : sorters) {
            String propertyName = orderBy.getProperty();
            sortOrder = orderBy.isAscending() ? ASCENDING_KEYWORD : DESCENDING_KEYWORD;
            if (ModelConstants.JCR_NAME.equals(propertyName)) {
                stmt.append(getJcrNameOrderByFunction()).append(sortOrder).append(", ");
                continue;
            }
            stmt.append(SELECTOR_NAME);
            stmt.append(".[").append(propertyName).append("]").append(sortOrder).append(", ");
        }
        stmt.delete(stmt.lastIndexOf(","), stmt.length());
    }
    log.debug("Constructed JCR query is {}", stmt);
    return stmt.toString();
}

From source file:org.codice.ddf.opensearch.endpoint.query.OpenSearchQuery.java

private String generateParsingError(ParsingResult<ASTNode> result) {
    StringBuilder parsingErrorBuilder = new StringBuilder(
            "Parsing error" + ((result.parseErrors.size() > 1) ? "s" : "") + ": \n");
    InputBuffer inputBuffer = result.inputBuffer;
    String parsedLine = inputBuffer.extract(0, Integer.MAX_VALUE);

    StringBuilder invalidInputLineBuilder = null;
    for (ParseError parseError : result.parseErrors) {
        StringBuilder otherErrorLineBuilder = getCaratLineStringBuilder(parsedLine);

        // NOTE for some reason, these indexes start at 1, not 0
        int originalEndIndex = inputBuffer.getOriginalIndex(parseError.getEndIndex()) - 1;
        int originalStartIndex = inputBuffer.getOriginalIndex(parseError.getStartIndex()) - 1;

        if (parseError.getClass().isAssignableFrom(InvalidInputError.class)) {
            // Combine all InvalidInputError's
            if (invalidInputLineBuilder == null) {
                invalidInputLineBuilder = getCaratLineStringBuilder(parsedLine);
            }//from www .ja  v  a 2  s .  c  o  m

            addCaretsToStringBuilder(invalidInputLineBuilder, originalEndIndex, originalStartIndex);
        } else {
            // output other types of errors separately
            parsingErrorBuilder.append("\nError found in: \n");

            addCaretsToStringBuilder(otherErrorLineBuilder, originalEndIndex, originalStartIndex);

            parsingErrorBuilder.append("\n\t");
            parsingErrorBuilder.append(parsedLine);
            parsingErrorBuilder.append("\n\t");
            parsingErrorBuilder.append(otherErrorLineBuilder);
        }
    }

    if (invalidInputLineBuilder != null) {
        // if the first and last occurrence of CARET aren't the same, there are more than one in
        // the string
        parsingErrorBuilder.append("\nInvalid character")
                .append((invalidInputLineBuilder.indexOf(CARET) != invalidInputLineBuilder.lastIndexOf(CARET))
                        ? "s"
                        : "")
                .append(" found in: \n");
        parsingErrorBuilder.append("\n\t");
        parsingErrorBuilder.append(parsedLine);
        parsingErrorBuilder.append("\n\t");
        parsingErrorBuilder.append(invalidInputLineBuilder);
    }
    return parsingErrorBuilder.toString();
}

From source file:org.apache.lens.driver.jdbc.ColumnarSQLRewriter.java

@Override
public String rewrite(String query, Configuration conf, HiveConf metastoreConf) throws LensException {
    this.query = query;
    StringBuilder mergedQuery;
    rewrittenQuery.setLength(0);//  w w w . j  av a 2  s. c  om
    String queryReplacedUdf;
    reset();

    try {
        String finalRewrittenQuery;
        if (query.toLowerCase().matches("(.*)union all(.*)")) {
            finalRewrittenQuery = "";
            String[] queries = query.toLowerCase().split("union all");
            for (int i = 0; i < queries.length; i++) {
                log.info("Union Query Part {} : {}", i, queries[i]);
                ast = HQLParser.parseHQL(queries[i], metastoreConf);
                buildQuery(conf, metastoreConf);
                mergedQuery = rewrittenQuery.append(" union all ");
                finalRewrittenQuery = mergedQuery.toString().substring(0, mergedQuery.lastIndexOf("union all"));
                reset();
            }
        } else {
            ast = HQLParser.parseHQL(query, metastoreConf);
            buildQuery(conf, metastoreConf);
            finalRewrittenQuery = rewrittenQuery.toString();
        }
        queryReplacedUdf = replaceUDFForDB(finalRewrittenQuery);
        log.info("Input Query : {}", query);
        log.info("Rewritten Query : {}", queryReplacedUdf);
    } catch (SemanticException e) {
        throw new LensException(e);
    }
    return queryReplacedUdf;
}

From source file:com.impetus.client.cassandra.query.CassQuery.java

/**
 * Create Update CQL query from a given JPA query.
 * /*from www . ja  v a 2s.co m*/
 * @param kunderaQuery
 *            the kundera query
 * @return the string
 */
public String createUpdateQuery(KunderaQuery kunderaQuery) {
    EntityMetadata metadata = kunderaQuery.getEntityMetadata();
    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(metadata.getPersistenceUnit());

    CQLTranslator translator = new CQLTranslator();
    String update_Query = translator.UPDATE_QUERY;

    String tableName = metadata.getTableName();
    update_Query = StringUtils.replace(update_Query, CQLTranslator.COLUMN_FAMILY,
            translator.ensureCase(new StringBuilder(), tableName, false).toString());

    StringBuilder builder = new StringBuilder(update_Query);

    Object ttlColumns = ((CassandraClientBase) persistenceDelegeator.getClient(metadata)).getTtlValues()
            .get(metadata.getTableName());

    if ((ttlColumns != null && ttlColumns instanceof Integer) || this.ttl != null) {
        int ttl = this.ttl != null ? this.ttl : ((Integer) ttlColumns).intValue();
        if (ttl != 0) {
            builder.append(" USING TTL ");
            builder.append(ttl);
            builder.append(" ");
        }
    }

    builder.append(CQLTranslator.ADD_SET_CLAUSE);

    for (UpdateClause updateClause : kunderaQuery.getUpdateClauseQueue()) {

        String property = updateClause.getProperty();

        String jpaColumnName = getColumnName(metadata, property);

        Object value = updateClause.getValue();

        translator.buildSetClause(metadata, builder, jpaColumnName, value);
    }
    builder.delete(builder.lastIndexOf(CQLTranslator.COMMA_STR), builder.length());
    builder.append(CQLTranslator.ADD_WHERE_CLAUSE);

    Class compoundKeyClass = metadata.getIdAttribute().getBindableJavaType();
    EmbeddableType compoundKey = null;
    String idColumn;
    if (metaModel.isEmbeddable(compoundKeyClass)) {
        compoundKey = metaModel.embeddable(compoundKeyClass);
        idColumn = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();
    } else {
        idColumn = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();
    }

    onCondition(metadata, metaModel, compoundKey, idColumn, builder, false, translator, false);

    return builder.toString();
}

From source file:org.bibsonomy.model.util.BibTexUtils.java

/**
 * return a bibtex string representation of the given bibtex object
 * //  www  . j  a va 2 s  . c  o m
 * @param bib - a bibtex object
 * @param mode - the serializing mode (parse misc fields or include misc fields as they are)
 * @return String bibtexString
 * 
 * TODO use BibTex.DEFAULT_OPENBRACKET etc.
 * 
 */
public static String toBibtexString(final BibTex bib, SerializeBibtexMode mode) {
    try {
        final BeanInfo bi = Introspector.getBeanInfo(bib.getClass());

        /*
         * start with entrytype and key
         */
        final StringBuilder buffer = new StringBuilder(
                "@" + bib.getEntrytype() + "{" + bib.getBibtexKey() + ",\n");

        /*
         * append all other fields
         */
        for (final PropertyDescriptor d : bi.getPropertyDescriptors()) {
            final Method getter = d.getReadMethod();
            // loop over all String attributes
            final Object o = getter.invoke(bib, (Object[]) null);
            if (String.class.equals(d.getPropertyType()) && o != null
                    && !EXCLUDE_FIELDS.contains(d.getName())) {

                /*
                 * Strings containing whitespace give empty fields ... we ignore them 
                 */
                String value = ((String) o);
                if (present(value)) {
                    if (!NUMERIC_PATTERN.matcher(value).matches()) {
                        value = DEFAULT_OPENING_BRACKET + value + DEFAULT_CLOSING_BRACKET;
                    }
                    buffer.append("  " + d.getName().toLowerCase() + " = " + value + ",\n");
                }
            }
        }
        /*
         * process miscFields map, if present
         */
        if (present(bib.getMiscFields())) {
            if (mode.equals(SerializeBibtexMode.PARSED_MISCFIELDS) && !bib.isMiscFieldParsed()) {
                // parse misc field, if not yet done
                bib.parseMiscField();
            }
            buffer.append(serializeMiscFields(bib.getMiscFields(), true));
        }

        /*
         * include plain misc fields if desired
         */
        if (mode.equals(SerializeBibtexMode.PLAIN_MISCFIELDS) && present(bib.getMisc())) {
            buffer.append("  " + bib.getMisc() + ",\n");
        }
        /*
         * add month
         */
        final String month = bib.getMonth();
        if (present(month)) {
            // we don't add {}, this is done by getMonth(), if necessary
            buffer.append("  month = " + getMonth(month) + ",\n");
        }
        /*
         * add abstract
         */
        final String bibAbstract = bib.getAbstract();
        if (present(bibAbstract)) {
            buffer.append("  abstract = {" + bibAbstract + "},\n");
        }
        /*
         * remove last comma
         */
        buffer.delete(buffer.lastIndexOf(","), buffer.length());
        buffer.append("\n}");

        return buffer.toString();

    } catch (IntrospectionException ex) {
        ex.printStackTrace();
    } catch (InvocationTargetException ex) {
        ex.printStackTrace();
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
    }
    return null;
}