Example usage for java.lang StringBuilder deleteCharAt

List of usage examples for java.lang StringBuilder deleteCharAt

Introduction

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

Prototype

@Override
public StringBuilder deleteCharAt(int index) 

Source Link

Usage

From source file:com.impetus.kundera.utils.KunderaCoreUtils.java

/**
 * Prepares composite key as a lucene key.
 * //from ww w  .j ava2s .  c o m
 * @param m
 *            entity metadata
 * @param metaModel
 *            meta model.
 * @param compositeKey
 *            composite key instance
 * @return redis key
 */
public static String prepareCompositeKey(final SingularAttribute attribute, final MetamodelImpl metaModel,
        final Object compositeKey) {
    Field[] fields = attribute.getBindableJavaType().getDeclaredFields();
    EmbeddableType embeddable = metaModel.embeddable(attribute.getBindableJavaType());
    StringBuilder stringBuilder = new StringBuilder();

    try {
        for (Field f : fields) {
            if (!ReflectUtils.isTransientOrStatic(f)) {
                if (metaModel.isEmbeddable(
                        ((AbstractAttribute) embeddable.getAttribute(f.getName())).getBindableJavaType())) {
                    f.setAccessible(true);
                    stringBuilder.append(
                            prepareCompositeKey((SingularAttribute) embeddable.getAttribute(f.getName()),
                                    metaModel, f.get(compositeKey)))
                            .append(LUCENE_COMPOSITE_KEY_SEPERATOR);
                } else {
                    String fieldValue = PropertyAccessorHelper.getString(compositeKey, f);
                    fieldValue = fieldValue.replaceAll("[^a-zA-Z0-9]", "_");

                    stringBuilder.append(fieldValue);
                    stringBuilder.append(LUCENE_COMPOSITE_KEY_SEPERATOR);
                }
            }
        }
    } catch (IllegalAccessException e) {
        logger.error(e.getMessage());
    } catch (IllegalArgumentException e) {
        logger.error("Error during prepare composite key, Caused by {}.", e);
        throw new PersistenceException(e);
    }

    if (stringBuilder.length() > 0) {
        stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(LUCENE_COMPOSITE_KEY_SEPERATOR));
    }
    return stringBuilder.toString();
}

From source file:fr.gael.dhus.olingo.ODataClient.java

/**
 * Builds and appends the query parameter part at the end of the given URL.
 * @param base_url an URL to append query parameters to.
 * @param query_parameters can be {@code null}, see {@link URI}.
 * @return the given URL with its query parameters.
 *//*w  w w.j  a va 2s.  c  o m*/
private String appendQueryParam(String base_url, Map<String, String> query_parameters) {
    if (query_parameters != null && !query_parameters.isEmpty()) {
        StringBuilder sb = new StringBuilder(base_url).append('?');
        for (Map.Entry<String, String> entry : query_parameters.entrySet()) {
            String value = entry.getValue().replaceAll(" ", "%20");
            sb.append(entry.getKey()).append('=').append(value);
            sb.append('&');
        }
        sb.deleteCharAt(sb.length() - 1);

        return sb.toString();
    } else {
        return base_url;
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.backBeans.departmentMember.ViewDepartmentTeachers.java

private String computeDegreeAcronyms(ExecutionCourse executionCourse) {
    StringBuilder degreeAcronyms = new StringBuilder();

    Collection<CurricularCourse> curricularCourses = executionCourse.getAssociatedCurricularCoursesSet();
    Set<String> processedAcronyns = new HashSet<String>();

    for (CurricularCourse curricularCourse : curricularCourses) {
        String degreeAcronym = curricularCourse.getDegreeCurricularPlan().getDegree().getSigla();

        if (!processedAcronyns.contains(degreeAcronym)) {
            degreeAcronyms.append(degreeAcronym).append(",");
            processedAcronyns.add(degreeAcronym);

        }/*from  w  w w  . jav a 2 s.  co m*/
    }

    if (degreeAcronyms.toString().endsWith(",")) {
        degreeAcronyms.deleteCharAt(degreeAcronyms.length() - 1);
    }

    return degreeAcronyms.toString();

}

From source file:com.aurel.track.item.ItemActionJSON.java

public static String encodeFieldDisplayValues(Set<Integer> presentFields, WorkItemContext workItemContext,
        boolean useProjectSpecificID, boolean isMobileApplication) {
    StringBuilder sb = new StringBuilder();
    sb.append("{");

    for (Iterator<Integer> iterator = presentFields.iterator(); iterator.hasNext();) {
        Integer fieldID = iterator.next();
        IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID);

        Object value = workItemContext.getWorkItemBean().getAttribute(fieldID);
        String displayValue = null;

        if (useProjectSpecificID && fieldID.intValue() == SystemFields.ISSUENO) {
            displayValue = ItemBL.getSpecificProjectID(workItemContext);
        } else {//from w w w  .j a v a  2  s.  c o  m
            if (fieldTypeRT != null) {
                displayValue = fieldTypeRT.getShowValue(value, workItemContext, fieldID);
            }
        }
        if (fieldID == SystemFields.DESCRIPTION) {
            displayValue = ItemDetailBL.formatDescription(displayValue, workItemContext.getLocale());
        }
        if (isMobileApplication) {
            try {
                if (fieldTypeRT.getValueType() == ValueType.LONGTEXT) {
                    displayValue = Html2Text.getNewInstance().convert(displayValue);
                    displayValue = displayValue.replaceAll("[\n\r]", "");
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                LOGGER.error(ExceptionUtils.getStackTrace(e));
            }
        }
        //append "," after each value. we need to remove the last one
        JSONUtility.appendStringValue(sb, "f" + fieldID, displayValue);
    }
    if (sb.length() > 1) {
        //remove last ","
        sb.deleteCharAt(sb.length() - 1);
    }
    sb.append("}");
    return sb.toString();
}

From source file:org.mule.module.http.functional.listener.HttpListenerHttpMessagePropertiesTestCase.java

public String buildQueryString(Map<String, Object> queryParams) throws UnsupportedEncodingException {
    final StringBuilder queryString = new StringBuilder();
    for (String paramName : queryParams.keySet()) {
        final Object value = queryParams.get(paramName);
        if (value instanceof Collection) {
            for (java.lang.Object eachValue : (Collection) value) {
                queryString.append(paramName + "="
                        + URLEncoder.encode(eachValue.toString(), Charset.defaultCharset().name()));
                queryString.append("&");
            }//  www  .  jav a  2s  .co  m
        } else {
            queryString.append(
                    paramName + "=" + URLEncoder.encode(value.toString(), Charset.defaultCharset().name()));
            queryString.append("&");
        }
    }
    queryString.deleteCharAt(queryString.length() - 1);
    return queryString.toString();
}

From source file:au.org.ala.delta.util.Utils.java

/**
 * Removes DELTA style <> comments from the supplied string.
 * /*from   www . j a v  a2s .  c  o m*/
 * @param text
 *            the string to remove comments from.
 * @param level
 *            0 = don't remove, 1 = remove all, 2 = remove only if other
 *            text, 3 = same as 2, but outer brackets are removed if
 *            commented text is used.
 * @return the string with comments removed
 */
public static String removeComments(String text, int level, boolean convertCommentsToBrackets,
        boolean removeInnerComments, boolean stripSpaces, boolean removeBrackets) {

    int mode = level;

    int commentLevel = 0;
    boolean hasText = mode == 1;
    boolean hadInner = false;
    char ch;
    int i, curStart = -1, start = -1, end = -1;
    int innerStart = -1;
    boolean wasSpace = true;
    boolean wasBrace = false;
    // TODO despaceRTF(text);
    if (stripSpaces) {
        text = stripExtraSpaces(text);
    }
    StringBuilder result = new StringBuilder(text);

    for (i = 0; i < result.length(); ++i) { // Work through string
        // Is character an opening bracket?
        if (result.charAt(i) == '<'
                && (wasSpace || wasBrace || (ch = result.charAt(i - 1)) == ' ' || ch == '<' || ch == '>')) {
            wasBrace = true;
            if (convertCommentsToBrackets) {
                result.setCharAt(i, ')');
            }
            if (removeBrackets || (mode == 3 && commentLevel == 0)) {
                result.deleteCharAt(i--);
            }
            if (commentLevel == 0) {
                curStart = i;
                if (start == -1)
                    start = i;
            } else if (commentLevel == 1) {
                innerStart = i;
                hadInner = true;
            }
            // Keep track of nesting level
            commentLevel++;
        }
        // Was it a closing bracket?
        else if (result.charAt(i) == '>' && commentLevel > 0 && result.charAt(i - 1) != '|'
                && (i + 1 == result.length() || (ch = result.charAt(i + 1)) == ' ' || ch == '<' || ch == '>')) {
            // Keep track of nesting level
            commentLevel--;
            wasBrace = true;
            if (convertCommentsToBrackets)
                result.setCharAt(i, ')');
            if (removeBrackets || (mode == 3 && commentLevel == 0))
                result.deleteCharAt(i--);
            if (commentLevel == 0) {
                if (start != -1) {
                    end = i;
                    if (removeInnerComments && hadInner) // In this case,
                                                         // check for
                                                         // and remove an empty
                                                         // comment...
                    {
                        int leng = end - curStart - 1;
                        String contents = result.substring(curStart + 1, end - 1);
                        contents = stripExtraSpaces(contents);
                        if (contents.isEmpty() || contents == " ") {
                            result.delete(curStart, end - 1);
                            i = curStart;
                        } else if (stripSpaces && contents.length() != leng) {
                            result.replace(curStart + 1, curStart + leng, contents);
                            i -= leng - contents.length();
                        }
                    }
                }
                hadInner = false;
            } else if (commentLevel == 1 && removeInnerComments) {
                // If we're removing inner comments, get rid of this
                // part of the string, and any space before it.
                int leng = i - innerStart + 1;
                result.delete(innerStart, innerStart + leng);
                i = innerStart - 1;
                while (result.length() > i && result.charAt(i) == ' ')
                    result.deleteCharAt(i--);
            }
        } else if (commentLevel == 0 && (hasText || result.charAt(i) != ' ')) {
            hasText = true;
            wasBrace = false;
            wasSpace = (end == i - 1 && i > 0);
            if (end != -1 && mode > 0) {
                result.delete(start, end + 1);
                i -= end - start + 2;
                // Hmm. How SHOULD spaces around the removed comments
                // be treated? This erases the spaces BEFORE the comment
                while (i >= 0 && result.length() > i && result.charAt(i) == ' ')
                    result.deleteCharAt(i--);
                start = -1;
                end = -1;
            }
        } else
            wasBrace = false;
    }
    if (end != -1 && hasText && mode > 0) {
        result.delete(start, end + 1);
        for (i = result.length() - 1; i >= 0 && result.charAt(i) == ' '; --i)
            result.deleteCharAt(i);
    }
    return result.toString();
}

From source file:Model.MDengue.java

public void addCluster(String pStrString) throws ParseException {

    IDataStorage objDS = CDataStorageFactory.getMasterStorage();

    StringBuilder objSB = new StringBuilder();
    objSB.append("INSERT INTO `dengue`(`polygon`, `region`, `noOfPeopleInfected`, `severity`)" + "VALUES ");

    JSONParser jsonParser = new JSONParser();

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

    for (Object objJson : aryJSON) {
        objSB.append("('");
        JSONObject objInnerObj = (JSONObject) objJson;

        objSB.append(objInnerObj.get("XYs").toString());
        objSB.append("','");

        objSB.append(objInnerObj.get("Location").toString());
        objSB.append("','");

        objSB.append(objInnerObj.get("Cases").toString());
        objSB.append("','");

        if (Integer.parseInt(objInnerObj.get("Cases").toString()) < 10) {
            objSB.append("warning'),");
        } else {/*from www . ja  v a  2s .  co m*/
            objSB.append("alert'),");
        }
    }

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

    objSB.append(";");

    System.out.println(objSB);

    objDS.openConnection();

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

    objDS.closeConnection();

}

From source file:sk.openhouse.web.recaptcha.LocaleReCaptchaImpl.java

@Override
public String createRecaptchaHtml(String errorMessage, Properties options) {

    String errorPart = "";
    if (errorMessage != null) {
        String encoding = "UTF-8";
        try {//from w  w  w.  j a va 2s  .  co m
            errorPart = "&amp;error=" + URLEncoder.encode(errorMessage, encoding);
        } catch (UnsupportedEncodingException ex) {
            logger.fatal(encoding + " encoding is not supported", ex);
        }
    }

    if (options == null) {
        options = new Properties();
    }

    String prefix = "reCaptcha.";
    /* message key with default value */
    Map<String, String> keys = new HashMap<String, String>();
    keys.put("visual_challenge", "Get a visual challenge");
    keys.put("audio_challenge", "Get an audio challenge");
    keys.put("refresh_btn", "Get a new challenge");
    keys.put("instructions_visual", "Type the two words:");
    keys.put("instructions_context", "Type the words in the boxes:");
    keys.put("instructions_audio", "Type what you hear:");
    keys.put("help_btn", "Help");
    keys.put("play_again", "Play sound again");
    keys.put("cant_hear_this", "Download sound as MP3");
    keys.put("incorrect_try_again", "Incorrect. Try again.");

    /* get locale from properties if set */
    Locale locale = null;
    String langKey = "lang";
    if (options.containsKey(langKey)) {
        List<String> langs = Arrays.asList(Locale.getISOLanguages());
        String lang = options.getProperty(langKey);
        if (langs.contains(lang)) {
            locale = new Locale(lang);
        }
    }

    /* if locale is not set, get it from context */
    if (locale == null) {
        locale = LocaleContextHolder.getLocale();
    }

    /* load messages for a given locale, if it fails, default to EN */
    StringBuilder sb = new StringBuilder("{");
    try {
        for (Map.Entry<String, String> entry : keys.entrySet()) {
            String key = entry.getKey();
            sb.append(key);
            sb.append(":\"");
            sb.append(messages.getMessage(prefix + key, locale));
            sb.append("\",");
        }
    } catch (NoSuchMessageException ex) {
        locale = Locale.ENGLISH;
        for (Map.Entry<String, String> entry : keys.entrySet()) {
            String key = entry.getKey();
            sb.append(key);
            sb.append(":\"");
            sb.append(messages.getMessage(prefix + key, entry.getValue(), locale));
            sb.append("\",");
        }
    }
    sb.deleteCharAt(sb.length() - 1);
    sb.append("}");

    options.put("custom_translations", sb.toString());
    options.put("lang", locale.getLanguage());

    String message = fetchJSOptions(options);

    message += "<script type=\"text/javascript\" src=\"" + recaptchaServer + "/challenge?k=" + publicKey
            + errorPart + "\"></script>\r\n";

    if (includeNoscript) {
        String noscript = "<noscript>\r\n" + "   <iframe src=\"" + recaptchaServer + "/noscript?k=" + publicKey
                + errorPart + "\" height=\"300\" width=\"500\" frameborder=\"0\"></iframe><br>\r\n"
                + "   <textarea name=\"recaptcha_challenge_field\" rows=\"3\" cols=\"40\"></textarea>\r\n"
                + "   <input type=\"hidden\" name=\"recaptcha_response_field\" value=\"manual_challenge\">\r\n"
                + "</noscript>";
        message += noscript;
    }

    return message;
}

From source file:com.wabacus.system.WabacusResponse.java

private String[] getInitChildSelectboxIdsOnloadMethod() {
    if (Tools.isEmpty(sChildSelectboxidsOnload))
        return null;
    StringBuilder bufTmp = new StringBuilder();
    for (String childidTmp : this.sChildSelectboxidsOnload) {
        if (Tools.isEmpty(childidTmp))
            continue;
        bufTmp.append(childidTmp).append(";");
    }/*from   w  w w . ja v  a  2s  . co m*/
    if (bufTmp.length() > 0 && bufTmp.charAt(bufTmp.length() - 1) == ';')
        bufTmp.deleteCharAt(bufTmp.length() - 1);
    return bufTmp.length() > 0
            ? new String[] { "wx_showChildSelectboxOptionsOnload", "{childids:'" + bufTmp.toString() + "'}" }
            : null;
}

From source file:org.helios.rindle.metric.UnsafeMetricDefinition.java

/**
 * {@inheritDoc}// w w w .j a  va  2  s  . c om
 * @see java.lang.Object#toString()
 */
@Override
public String toString() {
    final int maxLen = 10;
    StringBuilder builder = new StringBuilder();
    builder.append("Metric [Id:");
    builder.append(getId());
    builder.append(", ts:");
    builder.append(getCreatedTimestamp());
    builder.append(", ");
    String name = getName();
    if (name != null) {
        builder.append("name:");
        builder.append(name);
        builder.append(", ");
    }
    byte[] ok = getOpaqueKey();
    if (ok != null) {
        builder.append("opaqueKey:[");
        builder.append(MetricSerialization.base64EncodeToString(ok));
        builder.append("]");
    }
    if (ok == null && name != null) {
        builder.deleteCharAt(builder.length() - 1);
        builder.deleteCharAt(builder.length() - 1);
    }
    builder.append("]");
    return builder.toString();
}