Example usage for java.lang StringBuilder insert

List of usage examples for java.lang StringBuilder insert

Introduction

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

Prototype

@Override
public StringBuilder insert(int offset, double d) 

Source Link

Usage

From source file:com.espertech.esper.epl.expression.core.ExprNodeUtility.java

private static ExprNode resolveStaticMethodOrField(ExprIdentNode identNode,
        ExprValidationException propertyException, ExprValidationContext validationContext)
        throws ExprValidationException {
    // Reconstruct the original string
    StringBuilder mappedProperty = new StringBuilder(identNode.getUnresolvedPropertyName());
    if (identNode.getStreamOrPropertyName() != null) {
        mappedProperty.insert(0, identNode.getStreamOrPropertyName() + '.');
    }/*from   w  w  w .  j a v a  2 s. c  om*/

    // Parse the mapped property format into a class name, method and single string parameter
    MappedPropertyParseResult parse = parseMappedProperty(mappedProperty.toString());
    if (parse == null) {
        ExprConstantNode constNode = resolveIdentAsEnumConst(mappedProperty.toString(),
                validationContext.getMethodResolutionService());
        if (constNode == null) {
            throw propertyException;
        } else {
            return constNode;
        }
    }

    // If there is a class name, assume a static method is possible.
    if (parse.getClassName() != null) {
        List<ExprNode> parameters = Collections
                .singletonList((ExprNode) new ExprConstantNodeImpl(parse.getArgString()));
        List<ExprChainedSpec> chain = new ArrayList<ExprChainedSpec>();
        chain.add(new ExprChainedSpec(parse.getClassName(), Collections.<ExprNode>emptyList(), false));
        chain.add(new ExprChainedSpec(parse.getMethodName(), parameters, false));
        ExprNode result = new ExprDotNode(chain, validationContext.getMethodResolutionService().isDuckType(),
                validationContext.getMethodResolutionService().isUdfCache());

        // Validate
        try {
            result.validate(validationContext);
        } catch (ExprValidationException e) {
            throw new ExprValidationException(
                    "Failed to resolve enumeration method, date-time method or mapped property '"
                            + mappedProperty + "': " + e.getMessage());
        }

        return result;
    }

    // There is no class name, try a single-row function
    String functionName = parse.getMethodName();
    try {
        Pair<Class, EngineImportSingleRowDesc> classMethodPair = validationContext.getMethodResolutionService()
                .resolveSingleRow(functionName);
        List<ExprNode> parameters = Collections
                .singletonList((ExprNode) new ExprConstantNodeImpl(parse.getArgString()));
        List<ExprChainedSpec> chain = Collections.singletonList(
                new ExprChainedSpec(classMethodPair.getSecond().getMethodName(), parameters, false));
        ExprNode result = new ExprPlugInSingleRowNode(functionName, classMethodPair.getFirst(), chain,
                classMethodPair.getSecond());

        // Validate
        try {
            result.validate(validationContext);
        } catch (RuntimeException e) {
            throw new ExprValidationException("Plug-in aggregation function '" + parse.getMethodName()
                    + "' failed validation: " + e.getMessage());
        }

        return result;
    } catch (EngineImportUndefinedException e) {
        // Not an single-row function
    } catch (EngineImportException e) {
        throw new IllegalStateException("Error resolving single-row function: " + e.getMessage(), e);
    }

    // Try an aggregation function factory
    try {
        AggregationFunctionFactory aggregationFactory = validationContext.getMethodResolutionService()
                .resolveAggregationFactory(parse.getMethodName());
        ExprNode result = new ExprPlugInAggFunctionFactoryNode(false, aggregationFactory,
                parse.getMethodName());
        result.addChildNode(new ExprConstantNodeImpl(parse.getArgString()));

        // Validate
        try {
            result.validate(validationContext);
        } catch (RuntimeException e) {
            throw new ExprValidationException("Plug-in aggregation function '" + parse.getMethodName()
                    + "' failed validation: " + e.getMessage());
        }

        return result;
    } catch (EngineImportUndefinedException e) {
        // Not an aggregation function
    } catch (EngineImportException e) {
        throw new IllegalStateException("Error resolving aggregation: " + e.getMessage(), e);
    }

    // absolutely cannot be resolved
    throw propertyException;
}

From source file:com.flexive.war.beans.admin.search.ResultPreferencesBean.java

private SelectItem createSelectItem(FxPropertyAssignment assignment) {
    // add parent group path
    final StringBuilder label = new StringBuilder();
    FxGroupAssignment parent = assignment.getParentGroupAssignment();
    while (parent != null) {
        label.insert(0, parent.getLabel() + "/");
        parent = parent.getParentGroupAssignment();
    }/* w ww. jav a 2s.co  m*/
    // add property label
    label.append(assignment.getProperty().getLabel());

    final String value;
    final String propertyName = assignment.getProperty().getName();
    if ("CAPTION".equals(propertyName)) {
        // the caption property is often renamed (which breaks assignment inheritance)
        value = "CAPTION";
    } else if ("TYPEDEF".equals(propertyName)) {
        // select the type label instead
        value = "TYPEDEF.DESCRIPTION";
    } else if ("ACL".equals(propertyName)) {
        value = "ACL.LABEL";
    } else if ("STEP".equals(propertyName)) {
        value = "STEP.LABEL";
    } else if ("CREATED_BY".equals(propertyName) || "MODIFIED_BY".equals(propertyName)) {
        value = assignment.getProperty().getName() + ".USERNAME";
    } else {
        value = "#" + assignment.getXPath();
    }
    return new SelectItem(value, label.toString(), null,
            // disable properties/assignments that are already selected
            columnSelected(assignment.getProperty().getName()) || columnSelected("#" + assignment.getXPath()));
}

From source file:com.netflix.genie.common.model.Cluster.java

/**
 * Helper method to ensure that values are valid for a cluster.
 *
 * @param status      The status of the cluster
 * @param clusterType The type of cluster
 * @throws GeniePreconditionException If any precondition isn't met.
 *///ww  w.java2 s  .  c om
private void validate(final ClusterStatus status, final String clusterType, final String error)
        throws GeniePreconditionException {
    final StringBuilder builder = new StringBuilder();
    if (StringUtils.isNotBlank(error)) {
        builder.append(error);
    }
    if (status == null) {
        builder.append("No cluster status entered and is required.\n");
    }
    if (StringUtils.isBlank(clusterType)) {
        builder.append("No cluster type entered and is required.\n");
    }

    if (builder.length() > 0) {
        builder.insert(0, "Cluster configuration errors:\n");
        final String msg = builder.toString();
        LOG.error(msg);
        throw new GeniePreconditionException(msg);
    }
}

From source file:edu.arizona.kra.proposaldevelopment.dao.ojb.PropDevRoutingStateDaoOjb.java

/**
 * Method that builds the main query for searching for in route proposals
 * @param searchCriteria/*  w w w  . java  2 s. co m*/
 * @return
 * @throws SQLException
 * @throws LookupException
 */
private String buildSqlQuery(Map<String, String> searchCriteria) throws SQLException, LookupException {
    StringBuilder query = new StringBuilder(SQL_LOOKUP);

    if (searchCriteria.containsKey(ROUTE_UNIT_NBR)
            && StringUtils.isNotEmpty(searchCriteria.get(ROUTE_UNIT_NBR))) {
        String routeUnitNumber = searchCriteria.get(ROUTE_UNIT_NBR);

        query.insert(annotationCriteriaOffset, LEAD_UNIT_ANNOT_CRITERIA + routeUnitNumber + "%'");
    }

    if (searchCriteria.containsKey(PROPOSAL_PERSON_NAME)
            && StringUtils.isNotEmpty(searchCriteria.get(PROPOSAL_PERSON_NAME))) {
        String ppName = searchCriteria.get(PROPOSAL_PERSON_NAME).replaceAll("[\"?]", "");
        query.append(PROPOSAL_PERSON_NAME_CRITERIA);
        query.append(StringUtils.lowerCase(ppName.replaceAll("[*]", "%")));
        query.append("%')");
    }

    if (searchCriteria.containsKey(LEAD_COLLEGE) && StringUtils.isNotEmpty(searchCriteria.get(LEAD_COLLEGE))) {
        String leadCollege = searchCriteria.get(LEAD_COLLEGE);
        query.append(LEAD_COLLEGE_CRITERIA);
        query.append(leadCollege);
        query.append(LEAD_COLLEGE_CRITERIA_CONT);
    }

    for (String searchKey : SEARCH_QUERIES.keySet()) {
        if (searchCriteria.containsKey(searchKey) && StringUtils.isNotEmpty(searchCriteria.get(searchKey))) {
            query.append(SEARCH_QUERIES.get(searchKey));
            query.append(searchCriteria.get(searchKey));
            query.append("'");
        }
    }

    for (String searchKey : SEARCH_QUERIES_LIKE.keySet()) {
        if (searchCriteria.containsKey(searchKey) && StringUtils.isNotEmpty(searchCriteria.get(searchKey))) {
            String value = searchCriteria.get(searchKey).replaceAll("[\"?]", "");
            query.append(SEARCH_QUERIES_LIKE.get(searchKey));
            query.append(StringUtils.lowerCase(value.replaceAll("[*]", "%")));
            query.append("%'");
        }
    }

    addSearchDateCriteria(searchCriteria.get(SPONSOR_DATE), SPONSOR_DATE_CRITERIA, query);
    addSearchDateCriteria(searchCriteria.get(ROUTE_STOP_DATE), ROUTE_STOP_DATE_CRITERIA, query);

    query.append(ORDER_CRITERIA);

    LOG.debug("END getPropDevRoutingState sqlQuery={}.", query);
    return query.toString();
}

From source file:com.netflix.genie.common.model.Command.java

/**
 * Helper method for checking the validity of required parameters.
 *
 * @param status The status of the command
 * @param executable The executable of the command.
 * @param error The existing errors if any exist.
 * @throws GeniePreconditionException//from ww  w  .  j  a v a 2s  .  c om
 */
private void validate(final CommandStatus status, final String executable, final String error)
        throws GeniePreconditionException {
    final StringBuilder builder = new StringBuilder();
    if (StringUtils.isNotBlank(error)) {
        builder.append(error);
    }
    if (status == null) {
        builder.append("No command status entered and is required.\n");
    }
    if (StringUtils.isBlank(executable)) {
        builder.append("No executable entered for command and is required.\n");
    }

    if (builder.length() != 0) {
        builder.insert(0, "Command configuration errors:\n");
        final String msg = builder.toString();
        LOG.error(msg);
        throw new GeniePreconditionException(msg);
    }
}

From source file:com.wiiyaya.framework.common.utils.NumberFormatUtils.java

private static String formatCnWithUnit(String numS, boolean other, boolean money) {
    String[] numCn = NUM_CN_LC;/*ww w  . j av a  2 s  .  c  o  m*/
    String[] digitCnLow = DIGIT_CN_L_LC;
    String[] digitCnHigh = DIGIT_CN_H_LC;

    if (money) {
        numCn = NUM_CN_UC;
        digitCnLow = DIGIT_CN_L_UC;
        digitCnHigh = DIGIT_CN_H_UC;
    }

    int remaind = numS.length() % CN_NUM_GRP_LEN;
    int padLength = 0;
    if (remaind > 0) {
        padLength = numS.length() + CN_NUM_GRP_LEN - remaind;
    }
    String numSlpad = new StringBuilder(StringUtils.leftPad(numS, padLength, C_ZERO)).reverse().toString();

    Pattern p = Pattern.compile("\\d{4}");
    Matcher m = p.matcher(numSlpad);

    List<String> numList = new ArrayList<String>();
    while (m.find()) {
        numList.add(m.group());
    }
    if (numList.size() > digitCnHigh.length) {
        return "not support";
    }
    StringBuilder sb = new StringBuilder();
    boolean lastZero = false;
    for (int grountCount = numList.size() - 1; grountCount >= 0; grountCount = grountCount - 1) {
        String group = numList.get(grountCount);
        if (Integer.parseInt(group) == 0) {
            if (sb.length() == 0 || !sb.substring(sb.length() - 1).equals(numCn[0])) {
                sb.append(numCn[0]);
            }
            lastZero = true;
        } else {
            for (int i = CN_NUM_GRP_COUNT; i >= 0; i = i - 1) {
                int d = group.charAt(i) - C_ZERO;
                if (!lastZero || d != 0) {
                    sb.append(numCn[d]);
                }
                if (d != 0) {
                    sb.append(digitCnLow[i]);
                    lastZero = false;
                } else {
                    lastZero = true;
                }
            }
            if (numList.size() == 1) {
                removeFstZero(sb, numCn);
                removeLstZero(sb, numCn);
                removeFstOne(sb, numCn, digitCnLow);
            } else if (grountCount == numList.size() - 1) {
                removeFstZero(sb, numCn);
                removeFstOne(sb, numCn, digitCnLow);
            } else if (grountCount == 0) {
                removeLstZero(sb, numCn);
            }
            if (sb.length() > 1 && sb.substring(sb.length() - 1).equals(numCn[0])) {
                sb.insert(sb.length() - 1, digitCnHigh[grountCount]);
            } else {
                sb.append(digitCnHigh[grountCount]);
            }
        }
    }
    if (numList.size() > 1) {
        removeLstZero(sb, numCn);
    } else if (sb.length() == 1 && other) {
        if (sb.toString().equals(numCn[1])) {
            return OTHER_ONE;
        } else if (sb.toString().equals(numCn[2])) {
            return OTHER_TWO;
        }
    }
    return sb.toString();
}

From source file:com.mentor.questa.vrm.jenkins.QuestaVrmRegressionResult.java

@Override
public String getRelativePathFrom(TestObject it) {

    if (it == this) {
        return ".";
    }//from   w  ww.ja  v  a  2 s  .c o  m

    StringBuilder buf = new StringBuilder();
    TestObject next = this;
    TestObject cur = this;
    // Iterate over ancestors and construct relative url
    while (next != null && it != next) {
        cur = next;
        buf.insert(0, '/');
        buf.insert(0, cur.getSafeName());
        next = cur.getParent();
    }
    if (it == next) {
        return buf.toString();
    } else {
        QuestaVrmRegressionBuildAction action = getRun().getAction(QuestaVrmRegressionBuildAction.class);
        if (action == null) {

            return ""; // this won't take us to the right place, but it also won't 404.
        }
        buf.insert(0, '/');
        buf.insert(0, action.getUrlName());

        // Now the build
        Run<?, ?> myBuild = cur.getRun();
        if (myBuild == null) {

            return "";
        }
        buf.insert(0, '/');
        buf.insert(0, myBuild.getUrl());

        // If we're inside a stapler request, just delegate to Hudson.Util to get the relative path!
        StaplerRequest req = Stapler.getCurrentRequest();
        if (req != null && myBuild instanceof Item) {
            buf.insert(0, '/');

            Item myBuildAsItem = (Item) myBuild;
            buf.insert(0, Functions.getRelativeLinkTo(myBuildAsItem));
        } else {
            // We're not in a stapler request. Okay, give up.
            String hudsonRootUrl = Jenkins.getInstance().getRootUrl();
            if (hudsonRootUrl == null || hudsonRootUrl.length() == 0) {

                return "";

            }
            buf.insert(0, '/');
            buf.insert(0, hudsonRootUrl);
        }

        return buf.toString();
    }

}

From source file:info.mikaelsvensson.devtools.sitesearch.SiteSearchPlugin.java

private boolean modifyStringBuilder(final StringBuilder sb, final Pattern insertionPointPattern,
        final ModifyAction modifyAction, final String text) {
    Matcher matcher = insertionPointPattern.matcher(sb);
    if (matcher.find()) {
        switch (modifyAction) {
        case APPEND:
            sb.insert(matcher.end(), text);
            return true;
        case PREPEND:
            sb.insert(matcher.start(), text);
            return true;
        case REPLACE:
            sb.replace(matcher.start(), matcher.end(), text);
            return true;
        }//from   ww  w  .  ja va 2  s  . c o m
    }
    return false;
}

From source file:hudson.tasks.test.TestObject.java

/**
 * Computes the relative path to get to this test object from <code>it</code>. If
 * <code>it</code> does not appear in the parent chain for this object, a
 * relative path from the server root will be returned.
 *
 * @return A relative path to this object, potentially from the top of the
 * Hudson object model/*from ww  w .  j  a v a2  s. co m*/
 */
public String getRelativePathFrom(TestObject it) {

    // if (it is one of my ancestors) {
    //    return a relative path from it
    // } else {
    //    return a complete path starting with "/"
    // }
    if (it == this) {
        return ".";
    }

    StringBuilder buf = new StringBuilder();
    TestObject next = this;
    TestObject cur = this;
    // Walk up my ancestors from leaf to root, looking for "it"
    // and accumulating a relative url as I go
    while (next != null && it != next) {
        cur = next;
        buf.insert(0, '/');
        buf.insert(0, cur.getSafeName());
        next = cur.getParent();
    }
    if (it == next) {
        return buf.toString();
    } else {
        // Keep adding on to the string we've built so far

        // Start with the test result action
        AbstractTestResultAction action = getTestResultAction();
        if (action == null) {
            LOGGER.warning(
                    "trying to get relative path, but we can't determine the action that owns this result.");
            return ""; // this won't take us to the right place, but it also won't 404.
        }
        buf.insert(0, '/');
        buf.insert(0, action.getUrlName());

        // Now the build
        Run<?, ?> myBuild = cur.getRun();
        if (myBuild == null) {
            LOGGER.warning(
                    "trying to get relative path, but we can't determine the build that owns this result.");
            return ""; // this won't take us to the right place, but it also won't 404. 
        }
        buf.insert(0, '/');
        buf.insert(0, myBuild.getUrl());

        // If we're inside a stapler request, just delegate to Hudson.Functions to get the relative path!
        StaplerRequest req = Stapler.getCurrentRequest();
        if (req != null && myBuild instanceof Item) {
            buf.insert(0, '/');
            // Ugly but I don't see how else to convince the compiler that myBuild is an Item
            Item myBuildAsItem = (Item) myBuild;
            buf.insert(0, Functions.getRelativeLinkTo(myBuildAsItem));
        } else {
            // We're not in a stapler request. Okay, give up.
            LOGGER.info(
                    "trying to get relative path, but it is not my ancestor, and we're not in a stapler request. Trying absolute hudson url...");
            String hudsonRootUrl = Jenkins.getInstance().getRootUrl();
            if (hudsonRootUrl == null || hudsonRootUrl.length() == 0) {
                LOGGER.warning(
                        "Can't find anything like a decent hudson url. Punting, returning empty string.");
                return "";

            }
            buf.insert(0, '/');
            buf.insert(0, hudsonRootUrl);
        }

        LOGGER.info("Here's our relative path: " + buf.toString());
        return buf.toString();
    }

}

From source file:com.netflix.genie.common.model.CommonEntityFields.java

/**
 * Helper method for checking the validity of required parameters.
 *
 * @param name The name of the application
 * @param user The user who created the application
 * @throws GeniePreconditionException/*  w  w  w . ja va2s  .  co m*/
 */
private void validate(final String name, final String user, final String version, final String error)
        throws GeniePreconditionException {
    final StringBuilder builder = new StringBuilder();
    if (StringUtils.isNotBlank(error)) {
        builder.append(error);
    }
    if (StringUtils.isBlank(user)) {
        builder.append("User name is missing and is required.\n");
    }
    if (StringUtils.isBlank(name)) {
        builder.append("Name is missing and is required.\n");
    }
    if (StringUtils.isBlank(version)) {
        builder.append("Version is missing and is required.\n");
    }
    if (builder.length() > 0) {
        builder.insert(0, "CommonEntityFields configuration errors:\n");
        final String msg = builder.toString();
        LOG.error(msg);
        throw new GeniePreconditionException(msg);
    }
}