Example usage for java.lang StringBuffer insert

List of usage examples for java.lang StringBuffer insert

Introduction

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

Prototype

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

Source Link

Usage

From source file:com.dearho.cs.subscriber.service.impl.SubscriberServiceImpl.java

@Override
public Page querySubscriberRechargeMostByPage(Page page, Subscriber subscriber) {

    StringBuffer hql = new StringBuffer();
    hql.append(/* w w w  . j  a v  a  2  s. c  o m*/
            "select a.subscriber_id as subscriber_id ,sum(a.amount) as sum_amount from acc_current_account a ,sub_subscriber s  where s.id=a.subscriber_id and a.type="
                    + Account.TYPE_RECHARGE);
    //hql.append("select a.subscriber_id as subscriber_id ,sum(a.amount) as sum_amount from acc_current_account a   where  a.type="+Account.TYPE_RECHARGE);

    if (subscriber != null) {
        if (subscriber.getState() != null) {
            hql.append(" and s.state=" + subscriber.getState());
        }
        if (subscriber.getEventState() != null) {
            hql.append(" and s.event_state=" + subscriber.getEventState());
        }
        if (StringUtils.isNotEmpty(subscriber.getPhoneNo())) {
            hql.append(" and s.phone_no like '%" + subscriber.getPhoneNo() + "%'");
        }
        if (StringUtils.isNotEmpty(subscriber.getSex())) {
            hql.append(" and sex = '" + subscriber.getSex() + "'");
        }
        if (StringUtils.isNotEmpty(subscriber.getName())) {
            hql.append(" and name like '%" + subscriber.getName() + "%'");
        }
    }
    hql.append(" group by a.subscriber_id   ");
    hql.append(" order by sum(a.amount) desc ");

    hql.insert(0, "select b.subscriber_id ,sum_amount from ( ");
    hql.append(" )b");

    page.setCountField("b.subscriber_id");
    //      page=subscriberDao.querySubscriberRechargeMostByPage(page, hql.toString());
    return page;

}

From source file:com.ephesoft.dcma.kvfieldcreation.KVFieldCreator.java

/**
 * This method searches key to left of value.
 * //from   www .  j ava  2s  .  c o m
 * @param kvExtractionField {@link KVExtraction}
 * @param recCoordinates
 * @param span
 * @param lineDataCarrier
 * @param location
 * @param keyCoordinates
 * @param minKeyCharsInt
 * @param numericKeyLearningSwitch {@link String}
 * @return {@link Boolean}
 */
private boolean createKeyLeft(KVExtraction kvExtractionField, Coordinates recCoordinates, Span span,
        LineDataCarrier lineDataCarrier, LocationType location, Coordinates keyCoordinates, int minKeyCharsInt,
        final String numericKeyLearningSwitch) {
    LOGGER.info(MSG_KEY_CREATION + location.toString());
    int prevKeyX0 = 0;
    boolean keyFound = false;
    int gapBetweenWords = 0;
    StringBuffer keyString = new StringBuffer();
    List<Coordinates> keyCoordinatesList = new ArrayList<Coordinates>();
    Integer spanIndex = lineDataCarrier.getIndexOfSpan(span);
    if (spanIndex != null) {
        Span leftSpan = lineDataCarrier.getLeftSpan(spanIndex);
        while (leftSpan != null) {
            String key = leftSpan.getValue();
            if (keyFound && null != key && !key.trim().isEmpty()) {
                gapBetweenWords = prevKeyX0 - leftSpan.getCoordinates().getX1().intValue();
                if (Math.abs(gapBetweenWords) < gapBetweenKeys) {
                    keyCoordinatesList.add(leftSpan.getCoordinates());
                    keyString.insert(0, key.trim() + KVFieldCreatorConstants.SPACE);
                    prevKeyX0 = leftSpan.getCoordinates().getX0().intValue();
                    LOGGER.info("Key == " + keyString);
                } else {
                    break;
                }
            } else if (key != null && !key.trim().isEmpty()
                    && !KVFieldCreatorConstants.KEY_VALUE_SEPARATORS.contains(key) && validateKey(key,
                            recCoordinates, leftSpan.getCoordinates(), location, numericKeyLearningSwitch)) {
                keyCoordinatesList.add(leftSpan.getCoordinates());
                prevKeyX0 = leftSpan.getCoordinates().getX0().intValue();
                keyString.append(key.trim());
                LOGGER.info("Key == " + keyString);
                keyFound = true;
            }
            spanIndex = spanIndex - 1;
            leftSpan = lineDataCarrier.getLeftSpan(spanIndex);
        }
        if (keyFound) {
            keyFound = setKeyPattern(kvExtractionField, keyCoordinates, minKeyCharsInt, keyString,
                    keyCoordinatesList);
        }
    }
    return keyFound;
}

From source file:org.allcolor.yahp.converter.CClassLoader.java

/**
 * calculate the loader path/*  ww w  .j  av a2s .  c  om*/
 * 
 * @return the calculated path
 */
private final String nGetLoaderPath() {
    ClassLoader currentLoader = this;
    final StringBuffer buffer = new StringBuffer();
    buffer.append(this.name);

    while ((currentLoader = currentLoader.getParent()) != null) {
        if (currentLoader.getClass() == CClassLoader.class) {
            buffer.insert(0, "/");
            buffer.insert(0, ((CClassLoader) currentLoader).name);
        } else {
            break;
        }
    }

    return buffer.toString();
}

From source file:org.ourbeehive.mbp.builder.OprImplBuilder.java

/**
 * rectify content to adapt its parent's structure
 * @param content/*from w  w  w  .j av a 2s  . c  o m*/
 * @param parentIndents
 * @return
 */
private StringBuffer rectifyContent(String content, String parentIndents) {
    StringBuffer srcCode = new StringBuffer();
    if (content == null) {
        return srcCode;
    }
    String indents = BuilderHelper.exportIndents() + parentIndents;
    srcCode.append(content);
    srcCode.insert(0, indents);
    for (int offset = 1; offset < srcCode.length();) {
        int index = srcCode.indexOf(JavaSrcElm.LINE_SEPARATOR, offset);
        if (index == -1) {
            break;
        }
        srcCode.insert(index + 1, indents);
        offset = index + 1;
    }

    return srcCode;
}

From source file:forseti.JUtil.java

public static synchronized String obtCuentaFormato(String str_cuenta, HttpServletRequest request) {
    if (str_cuenta == null || str_cuenta.length() != 19)
        return "";

    StringBuffer cuenta = new StringBuffer(str_cuenta);
    HttpSession ses = request.getSession(true);
    JSesionPrincipal pr = (JSesionPrincipal) ses.getAttribute("forseti");

    byte nivel = pr.getNivelCC();

    for (int i = 1; i < 6; i++) {
        cuenta.insert(i * 4, '-');
    }/*from   w w  w.j av  a  2s. c  o  m*/

    String cuentaForm = cuenta.toString();
    return cuentaForm.substring(0, nivel * 4);

}

From source file:forseti.JUtil.java

public static synchronized String obtCuentaFormato(StringBuffer cuenta, HttpServletRequest request) {
    if (cuenta.length() != 19)
        return "";

    HttpSession ses = request.getSession(true);
    JSesionPrincipal pr = (JSesionPrincipal) ses.getAttribute("forseti");

    byte nivel = pr.getNivelCC();

    for (int i = 1; i < 6; i++) {
        cuenta.insert(i * 4, '-');
    }/*  w ww  .  j a  v a2s  .c o m*/

    String cuentaForm = cuenta.toString();
    return cuentaForm.substring(0, nivel * 4);

}

From source file:org.infoglue.deliver.invokers.PageInvoker.java

private void generateExtensionBundles(Map<String, Set<String>> extensionBundles, String contentType,
        String targetElement) {//from  www  . java 2  s  .c o  m
    Timer t = new Timer();

    Set<String> bundledSignatures = new HashSet<String>();

    Iterator<String> scriptExtensionBundlesIterator = extensionBundles.keySet().iterator();
    while (scriptExtensionBundlesIterator.hasNext()) {
        String bundleName = scriptExtensionBundlesIterator.next();
        if (logger.isInfoEnabled())
            logger.info("bundleName:" + bundleName);

        Set<String> scriptExtensionFileNames = extensionBundles.get(bundleName);

        if (scriptExtensionFileNames != null && scriptExtensionFileNames.size() > 0) {
            String scriptBundle = "";

            int i = 0;
            String filePath = CmsPropertyHandler.getDigitalAssetPath0();
            while (filePath != null) {
                try {
                    File extensionsDirectory = new File(filePath + File.separator + "extensions");
                    extensionsDirectory.mkdirs();

                    File extensionsBundleFile = new File(
                            filePath + File.separator + "extensions" + File.separator + bundleName + ".js");
                    if (contentType.equalsIgnoreCase("text/css"))
                        extensionsBundleFile = new File(filePath + File.separator + "extensions"
                                + File.separator + bundleName + ".css");

                    if (!extensionsBundleFile.exists()) {
                        if (logger.isInfoEnabled())
                            logger.info("No script - generating:" + bundleName);
                        if (scriptBundle.equals("")) {
                            Iterator<String> scriptExtensionFileNamesIterator = scriptExtensionFileNames
                                    .iterator();
                            while (scriptExtensionFileNamesIterator.hasNext()) {
                                String scriptExtensionFileName = scriptExtensionFileNamesIterator.next();
                                if (logger.isInfoEnabled())
                                    logger.info("scriptExtensionFileName:" + scriptExtensionFileName);
                                try {
                                    File file = new File(filePath + File.separator + scriptExtensionFileName);
                                    String signature = "" + file.getName() + "_" + file.length();
                                    if (logger.isInfoEnabled())
                                        logger.info("Checking file:" + filePath + File.separator
                                                + scriptExtensionFileName);

                                    if (file.exists() && !bundledSignatures.contains(signature)) {
                                        StringBuffer content = new StringBuffer(
                                                FileHelper.getFileAsStringOpt(file));
                                        //Wonder what is the best signature..
                                        bundledSignatures.add(signature);

                                        //If CSS we should change url:s to point to the original folder
                                        if (contentType.equalsIgnoreCase("text/css")) {
                                            if (logger.isInfoEnabled())
                                                logger.info("contentType:" + contentType);
                                            String extensionPath = file.getPath().substring(
                                                    extensionsDirectory.getPath().length() + 1,
                                                    file.getPath().lastIndexOf("/") + 1);
                                            if (logger.isInfoEnabled())
                                                logger.info("extensionPath:" + extensionPath);

                                            int urlStartIndex = content.indexOf("url(");
                                            while (urlStartIndex > -1) {
                                                if (content.charAt(urlStartIndex + 4) == '"'
                                                        || content.charAt(urlStartIndex + 4) == '\'')
                                                    content.insert(urlStartIndex + 5, extensionPath);
                                                else
                                                    content.insert(urlStartIndex + 4, extensionPath);
                                                urlStartIndex = content.indexOf("url(",
                                                        urlStartIndex + extensionPath.length());
                                            }
                                        }
                                        //logger.info("transformed content:" + content.substring(0, 500));

                                        scriptBundle = scriptBundle + "\n\n" + content;
                                    } else {
                                        if (logger.isInfoEnabled())
                                            logger.info("Not adding:" + signature + " as " + file.exists() + ":"
                                                    + bundledSignatures.contains(signature));
                                    }
                                } catch (Exception e) {
                                    logger.warn("Error trying to parse file and bundle it ("
                                            + scriptExtensionFileName + "):" + e.getMessage());
                                }
                            }
                        }

                        if (logger.isInfoEnabled())
                            logger.info("scriptBundle:" + scriptBundle.length());
                        if (scriptBundle != null && !scriptBundle.equals("")) {
                            if (contentType.equalsIgnoreCase("text/javascript")) {
                                try {
                                    JSMin jsmin = new JSMin(new ByteArrayInputStream(scriptBundle.getBytes()),
                                            new FileOutputStream(extensionsBundleFile));
                                    jsmin.jsmin();
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                FileHelper.writeToFile(extensionsBundleFile, scriptBundle, false);
                            }
                            if (logger.isInfoEnabled())
                                logger.info("extensionsBundleFile:" + extensionsBundleFile.length());
                        }
                    }

                    i++;
                    filePath = CmsPropertyHandler.getProperty("digitalAssetPath." + i);
                } catch (Exception e) {
                    logger.warn("Error trying to write bundled scripts:" + e.getMessage());
                }
            }
            try {
                SiteNodeVO siteNodeVO = NodeDeliveryController.getNodeDeliveryController(deliveryContext)
                        .getSiteNodeVO(getDatabase(), getTemplateController().getSiteNodeId());
                String dnsName = CmsPropertyHandler.getWebServerAddress();
                if (siteNodeVO != null) {
                    RepositoryVO repositoryVO = RepositoryController.getController()
                            .getRepositoryVOWithId(siteNodeVO.getRepositoryId(), getDatabase());
                    if (repositoryVO.getDnsName() != null && !repositoryVO.getDnsName().equals(""))
                        dnsName = repositoryVO.getDnsName();
                }

                String bundleUrl = "";
                String bundleUrlTag = "";

                if (contentType.equalsIgnoreCase("text/javascript")) {
                    bundleUrl = URLComposer.getURLComposer().composeDigitalAssetUrl(dnsName, "extensions",
                            bundleName + ".js", deliveryContext);
                    bundleUrlTag = "<script type=\"text/javascript\" src=\"" + bundleUrl + "\"></script>";
                } else if (contentType.equalsIgnoreCase("text/css")) {
                    bundleUrl = URLComposer.getURLComposer().composeDigitalAssetUrl(dnsName, "extensions",
                            bundleName + ".css", deliveryContext);
                    bundleUrlTag = "<link href=\"" + bundleUrl + "\" rel=\"stylesheet\" type=\"text/css\" />";
                }

                if (targetElement.equalsIgnoreCase("head"))
                    this.getTemplateController().getDeliveryContext().getHtmlHeadItems().add(bundleUrlTag);
                else
                    this.getTemplateController().getDeliveryContext().getHtmlBodyEndItems().add(bundleUrlTag);
            } catch (Exception e) {
                logger.warn("Error trying  get assetBaseUrl:" + e.getMessage());
            }
        }

    }
    if (logger.isInfoEnabled())
        t.printElapsedTime("Generating bundles took");
}

From source file:com.sfs.whichdoctor.dao.RotationDAOImpl.java

/**
 * Update the workplace./*from   www  . ja v  a 2s .co m*/
 *
 * @param rotation the rotation
 * @param existingOrganisationGUIDs the existing organisation gui ds
 * @param parentAction the parent action
 * @param checkUser the check user
 * @param privileges the privileges
 *
 * @throws WhichDoctorDaoException the which doctor dao exception
 */
private void updateWorkplace(final RotationBean rotation, final Collection<Integer> existingOrganisationGUIDs,
        final String parentAction, final UserBean checkUser, final PrivilegesBean privileges)
        throws WhichDoctorDaoException {

    ItemBean workplace = null;

    final int defaultWeighting = 10;

    Collection<Integer> newOrganisationGUIDs = new ArrayList<Integer>();
    if (rotation.getOrganisation1Id() > 0) {
        newOrganisationGUIDs.add(rotation.getOrganisation1Id());
    }
    if (rotation.getOrganisation2Id() > 0) {
        newOrganisationGUIDs.add(rotation.getOrganisation2Id());
    }

    /* Determine what workplaces need creating/modifying/deleting */
    HashMap<Integer, String> organisations = new HashMap<Integer, String>();

    for (Integer organisationGUID : existingOrganisationGUIDs) {
        organisations.put(organisationGUID, "delete");
    }
    if (!StringUtils.equals(parentAction, "delete")) {
        // If the rotation is not being deleted add the new workplaces
        for (Integer organisationGUID : newOrganisationGUIDs) {
            if (organisations.containsKey(organisationGUID)) {
                organisations.put(organisationGUID, "modify");
            } else {
                organisations.put(organisationGUID, "create");
            }
        }
    }

    for (Integer organisationGUID : organisations.keySet()) {
        final String action = organisations.get(organisationGUID);

        if (!StringUtils.equals(action, "create")) {
            // Load the workplace object
            workplace = this.getItemDAO().loadReference(rotation.getGUID(), organisationGUID, "Employer");
        }
        if (workplace == null && !StringUtils.equals(action, "delete")) {
            workplace = new ItemBean();
        }

        if (workplace != null) {
            workplace.setTitle(rotation.getDescription());
            workplace.setObject1GUID(organisationGUID);
            workplace.setObject2GUID(rotation.getPersonId());
            workplace.setReferenceGUID(rotation.getGUID());
            workplace.setStartDate(rotation.getStartDate());
            workplace.setEndDate(rotation.getEndDate());
            workplace.setWeighting(defaultWeighting);

            StringBuffer info = new StringBuffer();
            if (rotation.getSupervisors() != null && rotation.getSupervisors().size() > 0) {
                int i = 1;
                for (SupervisorBean supervisor : rotation.getSupervisors()) {
                    if (supervisor != null && supervisor.getPerson() != null) {
                        if (info.length() > 0) {
                            if (i == rotation.getSupervisors().size()) {
                                info.append(" and ");
                            } else {
                                info.append(", ");
                            }
                        }
                        info.append(OutputFormatter.toCasualName(supervisor.getPerson()));
                        i++;
                    }
                }
                if (info.length() > 0) {
                    info.insert(0, "Supervised by ");
                    info.append("\n");
                }
            }

            info.append(rotation.getTotalDays());
            info.append(" approximate days training (");
            info.append(Formatter.toPercent(rotation.getTrainingTime(), 0, "%"));
            info.append(" time");
            if (rotation.getLeaveDays() > 0) {
                info.append(", ");
                info.append(rotation.getLeaveDays());
                info.append(" days on leave");
            }
            info.append(")");

            workplace.setComment(info.toString());

            workplace.setItemType("Employer");

            updateWorkplace(workplace, action, checkUser, privileges);
        }
    }
}

From source file:org.itracker.web.util.ImportExportUtilities.java

/**
 * Takes an array of IssueModels and exports them as XML suitable for import into another
 * instance of ITracker, or another issue tracking tool.
 *
 * @param issues an array of Issue objects to export
 * @throws ImportExportException thrown if the array of issues can not be exported
 *//*from  ww  w .j a v a  2  s.  c o m*/
public static String exportIssues(List<Issue> issues, SystemConfiguration config) throws ImportExportException {
    StringBuffer buf = new StringBuffer();
    HashMap<String, Project> projects = new HashMap<String, Project>();
    HashMap<String, User> users = new HashMap<String, User>();

    if (issues == null || issues.size() == 0) {
        throw new ImportExportException("The issue list was null or zero length.");
    }
    buf.append("<" + TAG_ISSUES + ">\n");
    for (int i = 0; i < issues.size(); i++) {
        if (!projects.containsKey(issues.get(i).getProject().getId().toString())) {
            logger.debug("Adding new project " + issues.get(i).getProject().getId() + " to export.");
            projects.put(issues.get(i).getProject().getId().toString(), issues.get(i).getProject());
        }

        if (issues.get(i).getCreator() != null
                && !users.containsKey(issues.get(i).getCreator().getId().toString())) {
            logger.debug("Adding new user " + issues.get(i).getCreator().getId() + " to export.");
            users.put(issues.get(i).getCreator().getId().toString(), issues.get(i).getCreator());
        }
        if (issues.get(i).getOwner() != null
                && !users.containsKey(issues.get(i).getOwner().getId().toString())) {
            logger.debug("Adding new user " + issues.get(i).getOwner().getId() + " to export.");
            users.put(issues.get(i).getOwner().getId().toString(), issues.get(i).getOwner());
        }

        List<IssueHistory> history = issues.get(i).getHistory();
        for (int j = 0; j < history.size(); j++) {
            if (history.get(j) != null && history.get(j).getUser() != null
                    && !users.containsKey(history.get(j).getUser().getId().toString())) {
                logger.debug("Adding new user " + history.get(j).getUser().getId() + " to export.");
                users.put(history.get(j).getUser().getId().toString(), history.get(j).getUser());
            }
        }

        List<IssueAttachment> attachments = issues.get(i).getAttachments();
        for (int j = 0; j < attachments.size(); j++) {
            if (attachments.get(j) != null && attachments.get(j).getUser() != null
                    && !users.containsKey(attachments.get(j).getUser().getId().toString())) {
                logger.debug("Adding new user " + attachments.get(j).getUser().getId() + " to export.");
                users.put(attachments.get(j).getUser().getId().toString(), attachments.get(j).getUser());
            }
        }

        buf.append(exportModel((AbstractEntity) issues.get(i)));
    }
    buf.append("</" + TAG_ISSUES + ">\n");
    buf.append("</" + TAG_ROOT + ">\n");

    buf.insert(0, "</" + TAG_PROJECTS + ">\n");
    for (Iterator<String> iter = projects.keySet().iterator(); iter.hasNext();) {
        Project project = (Project) projects.get((String) iter.next());
        for (int i = 0; i < project.getOwners().size(); i++) {
            users.put(project.getOwners().get(i).getId().toString(), project.getOwners().get(i));
        }
        buf.insert(0, exportModel((AbstractEntity) project));
    }
    buf.insert(0, "<" + TAG_PROJECTS + ">\n");

    buf.insert(0, "</" + TAG_USERS + ">\n");
    for (Iterator<String> iter = users.keySet().iterator(); iter.hasNext();) {
        buf.insert(0, exportModel((AbstractEntity) users.get((String) iter.next())));
    }
    buf.insert(0, "<" + TAG_USERS + ">\n");

    if (config != null) {
        buf.insert(0, "</" + TAG_CONFIGURATION + ">\n");
        buf.insert(0, getConfigurationXML(config));
        buf.insert(0, "<" + TAG_CONFIGURATION + ">\n");
    }

    buf.insert(0, "<" + TAG_ROOT + ">\n");

    return buf.toString();
}

From source file:org.dspace.browse.BrowseDAOPostgres.java

/**
 * Build the query that will be used for a distinct select.  This incorporates
 * only the parts of the parameters that are actually useful for this type
 * of browse/*from  w  ww .  ja va  2 s  . com*/
 *
 * @return      the query to be executed
 * @throws BrowseException
 */
private String buildDistinctQuery(List<Serializable> params) throws BrowseException {
    StringBuffer queryBuf = new StringBuffer();

    if (!buildSelectListCount(queryBuf)) {
        if (!buildSelectListValues(queryBuf)) {
            throw new BrowseException("No arguments for SELECT statement");
        }
    }

    buildSelectStatementDistinct(queryBuf, params);
    buildWhereClauseOpReset();

    // assemble the focus clause if we are to have one
    // it will look like one of the following, for example
    //     sort_value <= myvalue
    //     sort_1 >= myvalue
    buildWhereClauseJumpTo(queryBuf, params);

    // assemble the where clause out of the two possible value clauses
    // and include container support
    buildWhereClauseDistinctConstraints(queryBuf, params);

    // assemble the order by field
    buildOrderBy(queryBuf);

    // prepare the limit and offset clauses
    buildRowLimitAndOffset(queryBuf, params);

    //If we want frequencies and this is not a count query, enchance the query accordingly
    if (isEnableBrowseFrequencies() && countValues == null) {
        String before = "SELECT count(*) AS num, dvalues.value, dvalues.authority FROM (";
        String after = ") dvalues , " + tableMap + " WHERE dvalues.id = " + tableMap + ".distinct_id GROUP BY "
                + tableMap + ".distinct_id, dvalues.value, dvalues.authority, dvalues.sort_value";

        queryBuf.insert(0, before);
        queryBuf.append(after);
        buildOrderBy(queryBuf);
    }

    return queryBuf.toString();
}