Example usage for java.lang StringBuilder delete

List of usage examples for java.lang StringBuilder delete

Introduction

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

Prototype

@Override
public StringBuilder delete(int start, int end) 

Source Link

Usage

From source file:org.apache.syncope.core.persistence.dao.impl.AbstractSubjectDAOImpl.java

/**
 * Generate one where clause for each different attribute schema into the derived schema expression provided.
 *
 * @param expression derived schema expression
 * @param value derived attribute value/*from w  w w .j a va  2s  . c o m*/
 * @param attrUtil USER / ROLE
 * @return where clauses to use to build the query
 */
private Set<String> getWhereClause(final String expression, final String value,
        final AttributableUtil attrUtil) {
    final Parser parser = new Parser(new StringReader(expression));

    // Schema names
    final List<String> identifiers = new ArrayList<String>();

    // Literals
    final List<String> literals = new ArrayList<String>();

    // Get schema names and literals
    Token token;
    while ((token = parser.getNextToken()) != null && StringUtils.isNotBlank(token.toString())) {
        if (token.kind == ParserConstants.STRING_LITERAL) {
            literals.add(token.toString().substring(1, token.toString().length() - 1));
        }

        if (token.kind == ParserConstants.IDENTIFIER) {
            identifiers.add(token.toString());
        }
    }

    // Sort literals in order to process later literals included into others
    Collections.sort(literals, new Comparator<String>() {

        @Override
        public int compare(final String t, final String t1) {
            if (t == null && t1 == null) {
                return 0;
            } else if (t != null && t1 == null) {
                return -1;
            } else if (t == null && t1 != null) {
                return 1;
            } else if (t.length() == t1.length()) {
                return 0;
            } else if (t.length() > t1.length()) {
                return -1;
            } else {
                return 1;
            }
        }
    });

    // Split value on provided literals
    final List<String> attrValues = split(value, literals);

    if (attrValues.size() != identifiers.size()) {
        LOG.error("Ambiguous jexl expression resolution.");
        throw new IllegalArgumentException("literals and values have different size");
    }

    // clauses to be used with INTERSECTed queries
    final Set<String> clauses = new HashSet<String>();

    // builder to build the clauses
    final StringBuilder bld = new StringBuilder();

    // Contains used identifiers in order to avoid replications
    final Set<String> used = new HashSet<String>();

    // Create several clauses: one for eanch identifiers
    for (int i = 0; i < identifiers.size(); i++) {
        if (!used.contains(identifiers.get(i))) {

            // verify schema existence and get schema type
            AbstractNormalSchema schema = schemaDAO.find(identifiers.get(i), attrUtil.schemaClass());
            if (schema == null) {
                LOG.error("Invalid schema name '{}'", identifiers.get(i));
                throw new IllegalArgumentException("Invalid schema name " + identifiers.get(i));
            }

            // clear builder
            bld.delete(0, bld.length());

            bld.append("(");

            // set schema name
            bld.append("s.name = '").append(identifiers.get(i)).append("'");

            bld.append(" AND ");

            bld.append("s.name = a.schema_name").append(" AND ");

            bld.append("a.id = v.attribute_id");

            bld.append(" AND ");

            // use a value clause different for eanch different schema type
            switch (schema.getType()) {
            case Boolean:
                bld.append("v.booleanValue = '").append(attrValues.get(i)).append("'");
                break;
            case Long:
                bld.append("v.longValue = ").append(attrValues.get(i));
                break;
            case Double:
                bld.append("v.doubleValue = ").append(attrValues.get(i));
                break;
            case Date:
                bld.append("v.dateValue = '").append(attrValues.get(i)).append("'");
                break;
            default:
                bld.append("v.stringValue = '").append(attrValues.get(i)).append("'");
            }

            bld.append(")");

            used.add(identifiers.get(i));

            clauses.add(bld.toString());
        }
    }

    LOG.debug("Generated where clauses {}", clauses);

    return clauses;
}

From source file:com.danielme.muspyforandroid.services.MusicBrainzClient.java

public List<Artist> searchArtists(String name, int offset, StringBuilder count, int size) throws Exception {
    List<Artist> artists = new ArrayList<Artist>();

    String url = String.format(Constants.MBRAINZ.URL_ARTISTSEARCH, URLEncoder.encode(name), size, offset);

    HttpGet httpGet = new HttpGet(url);
    httpGet.setHeader(Constants.CONTENT_TYPE, Constants.TYPE_JSON);

    HttpResponse response = httpClient.execute(httpGet);
    StatusLine statusLine = response.getStatusLine();
    //sometimes we receive HTTP 504
    if (statusLine != null && statusLine.getStatusCode() == MBGatewayTimeOutException.STATUS_CODE) {
        throw new MBGatewayTimeOutException();
    }// w w  w .ja v  a 2s  .  c  o m

    String responseString = EntityUtils.toString(response.getEntity());
    JSONObject responseJSON = new JSONObject(responseString);
    JSONObject list = new JSONObject(responseJSON.getString(Constants.MBRAINZ.ARTISTLIST));
    count.delete(0, count.length());
    count.append(list.getString(Constants.MBRAINZ.COUNT));

    if (list.has(Constants.MBRAINZ.ARTIST)) {
        JSONArray jsonArray = new JSONArray(list.getString(Constants.MBRAINZ.ARTIST));

        for (int i = 0; i < jsonArray.length(); i++) {
            artists.add(populateArtist(jsonArray.getJSONObject(i)));
        }
    }

    return artists;
}

From source file:org.apache.syncope.core.persistence.jpa.dao.AbstractSubjectDAO.java

/**
 * Generate one where clause for each different attribute schema into the derived schema expression provided.
 *
 * @param expression derived schema expression
 * @param value derived attribute value//from w  w w  . j a v  a 2s .  c  om
 * @param attrUtil USER / ROLE
 * @return where clauses to use to build the query
 */
private Set<String> getWhereClause(final String expression, final String value,
        final AttributableUtil attrUtil) {
    final Parser parser = new Parser(new StringReader(expression));

    // Schema names
    final List<String> identifiers = new ArrayList<>();

    // Literals
    final List<String> literals = new ArrayList<>();

    // Get schema names and literals
    Token token;
    while ((token = parser.getNextToken()) != null && StringUtils.isNotBlank(token.toString())) {
        if (token.kind == ParserConstants.STRING_LITERAL) {
            literals.add(token.toString().substring(1, token.toString().length() - 1));
        }

        if (token.kind == ParserConstants.IDENTIFIER) {
            identifiers.add(token.toString());
        }
    }

    // Sort literals in order to process later literals included into others
    Collections.sort(literals, new Comparator<String>() {

        @Override
        public int compare(final String t, final String t1) {
            if (t == null && t1 == null) {
                return 0;
            } else if (t != null && t1 == null) {
                return -1;
            } else if (t == null && t1 != null) {
                return 1;
            } else if (t.length() == t1.length()) {
                return 0;
            } else if (t.length() > t1.length()) {
                return -1;
            } else {
                return 1;
            }
        }
    });

    // Split value on provided literals
    final List<String> attrValues = split(value, literals);

    if (attrValues.size() != identifiers.size()) {
        LOG.error("Ambiguous JEXL expression resolution.");
        throw new IllegalArgumentException("literals and values have different size");
    }

    // clauses to be used with INTERSECTed queries
    final Set<String> clauses = new HashSet<>();

    // builder to build the clauses
    final StringBuilder bld = new StringBuilder();

    // Contains used identifiers in order to avoid replications
    final Set<String> used = new HashSet<>();

    // Create several clauses: one for eanch identifiers
    for (int i = 0; i < identifiers.size(); i++) {
        if (!used.contains(identifiers.get(i))) {

            // verify schema existence and get schema type
            PlainSchema schema = plainSchemaDAO.find(identifiers.get(i), attrUtil.plainSchemaClass());
            if (schema == null) {
                LOG.error("Invalid schema name '{}'", identifiers.get(i));
                throw new IllegalArgumentException("Invalid schema name " + identifiers.get(i));
            }

            // clear builder
            bld.delete(0, bld.length());

            bld.append("(");

            // set schema name
            bld.append("s.name = '").append(identifiers.get(i)).append("'");

            bld.append(" AND ");

            bld.append("s.name = a.schema_name").append(" AND ");

            bld.append("a.id = v.attribute_id");

            bld.append(" AND ");

            // use a value clause different for eanch different schema type
            switch (schema.getType()) {
            case Boolean:
                bld.append("v.booleanValue = '").append(attrValues.get(i)).append("'");
                break;
            case Long:
                bld.append("v.longValue = ").append(attrValues.get(i));
                break;
            case Double:
                bld.append("v.doubleValue = ").append(attrValues.get(i));
                break;
            case Date:
                bld.append("v.dateValue = '").append(attrValues.get(i)).append("'");
                break;
            default:
                bld.append("v.stringValue = '").append(attrValues.get(i)).append("'");
            }

            bld.append(")");

            used.add(identifiers.get(i));

            clauses.add(bld.toString());
        }
    }

    LOG.debug("Generated where clauses {}", clauses);

    return clauses;
}

From source file:org.dataconservancy.packaging.tool.integration.PackageGenerationTest.java

/**
 * Reads in any BagIt file that uses a ':' to delimit a keyword and value pair.
 *
 * @param bagItFile the file to read/*from   w ww.j  a v  a  2 s. c om*/
 * @return a Map keyed by the keywords, with the List of values as they appear in the file
 * @throws IOException
 */
private Map<String, List<String>> parseBagItKeyValuesFile(File bagItFile) throws IOException {
    Map<String, List<String>> result = new HashMap<>();

    // Used to track state; a streams no-no.  Probably should do this the old-fashioned way.
    BitSet bitSet = new BitSet(1);
    bitSet.set(0);
    StringBuilder key = new StringBuilder();

    Files.lines(bagItFile.toPath(), Charset.forName("UTF-8")).flatMap(line -> Stream
            .of(line.substring(0, line.indexOf(":")), line.substring(line.indexOf(":") + 1).trim()))
            .forEach(token -> {
                if (bitSet.get(0)) {
                    // key
                    key.delete(0, key.length());
                    result.putIfAbsent(token, new ArrayList<>());
                    key.append(token);
                    bitSet.clear(0);
                } else {
                    // value
                    result.get(key.toString()).add(token);
                    bitSet.set(0);
                }
            });

    return result;
}

From source file:com.virtusa.akura.student.controller.FaithLifeRatingController.java

/**
 * Method is to return FaithLifeComment list.
 * /*from w  w  w  .  j av  a2s .co  m*/
 * @param request - HttpServletRequest
 * @param modelMap - ModelMap attribute.
 * @return list of FaithLifeComment
 * @throws AkuraAppException - Detailed exception
 */
@ResponseBody
@RequestMapping(value = POPULATE_FAITHLIFE_COMMENT_HTM)
public String populateFaithLifeComment(ModelMap modelMap, HttpServletRequest request) throws AkuraAppException {

    StringBuilder allFaithLifeComment = new StringBuilder();
    int categoryId = Integer.parseInt(request.getParameter(SELECTED_VALUE));
    List<FaithLifeComment> commentList = SortUtil
            .sortFaithLifeComment(commonService.findFaithLifeCommentsByCategory(categoryId));
    boolean isFirst = true;
    StringBuilder comments = new StringBuilder();

    for (FaithLifeComment comment : commentList) {
        comments.append(comment.getDescription());
        comments.append("_");
        comments.append(comment.getFaithLifeCommentId());

        if (isFirst) {
            allFaithLifeComment.append(comments.toString()); // no comma
            isFirst = false;
        } else {
            allFaithLifeComment.append(","); // comma
            allFaithLifeComment.append(comments.toString());
        }
        comments.delete(0, comments.length());
    }
    return allFaithLifeComment.toString();
}

From source file:com.g3net.tool.StringUtils.java

public static String trimTailStrings(String str, String[] trimStrings) {
    if (str == null)
        return null;
    // String tempStr=str;
    StringBuilder sb = new StringBuilder(str);

    while (sb.length() > 0) {

        boolean flag = true;// ?false?
        for (int i = 0; i < trimStrings.length; i++) {

            int index = sb.length() - trimStrings[i].length();
            String ss = "";
            if (index >= 0 && index < sb.length()) {
                ss = sb.substring(index, sb.length());
            }//  www . j  a va  2  s  . c o  m
            if (ss.equals(trimStrings[i])) {

                sb.delete(index, sb.length());
                flag = false;
            }
        }
        // log.info(flag);
        if (flag)
            break;

    }
    return sb.toString();
}

From source file:com.virtusa.akura.attendance.controller.AttendanceDashboardController.java

/**
 * Method is to return GradeClass list.//w  ww .  j  a  va  2 s .co m
 *
 * @param request - HttpServletRequest
 * @param modelMap - ModelMap attribute.
 * @return list of classGrade
 * @throws AkuraAppException - Detailed exception
 */

@RequestMapping(value = ATTENDANCE_GRADE_CLASS_LIST_HTM)
@ResponseBody
public String populateGradeClass(ModelMap modelMap, HttpServletRequest request) throws AkuraAppException {

    StringBuilder allGradeClass = new StringBuilder();
    int gradeId = Integer.parseInt(request.getParameter(SELECTED_VALUE));
    Grade grade = commonService.findGradeById(gradeId);
    List<ClassGrade> classGrades = SortUtil.sortClassGradeList(commonService.getClassGradeListByGrade(grade));
    boolean isFirst = true;
    StringBuilder classes = new StringBuilder();

    for (ClassGrade classGrade : classGrades) {
        classes.append(classGrade.getDescription());
        classes.append(AkuraWebConstant.UNDERSCORE_STRING);
        classes.append(classGrade.getClassGradeId());

        if (isFirst) {
            allGradeClass.append(classes.toString()); // no comma
            isFirst = false;
        } else {
            allGradeClass.append(AkuraWebConstant.STRING_COMMA); // comma
            allGradeClass.append(classes.toString());
        }
        classes.delete(0, classes.length());
    }
    return allGradeClass.toString();
}

From source file:com.impetus.kundera.client.cassandra.dsdriver.DSClient.java

@Override
public List<Object> findByRelation(String colName, Object colValue, Class entityClazz) {
    EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
    CQLTranslator translator = new CQLTranslator();
    String selectQuery = translator.SELECTALL_QUERY;
    selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMN_FAMILY,
            translator.ensureCase(new StringBuilder(), m.getTableName(), false).toString());

    StringBuilder selectQueryBuilder = new StringBuilder(selectQuery);
    selectQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE);

    translator.buildWhereClause(selectQueryBuilder, colValue.getClass(), colName, colValue,
            CQLTranslator.EQ_CLAUSE, false);
    selectQueryBuilder.delete(selectQueryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE),
            selectQueryBuilder.length());

    ResultSet rSet = (ResultSet) this.execute(selectQueryBuilder.toString(), null);

    return iterateAndReturn(rSet, m);
}

From source file:com.baidu.rigel.biplatform.tesseract.util.DataModelBuilder.java

/**
 * ?ResultSet????/*from w  w  w .ja  v  a2s .co  m*/
 * 
 * @return ResultSet????
 * @throws Exception ?
 */
private Map<String, Map<String, BigDecimal>> parseResultSet(List<MemberTreePropResult> rowHeadNames,
        List<MemberTreePropResult> colHeadNames) throws Exception {

    //    
    Map<String, Map<String, BigDecimal>> data = Maps.newHashMap();
    while (this.tesseractResultSet.next()) {
        StringBuilder oneLine = new StringBuilder();
        for (MemberTreePropResult rowHeadName : rowHeadNames) {

            for (String prop : rowHeadName.queryPropers.keySet()) {
                String value = tesseractResultSet.getString(prop);
                if (rowHeadName.queryPropers.get(prop).isEmpty()
                        || rowHeadName.queryPropers.get(prop).contains(value)) {
                    oneLine.append(prop);
                    oneLine.append(PROP_KEY_SPLIT);
                    oneLine.append(value);
                    oneLine.append(HEAD_KEY_SPLIT);
                    break;
                }
            }
        }
        if (oneLine.length() > 1) {
            oneLine.delete(oneLine.length() - HEAD_KEY_SPLIT.length(), oneLine.length());
        } else {
            oneLine.append(BLANK_ROW);
        }
        Map<String, BigDecimal> colValues = Maps.newHashMap();
        StringBuilder oneColumn = new StringBuilder();
        for (MemberTreePropResult colHeadName : colHeadNames) {
            for (String prop : colHeadName.queryPropers.keySet()) {
                String value = tesseractResultSet.getString(prop);
                if (colHeadName.queryPropers.get(prop).isEmpty()
                        || colHeadName.queryPropers.get(prop).contains(value)) {
                    oneColumn.append(prop);
                    oneColumn.append(PROP_KEY_SPLIT);
                    oneColumn.append(value);
                    oneColumn.append(HEAD_KEY_SPLIT);
                    break;
                }
            }

        }
        for (MiniCubeMeasure measure : queryContext.getQueryMeasures()) {
            StringBuilder columnKey = new StringBuilder();
            columnKey.append(oneColumn);
            columnKey.append(measure.getName());
            colValues.put(columnKey.toString(), tesseractResultSet.getBigDecimal(measure.getDefine()));
        }
        data.put(oneLine.toString(), colValues);
    }

    return data;
}

From source file:com.mirth.connect.server.controllers.DefaultExtensionController.java

private List<String> parseUninstallScript(String script) {
    List<String> scriptList = new ArrayList<String>();
    StringBuilder sb = new StringBuilder();
    boolean blankLine = false;
    Scanner scanner = new Scanner(script);

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();

        if (StringUtils.isNotBlank(line)) {
            sb.append(line + " ");
        } else {/*from www . jav  a2s .  c om*/
            blankLine = true;
        }

        if (blankLine || !scanner.hasNextLine()) {
            scriptList.add(sb.toString().trim());
            blankLine = false;
            sb.delete(0, sb.length());
        }
    }

    return scriptList;
}