Example usage for java.lang StringBuilder replace

List of usage examples for java.lang StringBuilder replace

Introduction

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

Prototype

@Override
public StringBuilder replace(int start, int end, String str) 

Source Link

Usage

From source file:org.betaconceptframework.astroboa.model.impl.query.criteria.SimpleCriterionImpl.java

public String getXPath() {

    //No property path is provided. Return empty criterion
    if (StringUtils.isEmpty(property))
        return "";

    StringBuilder criterion = new StringBuilder();

    if (CollectionUtils.isNotEmpty(values) && values.size() > 1)
        criterion.append(CmsConstants.LEFT_PARENTHESIS_WITH_LEADING_AND_TRAILING_SPACE);

    criterion.append(CmsConstants.EMPTY_SPACE);

    if (operator == null)
        operator = QueryOperator.EQUALS;

    if (QueryOperator.IS_NULL == operator) {
        checkThatPropertyPathRefersToSimpleProperty();
        criterion.append(XPathUtils.createNullCriterion(property, propertyIsSimple));
    } else if (QueryOperator.IS_NOT_NULL == operator) {
        checkThatPropertyPathRefersToSimpleProperty();
        criterion.append(XPathUtils.createNotNullCriterion(property, propertyIsSimple));
    } else if (CollectionUtils.isEmpty(values)) {

        checkThatPropertyPathRefersToSimpleProperty();

        if (operator == QueryOperator.EQUALS)
            criterion.append(XPathUtils.createNullCriterion(property, propertyIsSimple));
        else if (operator == QueryOperator.NOT_EQUALS)
            criterion.append(XPathUtils.createNotNullCriterion(property, propertyIsSimple));
        else/*w  w w  .j  a v  a2s  .  c  o m*/
            //No value has been provided. No need to create an empty criterion
            return "";
    } else {
        String propertyPath = property;

        if (QueryOperator.EQUALS == operator || QueryOperator.NOT_EQUALS == operator
                || QueryOperator.LIKE == operator) {
            //Check for case matching to activate appropriate method.
            if (CaseMatching.LOWER_CASE == caseMatching) {
                propertyPath = CmsConstants.FN_LOWER_CASE + CmsConstants.LEFT_PARENTHESIS + property
                        + CmsConstants.RIGHT_PARENTHESIS;
            } else if (CaseMatching.UPPER_CASE == caseMatching) {
                propertyPath = CmsConstants.FN_UPPER_CASE + CmsConstants.LEFT_PARENTHESIS + property
                        + CmsConstants.RIGHT_PARENTHESIS;
            }
        }
        //Values exist. Create appropriate xpath criteria
        if (internalCondition == null)
            internalCondition = Condition.AND;

        performSpecialOperationsInCaseOfContainsOperator();

        for (Object value : values) {
            if (value instanceof String) {
                //Check for case matching and transform the value accordingly.
                value = transformValueIfCaseMatchingIsEnabled(value);

                value = checkIfValueIsAReferenceAndLoadReferenceId((String) value);

                value = checkIfPropertyIsOfTypeLongIntegerOrDoubleAndConvertValueAccordingly(propertyPath,
                        (String) value);
            }

            criterion.append(CmsConstants.EMPTY_SPACE
                    + XPathUtils.createObjectCriteria(propertyPath, operator, value, propertyIsSimple,
                            caseMatching, numberOfNodeLevelsToSearchInTheModelHierarchy)
                    + CmsConstants.EMPTY_SPACE + internalCondition.toString().toLowerCase());
        }

        //Remove the last internal condition
        criterion.replace(criterion.length() - internalCondition.toString().length(), criterion.length(), "");
    }

    criterion.append(CmsConstants.EMPTY_SPACE);

    if (CollectionUtils.isNotEmpty(values) && values.size() > 1)
        criterion.append(CmsConstants.RIGHT_PARENTHESIS_WITH_LEADING_AND_TRAILING_SPACE);

    return criterion.toString();
}

From source file:es.ehu.si.ixa.pipe.convert.Convert.java

public void absaSemEvalToMultiClassNER2015(String fileName) {
    SAXBuilder sax = new SAXBuilder();
    XPathFactory xFactory = XPathFactory.instance();
    try {// w  w w.  j  a  va  2s  .  co m
        Document doc = sax.build(fileName);
        XPathExpression<Element> expr = xFactory.compile("//sentence", Filters.element());
        List<Element> sentences = expr.evaluate(doc);
        for (Element sent : sentences) {

            String sentString = sent.getChildText("text");
            StringBuilder sb = new StringBuilder();
            sb = sb.append(sentString);
            Element opinionsElement = sent.getChild("Opinions");
            if (opinionsElement != null) {
                List<List<Integer>> offsetList = new ArrayList<List<Integer>>();
                HashSet<String> targetClassSet = new LinkedHashSet<String>();
                List<Integer> offsets = new ArrayList<Integer>();
                List<Element> opinionList = opinionsElement.getChildren();
                for (Element opinion : opinionList) {
                    if (!opinion.getAttributeValue("target").equals("NULL")) {
                        String className = opinion.getAttributeValue("category");
                        String targetString = opinion.getAttributeValue("target");
                        Integer offsetFrom = Integer.parseInt(opinion.getAttributeValue("from"));
                        Integer offsetTo = Integer.parseInt(opinion.getAttributeValue("to"));
                        offsets.add(offsetFrom);
                        offsets.add(offsetTo);
                        targetClassSet.add(targetString + "JAR!" + className + opinion.getAttributeValue("from")
                                + opinion.getAttributeValue("to"));
                    }
                }
                List<Integer> offsetsWithoutDuplicates = new ArrayList<Integer>(new HashSet<Integer>(offsets));
                Collections.sort(offsetsWithoutDuplicates);
                List<String> targetClassList = new ArrayList<String>(targetClassSet);

                for (int i = 0; i < offsetsWithoutDuplicates.size(); i++) {
                    List<Integer> offsetArray = new ArrayList<Integer>();
                    offsetArray.add(offsetsWithoutDuplicates.get(i++));
                    if (offsetsWithoutDuplicates.size() > i) {
                        offsetArray.add(offsetsWithoutDuplicates.get(i));
                    }
                    offsetList.add(offsetArray);
                }
                int counter = 0;
                for (int i = 0; i < offsetList.size(); i++) {
                    Integer offsetFrom = offsetList.get(i).get(0);
                    Integer offsetTo = offsetList.get(i).get(1);
                    String className = targetClassList.get(i);
                    String aspectString = sentString.substring(offsetFrom, offsetTo);
                    sb.replace(offsetFrom + counter, offsetTo + counter, "<START:"
                            + className.split("JAR!")[1].substring(0, 3) + "> " + aspectString + " <END>");
                    counter += 18;
                }
                System.out.println(sb.toString());
            }
        }
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }
}

From source file:org.rhq.core.pc.inventory.InventoryManager.java

public void mergeResourcesFromUpgrade(Set<ResourceUpgradeRequest> upgradeRequests) throws Exception {
    Set<ResourceUpgradeResponse> serverUpdates = null;
    try {/*  w  w  w.ja  va 2 s  .c o  m*/
        ServerServices serverServices = this.configuration.getServerServices();
        if (serverServices != null) {
            DiscoveryServerService discoveryServerService = serverServices.getDiscoveryServerService();

            serverUpdates = discoveryServerService.upgradeResources(upgradeRequests);
        }
    } catch (Exception e) {
        log.error("Failed to process resource upgrades on the server.", e);
        throw e;
    }

    if (serverUpdates != null) {
        for (ResourceUpgradeResponse upgradeResponse : serverUpdates) {
            String resourceKey = upgradeResponse.getUpgradedResourceKey();
            String name = upgradeResponse.getUpgradedResourceName();
            String description = upgradeResponse.getUpgradedResourceDescription();

            //only bother if there's something to upgrade at all on this resource.
            if (resourceKey != null || name != null || description != null) {
                ResourceContainer existingResourceContainer = getResourceContainer(
                        upgradeResponse.getResourceId());
                if (existingResourceContainer != null) {
                    Resource existingResource = existingResourceContainer.getResource();

                    StringBuilder logMessage = new StringBuilder("Resource [")
                            .append(existingResource.toString()).append("] upgraded its ");

                    if (resourceKey != null) {
                        existingResource.setResourceKey(resourceKey);
                        logMessage.append("resourceKey, ");
                    }

                    if (name != null) {
                        existingResource.setName(name);
                        logMessage.append("name, ");
                    }

                    if (description != null) {
                        existingResource.setDescription(description);
                        logMessage.append("description, ");
                    }

                    logMessage.replace(logMessage.length() - 1, logMessage.length(), "to become [")
                            .append(existingResource.toString()).append("]");

                    log.info(logMessage.toString());
                } else {
                    log.error("Upgraded a resource that is not present on the agent. This should not happen. "
                            + "The id of the missing resource is: " + upgradeResponse.getResourceId());
                }
            }
        }
    }
}

From source file:ch.puzzle.itc.mobiliar.business.deploy.boundary.DeploymentBoundary.java

/**
 * @param startIndex/* w  w w.  j  a v  a  2 s .  c o m*/
 * @param maxResults when maxResults > 0 it is expected to get the deployments for pagination. In this case an additional count() query will be executed.
 * @param filters
 * @param colToSort
 * @param sortingDirection
 * @param myAmw
 * @return a Tuple containing the filter deployments and the total deployments for that filter if doPagingCalculation is true
 */
public Tuple<Set<DeploymentEntity>, Integer> getFilteredDeployments(Integer startIndex, Integer maxResults,
        List<CustomFilter> filters, String colToSort, CommonFilterService.SortingDirectionType sortingDirection,
        List<Integer> myAmw) {
    Integer totalItemsForCurrentFilter;
    boolean doPaging = maxResults == null ? false : (maxResults > 0 ? true : false);

    StringBuilder stringQuery = new StringBuilder();

    DeploymentState lastDeploymentState = null;
    boolean hasLastDeploymentForAsEnvFilterSet = isLastDeploymentForAsEnvFilterSet(filters);
    Integer from = 0;
    Integer to = 0;

    filters.addAll(addFiltersForDeletedEnvironments(filters));

    if (hasLastDeploymentForAsEnvFilterSet) {
        for (CustomFilter customFilter : filters) {
            if (customFilter.getFilterDisplayName()
                    .equals(DeploymentFilterTypes.DEPLOYMENT_STATE.getFilterDisplayName())) {
                lastDeploymentState = DeploymentState.getByString(customFilter.getValue());
                from = startIndex != null ? startIndex : 0;
                to = maxResults != null ? from + maxResults : from + 200;
                // sever side pagination is done after fetching from db for this combination
                startIndex = null;
                maxResults = null;
                break;
            }
        }

        if (lastDeploymentState == null) {
            stringQuery.append(getListOfLastDeploymentsForAppServerAndContextQuery(false));
        } else {
            stringQuery.append("select " + DEPLOYMENT_QL_ALIAS + " from " + DEPLOYMENT_ENTITY_NAME + " "
                    + DEPLOYMENT_QL_ALIAS + " ");
        }
        commonFilterService.appendWhereAndMyAmwParameter(myAmw, stringQuery,
                "and " + getEntityDependantMyAmwParameterQl());
    } else {
        stringQuery.append("select " + DEPLOYMENT_QL_ALIAS + " from " + DEPLOYMENT_ENTITY_NAME + " "
                + DEPLOYMENT_QL_ALIAS + " ");
        commonFilterService.appendWhereAndMyAmwParameter(myAmw, stringQuery,
                getEntityDependantMyAmwParameterQl());
    }

    String baseQuery = stringQuery.toString();
    // left join required in order that order by works as expected on deployments having null references..
    String nullFix = stringQuery.toString()
            .replace(" from " + DEPLOYMENT_ENTITY_NAME + " " + DEPLOYMENT_QL_ALIAS + " ",
                    " from " + DEPLOYMENT_ENTITY_NAME + " " + DEPLOYMENT_QL_ALIAS + " left join fetch "
                            + DEPLOYMENT_QL_ALIAS + ".release left join fetch " + DEPLOYMENT_QL_ALIAS
                            + ".context ");
    stringQuery = stringQuery.replace(0, nullFix.length() - 1, nullFix);

    boolean lowerSortCol = DeploymentFilterTypes.APPSERVER_NAME.getFilterTabColumnName().equals(colToSort);

    Query query = commonFilterService.addFilterAndCreateQuery(stringQuery, filters, colToSort, sortingDirection,
            DEPLOYMENT_QL_ALIAS + ".id", lowerSortCol, hasLastDeploymentForAsEnvFilterSet, false);

    query = commonFilterService.setParameterToQuery(startIndex, maxResults, myAmw, query);

    Set<DeploymentEntity> deployments = new LinkedHashSet<>();
    // some stuff may be lazy loaded
    List<DeploymentEntity> resultList = query.getResultList();
    final int allResults = resultList.size();

    if (!hasLastDeploymentForAsEnvFilterSet) {
        deployments.addAll(resultList);
    } else {
        resultList = specialSort(latestPerContextAndGroup(resultList), colToSort, sortingDirection);
        if (to > 0) {
            resultList = new ArrayList<>(
                    resultList.subList(from, to < resultList.size() ? to : resultList.size()));
        }
        deployments.addAll(resultList);
    }

    if (doPaging) {
        String countQueryString = baseQuery.replace("select " + DEPLOYMENT_QL_ALIAS,
                "select count(" + DEPLOYMENT_QL_ALIAS + ".id)");
        // last param needs to be true if we are dealing with a combination of "State" and "Latest deployment job for App Server and Env"
        Query countQuery = commonFilterService.addFilterAndCreateQuery(new StringBuilder(countQueryString),
                filters, null, null, null, lowerSortCol, hasLastDeploymentForAsEnvFilterSet,
                lastDeploymentState != null);

        commonFilterService.setParameterToQuery(null, null, myAmw, countQuery);
        totalItemsForCurrentFilter = (lastDeploymentState == null)
                ? ((Long) countQuery.getSingleResult()).intValue()
                : countQuery.getResultList().size();
        // fix for the special case of multiple deployments on the same environment with exactly the same deployment date
        if (hasLastDeploymentForAsEnvFilterSet && lastDeploymentState == null
                && deployments.size() != allResults) {
            totalItemsForCurrentFilter -= allResults - deployments.size();
        }
    } else {
        totalItemsForCurrentFilter = deployments.size();
    }

    return new Tuple<>(deployments, totalItemsForCurrentFilter);
}

From source file:org.kuali.ole.select.document.OleOrderQueueDocument.java

/**
 * This method invokes cancelDocument of DocumentService to delete selected requisitions.
 * Sets error message appriopriately if this action fails.
 *//*w ww. j ava2  s  .co m*/
public void delete() {
    LOG.debug("Inside delete of OleOrderQueueDocument");
    WorkflowDocumentService workflowDocumentService = SpringContext.getBean(WorkflowDocumentService.class);
    Person principalPerson = SpringContext.getBean(PersonService.class)
            .getPerson(GlobalVariables.getUserSession().getPerson().getPrincipalId());
    WorkflowDocument workflowDocument;
    List<OleRequisitionItem> refreshItems = new ArrayList<OleRequisitionItem>();
    OleRequisitionDocument requisitionDocument;
    StringBuilder orderQueueRequisitionDeleted = new StringBuilder();
    boolean isErrorMsg = false;
    for (OleRequisitionItem item : requisitionItems) {
        boolean itemAdded = item.isItemAdded();
        if (itemAdded) {
            try {
                workflowDocument = workflowDocumentService
                        .loadWorkflowDocument(item.getRequisition().getDocumentNumber(), principalPerson);
                if (workflowDocument.isSaved()) {
                    requisitionDocument = SpringContext.getBean(BusinessObjectService.class)
                            .findBySinglePrimaryKey(OleRequisitionDocument.class,
                                    Long.valueOf(item.getRequisition().getPurapDocumentIdentifier()));
                    requisitionDocument.setDocumentHeader(SpringContext.getBean(DocumentHeaderService.class)
                            .getDocumentHeaderById(item.getRequisition().getDocumentNumber()));

                    try {
                        requisitionDocument.getDocumentHeader().setWorkflowDocument(workflowDocument);
                        SpringContext.getBean(DocumentService.class).cancelDocument(requisitionDocument,
                                OLEConstants.OrderQueue.CANCEL_ANNOTATION);
                        orderQueueRequisitionDeleted.append(item.getRequisition().getDocumentNumber())
                                .append(",");
                        isErrorMsg = true;
                    } catch (WorkflowException wfe) {
                        GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS,
                                OLEKeyConstants.ERROR_ORDERQUEUE_REQUISITIONS_CANCELED_WFE,
                                new String[] { requisitionDocument.getDocumentNumber(), wfe.getMessage() });
                        refreshItems.add(item);
                    }
                } else {
                    GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS,
                            OLEKeyConstants.ERROR_ORDERQUEUE_REQUISITIONS_CANCELED,
                            new String[] { workflowDocument.getStatus().toString(),
                                    item.getRequisition().getDocumentNumber() });
                    refreshItems.add(item);
                }
            } catch (WorkflowException ex) {
                GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS,
                        RiceKeyConstants.ERROR_CUSTOM, ex.getMessage());
                refreshItems.add(item);
            }
        } else {
            refreshItems.add(item);
        }
    }

    int len = orderQueueRequisitionDeleted.lastIndexOf(",");
    if (isErrorMsg) {
        orderQueueRequisitionDeleted.replace(len, len + 1, " ");
        GlobalVariables.getMessageMap().putInfo(OLEConstants.OrderQueue.REQUISITIONS,
                OLEKeyConstants.MESSAGE_ORDERQUEUE_REQUISITIONS_CANCELED,
                new String[] { orderQueueRequisitionDeleted.toString() });
    }
    requisitionItems = refreshItems;
    LOG.debug("Leaving delete of OleOrderQueueDocument");
}

From source file:ffx.potential.parsers.BiojavaFilter.java

/**
 * <p>/*  w w  w  .j a  v a2 s .  co  m*/
 * writeAtom</p>
 *
 * @param atom a {@link ffx.potential.bonded.Atom} object.
 * @param serial a int.
 * @param sb a {@link java.lang.StringBuilder} object.
 * @param anisouSB a {@link java.lang.StringBuilder} object.
 * @param bw a {@link java.io.BufferedWriter} object.
 * @throws java.io.IOException if any.
 */
public void writeAtom(Atom atom, int serial, StringBuilder sb, StringBuilder anisouSB, BufferedWriter bw)
        throws IOException {
    String name = atom.getName();
    if (name.length() > 4) {
        name = name.substring(0, 4);
    } else if (name.length() == 1) {
        name = name + "  ";
    } else if (name.length() == 2) {
        if (atom.getAtomType().valence == 0) {
            name = name + "  ";
        } else {
            name = name + " ";
        }
    }
    double xyz[] = vdwH ? atom.getRedXYZ() : atom.getXYZ(null);
    sb.replace(6, 16, String.format("%5s " + padLeft(name.toUpperCase(), 4), Hybrid36.encode(5, serial)));
    Character altLoc = atom.getAltLoc();
    if (altLoc != null) {
        sb.setCharAt(16, altLoc);
    } else {
        sb.setCharAt(16, ' ');
    }
    sb.replace(30, 66, String.format("%8.3f%8.3f%8.3f%6.2f%6.2f", xyz[0], xyz[1], xyz[2], atom.getOccupancy(),
            atom.getTempFactor()));
    name = Atom.ElementSymbol.values()[atom.getAtomicNumber() - 1].toString();
    name = name.toUpperCase();
    if (atom.isDeuterium()) {
        name = "D";
    }
    sb.replace(76, 78, padLeft(name, 2));
    sb.replace(78, 80, String.format("%2d", 0));
    if (!listMode) {
        bw.write(sb.toString());
        bw.newLine();
    } else {
        listOutput.add(sb.toString());
    }
    // =============================================================================
    //  1 - 6        Record name   "ANISOU"
    //  7 - 11       Integer       serial         Atom serial number.
    // 13 - 16       Atom          name           Atom name.
    // 17            Character     altLoc         Alternate location indicator
    // 18 - 20       Residue name  resName        Residue name.
    // 22            Character     chainID        Chain identifier.
    // 23 - 26       Integer       resSeq         Residue sequence number.
    // 27            AChar         iCode          Insertion code.
    // 29 - 35       Integer       u[0][0]        U(1,1)
    // 36 - 42       Integer       u[1][1]        U(2,2)
    // 43 - 49       Integer       u[2][2]        U(3,3)
    // 50 - 56       Integer       u[0][1]        U(1,2)
    // 57 - 63       Integer       u[0][2]        U(1,3)
    // 64 - 70       Integer       u[1][2]        U(2,3)
    // 77 - 78       LString(2)    element        Element symbol, right-justified.
    // 79 - 80       LString(2)    charge         Charge on the atom.
    // =============================================================================
    double[] anisou = atom.getAnisou(null);
    if (anisou != null) {
        anisouSB.replace(6, 80, sb.substring(6, 80));
        anisouSB.replace(28, 70,
                String.format("%7d%7d%7d%7d%7d%7d", (int) (anisou[0] * 1e4), (int) (anisou[1] * 1e4),
                        (int) (anisou[2] * 1e4), (int) (anisou[3] * 1e4), (int) (anisou[4] * 1e4),
                        (int) (anisou[5] * 1e4)));
        if (!listMode) {
            bw.write(anisouSB.toString());
            bw.newLine();
        } else {
            listOutput.add(anisouSB.toString());
        }
    }
}

From source file:ffx.potential.parsers.BiojavaFilter.java

public void writeSIFTAtom(Atom atom, int serial, StringBuilder sb, StringBuilder anisouSB, BufferedWriter bw,
        String siftScore) throws IOException {
    String name = atom.getName();
    if (name.length() > 4) {
        name = name.substring(0, 4);//from   w  w  w.j  a  va2 s .c  o m
    } else if (name.length() == 1) {
        name = name + "  ";
    } else if (name.length() == 2) {
        if (atom.getAtomType().valence == 0) {
            name = name + "  ";
        } else {
            name = name + " ";
        }
    }
    double xyz[] = vdwH ? atom.getRedXYZ() : atom.getXYZ(null);
    sb.replace(6, 16, String.format("%5s " + padLeft(name.toUpperCase(), 4), Hybrid36.encode(5, serial)));
    Character altLoc = atom.getAltLoc();
    if (altLoc != null) {
        sb.setCharAt(16, altLoc);
    } else {
        sb.setCharAt(16, ' ');
    }
    if (siftScore == null) {
        sb.replace(30, 66,
                String.format("%8.3f%8.3f%8.3f%6.2f%6.2f", xyz[0], xyz[1], xyz[2], atom.getOccupancy(), 110.0));
    } else {
        sb.replace(30, 66, String.format("%8.3f%8.3f%8.3f%6.2f%6.2f", xyz[0], xyz[1], xyz[2],
                atom.getOccupancy(), (1 + (-1 * Float.parseFloat(siftScore))) * 100));
    }
    name = Atom.ElementSymbol.values()[atom.getAtomicNumber() - 1].toString();
    name = name.toUpperCase();
    if (atom.isDeuterium()) {
        name = "D";
    }
    sb.replace(76, 78, padLeft(name, 2));
    sb.replace(78, 80, String.format("%2d", 0));
    if (!listMode) {
        bw.write(sb.toString());
        bw.newLine();
    } else {
        listOutput.add(sb.toString());
    }
    // =============================================================================
    //  1 - 6        Record name   "ANISOU"
    //  7 - 11       Integer       serial         Atom serial number.
    // 13 - 16       Atom          name           Atom name.
    // 17            Character     altLoc         Alternate location indicator
    // 18 - 20       Residue name  resName        Residue name.
    // 22            Character     chainID        Chain identifier.
    // 23 - 26       Integer       resSeq         Residue sequence number.
    // 27            AChar         iCode          Insertion code.
    // 29 - 35       Integer       u[0][0]        U(1,1)
    // 36 - 42       Integer       u[1][1]        U(2,2)
    // 43 - 49       Integer       u[2][2]        U(3,3)
    // 50 - 56       Integer       u[0][1]        U(1,2)
    // 57 - 63       Integer       u[0][2]        U(1,3)
    // 64 - 70       Integer       u[1][2]        U(2,3)
    // 77 - 78       LString(2)    element        Element symbol, right-justified.
    // 79 - 80       LString(2)    charge         Charge on the atom.
    // =============================================================================
    double[] anisou = atom.getAnisou(null);
    if (anisou != null) {
        anisouSB.replace(6, 80, sb.substring(6, 80));
        anisouSB.replace(28, 70,
                String.format("%7d%7d%7d%7d%7d%7d", (int) (anisou[0] * 1e4), (int) (anisou[1] * 1e4),
                        (int) (anisou[2] * 1e4), (int) (anisou[3] * 1e4), (int) (anisou[4] * 1e4),
                        (int) (anisou[5] * 1e4)));
        if (!listMode) {
            bw.write(anisouSB.toString());
            bw.newLine();
        } else {
            listOutput.add(anisouSB.toString());
        }
    }
}

From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java

/**
 * Shorten the specified name to the specified target name. This will
 * be done by first stripping out the vowels, and then removing
 * characters from the middle of the word until it reaches the target
 * length./*  w w w. ja v  a 2  s .c  o  m*/
 */
public static String shorten(String name, int targetLength) {
    if (name == null || name.length() <= targetLength)
        return name;

    StringBuilder nm = new StringBuilder(name);
    while (nm.length() > targetLength) {
        if (!stripVowel(nm)) {
            // cut out the middle char
            nm.replace(nm.length() / 2, (nm.length() / 2) + 1, "");
        }
    }
    return nm.toString();
}

From source file:org.sakaiproject.message.impl.BaseMessageService.java

/**
 * Access the internal reference which can be used to access the message from within the system.
 * //from ww w .  j a v  a 2s.  c om
 * @param channelRef
 *        The channel reference.
 * @param id
 *        The message id.
 * @return The the internal reference which can be used to access the message from within the system.
 */
public String messageReference(String channelRef, String id) {
    StringBuilder buf = new StringBuilder();

    // start with the channel ref
    buf.append(channelRef);

    // swap channel for msg
    int pos = buf.indexOf(REF_TYPE_CHANNEL);
    buf.replace(pos, pos + REF_TYPE_CHANNEL.length(), REF_TYPE_MESSAGE);

    // add the id
    buf.append(Entity.SEPARATOR);
    buf.append(id);

    return buf.toString();
}

From source file:com.liferay.portlet.journal.lar.JournalPortletDataHandlerImpl.java

protected static String exportLayoutFriendlyURLs(PortletDataContext portletDataContext, String content) {

    Group group = null;//from  w  ww.ja va2 s .c o  m

    try {
        group = GroupLocalServiceUtil.getGroup(portletDataContext.getScopeGroupId());
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e);
        }

        return content;
    }

    StringBuilder sb = new StringBuilder(content);

    String friendlyURLPrivateGroupPath = PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING;
    String friendlyURLPrivateUserPath = PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING;
    String friendlyURLPublicPath = PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING;

    String href = "href=";

    int beginPos = content.length();

    while (true) {
        int hrefLength = href.length();

        beginPos = content.lastIndexOf(href, beginPos);

        if (beginPos == -1) {
            break;
        }

        char c = content.charAt(beginPos + hrefLength);

        if ((c == CharPool.APOSTROPHE) || (c == CharPool.QUOTE)) {
            hrefLength++;
        }

        int endPos1 = content.indexOf(CharPool.APOSTROPHE, beginPos + hrefLength);
        int endPos2 = content.indexOf(CharPool.CLOSE_BRACKET, beginPos + hrefLength);
        int endPos3 = content.indexOf(CharPool.CLOSE_CURLY_BRACE, beginPos + hrefLength);
        int endPos4 = content.indexOf(CharPool.CLOSE_PARENTHESIS, beginPos + hrefLength);
        int endPos5 = content.indexOf(CharPool.LESS_THAN, beginPos + hrefLength);
        int endPos6 = content.indexOf(CharPool.QUESTION, beginPos + hrefLength);
        int endPos7 = content.indexOf(CharPool.QUOTE, beginPos + hrefLength);
        int endPos8 = content.indexOf(CharPool.SPACE, beginPos + hrefLength);

        int endPos = endPos1;

        if ((endPos == -1) || ((endPos2 != -1) && (endPos2 < endPos))) {
            endPos = endPos2;
        }

        if ((endPos == -1) || ((endPos3 != -1) && (endPos3 < endPos))) {
            endPos = endPos3;
        }

        if ((endPos == -1) || ((endPos4 != -1) && (endPos4 < endPos))) {
            endPos = endPos4;
        }

        if ((endPos == -1) || ((endPos5 != -1) && (endPos5 < endPos))) {
            endPos = endPos5;
        }

        if ((endPos == -1) || ((endPos6 != -1) && (endPos6 < endPos))) {
            endPos = endPos6;
        }

        if ((endPos == -1) || ((endPos7 != -1) && (endPos7 < endPos))) {
            endPos = endPos7;
        }

        if ((endPos == -1) || ((endPos8 != -1) && (endPos8 < endPos))) {
            endPos = endPos8;
        }

        if (endPos == -1) {
            beginPos--;

            continue;
        }

        String url = content.substring(beginPos + hrefLength, endPos);

        if (!url.startsWith(friendlyURLPrivateGroupPath) && !url.startsWith(friendlyURLPrivateUserPath)
                && !url.startsWith(friendlyURLPublicPath)) {

            beginPos--;

            continue;
        }

        int beginGroupPos = content.indexOf(CharPool.SLASH, beginPos + hrefLength + 1);

        if (beginGroupPos == -1) {
            beginPos--;

            continue;
        }

        int endGroupPos = content.indexOf(CharPool.SLASH, beginGroupPos + 1);

        if (endGroupPos == -1) {
            beginPos--;

            continue;
        }

        String groupFriendlyURL = content.substring(beginGroupPos, endGroupPos);

        if (groupFriendlyURL.equals(group.getFriendlyURL())) {
            sb.replace(beginGroupPos, endGroupPos, "@data_handler_group_friendly_url@");
        }

        beginPos--;
    }

    return sb.toString();
}