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:com.impetus.client.rdbms.query.RDBMSEntityReader.java

/**
 * /*from   www . j a  va2s  .  co m*/
 * @param entityMetadata
 * @param primaryKeys
 * @param aliasName
 * @param queryBuilder
 * @param entityType
 */
private void onCondition(EntityMetadata entityMetadata, MetamodelImpl metamodel, Set<String> primaryKeys,
        String aliasName, StringBuilder queryBuilder, EntityType entityType) {
    if (primaryKeys == null) {
        for (Object o : conditions) {
            if (o instanceof FilterClause) {
                FilterClause clause = ((FilterClause) o);
                Object value = clause.getValue().get(0);
                String propertyName = clause.getProperty();
                String condition = clause.getCondition();

                if (StringUtils.contains(propertyName, '.')) {
                    int indexOf = propertyName.indexOf(".");
                    String jpaColumnName = propertyName.substring(0, indexOf);
                    String embeddedColumnName = propertyName.substring(indexOf + 1, propertyName.length());
                    String fieldName = entityMetadata.getFieldName(jpaColumnName);
                    Attribute attribute = entityType.getAttribute(fieldName);
                    EmbeddableType embeddedType = metamodel
                            .embeddable(((AbstractAttribute) attribute).getBindableJavaType());
                    Attribute embeddedAttribute = embeddedType.getAttribute(embeddedColumnName);

                    addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition, fieldName,
                            embeddedAttribute);
                } else {
                    String fieldName = entityMetadata.getFieldName(propertyName);
                    Attribute attribute = entityType.getAttribute(fieldName);
                    if (metamodel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) {
                        EmbeddableType embeddedType = metamodel
                                .embeddable(((AbstractAttribute) attribute).getBindableJavaType());
                        Set<Attribute> attributes = embeddedType.getAttributes();
                        for (Attribute embeddedAttribute : attributes) {
                            Object embeddedAttributevalue = PropertyAccessorHelper.getObject(value,
                                    (Field) embeddedAttribute.getJavaMember());
                            addClause(entityMetadata, aliasName, queryBuilder, entityType,
                                    embeddedAttributevalue, condition, propertyName, embeddedAttribute);
                            queryBuilder.append(" and ");
                        }

                        queryBuilder.delete(queryBuilder.lastIndexOf("and"),
                                queryBuilder.lastIndexOf("and") + 3);
                    } else if (((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()
                            .equals(propertyName)) {
                        addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition,
                                propertyName, entityMetadata.getIdAttribute());
                    } else {
                        addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition,
                                propertyName, attribute);
                    }
                }
            } else {
                queryBuilder.append(" ");
                queryBuilder.append(o);
                queryBuilder.append(" ");
            }
        }
    } else {
        queryBuilder.append(aliasName);
        queryBuilder.append(".");
        queryBuilder.append(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName());
        queryBuilder.append(" ");
        queryBuilder.append("IN(");
        int count = 0;
        Attribute col = entityMetadata.getIdAttribute();
        boolean isString = isStringProperty(entityType, col);
        for (String key : primaryKeys) {
            appendStringPrefix(queryBuilder, isString);
            queryBuilder.append(key);
            appendStringPrefix(queryBuilder, isString);
            if (++count != primaryKeys.size()) {
                queryBuilder.append(",");
            } else {
                queryBuilder.append(")");
            }
        }
    }
}

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

/**
 * Append order by clause.//w  w w. j  ava  2  s . com
 * 
 * @param metaModel
 *            the meta model
 * @param m
 *            the m
 * @param keyObj
 *            the key obj
 * @param builder
 *            the builder
 * @param translator
 *            the translator
 * @return the string builder
 */
private StringBuilder appendOrderByClause(MetamodelImpl metaModel, EntityMetadata m, EmbeddableType keyObj,
        StringBuilder builder, CQLTranslator translator) {
    List<SortOrdering> orders = getKunderaQuery().getOrdering();

    if (orders != null) {
        builder.append(CQLTranslator.SPACE_STRING);
        builder.append(CQLTranslator.SORT_CLAUSE);

        for (SortOrdering order : orders) {
            String orderColumnName = order.getColumnName();

            orderColumnName = orderColumnName.substring(orderColumnName.indexOf(".") + 1,
                    orderColumnName.length());

            String orderByColumnName;

            if (StringUtils.contains(orderColumnName, '.')) {
                String propertyName = orderColumnName.substring(0, orderColumnName.indexOf("."));
                Attribute embeddableAttribute = metaModel.getEntityAttribute(m.getEntityClazz(), propertyName);
                EmbeddableType embeddableType = metaModel
                        .embeddable(((AbstractAttribute) embeddableAttribute).getBindableJavaType());
                orderColumnName = orderColumnName.substring(orderColumnName.indexOf(".") + 1);
                AbstractAttribute attribute = (AbstractAttribute) embeddableType.getAttribute(orderColumnName);
                orderByColumnName = attribute.getJPAColumnName();

            } else {
                Attribute attribute = metaModel.getEntityAttribute(m.getEntityClazz(), orderColumnName);
                orderByColumnName = ((AbstractAttribute) attribute).getJPAColumnName();
            }

            builder = translator.ensureCase(builder, orderByColumnName, false);
            builder.append(CQLTranslator.SPACE_STRING);
            builder.append(order.getOrder());
            builder.append(CQLTranslator.COMMA_STR);
        }

        if (!orders.isEmpty()) {
            builder.deleteCharAt(builder.lastIndexOf(CQLTranslator.COMMA_STR));
        }
    }
    return builder;
}

From source file:com.impetus.client.cassandra.schemamanager.CassandraSchemaManager.java

/**
 * On cql3 create keyspace.//from   w ww . j a  va  2  s .c o  m
 * 
 * @throws InvalidRequestException
 *             the invalid request exception
 * @throws UnavailableException
 *             the unavailable exception
 * @throws TimedOutException
 *             the timed out exception
 * @throws SchemaDisagreementException
 *             the schema disagreement exception
 * @throws TException
 *             the t exception
 * @throws UnsupportedEncodingException
 *             the unsupported encoding exception
 */
private void onCql3CreateKeyspace() throws InvalidRequestException, UnavailableException, TimedOutException,
        SchemaDisagreementException, TException, UnsupportedEncodingException {
    String createKeyspace = CQLTranslator.CREATE_KEYSPACE;
    String placement_strategy = csmd.getPlacement_strategy(databaseName);
    String replication_conf = CQLTranslator.SIMPLE_REPLICATION;
    createKeyspace = createKeyspace.replace("$KEYSPACE",
            Constants.ESCAPE_QUOTE + databaseName + Constants.ESCAPE_QUOTE);

    Schema schema = CassandraPropertyReader.csmd.getSchema(databaseName);

    if (schema != null && schema.getName() != null && schema.getName().equalsIgnoreCase(databaseName)
            && schema.getSchemaProperties() != null) {
        Properties schemaProperties = schema.getSchemaProperties();
        if (placement_strategy.equalsIgnoreCase(SimpleStrategy.class.getSimpleName())
                || placement_strategy.equalsIgnoreCase(SimpleStrategy.class.getName())) {
            String replicationFactor = schemaProperties.getProperty(CassandraConstants.REPLICATION_FACTOR,
                    CassandraConstants.DEFAULT_REPLICATION_FACTOR);

            replication_conf = replication_conf.replace("$REPLICATION_FACTOR", replicationFactor);
            createKeyspace = createKeyspace.replace("$CLASS", placement_strategy);
        } else if (placement_strategy.equalsIgnoreCase(NetworkTopologyStrategy.class.getSimpleName())
                || placement_strategy.equalsIgnoreCase(NetworkTopologyStrategy.class.getName())) {

            if (schema.getDataCenters() != null && !schema.getDataCenters().isEmpty()) {
                StringBuilder builder = new StringBuilder();

                for (DataCenter dc : schema.getDataCenters()) {
                    builder.append(CQLTranslator.QUOTE_STR);
                    builder.append(dc.getName());
                    builder.append(CQLTranslator.QUOTE_STR);
                    builder.append(":");
                    builder.append(dc.getValue());
                    builder.append(CQLTranslator.COMMA_STR);
                }

                builder.delete(builder.lastIndexOf(CQLTranslator.COMMA_STR), builder.length());

                replication_conf = builder.toString();
            }
        }

        createKeyspace = createKeyspace.replace("$CLASS", placement_strategy);
        createKeyspace = createKeyspace.replace("$REPLICATION", replication_conf);

        boolean isDurableWrites = Boolean
                .parseBoolean(schemaProperties.getProperty(CassandraConstants.DURABLE_WRITES, "true"));
        createKeyspace = createKeyspace.replace("$DURABLE_WRITES", isDurableWrites + "");
    } else {
        createKeyspace = createKeyspace.replace("$CLASS", placement_strategy);
        replication_conf = replication_conf.replace("$REPLICATION_FACTOR",
                CassandraConstants.DEFAULT_REPLICATION_FACTOR);
        createKeyspace = createKeyspace.replace("$REPLICATION", replication_conf);
        createKeyspace = createKeyspace.replace("$DURABLE_WRITES", "true");
    }
    cassandra_client.execute_cql3_query(ByteBuffer.wrap(createKeyspace.getBytes(Constants.CHARSET_UTF8)),
            Compression.NONE, ConsistencyLevel.ONE);
    KunderaCoreUtils.printQuery(createKeyspace, showQuery);
}

From source file:com.impetus.client.rdbms.query.RDBMSEntityReader.java

/**
 * Gets the sql query from jpa.//from  ww w . ja v  a2 s.  c o m
 * 
 * @param entityMetadata
 *            the entity metadata
 * @param relations
 *            the relations
 * @param primaryKeys
 *            the primary keys
 * @return the sql query from jpa
 */
public String getSqlQueryFromJPA(EntityMetadata entityMetadata, List<String> relations,
        Set<String> primaryKeys) {
    ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
    Metamodel metaModel = appMetadata.getMetamodel(entityMetadata.getPersistenceUnit());

    if (jpaQuery != null) {
        String query = appMetadata.getQuery(jpaQuery);
        boolean isNative = kunderaQuery != null ? kunderaQuery.isNative() : false;

        if (isNative) {
            return query != null ? query : jpaQuery;
        }
    }

    // Suffixing the UNDERSCORE instead of prefix as Oracle 11g complains
    // about invalid characters error while executing the request.
    String aliasName = entityMetadata.getTableName() + "_";

    StringBuilder queryBuilder = new StringBuilder("Select ");

    EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());
    Set<Attribute> attributes = entityType.getAttributes();
    for (Attribute field : attributes) {
        if (!field.isAssociation() && !field.isCollection()
                && !((Field) field.getJavaMember()).isAnnotationPresent(ManyToMany.class)
                && !((Field) field.getJavaMember()).isAnnotationPresent(Transient.class)
                && !((MetamodelImpl) metaModel)
                        .isEmbeddable(((AbstractAttribute) field).getBindableJavaType())) {
            queryBuilder.append(aliasName);
            queryBuilder.append(".");
            queryBuilder.append(((AbstractAttribute) field).getJPAColumnName());
            queryBuilder.append(", ");
        }
    }

    // Handle embedded columns, add them to list.
    Map<String, EmbeddableType> embeddedColumns = ((MetamodelImpl) metaModel)
            .getEmbeddables(entityMetadata.getEntityClazz());
    for (EmbeddableType embeddedCol : embeddedColumns.values()) {
        Set<Attribute> embeddedAttributes = embeddedCol.getAttributes();
        for (Attribute column : embeddedAttributes) {
            queryBuilder.append(aliasName);
            queryBuilder.append(".");
            queryBuilder.append(((AbstractAttribute) column).getJPAColumnName());
            queryBuilder.append(", ");
        }
    }

    if (relations != null) {
        for (String relation : relations) {
            Relation rel = entityMetadata.getRelation(entityMetadata.getFieldName(relation));
            String r = MetadataUtils.getMappedName(entityMetadata, rel, kunderaMetadata);
            if (!((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()
                    .equalsIgnoreCase(r != null ? r : relation) && rel != null
                    && !rel.getProperty().isAnnotationPresent(ManyToMany.class)
                    && !rel.getProperty().isAnnotationPresent(OneToMany.class)
                    && (rel.getProperty().isAnnotationPresent(OneToOne.class)
                            && StringUtils.isBlank(rel.getMappedBy())
                            || rel.getProperty().isAnnotationPresent(ManyToOne.class))) {
                queryBuilder.append(aliasName);
                queryBuilder.append(".");
                queryBuilder.append(r != null ? r : relation);
                queryBuilder.append(", ");
            }
        }
    }

    // Remove last ","
    queryBuilder.deleteCharAt(queryBuilder.lastIndexOf(","));

    queryBuilder.append(" From ");
    if (entityMetadata.getSchema() != null && !entityMetadata.getSchema().isEmpty()) {
        queryBuilder.append(entityMetadata.getSchema() + ".");
    }
    queryBuilder.append(entityMetadata.getTableName());
    queryBuilder.append(" ");
    queryBuilder.append(aliasName);
    // add conditions
    if (filter != null) {
        queryBuilder.append(" Where ");
    }

    // Append conditions
    onCondition(entityMetadata, (MetamodelImpl) metaModel, primaryKeys, aliasName, queryBuilder, entityType);

    return queryBuilder.toString();
}

From source file:us.mn.state.health.lims.sample.daoimpl.SearchResultsDAOImp.java

/**
 * @param lastName//  w  ww  .  j  a v  a  2 s  .c o m
 * @param firstName
 * @param STNumber
 * @param subjectNumber
 * @param nationalID
 * @param externalID
 * @param patientID - if a previous query has already found a candidate patient
 */
private String buildQueryString(boolean lastName, boolean firstName, boolean STNumber, boolean subjectNumber,
        boolean nationalID, boolean externalID, boolean anyID, boolean patientID, boolean guid) {

    StringBuilder queryBuilder = new StringBuilder();
    queryBuilder.append(
            "select p.id, pr.first_name, pr.last_name, p.gender, p.entered_birth_date, p.national_id, p.external_id, pi.identity_data as st, piSN.identity_data as subject, piGUID.identity_data as guid from patient p join person pr on p.person_id = pr.id ");
    queryBuilder.append("left join patient_identity  pi on pi.patient_id = p.id and pi.identity_type_id = '");
    queryBuilder.append(PatientIdentityTypeMap.getInstance().getIDForType("ST"));
    queryBuilder.append("' ");

    queryBuilder
            .append("left join patient_identity  piSN on piSN.patient_id = p.id and piSN.identity_type_id = '");
    queryBuilder.append(PatientIdentityTypeMap.getInstance().getIDForType("SUBJECT"));
    queryBuilder.append("' ");

    queryBuilder.append(
            "left join patient_identity  piGUID on piGUID.patient_id = p.id and piGUID.identity_type_id = '");
    queryBuilder.append(PatientIdentityTypeMap.getInstance().getIDForType("GUID"));
    queryBuilder.append("' where ");

    if (lastName) {
        queryBuilder.append(" pr.last_name ilike :");
        queryBuilder.append(LAST_NAME_PARAM);
        queryBuilder.append(" and");
    }

    if (firstName) {
        queryBuilder.append(" pr.first_name ilike :");
        queryBuilder.append(FIRST_NAME_PARAM);
        queryBuilder.append(" and");
    }

    if (anyID) {
        if (nationalID) {
            queryBuilder.append(" p.national_id ilike :");
            queryBuilder.append(NATIONAL_ID_PARAM);
            queryBuilder.append(" or ");
        }

        if (externalID) {
            queryBuilder.append(" p.external_id ilike :");
            queryBuilder.append(EXTERNAL_ID_PARAM);
            queryBuilder.append(" or");
        }
    } else {

        if (nationalID) {
            queryBuilder.append(" p.national_id ilike :");
            queryBuilder.append(NATIONAL_ID_PARAM);
            queryBuilder.append(" or");
        }

        if (externalID) {
            queryBuilder.append(" p.external_id ilike :");
            queryBuilder.append(EXTERNAL_ID_PARAM);
            queryBuilder.append(" or");
        }
    }

    if (STNumber) {
        queryBuilder.append(" pi.identity_data like :");
        queryBuilder.append(ST_NUMBER_PARAM);
        queryBuilder.append(" or");
    }

    if (subjectNumber) {
        queryBuilder.append(" piSN.identity_data like :");
        queryBuilder.append(SUBJECT_NUMBER_PARAM);
        queryBuilder.append(" or");
    }

    if (patientID) {
        queryBuilder.append(" p.id = :");
        queryBuilder.append(ID_PARAM);
        queryBuilder.append(" or");
    }

    if (guid) {
        queryBuilder.append(" piGUID.identity_data = :");
        queryBuilder.append(GUID);
        queryBuilder.append(" or");
    }
    // No matter which was added last there is one dangling AND to remove.
    int lastAndIndex = queryBuilder.lastIndexOf("and");
    int lastOrIndex = queryBuilder.lastIndexOf("or");

    if (lastAndIndex > lastOrIndex) {
        queryBuilder.delete(lastAndIndex, queryBuilder.length());
    } else if (lastOrIndex > lastAndIndex) {
        queryBuilder.delete(lastOrIndex, queryBuilder.length());
    }

    return queryBuilder.toString();
}

From source file:net.ymate.platform.persistence.jdbc.dialect.impl.MySQLDialect.java

@Override
public String buildCreateSQL(Class<? extends IEntity> entityClass, String prefix, IShardingable shardingable) {
    EntityMeta _meta = EntityMeta.createAndGet(entityClass);
    if (_meta != null) {
        ExpressionUtils _exp = ExpressionUtils
                .bind("CREATE TABLE ${table_name} (\n${fields} ${primary_keys} ${indexes}) ${comment} ")
                .set("table_name", buildTableName(prefix, _meta, shardingable));
        if (StringUtils.isNotBlank(_meta.getComment())) {
            _exp.set("comment", "COMMENT='" + StringUtils.trimToEmpty(_meta.getComment()) + "'");
        } else {/*ww w.ja  v  a2 s  .c o m*/
            _exp.set("comment", "");
        }
        StringBuilder _tmpBuilder = new StringBuilder();
        // FIELDs
        List<EntityMeta.PropertyMeta> _propMetas = new ArrayList<EntityMeta.PropertyMeta>(
                _meta.getProperties());
        Collections.sort(_propMetas, new Comparator<EntityMeta.PropertyMeta>() {
            @Override
            public int compare(EntityMeta.PropertyMeta o1, EntityMeta.PropertyMeta o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        for (EntityMeta.PropertyMeta _propMeta : _propMetas) {
            _tmpBuilder.append("\t").append(wrapIdentifierQuote(_propMeta.getName())).append(" ");
            String _propType = "";
            if (!_propMeta.getType().equals(Type.FIELD.UNKNOW)) {
                _propType = _propMeta.getType().name();
            } else {
                _propType = __doGetColumnType(_propMeta.getField().getType());
            }
            if ("VARCHAR".equals(_propType) && _propMeta.getLength() > 2000) {
                _propType = "TEXT";
            } else if ("BOOLEAN".equals(_propType) || "BIT".equals(_propType)) {
                _propType = "SMALLINT";
            }
            boolean _needLength = true;
            if ("DATE".equals(_propType) || "TIME".equals(_propType) || "TIMESTAMP".equals(_propType)
                    || "TEXT".equals(_propType)) {
                _needLength = false;
            }
            _tmpBuilder.append(_propType);
            if (_needLength) {
                _tmpBuilder.append("(").append(_propMeta.getLength());
                if (_propMeta.getDecimals() > 0) {
                    _tmpBuilder.append(",").append(_propMeta.getDecimals());
                }
                _tmpBuilder.append(")");
            }
            if (_propMeta.isUnsigned()) {
                if ("NUMERIC".equals(_propType) || "LONG".equals(_propType) || "FLOAT".equals(_propType)
                        || "DOUBLE".equals(_propType) || "SMALLINT".equals(_propType)
                        || "TINYINT".equals(_propType) || "DOUBLE".equals(_propType)
                        || "INTEGER".equals(_propType)) {
                    _tmpBuilder.append(" unsigned ");
                }
            }
            if (_propMeta.isNullable()) {
                if (StringUtils.isNotBlank(_propMeta.getDefaultValue())) {
                    if ("@NULL".equals(_propMeta.getDefaultValue())) {
                        _tmpBuilder.append(" DEFAULT NULL");
                    } else {
                        _tmpBuilder.append(" DEFAULT '").append(_propMeta.getDefaultValue()).append("'");
                    }
                }
            } else {
                _tmpBuilder.append(" NOT NULL");
            }
            if (_propMeta.isAutoincrement()) {
                _tmpBuilder.append(" AUTO_INCREMENT");
            }
            if (StringUtils.isNotBlank(_propMeta.getComment())) {
                _tmpBuilder.append(" COMMENT '").append(_propMeta.getComment()).append("'");
            }
            _tmpBuilder.append(__LINE_END_FLAG);
        }
        _exp.set("fields",
                _tmpBuilder.length() > 2 ? _tmpBuilder.substring(0, _tmpBuilder.lastIndexOf(__LINE_END_FLAG))
                        : "");
        // PKs
        _tmpBuilder.setLength(0);
        for (String _key : _meta.getPrimaryKeys()) {
            _tmpBuilder.append(wrapIdentifierQuote(_key)).append(",");
        }
        if (_tmpBuilder.length() > 0) {
            _tmpBuilder.setLength(_tmpBuilder.length() - 1);
            _tmpBuilder.insert(0, ",\n\tPRIMARY KEY (").append(")");
            _exp.set("primary_keys", _tmpBuilder.toString());
        }
        // INDEXs
        _tmpBuilder.setLength(0);
        if (!_meta.getIndexes().isEmpty()) {
            _tmpBuilder.append(__LINE_END_FLAG);
            for (EntityMeta.IndexMeta _index : _meta.getIndexes()) {
                if (!_index.getFields().isEmpty()) {
                    List<String> _idxFields = new ArrayList<String>(_index.getFields().size());
                    for (String _idxField : _index.getFields()) {
                        _idxFields.add(wrapIdentifierQuote(_idxField));
                    }
                    if (_index.isUnique()) {
                        _tmpBuilder.append("\tUNIQUE KEY ");
                    } else {
                        _tmpBuilder.append("\tINDEX ");
                    }
                    _tmpBuilder.append(wrapIdentifierQuote(_index.getName())).append(" (")
                            .append(StringUtils.join(_idxFields, ",")).append(")").append(__LINE_END_FLAG);
                }
            }
            if (_tmpBuilder.length() > 2) {
                _tmpBuilder.setLength(_tmpBuilder.length() - 2);
            }
        } else {
            _tmpBuilder.append("");
        }
        return _exp.set("indexes", _tmpBuilder.toString()).getResult();
    }
    return null;
}

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

/**
 * Return update query string for given entity intended for counter column
 * family.//from w  w w  .  j  a v  a2  s  . c  o m
 * 
 * @param entityMetadata
 *            the entity metadata
 * @param entity
 *            the entity
 * @param cassandra_client
 *            the cassandra_client
 * @param rlHolders
 *            the rl holders
 * @return the list
 */
protected List<String> createUpdateQueryForCounter(EntityMetadata entityMetadata, Object entity,
        Cassandra.Client cassandra_client, List<RelationHolder> rlHolders) {
    Map<String, String> builders = new HashMap<String, String>();

    CQLTranslator translator = new CQLTranslator();

    Object rowId = PropertyAccessorHelper.getId(entity, entityMetadata);
    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(entityMetadata.getPersistenceUnit());

    EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());

    Set<Attribute> attributes = entityType.getAttributes();

    for (Attribute attrib : attributes) {
        if (!entityMetadata.getIdAttribute().getName().equals(attrib.getName())
                && !metaModel.isEmbeddable(attrib.getJavaType()) && !attrib.isAssociation()) {
            String tableName = ((AbstractAttribute) attrib).getTableName() != null
                    ? ((AbstractAttribute) attrib).getTableName()
                    : entityMetadata.getTableName();

            String queryString = builders.get(tableName);
            StringBuilder builder;
            if (queryString == null) {
                builder = new StringBuilder();
            } else {
                builder = new StringBuilder(queryString);
            }
            translator.buildSetClauseForCounters(builder, ((AbstractAttribute) attrib).getJPAColumnName(),
                    PropertyAccessorHelper.getObject(entity, attrib.getName()));
            builders.put(tableName, builder.toString());
        }
    }
    for (RelationHolder rl : rlHolders) {
        translator.buildSetClauseForCounters(new StringBuilder(builders.get(entityMetadata.getTableName())),
                rl.getRelationName(), rl.getRelationValue());
    }

    for (String tableName : builders.keySet()) {
        StringBuilder builder = new StringBuilder(builders.get(tableName));

        String update_Query = translator.UPDATE_QUERY;

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

        // strip last "," clause.
        builder.delete(builder.lastIndexOf(CQLTranslator.COMMA_STR), builder.length());

        builder.append(CQLTranslator.ADD_WHERE_CLAUSE);
        onWhereClause(entityMetadata, rowId, translator, builder, metaModel, entityMetadata.getIdAttribute());

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

        StringBuilder queryBuilder = new StringBuilder(update_Query);
        queryBuilder.append(CQLTranslator.ADD_SET_CLAUSE);
        queryBuilder.append(builder);

        if (log.isDebugEnabled()) {
            log.debug("Returning update query {}.", queryBuilder.toString());
        }

        builders.put(tableName, queryBuilder.toString());
    }
    return new ArrayList(builders.values());
}

From source file:com.impetus.client.cassandra.schemamanager.CassandraSchemaManager.java

/**
 * Sets the column family properties.//from ww w  .  j av  a2s .  com
 * 
 * @param cfDef
 *            the cf def
 * @param cfProperties
 *            the c f properties
 * @param builder
 *            the builder
 */
private void setColumnFamilyProperties(CfDef cfDef, Properties cfProperties, StringBuilder builder) {
    if ((cfDef != null && cfProperties != null) || (builder != null && cfProperties != null)) {
        if (builder != null) {
            builder.append(CQLTranslator.WITH_CLAUSE);
        }
        onSetKeyValidation(cfDef, cfProperties, builder);

        onSetCompactionStrategy(cfDef, cfProperties, builder);

        onSetComparatorType(cfDef, cfProperties, builder);

        onSetSubComparator(cfDef, cfProperties, builder);

        //            onSetReplicateOnWrite(cfDef, cfProperties, builder);

        onSetCompactionThreshold(cfDef, cfProperties, builder);

        onSetComment(cfDef, cfProperties, builder);

        onSetTableId(cfDef, cfProperties, builder);

        onSetGcGrace(cfDef, cfProperties, builder);

        onSetCaching(cfDef, cfProperties, builder);

        onSetBloomFilter(cfDef, cfProperties, builder);

        onSetRepairChance(cfDef, cfProperties, builder);

        onSetReadRepairChance(cfDef, cfProperties, builder);

        // Strip last AND clause.
        if (builder != null && StringUtils.contains(builder.toString(), CQLTranslator.AND_CLAUSE)) {
            builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length());
            // builder.deleteCharAt(builder.length() - 2);
        }

        // Strip last WITH clause.
        if (builder != null && StringUtils.contains(builder.toString(), CQLTranslator.WITH_CLAUSE)) {
            builder.delete(builder.lastIndexOf(CQLTranslator.WITH_CLAUSE), builder.length());
            // builder.deleteCharAt(builder.length() - 2);
        }
    }
}

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

/**
 * This method invokes cancelDocument of DocumentService to delete selected requisitions.
 * Sets error message appriopriately if this action fails.
 *//*  w  w  w.  j ava2 s  .co  m*/
public void delete() {
    LOG.debug("Inside delete of OleOrderQueueDocument");
    WorkflowDocumentService workflowDocumentService = SpringContext.getBean(WorkflowDocumentService.class);
    Person principalPerson = SpringContext.getBean(PersonService.class)
            .getPerson(GlobalVariables.getUserSession().getPerson().getPrincipalId());
    WorkflowDocument workflowDocument;
    List<OleRequisitionItem> refreshItems = new ArrayList<OleRequisitionItem>();
    OleRequisitionDocument requisitionDocument;
    StringBuilder orderQueueRequisitionDeleted = new StringBuilder();
    boolean isErrorMsg = false;
    for (OleRequisitionItem item : requisitionItems) {
        boolean itemAdded = item.isItemAdded();
        if (itemAdded) {
            try {
                workflowDocument = workflowDocumentService
                        .loadWorkflowDocument(item.getRequisition().getDocumentNumber(), principalPerson);
                if (workflowDocument.isSaved()) {
                    requisitionDocument = SpringContext.getBean(BusinessObjectService.class)
                            .findBySinglePrimaryKey(OleRequisitionDocument.class,
                                    Long.valueOf(item.getRequisition().getPurapDocumentIdentifier()));
                    requisitionDocument.setDocumentHeader(SpringContext.getBean(DocumentHeaderService.class)
                            .getDocumentHeaderById(item.getRequisition().getDocumentNumber()));

                    try {
                        requisitionDocument.getDocumentHeader().setWorkflowDocument(workflowDocument);
                        SpringContext.getBean(DocumentService.class).cancelDocument(requisitionDocument,
                                OLEConstants.OrderQueue.CANCEL_ANNOTATION);
                        orderQueueRequisitionDeleted.append(item.getRequisition().getDocumentNumber())
                                .append(",");
                        isErrorMsg = true;
                    } catch (WorkflowException wfe) {
                        GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS,
                                OLEKeyConstants.ERROR_ORDERQUEUE_REQUISITIONS_CANCELED_WFE,
                                new String[] { requisitionDocument.getDocumentNumber(), wfe.getMessage() });
                        refreshItems.add(item);
                    }
                } else {
                    GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS,
                            OLEKeyConstants.ERROR_ORDERQUEUE_REQUISITIONS_CANCELED,
                            new String[] { workflowDocument.getStatus().toString(),
                                    item.getRequisition().getDocumentNumber() });
                    refreshItems.add(item);
                }
            } catch (WorkflowException ex) {
                GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS,
                        RiceKeyConstants.ERROR_CUSTOM, ex.getMessage());
                refreshItems.add(item);
            }
        } else {
            refreshItems.add(item);
        }
    }

    int len = orderQueueRequisitionDeleted.lastIndexOf(",");
    if (isErrorMsg) {
        orderQueueRequisitionDeleted.replace(len, len + 1, " ");
        GlobalVariables.getMessageMap().putInfo(OLEConstants.OrderQueue.REQUISITIONS,
                OLEKeyConstants.MESSAGE_ORDERQUEUE_REQUISITIONS_CANCELED,
                new String[] { orderQueueRequisitionDeleted.toString() });
    }
    requisitionItems = refreshItems;
    LOG.debug("Leaving delete of OleOrderQueueDocument");
}

From source file:edu.chalmers.dat076.moviefinder.service.TitleParser.java

private TemporaryMedia getInformation(StringBuilder mySb) {

    TemporaryMedia returnMedia = new TemporaryMedia();
    StringBuilder wordSb = new StringBuilder();

    int tmpYear;//from  w w  w  .  j  a  v a2  s  . c om
    int year = -1;
    int thisYear = Calendar.getInstance().get(Calendar.YEAR);

    boolean deleteYear = false;
    boolean finalWord = true;

    for (int i = 0; i < mySb.length(); i++) {
        if (mySb.charAt(i) == '.' || mySb.charAt(i) == ' ' || mySb.charAt(i) == '-' || mySb.charAt(i) == '_') {

            if (Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) {
                mySb.delete(i - (wordSb.length() + 1), mySb.length());
                finalWord = false;
                // final useful word found. No point in continuing.
                break;
            }
            mySb.replace(i, i + 1, " ");

            tmpYear = checkForYear(wordSb);
            if (tmpYear > 1900 && tmpYear <= thisYear) {
                year = tmpYear;
                deleteYear = true;
            }
            wordSb.setLength(0);

        } else if (wordSb.length() == 0
                && (mySb.charAt(i) == 'S' || mySb.charAt(i) == 's' || Character.isDigit(mySb.charAt(i)))) {
            // See if new word contains series and episode information.

            StringBuilder whatsLeft = new StringBuilder(mySb.subSequence(i, mySb.length()));
            if (getEpisodePotential(whatsLeft)) {
                TemporaryMedia tmpMedia = getEpisodeInfo(whatsLeft);
                returnMedia.setIsMovie(false);
                returnMedia.setSeason(tmpMedia.getSeason());
                returnMedia.setEpisode(tmpMedia.getEpisode());
                mySb.delete(i, mySb.length());
                // series and episode information saved. No point in continuing.
                break;

            } else {
                wordSb.append(mySb.charAt(i));
            }
        } else if (mySb.charAt(i) == '[' || mySb.charAt(i) == '(') {
            // Brackets shoudl usually be removed. They could possibly contain realease year.

            if (Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) {
                mySb.delete(i - (wordSb.length() + 1), mySb.length());
                finalWord = false;
                // final useful word found. No point in continuing.
                break;
            }
            tmpYear = checkForYear(wordSb);
            if (tmpYear > 1900 && tmpYear <= thisYear) {
                year = tmpYear;
                deleteYear = true;
            }
            wordSb.setLength(0);

            if (mySb.charAt(i) == '[') {
                tmpYear = removeUntil(mySb, i, ']');
            } else if (mySb.charAt(i) == '(') {
                tmpYear = removeUntil(mySb, i, ')');
            }
            if (tmpYear > 1900 && tmpYear <= thisYear) {
                year = tmpYear;
                deleteYear = false;
            }
            i--; // Need to compensate for removing bracket.

        } else {
            // Nothing useful here. Save the char and continue.
            wordSb.append(mySb.charAt(i));
        }
    }

    if (finalWord && Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) {
        mySb.delete(mySb.length() - wordSb.length(), mySb.length());
    } else {
        tmpYear = checkForYear(wordSb);
        if (tmpYear > 1900 && tmpYear <= thisYear) {
            year = tmpYear;
            deleteYear = true;
        }
    }
    if (deleteYear && returnMedia.IsMovie()) {
        int i = mySb.lastIndexOf(year + "");
        mySb.delete(i, i + 4);
    }

    returnMedia.setYear(year);
    returnMedia.setName(mySb.toString().trim());

    return returnMedia;
}