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:org.apache.sling.scripting.sightly.impl.filter.URIManipulationFilter.java

@Override
@SuppressWarnings("unchecked")
public Object call(RenderContext renderContext, Object... arguments) {
    ExtensionUtils.checkArgumentCount(URI_MANIPULATION_FUNCTION, arguments, 2);
    RenderContextImpl rci = (RenderContextImpl) renderContext;
    String uriString = rci.toString(arguments[0]);
    Map<String, Object> options = rci.toMap(arguments[1]);
    if (uriString == null) {
        return null;
    }/*from  ww w  . j a  v  a2s.  co m*/
    StringBuilder sb = new StringBuilder();
    PathInfo pathInfo = new PathInfo(uriString);
    uriAppender(sb, SCHEME, options, pathInfo.getScheme());
    if (sb.length() > 0) {
        sb.append(":");
        sb.append(StringUtils.defaultIfEmpty(pathInfo.getBeginPathSeparator(), "//"));
    }
    if (sb.length() > 0) {
        uriAppender(sb, DOMAIN, options, pathInfo.getHost());
    } else {
        String domain = getOption(DOMAIN, options, pathInfo.getHost());
        if (StringUtils.isNotEmpty(domain)) {
            sb.append("//").append(domain);
        }
    }
    if (pathInfo.getPort() > -1) {
        sb.append(":").append(pathInfo.getPort());
    }
    String prependPath = getOption(PREPEND_PATH, options, StringUtils.EMPTY);
    if (prependPath == null) {
        prependPath = StringUtils.EMPTY;
    }
    if (StringUtils.isNotEmpty(prependPath)) {
        if (sb.length() > 0 && !prependPath.startsWith("/")) {
            prependPath = "/" + prependPath;
        }
        if (!prependPath.endsWith("/")) {
            prependPath += "/";
        }
    }
    String path = getOption(PATH, options, pathInfo.getPath());
    if (StringUtils.isEmpty(path)) {
        // if the path is forced to be empty don't remove the path
        path = pathInfo.getPath();
    }
    String appendPath = getOption(APPEND_PATH, options, StringUtils.EMPTY);
    if (appendPath == null) {
        appendPath = StringUtils.EMPTY;
    }
    if (StringUtils.isNotEmpty(appendPath)) {
        if (!appendPath.startsWith("/")) {
            appendPath = "/" + appendPath;
        }
    }
    String newPath;
    try {
        newPath = new URI(prependPath + path + appendPath).normalize().getPath();
    } catch (URISyntaxException e) {
        newPath = prependPath + path + appendPath;
    }
    if (sb.length() > 0 && sb.lastIndexOf("/") != sb.length() - 1 && StringUtils.isNotEmpty(newPath)
            && !newPath.startsWith("/")) {
        sb.append("/");
    }
    sb.append(newPath);
    Set<String> selectors = pathInfo.getSelectors();
    handleSelectors(rci, selectors, options);
    for (String selector : selectors) {
        if (StringUtils.isNotBlank(selector) && !selector.contains(" ")) {
            // make sure not to append empty or invalid selectors
            sb.append(".").append(selector);
        }
    }
    String extension = getOption(EXTENSION, options, pathInfo.getExtension());
    if (StringUtils.isNotEmpty(extension)) {
        sb.append(".").append(extension);
    }

    String prependSuffix = getOption(PREPEND_SUFFIX, options, StringUtils.EMPTY);
    if (StringUtils.isNotEmpty(prependSuffix)) {
        if (!prependSuffix.startsWith("/")) {
            prependSuffix = "/" + prependSuffix;
        }
        if (!prependSuffix.endsWith("/")) {
            prependSuffix += "/";
        }
    }
    String pathInfoSuffix = pathInfo.getSuffix();
    String suffix = getOption(SUFFIX, options, pathInfoSuffix == null ? StringUtils.EMPTY : pathInfoSuffix);
    if (suffix == null) {
        suffix = StringUtils.EMPTY;
    }
    String appendSuffix = getOption(APPEND_SUFFIX, options, StringUtils.EMPTY);
    if (StringUtils.isNotEmpty(appendSuffix)) {
        appendSuffix = "/" + appendSuffix;
    }
    String newSuffix = ResourceUtil.normalize(prependSuffix + suffix + appendSuffix);
    if (StringUtils.isNotEmpty(newSuffix)) {
        if (!newSuffix.startsWith("/")) {
            sb.append("/");
        }
        sb.append(newSuffix);
    }
    Map<String, Collection<String>> parameters = pathInfo.getParameters();
    handleParameters(rci, parameters, options);
    if (!parameters.isEmpty()) {
        sb.append("?");
        for (Map.Entry<String, Collection<String>> entry : parameters.entrySet()) {
            for (String value : entry.getValue()) {
                sb.append(entry.getKey()).append("=").append(value).append("&");
            }
        }
        // delete the last &
        sb.deleteCharAt(sb.length() - 1);
    }
    String fragment = getOption(FRAGMENT, options, pathInfo.getFragment());
    if (StringUtils.isNotEmpty(fragment)) {
        sb.append("#").append(fragment);
    }
    return sb.toString();
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

private String calculatedSharedKeyLiteSignature(@Nonnull HttpRequestBase method,
        @Nonnull Map<String, String> queryParams) throws CloudException, InternalException {
    fetchKeys();/*from w  w w .j  a va 2  s  . co  m*/

    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new AzureConfigException("No context was specified for this request");
    }
    Header h = method.getFirstHeader("content-type");
    String contentType = (h == null ? null : h.getValue());

    if (contentType == null) {
        contentType = "";
    }
    StringBuilder stringToSign = new StringBuilder();

    stringToSign.append(method.getMethod().toUpperCase()).append("\n");
    stringToSign.append("\n"); // content-md5
    stringToSign.append(contentType).append("\n");
    stringToSign.append(method.getFirstHeader("date").getValue()).append("\n");

    Header[] headers = method.getAllHeaders();
    TreeSet<String> keys = new TreeSet<String>();

    for (Header header : headers) {
        if (header.getName().startsWith(Header_Prefix_MS)) {
            keys.add(header.getName().toLowerCase());
        }
    }

    for (String key : keys) {
        Header header = method.getFirstHeader(key);

        if (header != null) {
            Header[] all = method.getHeaders(key);

            stringToSign.append(key.toLowerCase().trim()).append(":");
            if (all != null && all.length > 0) {
                for (Header current : all) {
                    String v = (current.getValue() != null ? current.getValue() : "");

                    stringToSign.append(v.trim().replaceAll("\n", " ")).append(",");
                }
            }
            stringToSign.deleteCharAt(stringToSign.lastIndexOf(","));
        } else {
            stringToSign.append(key.toLowerCase().trim()).append(":");
        }
        stringToSign.append("\n");
    }

    stringToSign.append("/").append(getStorageAccount()).append(method.getURI().getPath());

    keys.clear();
    for (String key : queryParams.keySet()) {
        if (key.equalsIgnoreCase("comp")) {
            key = key.toLowerCase();
            keys.add(key);
        }
    }
    if (!keys.isEmpty()) {
        stringToSign.append("?");
        for (String key : keys) {
            String value = queryParams.get(key);

            if (value == null) {
                value = "";
            }
            stringToSign.append(key).append("=").append(value).append("&");
        }
        stringToSign.deleteCharAt(stringToSign.lastIndexOf("&"));
    }
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("BEGIN STRING TO SIGN");
            logger.debug(stringToSign.toString());
            logger.debug("END STRING TO SIGN");
        }
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(Base64.decodeBase64(ctx.getStoragePrivate()), "HmacSHA256"));

        String signature = new String(
                Base64.encodeBase64(mac.doFinal(stringToSign.toString().getBytes("UTF-8"))));

        if (logger.isDebugEnabled()) {
            logger.debug("signature=" + signature);
        }
        return signature;
    } catch (UnsupportedEncodingException e) {
        logger.error("UTF-8 not supported: " + e.getMessage());
        throw new InternalException(e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("No such algorithm: " + e.getMessage());
        throw new InternalException(e);
    } catch (InvalidKeyException e) {
        logger.error("Invalid key: " + e.getMessage());
        throw new InternalException(e);
    }
}

From source file:org.kuali.ole.select.document.OleOrderQueueDocument.java

/**
 * This method returns total price of the selected requisition items.
 *
 * @return Total Price of selected items
 *///w w w.  j  a  v a  2  s.  c  om
public KualiDecimal getTotalSelectedItemsPrice() {
    LOG.debug("Inside totalSelectedItems of OleOrderQueueDocument");
    KualiDecimal totalPrice = KualiDecimal.ZERO;
    ;
    StringBuilder orderQueueRequisitionHasNoPrice = new StringBuilder();
    boolean isInfoMsg = false;
    List<OleRequisitionItem> refreshItems = new ArrayList<OleRequisitionItem>();
    for (OleRequisitionItem item : requisitionItems) {
        if (item.isItemAdded()) {
            if (item.getSourceAccountingLines().size() > 0) {
                if (item.getTotalAmount().equals(KualiDecimal.ZERO)) {
                    orderQueueRequisitionHasNoPrice.append(item.getRequisition().getDocumentNumber())
                            .append(",");
                    isInfoMsg = true;
                }
                for (int i = 0; i < item.getSourceAccountingLines().size(); i++) {
                    KualiDecimal amount = item.getSourceAccountingLines().get(i).getAmount();
                    totalPrice = totalPrice.add(amount);
                }
            } else {
                if (item.getItemListPrice().equals(KualiDecimal.ZERO)) {
                    orderQueueRequisitionHasNoPrice.append(item.getRequisition().getDocumentNumber())
                            .append(",");
                    isInfoMsg = true;
                }
                totalPrice = totalPrice.add(item.getItemListPrice());
            }
        }
        refreshItems.add(item);
    }
    requisitionItems = refreshItems;
    int len = orderQueueRequisitionHasNoPrice.lastIndexOf(",");
    if (isInfoMsg) {
        orderQueueRequisitionHasNoPrice.replace(len, len + 1, " ");
        GlobalVariables.getMessageMap().putInfo(OLEConstants.OrderQueue.REQUISITIONS,
                OLEKeyConstants.MESSAGE_ORDERQUEUE_REQUISITIONS_HAS_NO_PRICE,
                new String[] { orderQueueRequisitionHasNoPrice.toString() });
    }
    LOG.debug("Leaving totalSelectedItems of OleOrderQueueDocument");
    return totalPrice;
}

From source file:org.apache.roller.weblogger.business.jpa.JPAMediaFileManagerImpl.java

/**
 * {@inheritDoc}/*from  w ww .j  a v  a 2s.c om*/
 */
public List<MediaFile> searchMediaFiles(Weblog weblog, MediaFileFilter filter) throws WebloggerException {

    List<Object> params = new ArrayList<Object>();
    int size = 0;
    StringBuilder queryString = new StringBuilder();
    StringBuilder whereClause = new StringBuilder();
    StringBuilder orderBy = new StringBuilder();

    queryString.append("SELECT m FROM MediaFile m WHERE ");

    params.add(size++, weblog);
    whereClause.append("m.directory.weblog = ?").append(size);

    if (!StringUtils.isEmpty(filter.getName())) {
        String nameFilter = filter.getName();
        nameFilter = nameFilter.trim();
        if (!nameFilter.endsWith("%")) {
            nameFilter = nameFilter + "%";
        }
        params.add(size++, nameFilter);
        whereClause.append(" AND m.name like ?").append(size);
    }

    if (filter.getSize() > 0) {
        params.add(size++, filter.getSize());
        whereClause.append(" AND m.length ");
        switch (filter.getSizeFilterType()) {
        case GT:
            whereClause.append(">");
            break;
        case GTE:
            whereClause.append(">=");
            break;
        case EQ:
            whereClause.append("=");
            break;
        case LT:
            whereClause.append("<");
            break;
        case LTE:
            whereClause.append("<=");
            break;
        default:
            whereClause.append("=");
            break;
        }
        whereClause.append(" ?").append(size);
    }

    if (filter.getTags() != null && filter.getTags().size() > 1) {
        whereClause.append(" AND EXISTS (SELECT t FROM MediaFileTag t WHERE t.mediaFile = m and t.name IN (");
        for (String tag : filter.getTags()) {
            params.add(size++, tag);
            whereClause.append("?").append(size).append(",");
        }
        whereClause.deleteCharAt(whereClause.lastIndexOf(","));
        whereClause.append("))");
    } else if (filter.getTags() != null && filter.getTags().size() == 1) {
        params.add(size++, filter.getTags().get(0));
        whereClause.append(" AND EXISTS (SELECT t FROM MediaFileTag t WHERE t.mediaFile = m and t.name = ?")
                .append(size).append(")");
    }

    if (filter.getType() != null) {
        if (filter.getType() == MediaFileType.OTHERS) {
            for (MediaFileType type : MediaFileType.values()) {
                if (type != MediaFileType.OTHERS) {
                    params.add(size++, type.getContentTypePrefix() + "%");
                    whereClause.append(" AND m.contentType not like ?").append(size);
                }
            }
        } else {
            params.add(size++, filter.getType().getContentTypePrefix() + "%");
            whereClause.append(" AND m.contentType like ?").append(size);
        }
    }

    if (filter.getOrder() != null) {
        switch (filter.getOrder()) {
        case NAME:
            orderBy.append(" order by m.name");
            break;
        case DATE_UPLOADED:
            orderBy.append(" order by m.dateUploaded");
            break;
        case TYPE:
            orderBy.append(" order by m.contentType");
            break;
        default:
        }
    } else {
        orderBy.append(" order by m.name");
    }

    Query query = strategy
            .getDynamicQuery(queryString.toString() + whereClause.toString() + orderBy.toString());
    for (int i = 0; i < params.size(); i++) {
        query.setParameter(i + 1, params.get(i));
    }

    if (filter.getStartIndex() >= 0) {
        query.setFirstResult(filter.getStartIndex());
        query.setMaxResults(filter.getLength());
    }
    return query.getResultList();
}

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

private void buildPartitionKeyTokens(MetamodelImpl metaModel, SingularAttribute idAttribute, Object id,
        CQLTranslator translator, StringBuilder pkNameTokens, StringBuilder pkValueTokens) {
    EmbeddableType keyObj = metaModel.embeddable(entityMetadata.getIdAttribute().getBindableJavaType());
    Field embeddedField = getPartitionKeyField();

    if (embeddedField == null) {
        // use tokens on the fields (no clustering keys
        Field[] fields = entityMetadata.getIdAttribute().getBindableJavaType().getDeclaredFields();

        for (Field field : fields) {
            Object value = PropertyAccessorHelper.getObject(id, field);
            String columnName = ((AbstractAttribute) keyObj.getAttribute(field.getName())).getJPAColumnName();
            translator.appendColumnName(pkNameTokens, columnName);
            translator.appendValue(pkValueTokens, field.getType(), value, false, false);
        }//from ww  w  . ja v  a  2  s . c o  m
    } else {
        // use tokens for partition key fields (fields in embeddedField) and
        // where clause for clustering fields
        Attribute partitionKey = keyObj.getAttribute(embeddedField.getName());
        EmbeddableType partitionKeyObj = metaModel.embeddable(partitionKey.getJavaType());
        Object partitionKeyValue = PropertyAccessorHelper.getObject(id, (Field) partitionKey.getJavaMember());
        Field[] fields = partitionKey.getJavaType().getDeclaredFields();
        // handle for part keys
        for (Field field : fields) {
            if (!ReflectUtils.isTransientOrStatic(field)) {
                Object value = PropertyAccessorHelper.getObject(partitionKeyValue, field);
                String columnName = ((AbstractAttribute) partitionKeyObj.getAttribute(field.getName()))
                        .getJPAColumnName();
                translator.appendColumnName(pkNameTokens, columnName);
                translator.appendValue(pkValueTokens, field.getType(), value, false, false);
                pkNameTokens.append(CQLTranslator.COMMA_STR);
                pkValueTokens.append(CQLTranslator.COMMA_STR);
            }
        }
        pkNameTokens.delete(pkNameTokens.lastIndexOf(CQLTranslator.COMMA_STR), pkNameTokens.length());
        pkValueTokens.delete(pkValueTokens.lastIndexOf(CQLTranslator.COMMA_STR), pkValueTokens.length());
        pkNameTokens.append(CQLTranslator.CLOSE_BRACKET);
        pkValueTokens.append(CQLTranslator.CLOSE_BRACKET);

        // TODO: handle for cluster keys
        throw new UnsupportedOperationException(
                "Pagination is not suported via ThriftClient on primary key with clustering keys...");
    }

}

From source file:org.apache.sling.scripting.sightly.impl.engine.extension.URIManipulationFilterExtension.java

@Override
@SuppressWarnings("unchecked")
public Object call(RenderContext renderContext, Object... arguments) {
    ExtensionUtils.checkArgumentCount(RuntimeFunction.URI_MANIPULATION, arguments, 2);
    RuntimeObjectModel runtimeObjectModel = renderContext.getObjectModel();
    String uriString = runtimeObjectModel.toString(arguments[0]);
    Map<String, Object> options = runtimeObjectModel.toMap(arguments[1]);
    StringBuilder sb = new StringBuilder();
    PathInfo pathInfo = new PathInfo(uriString);
    uriAppender(sb, SCHEME, options, pathInfo.getScheme());
    if (sb.length() > 0) {
        sb.append(":");
        sb.append(StringUtils.defaultIfEmpty(pathInfo.getBeginPathSeparator(), "//"));
    }// ww  w.  jav a2s .  c  o m
    if (sb.length() > 0) {
        uriAppender(sb, DOMAIN, options, pathInfo.getHost());
    } else {
        String domain = getOption(DOMAIN, options, pathInfo.getHost());
        if (StringUtils.isNotEmpty(domain)) {
            sb.append("//").append(domain);
        }
    }
    if (pathInfo.getPort() > -1) {
        sb.append(":").append(pathInfo.getPort());
    }
    String prependPath = getOption(PREPEND_PATH, options, StringUtils.EMPTY);
    if (prependPath == null) {
        prependPath = StringUtils.EMPTY;
    }
    String path = getOption(PATH, options, pathInfo.getPath());
    if (StringUtils.isEmpty(path)) {
        // if the path is forced to be empty don't remove the path
        path = pathInfo.getPath();
    }
    if (StringUtils.isNotEmpty(path) && !"/".equals(path)) {
        if (StringUtils.isNotEmpty(prependPath)) {
            if (sb.length() > 0 && !prependPath.startsWith("/")) {
                prependPath = "/" + prependPath;
            }
            if (!prependPath.endsWith("/")) {
                prependPath += "/";
            }
        }

        String appendPath = getOption(APPEND_PATH, options, StringUtils.EMPTY);
        if (appendPath == null) {
            appendPath = StringUtils.EMPTY;
        }
        if (StringUtils.isNotEmpty(appendPath)) {
            if (!appendPath.startsWith("/")) {
                appendPath = "/" + appendPath;
            }
        }
        String newPath;
        try {
            newPath = new URI(prependPath + path + appendPath).normalize().getPath();
        } catch (URISyntaxException e) {
            newPath = prependPath + path + appendPath;
        }
        if (sb.length() > 0 && sb.lastIndexOf("/") != sb.length() - 1 && StringUtils.isNotEmpty(newPath)
                && !newPath.startsWith("/")) {
            sb.append("/");
        }
        sb.append(newPath);
        Set<String> selectors = pathInfo.getSelectors();
        handleSelectors(runtimeObjectModel, selectors, options);
        for (String selector : selectors) {
            if (StringUtils.isNotBlank(selector) && !selector.contains(" ")) {
                // make sure not to append empty or invalid selectors
                sb.append(".").append(selector);
            }
        }
        String extension = getOption(EXTENSION, options, pathInfo.getExtension());
        if (StringUtils.isNotEmpty(extension)) {
            sb.append(".").append(extension);
        }

        String prependSuffix = getOption(PREPEND_SUFFIX, options, StringUtils.EMPTY);
        if (StringUtils.isNotEmpty(prependSuffix)) {
            if (!prependSuffix.startsWith("/")) {
                prependSuffix = "/" + prependSuffix;
            }
            if (!prependSuffix.endsWith("/")) {
                prependSuffix += "/";
            }
        }
        String pathInfoSuffix = pathInfo.getSuffix();
        String suffix = getOption(SUFFIX, options, pathInfoSuffix == null ? StringUtils.EMPTY : pathInfoSuffix);
        if (suffix == null) {
            suffix = StringUtils.EMPTY;
        }
        String appendSuffix = getOption(APPEND_SUFFIX, options, StringUtils.EMPTY);
        if (StringUtils.isNotEmpty(appendSuffix)) {
            appendSuffix = "/" + appendSuffix;
        }
        String newSuffix = FilenameUtils.normalize(prependSuffix + suffix + appendSuffix, true);
        if (StringUtils.isNotEmpty(newSuffix)) {
            if (!newSuffix.startsWith("/")) {
                sb.append("/");
            }
            sb.append(newSuffix);
        }

    } else if ("/".equals(path)) {
        sb.append(path);
    }
    Map<String, Collection<String>> parameters = pathInfo.getParameters();
    handleParameters(runtimeObjectModel, parameters, options);
    if (sb.length() > 0 && !parameters.isEmpty()) {
        if (StringUtils.isEmpty(path)) {
            sb.append("/");
        }
        sb.append("?");
        for (Map.Entry<String, Collection<String>> entry : parameters.entrySet()) {
            for (String value : entry.getValue()) {
                sb.append(entry.getKey()).append("=").append(value).append("&");
            }
        }
        // delete the last &
        sb.deleteCharAt(sb.length() - 1);
    }
    String fragment = getOption(FRAGMENT, options, pathInfo.getFragment());
    if (StringUtils.isNotEmpty(fragment)) {
        sb.append("#").append(fragment);
    }
    return sb.toString();
}

From source file:com.impetus.client.cassandra.CassandraClientBase.java

/**
 * On delete query./*from w  w w. j  a v  a 2s .  co  m*/
 * 
 * @param metadata
 *            the metadata
 * @param tableName
 *            TODO
 * @param metaModel
 *            the meta model
 * @param keyObject
 *            the compound key object
 * @return the string
 */
protected String onDeleteQuery(EntityMetadata metadata, String tableName, MetamodelImpl metaModel,
        Object keyObject) {
    CQLTranslator translator = new CQLTranslator();
    String deleteQuery = CQLTranslator.DELETE_QUERY;

    deleteQuery = StringUtils.replace(deleteQuery, CQLTranslator.COLUMN_FAMILY,
            translator.ensureCase(new StringBuilder(), tableName, false).toString());

    StringBuilder deleteQueryBuilder = new StringBuilder(deleteQuery);

    deleteQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE);
    onWhereClause(metadata, keyObject, translator, deleteQueryBuilder, metaModel, metadata.getIdAttribute());

    // strip last "AND" clause.
    deleteQueryBuilder.delete(deleteQueryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE),
            deleteQueryBuilder.length());

    if (log.isDebugEnabled()) {
        log.debug("Returning delete query {}.", deleteQueryBuilder.toString());
    }
    return deleteQueryBuilder.toString();
}

From source file:com.impetus.client.cassandra.CassandraClientBase.java

/**
 * Find inverse join column values for join column.
 * //  ww w.  j  a v a  2  s  .c  om
 * @param <E>
 *            the element type
 * @param schemaName
 *            the schema name
 * @param tableName
 *            the table name
 * @param pKeyColumnName
 *            the key column name
 * @param columnName
 *            the column name
 * @param pKeyColumnValue
 *            the key column value
 * @param columnJavaType
 *            the column java type
 * @return the columns by id using cql
 */
protected <E> List<E> getColumnsByIdUsingCql(String schemaName, String tableName, String pKeyColumnName,
        String columnName, Object pKeyColumnValue, Class columnJavaType) {
    // select columnName from tableName where pKeyColumnName =
    // pKeyColumnValue
    List results = new ArrayList();
    CQLTranslator translator = new CQLTranslator();
    String selectQuery = translator.SELECT_QUERY;
    selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMN_FAMILY,
            translator.ensureCase(new StringBuilder(), tableName, false).toString());
    selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMNS,
            translator.ensureCase(new StringBuilder(), columnName, false).toString());

    StringBuilder selectQueryBuilder = new StringBuilder(selectQuery);

    selectQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE);

    translator.buildWhereClause(selectQueryBuilder, columnJavaType, pKeyColumnName, pKeyColumnValue,
            CQLTranslator.EQ_CLAUSE, false);
    selectQueryBuilder.delete(selectQueryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE),
            selectQueryBuilder.length());

    CqlResult cqlResult = execute(selectQueryBuilder.toString(), getRawClient(schemaName));

    Iterator<CqlRow> rowIter = cqlResult.getRows().iterator();
    while (rowIter.hasNext()) {
        CqlRow row = rowIter.next();

        if (!row.getColumns().isEmpty()) {
            Column column = row.getColumns().get(0);
            Object columnValue = CassandraDataTranslator.decompose(columnJavaType, column.getValue(), true);
            results.add(columnValue);
        }
    }
    return results;
}

From source file:org.apache.xml.security.c14n.implementations.Canonicalizer11.java

private static String removeDotSegments(String path) {
    if (log.isDebugEnabled()) {
        log.debug("STEP   OUTPUT BUFFER\t\tINPUT BUFFER");
    }//from ww w  .  ja v  a  2  s  .co m

    // 1. The input buffer is initialized with the now-appended path
    // components then replace occurrences of "//" in the input buffer
    // with "/" until no more occurrences of "//" are in the input buffer.
    String input = path;
    while (input.indexOf("//") > -1) {
        input = input.replaceAll("//", "/");
    }

    // Initialize the output buffer with the empty string.
    StringBuilder output = new StringBuilder();

    // If the input buffer starts with a root slash "/" then move this
    // character to the output buffer.
    if (input.charAt(0) == '/') {
        output.append("/");
        input = input.substring(1);
    }

    printStep("1 ", output.toString(), input);

    // While the input buffer is not empty, loop as follows
    while (input.length() != 0) {
        // 2A. If the input buffer begins with a prefix of "./",
        // then remove that prefix from the input buffer
        // else if the input buffer begins with a prefix of "../", then
        // if also the output does not contain the root slash "/" only,
        // then move this prefix to the end of the output buffer else
        // remove that prefix
        if (input.startsWith("./")) {
            input = input.substring(2);
            printStep("2A", output.toString(), input);
        } else if (input.startsWith("../")) {
            input = input.substring(3);
            if (!output.toString().equals("/")) {
                output.append("../");
            }
            printStep("2A", output.toString(), input);
            // 2B. if the input buffer begins with a prefix of "/./" or "/.",
            // where "." is a complete path segment, then replace that prefix
            // with "/" in the input buffer; otherwise,
        } else if (input.startsWith("/./")) {
            input = input.substring(2);
            printStep("2B", output.toString(), input);
        } else if (input.equals("/.")) {
            // FIXME: what is complete path segment?
            input = input.replaceFirst("/.", "/");
            printStep("2B", output.toString(), input);
            // 2C. if the input buffer begins with a prefix of "/../" or "/..",
            // where ".." is a complete path segment, then replace that prefix
            // with "/" in the input buffer and if also the output buffer is
            // empty, last segment in the output buffer equals "../" or "..",
            // where ".." is a complete path segment, then append ".." or "/.."
            // for the latter case respectively to the output buffer else
            // remove the last segment and its preceding "/" (if any) from the
            // output buffer and if hereby the first character in the output
            // buffer was removed and it was not the root slash then delete a
            // leading slash from the input buffer; otherwise,
        } else if (input.startsWith("/../")) {
            input = input.substring(3);
            if (output.length() == 0) {
                output.append("/");
            } else if (output.toString().endsWith("../")) {
                output.append("..");
            } else if (output.toString().endsWith("..")) {
                output.append("/..");
            } else {
                int index = output.lastIndexOf("/");
                if (index == -1) {
                    output = new StringBuilder();
                    if (input.charAt(0) == '/') {
                        input = input.substring(1);
                    }
                } else {
                    output = output.delete(index, output.length());
                }
            }
            printStep("2C", output.toString(), input);
        } else if (input.equals("/..")) {
            // FIXME: what is complete path segment?
            input = input.replaceFirst("/..", "/");
            if (output.length() == 0) {
                output.append("/");
            } else if (output.toString().endsWith("../")) {
                output.append("..");
            } else if (output.toString().endsWith("..")) {
                output.append("/..");
            } else {
                int index = output.lastIndexOf("/");
                if (index == -1) {
                    output = new StringBuilder();
                    if (input.charAt(0) == '/') {
                        input = input.substring(1);
                    }
                } else {
                    output = output.delete(index, output.length());
                }
            }
            printStep("2C", output.toString(), input);
            // 2D. if the input buffer consists only of ".", then remove
            // that from the input buffer else if the input buffer consists
            // only of ".." and if the output buffer does not contain only
            // the root slash "/", then move the ".." to the output buffer
            // else delte it.; otherwise,
        } else if (input.equals(".")) {
            input = "";
            printStep("2D", output.toString(), input);
        } else if (input.equals("..")) {
            if (!output.toString().equals("/"))
                output.append("..");
            input = "";
            printStep("2D", output.toString(), input);
            // 2E. move the first path segment (if any) in the input buffer
            // to the end of the output buffer, including the initial "/"
            // character (if any) and any subsequent characters up to, but not
            // including, the next "/" character or the end of the input buffer.
        } else {
            int end = -1;
            int begin = input.indexOf('/');
            if (begin == 0) {
                end = input.indexOf('/', 1);
            } else {
                end = begin;
                begin = 0;
            }
            String segment;
            if (end == -1) {
                segment = input.substring(begin);
                input = "";
            } else {
                segment = input.substring(begin, end);
                input = input.substring(end);
            }
            output.append(segment);
            printStep("2E", output.toString(), input);
        }
    }

    // 3. Finally, if the only or last segment of the output buffer is
    // "..", where ".." is a complete path segment not followed by a slash
    // then append a slash "/". The output buffer is returned as the result
    // of remove_dot_segments
    if (output.toString().endsWith("..")) {
        output.append("/");
        printStep("3 ", output.toString(), input);
    }

    return output.toString();
}

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

/**
 * Builds where Clause.//from ww  w . j  a  v a  2 s.c  om
 * 
 * @param kunderaQuery
 *            the kundera query
 * @param metadata
 *            the metadata
 * @param metaModel
 *            the meta model
 * @param translator
 *            the translator
 * @param builder
 *            the builder
 */
private void buildWhereClause(KunderaQuery kunderaQuery, EntityMetadata metadata, MetamodelImpl metaModel,
        CQLTranslator translator, StringBuilder builder) {
    for (Object clause : kunderaQuery.getFilterClauseQueue()) {
        FilterClause filterClause = (FilterClause) clause;
        Field f = (Field) metaModel.entity(metadata.getEntityClazz())
                .getAttribute(metadata.getFieldName(filterClause.getProperty())).getJavaMember();
        String jpaColumnName = getColumnName(metadata, filterClause.getProperty());

        if (metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {
            Field[] fields = metadata.getIdAttribute().getBindableJavaType().getDeclaredFields();
            EmbeddableType compoundKey = metaModel.embeddable(metadata.getIdAttribute().getBindableJavaType());
            for (Field field : fields) {
                if (field != null && !Modifier.isStatic(field.getModifiers())
                        && !Modifier.isTransient(field.getModifiers())
                        && !field.isAnnotationPresent(Transient.class)) {
                    Attribute attribute = compoundKey.getAttribute(field.getName());
                    String columnName = ((AbstractAttribute) attribute).getJPAColumnName();
                    Object value = PropertyAccessorHelper.getObject(filterClause.getValue().get(0), field);
                    // TODO
                    translator.buildWhereClause(builder, field.getType(), columnName, value,
                            filterClause.getCondition(), false);
                }
            }
        } else {
            translator.buildWhereClause(builder, f.getType(), jpaColumnName, filterClause.getValue().get(0),
                    filterClause.getCondition(), false);
        }
    }
    builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length());
}