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:info.magnolia.ui.workbench.container.AbstractJcrContainer.java

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

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

From source file:com.jkoolcloud.tnt4j.core.UsecTimestamp.java

/**
 * <p>Creates UsecTimestamp from string representation of timestamp in the
 * specified format.</p>/*from  ww w .  ja  v  a  2  s  . com*/
 * <p>This is based on {@link SimpleDateFormat}, but extends its support to
 * recognize microsecond fractional seconds. If number of fractional second
 * characters is greater than 3, then it's assumed to be microseconds.
 * Otherwise, it's assumed to be milliseconds (as this is the behavior of
 * {@link SimpleDateFormat}.
 *
 * @param timeStampStr timestamp string
 * @param formatStr format specification for timestamp string
 * @param timeZone time zone that timeStampStr represents. This is only needed when formatStr does not include
 *                   time zone specification and timeStampStr does not represent a string in local time zone.
 * @param locale locale for date format to use.
 * @throws NullPointerException if timeStampStr is {@code null}
 * @throws IllegalArgumentException if timeStampStr is not in the correct format
 * @throws ParseException if failed to parse string based on specified format
 * @see java.util.TimeZone
 */
public UsecTimestamp(String timeStampStr, String formatStr, TimeZone timeZone, String locale)
        throws ParseException {
    if (timeStampStr == null)
        throw new NullPointerException("timeStampStr must be non-null");

    int usecs = 0;

    SimpleDateFormat dateFormat;

    if (StringUtils.isEmpty(formatStr)) {
        dateFormat = new SimpleDateFormat();
    } else {
        // Java date formatter cannot deal with usecs, so we need to extract those ourselves
        int fmtPos = formatStr.indexOf('S');
        if (fmtPos > 0) {
            int endFmtPos = formatStr.lastIndexOf('S');
            int fmtFracSecLen = endFmtPos - fmtPos + 1;

            if (fmtFracSecLen > 6)
                throw new ParseException(
                        "Date format containing more than 6 significant digits for fractional seconds is not supported",
                        0);

            StringBuilder sb = new StringBuilder();
            int usecPos = timeStampStr.lastIndexOf('.') + 1;
            int usecEndPos;
            if (usecPos > 2) {
                for (usecEndPos = usecPos; usecEndPos < timeStampStr.length(); usecEndPos++) {
                    if (!StringUtils.containsAny("0123456789", timeStampStr.charAt(usecEndPos)))
                        break;
                }

                if (fmtFracSecLen > 3) {
                    // format specification represents more than milliseconds, assume microseconds
                    String usecStr = String.format("%s", timeStampStr.substring(usecPos, usecEndPos));
                    if (usecStr.length() < fmtFracSecLen)
                        usecStr = StringUtils.rightPad(usecStr, fmtFracSecLen, '0');
                    else if (usecStr.length() > fmtFracSecLen)
                        usecStr = usecStr.substring(0, fmtFracSecLen);
                    usecs = Integer.parseInt(usecStr);

                    // trim off fractional part < microseconds from both timestamp and format strings
                    sb.append(timeStampStr);
                    sb.delete(usecPos - 1, usecEndPos);
                    timeStampStr = sb.toString();

                    sb.setLength(0);
                    sb.append(formatStr);
                    sb.delete(fmtPos - 1, endFmtPos + 1);
                    formatStr = sb.toString();
                } else if ((usecEndPos - usecPos) < 3) {
                    // pad msec value in date string with 0's so that it is 3 digits long
                    sb.append(timeStampStr);
                    while ((usecEndPos - usecPos) < 3) {
                        sb.insert(usecEndPos, '0');
                        usecEndPos++;
                    }
                    timeStampStr = sb.toString();
                }
            }
        }

        dateFormat = StringUtils.isEmpty(locale) ? new SimpleDateFormat(formatStr)
                : new SimpleDateFormat(formatStr, Utils.getLocale(locale));
    }

    dateFormat.setLenient(true);
    if (timeZone != null)
        dateFormat.setTimeZone(timeZone);

    Date date = dateFormat.parse(timeStampStr);

    setTimestampValues(date.getTime(), 0, 0);
    add(0, usecs);
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

public void updateNearby(Set<byte[]> nearby) {
    StringBuilder kl = new StringBuilder(" ");
    for (byte[] bs : nearby) {
        kl.append("'");
        kl.append(Hex.encodeHex(bs));//from  ww w .  j  av a2s. c o m
        //WTF- this hex encoder suxs and adds extra 00s at the end
        kl.delete(kl.length() - 2, kl.length());
        kl.append("'");
        kl.append(",");
    }
    getWritableDatabase().execSQL("UPDATE " + Contact.TABLE + " SET nearby = HEX(" + Contact.PUBLIC_KEY
            + ") in (" + kl.substring(0, kl.length() - 1).toUpperCase() + ")");
}

From source file:it.unibas.spicy.model.algebra.query.operators.sql.GenerateSQLForSourceToTargetExchange.java

private void generateInsertsForRelation(String relationName,
        Map<String, List<SetAlias>> relevantVariablesForRelationName,
        Map<SetAlias, List<FORule>> relevantRulesForVariable, MappingTask mappingTask, StringBuilder result) {
    int numberOfRelevantRules = countRelevantRules(relationName, relevantVariablesForRelationName,
            relevantRulesForVariable);/*from w w w. j  a  v a2s  . com*/
    if (numberOfRelevantRules == 0) {
        return;
    }
    List<SetAlias> relevantVariablesForRelation = relevantVariablesForRelationName.get(relationName);
    String newViewName = GenerateSQL.finalSqlNameAfterExchange(relevantVariablesForRelation.get(0));
    allViewsToDelete.add(newViewName);
    if (mappingTask.getConfig().useSkolemTable()) {
        //giannisk
        result.append(DELETE_EXISTING_TABLE).append(newViewName).append(";\n");

        result.append(CREATE_TABLE_OR_VIEW).append(newViewName).append(" AS \n");
    } else {
        result.append("insert into ").append(relationName).append("\n");
    }
    for (int j = 0; j < relevantVariablesForRelation.size(); j++) {
        SetAlias relevantVariable = relevantVariablesForRelation.get(j);
        generateInsertForVariableInTgd(relevantRulesForVariable, relevantVariable, mappingTask, result);
    }
    result.delete(result.length() - 1 - (INDENT.length() + "UNION\n".length()), result.length() - 1);
    result.append(";\n");
}

From source file:it.unibas.spicy.model.algebra.query.operators.sql.GenerateSQLForSourceToTargetExchange.java

private void generateInsertsForConstantRelation(String relationName,
        Map<String, List<SetAlias>> relevantVariablesForRelationName,
        Map<SetAlias, List<ConstantFORule>> relevantRulesForVariable, MappingTask mappingTask,
        StringBuilder result) {
    int numberOfRelevantRules = countRelevantConstantRules(relationName, relevantVariablesForRelationName,
            relevantRulesForVariable);//w w  w. ja  va2s.co m
    if (numberOfRelevantRules == 0) {
        return;
    }
    List<SetAlias> relevantVariablesForRelation = relevantVariablesForRelationName.get(relationName);
    String newViewName = GenerateSQL.finalSqlNameAfterExchange(relevantVariablesForRelation.get(0));
    allViewsToDelete.add(newViewName);
    if (mappingTask.getConfig().useSkolemTable()) {
        //giannisk
        result.append(DELETE_EXISTING_TABLE).append(newViewName).append(";\n");

        result.append(CREATE_TABLE_OR_VIEW).append(newViewName).append(" AS \n");
    } else {
        result.append("insert into ").append(relationName).append("\n");
    }
    for (int j = 0; j < relevantVariablesForRelation.size(); j++) {
        SetAlias relevantVariable = relevantVariablesForRelation.get(j);
        generateInsertForVariableInConstantTgd(relevantRulesForVariable, relevantVariable, mappingTask, result);
    }
    result.delete(result.length() - 1 - (INDENT.length() + "UNION\n".length()), result.length() - 1);
    result.append(";\n");
}

From source file:com.edgenius.wiki.service.impl.NotificationServiceImpl.java

public List<String> parseReceivers(StringBuilder buf) {
    int len = buf.length();
    List<String> receivers = new ArrayList<String>();
    StringBuilder rece = new StringBuilder();
    int isReceiver = 0;
    int idx;//from   w ww . ja  v a2s . co m
    for (idx = 0; idx < len; idx++) {
        char ch = buf.charAt(idx);

        if (ch == '@' && isReceiver != 2) {
            rece.append(ch);
            isReceiver = 1; //expect text or '
            continue;
        }

        if (isReceiver == 0) {
            if (ch != ' ') {
                break;
            } else {
                continue;
            }
        }

        if (ch == '\'' && isReceiver > 0) {
            rece.append(ch);
            if (isReceiver == 1 && idx > 0 && buf.charAt(idx - 1) == '@') {
                isReceiver = 2; //expect end '
            } else if (isReceiver == 2) {
                receivers.add(rece.toString());
                rece = new StringBuilder();
                isReceiver = 0;
            }
            continue;
        }

        if (ch == ' ' && isReceiver == 1) {
            receivers.add(rece.toString());
            rece = new StringBuilder();
            isReceiver = 0;
            continue;
        }
        if (isReceiver > 0) {
            rece.append(ch);
        }
    }
    if (rece.length() != 0) {
        //this already means something wrong - no message in text body, only receivers.  
        //however, just put receiver in list and let outside method to process this case 
        receivers.add(rece.toString());
    }
    buf.delete(0, idx);

    return receivers;
}

From source file:jp.terasoluna.fw.file.dao.standard.VariableFileLineIterator.java

/**
 * ????? ???? ????<br>/*  www. ja v  a 2  s .c om*/
 * <code>fileLineString</code>?<code>null</code>???? ?????????<code>String</code>????
 * @param fileLineString ??1?
 * @return ?
 */
@Override
protected String[] separateColumns(String fileLineString) {

    if (fileLineString == null || "".equals(fileLineString)) {
        return new String[0];
    }

    // 1???
    StringBuilder columnBuilder = new StringBuilder();

    // ????
    char previousChar = Character.MIN_VALUE;

    // ??????
    List<String> columnList = new ArrayList<String>();

    boolean isEnclosed = true;
    boolean isEscaped = false;

    int fieldCount = 0;
    char[] columnEncloseChar = getColumnEncloseChar();

    if (!isEnclosed()) {
        return StringUtils.splitByWholeSeparatorPreserveAllTokens(fileLineString,
                Character.toString(delimiter));
    } else {
        for (char currentChar : fileLineString.toCharArray()) {
            if (previousChar == Character.MIN_VALUE) {
                previousChar = currentChar;
            }
            if (previousChar == getEncloseCharcter(columnEncloseChar, fieldCount)) {
                if (isEnclosed) {
                    if (currentChar == getEncloseCharcter(columnEncloseChar, fieldCount)) {
                        isEnclosed = false;
                    }
                } else {
                    if (currentChar == getEncloseCharcter(columnEncloseChar, fieldCount)) {
                        if (isEscaped) {
                            columnBuilder.append(currentChar);
                            isEscaped = false;
                        } else {
                            isEscaped = true;
                        }
                    } else if (currentChar == getDelimiter()) {
                        if (isEscaped) {
                            columnList.add(columnBuilder.toString());
                            previousChar = Character.MIN_VALUE;
                            columnBuilder.delete(0, columnBuilder.length());
                            isEnclosed = true;
                            isEscaped = false;
                            fieldCount++;
                        } else {
                            columnBuilder.append(currentChar);
                            isEscaped = false;
                        }
                    } else {
                        columnBuilder.append(currentChar);
                    }
                }
            } else {
                if (currentChar != getDelimiter()) {
                    columnBuilder.append(currentChar);
                } else {
                    columnList.add(columnBuilder.toString());
                    previousChar = Character.MIN_VALUE;
                    columnBuilder.delete(0, columnBuilder.length());
                    fieldCount++;
                }
            }
        }
        columnList.add(columnBuilder.toString());
        return columnList.toArray(new String[columnList.size()]);
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.backBeans.sop.evaluation.SOPEvaluationManagementBackingBean.java

public String getAssociatedRooms() throws FenixServiceException {
    StringBuilder result = new StringBuilder();

    if (this.getChosenRoomsIDs() != null && this.getChosenRoomsIDs().length != 0) {
        for (String chosenRoomString : this.getChosenRoomsIDs()) {
            String chosenRoomID = getRoomID(chosenRoomString);
            Space room = (Space) FenixFramework.getDomainObject(chosenRoomID);
            result.append(room.getName());
            result.append("; ");
        }//from   ww  w .  ja va  2s.  com

        if (result.length() > 0) {
            result.delete(result.length() - 2, result.length() - 1);
        }

        return result.toString();
    } else {
        return messages.getMessage(I18N.getLocale(), "label.no.associated.rooms");
    }
}

From source file:org.alfresco.web.bean.wcm.SubmitDialog.java

@Override
public String finish() {
    // NOTE: We need to handle the transaction ourselves in this dialog as the store needs
    //       to be committed and the virtualisation server informed of the workflow
    //       sandbox BEFORE the workflow gets started. This is so that the link validation
    //       service can use the virtualisation server to produce the link report.
    //       The best solution would be for the link check node of the workflow to be
    //       asynchronous and to wait until the initiating transaction had committed
    //       before running but there's no support for this.
    //       We therefore need to use 2 transactions, one to create the workflow store
    //       (if necessary) and one to start the workflow

    if (getSubmitItemsSize() == 0) {
        return null;
    }/*w  w  w .  ja  v a2  s  .  c o m*/

    FacesContext context = FacesContext.getCurrentInstance();
    String outcome = null;

    // check the isFinished flag to stop the finish button
    // being pressed multiple times
    if (this.isFinished == false) {
        this.isFinished = true;

        try {
            // note: always submit via workflow (always defaults to direct submit workflow)
            //outcome = submitViaWorkflow(context);

            String workflowName = null;
            if ((this.workflowSelectedValue != null) && (this.workflowSelectedValue.length > 0)) {
                // get the defaults from the workflow configuration attached to the selected workflow
                workflowName = this.workflowSelectedValue[0];
                for (FormWorkflowWrapper wrapper : this.workflows) {
                    if (wrapper.name.equals(workflowName)) {
                        this.workflowParams = wrapper.params;
                    }
                }

                if (this.workflowParams == null) {
                    // create error msg for display in dialog - the user must configure the workflow params
                    Utils.addErrorMessage(Application.getMessage(context, MSG_ERR_WORKFLOW_CONFIG));
                    return outcome;
                }
            }

            final String finalWorkflowName = workflowName;

            List<ItemWrapper> items = getSubmitItems();

            final List<String> relativePaths = new ArrayList<String>(items.size());

            for (ItemWrapper wrapper : items) {
                relativePaths.add(AVMUtil.getStoreRelativePath(wrapper.getDescriptor().getPath()));
            }

            Date currentDate = new Date();
            if (launchDate != null) {
                if (launchDate.before(currentDate)) {
                    Utils.addErrorMessage(Application.getMessage(context, MSG_ERR_INVALID_LAUNCH_DATE));
                    return null;
                }
            }

            if ((submitItems != null) && (!submitItems.isEmpty()) && (expirationDates != null)
                    && (!expirationDates.isEmpty())) {
                StringBuilder errorMessage = new StringBuilder();
                byte errFlag = 0;
                for (ItemWrapper wrapper : submitItems) {
                    String key = wrapper.descriptor.getPath();
                    Date expiritionDate = expirationDates.get(key);
                    if (expiritionDate != null) {
                        if (launchDate != null) {
                            if (expiritionDate.before(launchDate)) {
                                errFlag = 1;
                                errorMessage.append(wrapper.descriptor.getName()).append(", ");
                            }
                        } else {
                            if (expiritionDate.before(currentDate)) {
                                errorMessage.append(wrapper.descriptor.getName()).append(", ");
                                errFlag = 2;
                            }
                        }
                    }
                }
                if (errorMessage.length() > 0) {
                    errorMessage.delete(errorMessage.length() - 2, errorMessage.length());
                }
                switch (errFlag) {
                case 1: {
                    Utils.addErrorMessage(MessageFormat.format(
                            Application.getMessage(context, MSG_ERR_PATTERN_INVALID_EXPIRATION_DATE),
                            errorMessage.toString()));
                    return null;
                }
                case 2: {
                    Utils.addErrorMessage(MessageFormat.format(
                            Application.getMessage(context, MSG_ERR_INVALID_EXPIRATION_DATE),
                            errorMessage.toString()));
                    return null;
                }
                }
            }

            final String sbStoreId = this.avmBrowseBean.getSandbox();

            String submitLabel = this.label;
            String submitComment = this.comment;
            // crop to maximum length
            if (submitLabel != null && submitLabel.length() > 255) {
                submitLabel = submitLabel.substring(0, 255);
            }
            if (submitComment != null && submitComment.length() > 255) {
                submitComment = submitComment.substring(0, 255);
            }

            final String finalSubmitLabel = submitLabel;
            final String finalSubmitComment = submitComment;

            // note: always submit via workflow (if no workflow selected, then defaults to direct submit workflow)

            // This nees to run with higher rights to push into the work flow store ....

            AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>() {

                public Object doWork() throws Exception {
                    getSandboxService().submitListAssets(sbStoreId, relativePaths, finalWorkflowName,
                            workflowParams, finalSubmitLabel, finalSubmitComment, expirationDates, launchDate,
                            autoDeploy);
                    return null;
                }

            }, AuthenticationUtil.getSystemUserName());

            // if we get this far return the default outcome
            outcome = this.getDefaultFinishOutcome();
        } finally {
            // reset the flag so we can re-attempt the operation
            isFinished = false;
        }
    }

    return outcome;
}

From source file:com.virtusa.akura.common.controller.ManageSpecialEventsController.java

/**
 * Method is to return String of participant list.
 * /*  w w  w.  j a v a 2s  . com*/
 * @param specialEvents - SpecialEvents object
 * @param toList - String array
 * @return string of participant list
 * @throws AkuraAppException - Detailed exception
 */
private String toListToString(@ModelAttribute(MODEL_ATT_SPECIAL_EVENT) SpecialEvents specialEvents,
        String[] toList) throws AkuraAppException {

    ClassGrade cg = null;
    SportCategory sc = null;
    ClubSociety cs = null;

    StringBuilder allParticipents = new StringBuilder();

    StringBuilder participents = new StringBuilder();
    boolean isFirst = true;

    for (String z : toList) {

        int id = Integer.parseInt(z);

        if (specialEvents.getParticipantCategory().getParticipantCategoryId() == 1) {
            // class wise
            cg = commonService.findClassGrade(id);
        } else if (specialEvents.getParticipantCategory().getParticipantCategoryId() == 2) {
            // sport wise
            sc = commonService.findSportCategoryById(id);
        } else if (specialEvents.getParticipantCategory().getParticipantCategoryId() == CATEGORY_TYPE_3) {
            // clubSociety wise
            cs = commonService.findClubSocietyById(id);
        }

        if (cg != null) {

            participents.append(cg.getDescription());

        }
        if (cs != null) {

            participents.append(cs.getName());

        }
        if (sc != null) {

            participents.append(sc.getSport().getDescription());
            participents.append("-");
            participents.append(sc.getSportSubCategory().getDescription());

        }

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

    }

    return allParticipents.toString();
}