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:com.ah.ui.actions.teacherView.TvRedirectionAction.java

private List<String> getResourceMapCLIs() {
    StringBuilder cli = new StringBuilder();

    List<String> clis = new ArrayList<String>();
    clis.add("no teacher-view resource-map\n");

    List<TvResourceMap> maps = QueryUtil.executeQuery(TvResourceMap.class, null, null, this.getDomainId());

    for (TvResourceMap map : maps) {
        cli.append("teacher-view resource-map name ").append("\"" + map.getResource() + "\"").append(" ip ")
                .append(map.getAlias()).append(" port ").append(map.getPort()).append("\n");
        clis.add(cli.toString());/*from  w  w  w . j  a  v  a  2  s.c om*/
        cli.delete(0, cli.length());
    }

    return clis;
}

From source file:hu.bme.mit.sette.common.tasks.TestSuiteGenerator.java

private void appendMethodCall(final StringBuilder sb, final Class<?> javaClass, final Method method,
        final InputElement inputElement) {
    sb.append(javaClass.getSimpleName()).append('.').append(method.getName());
    sb.append("(");

    for (AbstractParameterElement parameter : inputElement.getParameters()) {
        if (parameter instanceof ParameterElement) {
            ParameterElement p = (ParameterElement) parameter;
            String value = p.getValue();

            if (p.getType() == ParameterType.CHAR) {
                sb.append('\'').append(value).append('\'');
            } else if (p.getType() == ParameterType.BYTE) {
                sb.append("(byte) ").append(value);
            } else if (p.getType() == ParameterType.SHORT) {
                sb.append("(short) ").append(value);
            } else if (p.getType() == ParameterType.LONG) {
                value = value.toUpperCase();
                sb.append(value);/*from w  w  w . j  a v  a2s.c om*/
                if (!value.endsWith("L")) {
                    sb.append("L");
                }
            } else if (p.getType() == ParameterType.FLOAT) {
                value = value.toLowerCase();
                sb.append(value);
                if (!value.endsWith("f")) {
                    sb.append("f");
                }
            } else if (p.getType() == ParameterType.DOUBLE) {
                sb.append(value);
                if (value.indexOf('.') < 0) {
                    sb.append(".0");
                }
            } else {
                sb.append(value);
            }
            sb.append(", ");
        } else {
            System.err.println("Unhandled type: " + parameter.getClass());
        }
    }

    if (inputElement.getParameters().size() > 0) {
        sb.delete(sb.length() - 2, sb.length());
    }

    sb.append(");\n");
}

From source file:com.redhat.rhn.domain.server.Server.java

/**
 * Returns a comma-delimted list of add-on entitlements with their human readable
 * labels.//  w w  w  . ja v  a2s  . c  o m
 *
 * @return A comma-delimted list of add-on entitlements with their human readable
 * labels.
 */
public String getAddOnEntitlementsAsText() {
    Set<?> addOnEntitlements = getAddOnEntitlements();
    Iterator<?> iterator = addOnEntitlements.iterator();
    StringBuilder buffer = new StringBuilder();
    Entitlement entitlement = null;

    while (iterator.hasNext()) {
        entitlement = (Entitlement) iterator.next();
        buffer.append(entitlement.getHumanReadableLabel()).append(", ");
    }

    if (!addOnEntitlements.isEmpty()) {
        buffer.delete(buffer.length() - 2, buffer.length());
    }

    return buffer.toString();
}

From source file:org.apache.hadoop.mapreduce.v2.app.webapp.TasksBlock.java

@Override
protected void render(Block html) {
    if (app.getJob() == null) {
        html.h2($(TITLE));//w ww  . jav a2 s. co m
        return;
    }
    TaskType type = null;
    String symbol = $(TASK_TYPE);
    if (!symbol.isEmpty()) {
        type = MRApps.taskType(symbol);
    }
    TBODY<TABLE<Hamlet>> tbody = html.table("#tasks").thead().tr().th("Task").th("Progress").th("Status")
            .th("State").th("Start Time").th("Finish Time").th("Elapsed Time")._()._().tbody();
    StringBuilder tasksTableData = new StringBuilder("[\n");

    for (Task task : app.getJob().getTasks().values()) {
        if (type != null && task.getType() != type) {
            continue;
        }
        String taskStateStr = $(TASK_STATE);
        if (taskStateStr == null || taskStateStr.trim().equals("")) {
            taskStateStr = "ALL";
        }

        if (!taskStateStr.equalsIgnoreCase("ALL")) {
            try {
                // get stateUI enum
                MRApps.TaskStateUI stateUI = MRApps.taskState(taskStateStr);
                if (!stateUI.correspondsTo(task.getState())) {
                    continue;
                }
            } catch (IllegalArgumentException e) {
                continue; // not supported state, ignore
            }
        }

        TaskInfo info = new TaskInfo(task);
        String tid = info.getId();
        String pct = StringUtils.format("%.2f", info.getProgress());
        tasksTableData.append("[\"<a href='").append(url("task", tid)).append("'>").append(tid)
                .append("</a>\",\"")
                //Progress bar
                .append("<br title='").append(pct).append("'> <div class='").append(C_PROGRESSBAR)
                .append("' title='").append(join(pct, '%')).append("'> ").append("<div class='")
                .append(C_PROGRESSBAR_VALUE).append("' style='").append(join("width:", pct, '%'))
                .append("'> </div> </div>\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(info.getStatus())))
                .append("\",\"")

                .append(info.getState()).append("\",\"").append(info.getStartTime()).append("\",\"")
                .append(info.getFinishTime()).append("\",\"").append(info.getElapsedTime()).append("\"],\n");
    }
    //Remove the last comma and close off the array of arrays
    if (tasksTableData.charAt(tasksTableData.length() - 2) == ',') {
        tasksTableData.delete(tasksTableData.length() - 2, tasksTableData.length() - 1);
    }
    tasksTableData.append("]");
    html.script().$type("text/javascript")._("var tasksTableData=" + tasksTableData)._();

    tbody._()._();
}

From source file:meff.Function.java

private Map<String, String> compile() {
    class Compiler {
        private Map<String, StringBuilder> functions;
        private String currentFunctionName;
        private StringBuilder currentFunction;

        Compiler(String functionName) {
            functions = new HashMap<>();
            currentFunctionName = functionName;
            currentFunction = new StringBuilder();
            functions.put(currentFunctionName, currentFunction);
        }/*  w  w w .  j  a  va2 s .  co m*/

        void compileLine(StringBuilder line) {
            // Manage score value features
            {
                Matcher m = Pattern.compile("(score_\\w+)(>=|>|<=|<|==)(-?\\d+)").matcher(line);
                while (m.find()) {
                    int offset = m.start();

                    String beginning = m.group(1);
                    String operator = m.group(2);
                    String end = m.group(3);

                    StringBuilder newScore = new StringBuilder();
                    switch (operator) {
                    case ">=":
                        newScore.append(beginning).append("_min=").append(end);
                        break;
                    case ">":
                        newScore.append(beginning).append("_min=").append(Integer.parseInt(end) + 1);
                        break;
                    case "<=":
                        newScore.append(beginning).append("=").append(end);
                        break;
                    case "<":
                        newScore.append(beginning).append("=").append(Integer.parseInt(end) - 1);
                        break;
                    case "==":
                        newScore.append(beginning).append("_min=").append(end).append(",").append(beginning)
                                .append("=").append(end);
                        break;
                    }

                    line.replace(offset, offset + m.group().length(), newScore.toString());

                    m.reset(); // Need to reset the matcher, so it updates the length of the text
                }
            }

            currentFunction.append(line).append("\n");
        }

        Map<String, String> getOutput() {
            Map<String, String> outputMap = new HashMap<>(functions.size());

            for (Map.Entry<String, StringBuilder> entry : functions.entrySet()) {
                outputMap.put(entry.getKey() + ".mcfunction", entry.getValue().toString());
            }

            return outputMap;
        }
    }

    Compiler compiler = new Compiler(getName());

    boolean comment = false;

    StringBuilder sb = new StringBuilder();

    for (String line : data.lines) {
        line = line.trim();
        if (line.startsWith("#") || line.startsWith("//")) {
            continue;
        }
        if (line.isEmpty()) {
            continue;
        }

        int si = 0; // start index
        int bci = -1; // block comment index
        int bcei = -1; // block comment end index
        int prevBci = -1;
        int prevBcei = -1;
        while ((!comment && (bci = line.indexOf("/*", si)) > -1)
                || (comment && (bcei = line.indexOf("*/", si)) > -1)) {
            if (comment) {
                if (line.charAt(bcei - 1) == '\\') {
                    si = bcei + 2;
                    bcei = prevBcei;
                    continue;
                }
                comment = false;
                si = bcei + 2;
            } else {
                if (line.charAt(bci - 1) == '\\') {
                    sb.append(line.substring(si, bci - 1)).append("/*");
                    si = bci + 2;
                    bci = prevBci;
                    continue;
                }
                sb.append(line.substring(si, bci));
                comment = true;
                si = bci + 2;
            }
            prevBci = bci;
            prevBcei = bcei;
        }

        if (comment) {
            continue;
        }

        if (line.endsWith("\\")) {
            line = line.substring(si, line.length() - 1);
            sb.append(line);
        } else {
            sb.append(line.substring(si));
            compiler.compileLine(sb);
            sb.delete(0, sb.length());
        }
    }

    return compiler.getOutput();
}

From source file:fi.kela.kanta.util.GenericToString.java

/**
 * Geneerinen toString metodi, jolla saadaan yksinkertainen siisti key=value listaus annetun luokan attribuuteista.
 *
 * @param obj//from w  ww  .  ja  v a2  s  .  co  m
 *            Objekti jonka tiedot halutaan tulostaa.
 * @return Listaus annetun objektin attribuuteista ja niiden arvoista.
 */
public String toString(Object obj) {

    StringBuilder sb = new StringBuilder();
    sb.append(obj.getClass().getSimpleName());
    sb.append(GenericToString.open_parameters);

    boolean fieldsAdded = false;
    for (Field field : GenericToString.getAllFields(obj.getClass())) {
        // Ei nytet staattisia kentti
        if (field != null && !java.lang.reflect.Modifier.isStatic(field.getModifiers())
                && !(field.getName().startsWith("this$") || field.getName().startsWith("_persistence"))) {
            fieldsAdded = true;
            sb.append(field.getName()).append(GenericToString.equals);
            try {
                if (field.getType().isPrimitive() || field.getType().isAssignableFrom(String.class)) {
                    if (field.getAnnotation(OmitFromToString.class) != null) {
                        sb.append(hidden_value);
                    } else {
                        sb.append(FieldUtils.readField(obj, field.getName(), true));
                    }
                } else if (field.getType().isArray()) {
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                    }
                    // TODO: Voi jatkokehitt siten ett tulostaa siististi arrayn
                    Object fieldValue = field.get(obj);
                    if (fieldValue != null) {
                        sb.append(GenericToString.na_array);
                    } else {
                        sb.append(GenericToString.null_array);
                    }
                } else {
                    addObjectInfo(sb, field, obj);
                }
            } catch (IllegalAccessException e) {
                LOGGER.error(e);
                sb.append(GenericToString.na_access);
            }

            sb.append(GenericToString.comma);
        }
    }

    if (fieldsAdded) {
        // remove last comma and space
        sb.delete(sb.length() - 2, sb.length());
    }
    sb.append(GenericToString.close_parameters);
    return sb.toString();
}

From source file:org.apache.tinkerpop.gremlin.python.jsr223.PythonTranslator.java

private String internalTranslate(final String start, final Bytecode bytecode) {
    final StringBuilder traversalScript = new StringBuilder(start);
    for (final Bytecode.Instruction instruction : bytecode.getInstructions()) {
        final String methodName = instruction.getOperator();
        final Object[] arguments = instruction.getArguments();
        if (0 == arguments.length)
            traversalScript.append(".").append(SymbolHelper.toPython(methodName)).append("()");
        else if (methodName.equals("range") && 2 == arguments.length
                && ((Number) arguments[0]).intValue() != 0) {
            if (((Number) arguments[0]).longValue() + 1 == ((Number) arguments[1]).longValue())
                traversalScript.append("[").append(arguments[0]).append("]");
            else//from ww w.  j a v a  2 s.com
                traversalScript.append("[").append(arguments[0]).append(":").append(arguments[1]).append("]");
        } else if (methodName.equals("limit") && 1 == arguments.length)
            traversalScript.append("[0:").append(arguments[0]).append("]");
        else if (methodName.equals("values") && 1 == arguments.length && traversalScript.length() > 3
                && !STEP_NAMES.contains(arguments[0].toString()))
            traversalScript.append(".").append(arguments[0]);
        else {
            traversalScript.append(".");
            String temp = SymbolHelper.toPython(methodName) + "(";
            for (final Object object : arguments) {
                temp = temp + convertToString(object) + ",";
            }
            traversalScript.append(temp.substring(0, temp.length() - 1)).append(")");
        }
        // clip off __.
        if (this.importStatics && traversalScript.substring(0, 3).startsWith("__.")
                && !NO_STATIC.stream()
                        .filter(name -> traversalScript.substring(3).startsWith(SymbolHelper.toPython(name)))
                        .findAny().isPresent()) {
            traversalScript.delete(0, 3);
        }
    }
    return traversalScript.toString();
}

From source file:com.vmware.bdd.cli.commands.ClusterCommands.java

private String getValidateWarningMsg(Map<String, List<String>> noExistingFilesMap) {
    StringBuilder warningMsgBuff = new StringBuilder();
    if (noExistingFilesMap != null && !noExistingFilesMap.isEmpty()) {
        warningMsgBuff.append("Warning: ");
        for (Entry<String, List<String>> noExistingFilesEntry : noExistingFilesMap.entrySet()) {
            List<String> noExistingFileNames = noExistingFilesEntry.getValue();
            for (String noExistingFileName : noExistingFileNames) {
                warningMsgBuff.append(noExistingFileName).append(", ");
            }//from  w  ww.j  a  va2  s.co  m
            warningMsgBuff.delete(warningMsgBuff.length() - 2, warningMsgBuff.length());
            if (noExistingFileNames.size() > 1) {
                warningMsgBuff.append(" are ");
            } else {
                warningMsgBuff.append(" is ");
            }
            warningMsgBuff.append("not existing in ");
            warningMsgBuff.append(noExistingFilesEntry.getKey() + " scope , ");
        }
        warningMsgBuff.replace(warningMsgBuff.length() - 2, warningMsgBuff.length(), ". ");
        warningMsgBuff.append(Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT);
    }
    return warningMsgBuff.toString();
}

From source file:com.evolveum.polygon.scim.StandardScimHandlingStrategy.java

@Override
public ConnectorObject buildConnectorObject(JSONObject resourceJsonObject, String resourceEndPoint)
        throws ConnectorException {

    List<String> excludedAttributes = new ArrayList<String>();

    LOGGER.info("Building the connector object from provided json");

    if (resourceJsonObject == null) {
        LOGGER.error(/*from   w  ww .  j av  a 2s .  c  om*/
                "Empty json object was passed from data provider. Error ocourance while building connector object");
        throw new ConnectorException(
                "Empty json object was passed from data provider. Error ocourance while building connector object");
    }

    ConnectorObjectBuilder cob = new ConnectorObjectBuilder();
    cob.setUid(resourceJsonObject.getString(ID));
    excludedAttributes.add(ID);
    if (USERS.equals(resourceEndPoint)) {
        cob.setName(resourceJsonObject.getString(USERNAME));
        excludedAttributes.add(USERNAME);
    } else if (GROUPS.equals(resourceEndPoint)) {

        cob.setName(resourceJsonObject.getString(DISPLAYNAME));
        excludedAttributes.add(DISPLAYNAME);
        cob.setObjectClass(ObjectClass.GROUP);
    } else {
        cob.setName(resourceJsonObject.getString(DISPLAYNAME));
        excludedAttributes.add(DISPLAYNAME);
        ObjectClass objectClass = new ObjectClass(resourceEndPoint);
        cob.setObjectClass(objectClass);

    }
    for (String key : resourceJsonObject.keySet()) {
        Object attribute = resourceJsonObject.get(key);

        excludedAttributes = excludeFromAssembly(excludedAttributes);

        if (excludedAttributes.contains(key)) {

            //LOGGER.warn("The attribute \"{0}\" was omitted from the connId object build.", key);

        } else

        if (attribute instanceof JSONArray) {

            JSONArray attributeArray = (JSONArray) attribute;

            Map<String, Collection<Object>> multivaluedAttributeMap = new HashMap<String, Collection<Object>>();
            Collection<Object> attributeValues = new ArrayList<Object>();

            for (Object singleAttribute : attributeArray) {
                StringBuilder objectNameBilder = new StringBuilder(key);
                String objectKeyName = "";
                if (singleAttribute instanceof JSONObject) {
                    for (String singleSubAttribute : ((JSONObject) singleAttribute).keySet()) {
                        if (TYPE.equals(singleSubAttribute)) {
                            objectKeyName = objectNameBilder.append(DOT)
                                    .append(((JSONObject) singleAttribute).get(singleSubAttribute)).toString();
                            objectNameBilder.delete(0, objectNameBilder.length());
                            break;
                        }
                    }

                    for (String singleSubAttribute : ((JSONObject) singleAttribute).keySet()) {
                        Object sAttributeValue;
                        if (((JSONObject) singleAttribute).isNull(singleSubAttribute)) {
                            sAttributeValue = null;
                        } else {

                            sAttributeValue = ((JSONObject) singleAttribute).get(singleSubAttribute);
                        }

                        if (TYPE.equals(singleSubAttribute)) {
                        } else {

                            if (!"".equals(objectKeyName)) {
                                objectNameBilder = objectNameBilder.append(objectKeyName).append(DOT)
                                        .append(singleSubAttribute);
                            } else {
                                objectKeyName = objectNameBilder.append(DOT).append(DEFAULT).toString();
                                objectNameBilder = objectNameBilder.append(DOT).append(singleSubAttribute);
                            }

                            if (attributeValues.isEmpty()) {

                                attributeValues.add(sAttributeValue);
                                multivaluedAttributeMap.put(objectNameBilder.toString(), attributeValues);
                            } else {
                                if (multivaluedAttributeMap.containsKey(objectNameBilder.toString())) {
                                    attributeValues = multivaluedAttributeMap.get(objectNameBilder.toString());
                                    attributeValues.add(sAttributeValue);
                                } else {
                                    Collection<Object> newAttributeValues = new ArrayList<Object>();
                                    newAttributeValues.add(sAttributeValue);
                                    multivaluedAttributeMap.put(objectNameBilder.toString(),
                                            newAttributeValues);
                                }

                            }
                            objectNameBilder.delete(0, objectNameBilder.length());

                        }
                    }
                } else {
                    objectKeyName = objectNameBilder.append(DOT).append(singleAttribute.toString()).toString();
                    cob.addAttribute(objectKeyName, singleAttribute);
                }
            }

            if (!multivaluedAttributeMap.isEmpty()) {
                for (String attributeName : multivaluedAttributeMap.keySet()) {
                    cob.addAttribute(attributeName, multivaluedAttributeMap.get(attributeName));
                }

            }

        } else if (attribute instanceof JSONObject) {
            for (String s : ((JSONObject) attribute).keySet()) {
                Object attributeValue;
                if (key.contains(FORBIDENSEPPARATOR)) {
                    key = key.replace(FORBIDENSEPPARATOR, SEPPARATOR);
                }

                if (((JSONObject) attribute).isNull(s)) {

                    attributeValue = null;

                } else {

                    attributeValue = ((JSONObject) attribute).get(s);

                }

                StringBuilder objectNameBilder = new StringBuilder(key);
                cob.addAttribute(objectNameBilder.append(DOT).append(s).toString(), attributeValue);
            }

        } else {

            if (ACTIVE.equals(key)) {
                cob.addAttribute(OperationalAttributes.ENABLE_NAME, resourceJsonObject.get(key));
            } else {

                if (!resourceJsonObject.isNull(key)) {

                    cob.addAttribute(key, resourceJsonObject.get(key));
                } else {
                    Object value = null;
                    cob.addAttribute(key, value);

                }
            }
        }
    }
    ConnectorObject finalConnectorObject = cob.build();
    // LOGGER.info("The connector object returned from the processed json:
    // {0}", finalConnectorObject);
    return finalConnectorObject;

}

From source file:org.alfresco.repo.audit.AuditComponentTest.java

public void testQuery_Action01() throws Exception {
    final Long beforeTime = new Long(System.currentTimeMillis());

    // Make sure that we have something to search for
    testAudit_Action01();/*from  w w  w  .  j  a v  a2s. c  o m*/

    final StringBuilder sb = new StringBuilder();
    final MutableInt rowCount = new MutableInt();

    AuditQueryCallback callback = new AuditQueryCallback() {
        public boolean valuesRequired() {
            return true;
        }

        public boolean handleAuditEntry(Long entryId, String applicationName, String user, long time,
                Map<String, Serializable> values) {
            assertNotNull(applicationName);
            assertNotNull(user);

            sb.append("Row: ").append(entryId).append(" | ").append(applicationName).append(" | ").append(user)
                    .append(" | ").append(new Date(time)).append(" | ").append(values).append(" | ")
                    .append("\n");
            ;
            rowCount.setValue(rowCount.intValue() + 1);
            return true;
        }

        public boolean handleAuditEntryError(Long entryId, String errorMsg, Throwable error) {
            throw new AlfrescoRuntimeException(errorMsg, error);
        }
    };

    AuditQueryParameters params = new AuditQueryParameters();
    params.setForward(true);
    params.setApplicationName(APPLICATION_ACTIONS_TEST);

    sb.delete(0, sb.length());
    rowCount.setValue(0);
    auditComponent.auditQuery(callback, params, Integer.MAX_VALUE);
    assertTrue("Expected some data", rowCount.intValue() > 0);
    logger.debug(sb.toString());
    int allResults = rowCount.intValue();

    // Limit by count
    sb.delete(0, sb.length());
    rowCount.setValue(0);
    auditComponent.auditQuery(callback, params, 1);
    assertEquals("Expected to limit data", 1, rowCount.intValue());
    logger.debug(sb.toString());

    // Limit by time and query up to and excluding the 'before' time
    sb.delete(0, sb.length());
    rowCount.setValue(0);
    params.setToTime(beforeTime);
    auditComponent.auditQuery(callback, params, Integer.MAX_VALUE);
    params.setToTime(null);
    logger.debug(sb.toString());
    int resultsBefore = rowCount.intValue();

    // Limit by time and query from and including the 'before' time
    sb.delete(0, sb.length());
    rowCount.setValue(0);
    params.setFromTime(beforeTime);
    auditComponent.auditQuery(callback, params, Integer.MAX_VALUE);
    params.setFromTime(null);
    logger.debug(sb.toString());
    int resultsAfter = rowCount.intValue();

    assertEquals("Time-limited queries did not get all results before and after a time", allResults,
            (resultsBefore + resultsAfter));

    sb.delete(0, sb.length());
    rowCount.setValue(0);
    params.setUser(user);
    auditComponent.auditQuery(callback, params, Integer.MAX_VALUE);
    params.setUser(null);
    assertTrue("Expected some data for specific user", rowCount.intValue() > 0);
    logger.debug(sb.toString());

    sb.delete(0, sb.length());
    rowCount.setValue(0);
    params.setUser("Numpty");
    auditComponent.auditQuery(callback, params, Integer.MAX_VALUE);
    params.setUser(null);
    assertTrue("Expected no data for bogus user", rowCount.intValue() == 0);
    logger.debug(sb.toString());

}