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:org.nordapp.web.servlet.AbstractControlImpl.java

/**
 * Converts the current time into a time prefix.
 * /*from   ww  w. ja v  a2s .  c om*/
 * @return Returns the time prefix.
 */
protected String makeTimePrefix() {
    long raw = System.currentTimeMillis();
    int time = (int) (raw & maskTimePrefix); //0-16777215

    StringBuffer buf = new StringBuffer(Integer.toHexString(time));
    for (int i = buf.length(); i < sizeTimePrefix; i++)
        buf.insert(0, '0');

    return buf.toString();
}

From source file:org.apache.velocity.util.ExtProperties.java

/**
 * Inserts a backslash before every comma and backslash.
 *//*from w w w  . j av a2s. co m*/
private static String escape(String s) {
    StringBuffer buf = new StringBuffer(s);
    for (int i = 0; i < buf.length(); i++) {
        char c = buf.charAt(i);
        if (c == ',' || c == '\\') {
            buf.insert(i, '\\');
            i++;
        }
    }
    return buf.toString();
}

From source file:com.npower.dm.hibernate.entity.DDFNodeEntity.java

/**
 * Caculate relative node path./*  www  .  j a v  a  2s.c  o m*/
 * For exmaple:
 *   RootNode: /AP/A1
 *   Node: /AP/A1/B1/B2/B3
 *   Will return result: B1/B2/B3
 *   
 * @param rootNode
 * @return
 * @throws DMException
 */
public String caculateRelativeNodePath(DDFNode rootNode) throws DMException {
    assert rootNode != null : "RootNode is null";

    if (this.getID() == rootNode.getID()) {
        return "";
    }
    DDFNode parent = this.getParentDDFNode();
    boolean isParent = false;
    while (parent != null) {
        if (parent.getID() == rootNode.getID()) {
            isParent = true;
            break;
        }
        parent = parent.getParentDDFNode();
    }
    if (!isParent) {
        throw new DMException(
                "The RootNode: " + rootNode.getID() + " doesn't include the childnode: " + this.getID());
    }

    StringBuffer result = new StringBuffer();
    String name = this.getName();
    name = (name == null) ? "${NodeName}" : name;
    result.append(name);
    parent = this.getParentDDFNode();
    while (parent != null && parent.getID() != rootNode.getID()) {
        result.insert(0, "/");
        name = parent.getName();
        name = (name == null) ? "${NodeName}" : name;
        result.insert(0, name);
        parent = parent.getParentDDFNode();
    }
    return result.toString();
}

From source file:DomUtils.java

/**
 * Construct the XPath of the supplied DOM Node.
 * <p/>//  w  w  w. java 2s  . c  om
 * Supports element, comment and cdata sections DOM Node types.
 * @param node DOM node for XPath generation.
 * @return XPath string representation of the supplied DOM Node.
 */
public static String getXPath(Node node) {

    StringBuffer xpath = new StringBuffer();
    Node parent = node.getParentNode();

    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        xpath.append(getXPathToken((Element) node));
        break;
    case Node.COMMENT_NODE:
        int commentNum = DomUtils.countNodesBefore(node, Node.COMMENT_NODE);
        xpath.append("/{COMMENT}[" + commentNum + 1 + "]");
        break;
    case Node.CDATA_SECTION_NODE:
        int cdataNum = DomUtils.countNodesBefore(node, Node.CDATA_SECTION_NODE);
        xpath.append("/{CDATA}[" + cdataNum + 1 + "]");
        break;
    default:
        throw new UnsupportedOperationException(
                "XPath generation for supplied DOM Node type not supported.  Only supports element, comment and cdata section DOM nodes.");
    }

    while (parent != null && parent.getNodeType() == Node.ELEMENT_NODE) {
        xpath.insert(0, getXPathToken((Element) parent));
        parent = parent.getParentNode();
    }

    return xpath.toString();
}

From source file:org.apache.ofbiz.content.data.DataResourceWorker.java

public static void renderDataResourceAsText(Delegator delegator, String dataResourceId, Appendable out,
        Map<String, Object> templateContext, Locale locale, String targetMimeTypeId, boolean cache,
        List<GenericValue> webAnalytics) throws GeneralException, IOException {
    if (dataResourceId == null) {
        throw new GeneralException("Cannot lookup data resource with for a null dataResourceId");
    }//  w  ww  . j a  v  a  2 s.com
    if (templateContext == null) {
        templateContext = new HashMap<String, Object>();
    }
    if (UtilValidate.isEmpty(targetMimeTypeId)) {
        targetMimeTypeId = "text/html";
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }

    // if the target mimeTypeId is not a text type, throw an exception
    if (!targetMimeTypeId.startsWith("text/")) {
        throw new GeneralException(
                "The desired mime-type is not a text type, cannot render as text: " + targetMimeTypeId);
    }

    // get the data resource object
    GenericValue dataResource = EntityQuery.use(delegator).from("DataResource")
            .where("dataResourceId", dataResourceId).cache(cache).queryOne();

    if (dataResource == null) {
        throw new GeneralException(
                "No data resource object found for dataResourceId: [" + dataResourceId + "]");
    }

    // a data template attached to the data resource
    String dataTemplateTypeId = dataResource.getString("dataTemplateTypeId");

    // no template; or template is NONE; render the data
    if (UtilValidate.isEmpty(dataTemplateTypeId) || "NONE".equals(dataTemplateTypeId)) {
        DataResourceWorker.writeDataResourceText(dataResource, targetMimeTypeId, locale, templateContext,
                delegator, out, cache);
    } else {
        // a template is defined; render the template first
        templateContext.put("mimeTypeId", targetMimeTypeId);

        // FTL template
        if ("FTL".equals(dataTemplateTypeId)) {
            try {
                // get the template data for rendering
                String templateText = getDataResourceText(dataResource, targetMimeTypeId, locale,
                        templateContext, delegator, cache);

                // if use web analytics.
                if (UtilValidate.isNotEmpty(webAnalytics)) {
                    StringBuffer newTemplateText = new StringBuffer(templateText);
                    String webAnalyticsCode = "<script language=\"JavaScript\" type=\"text/javascript\">";
                    for (GenericValue webAnalytic : webAnalytics) {
                        StringWrapper wrapString = StringUtil
                                .wrapString((String) webAnalytic.get("webAnalyticsCode"));
                        webAnalyticsCode += wrapString.toString();
                    }
                    webAnalyticsCode += "</script>";
                    newTemplateText.insert(templateText.lastIndexOf("</head>"), webAnalyticsCode);
                    templateText = newTemplateText.toString();
                }

                // render the FTL template
                boolean useTemplateCache = cache
                        && !UtilProperties.getPropertyAsBoolean("content", "disable.ftl.template.cache", false);
                Timestamp lastUpdatedStamp = dataResource.getTimestamp("lastUpdatedStamp");
                FreeMarkerWorker.renderTemplateFromString(
                        "delegator:" + delegator.getDelegatorName() + ":DataResource:" + dataResourceId,
                        templateText, templateContext, out, lastUpdatedStamp.getTime(), useTemplateCache);
            } catch (TemplateException e) {
                throw new GeneralException("Error rendering FTL template", e);
            }

        } else if ("XSLT".equals(dataTemplateTypeId)) {
            File sourceFileLocation = null;
            File targetFileLocation = new File(
                    System.getProperty("ofbiz.home") + "/runtime/tempfiles/docbook.css");
            if (templateContext.get("visualThemeId") != null) {
                Map<String, Object> layoutSettings = UtilGenerics
                        .checkMap(templateContext.get("layoutSettings"));
                List<String> docbookStyleSheets = UtilGenerics
                        .checkList(layoutSettings.get("VT_DOCBOOKSTYLESHEET"));
                String docbookStyleLocation = docbookStyleSheets.get(0);
                sourceFileLocation = new File(
                        System.getProperty("ofbiz.home") + "/themes" + docbookStyleLocation);
            }
            if (sourceFileLocation != null && sourceFileLocation.exists()) {
                UtilMisc.copyFile(sourceFileLocation, targetFileLocation);
            } else {
                String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME",
                        delegator);
                if (defaultVisualThemeId != null) {
                    GenericValue themeValue = EntityQuery.use(delegator).from("VisualThemeResource")
                            .where("visualThemeId", defaultVisualThemeId, "resourceTypeEnumId",
                                    "VT_DOCBOOKSTYLESHEET", "sequenceId", "01")
                            .cache().queryOne();
                    sourceFileLocation = new File(
                            System.getProperty("ofbiz.home") + "/themes" + themeValue.get("resourceValue"));
                    UtilMisc.copyFile(sourceFileLocation, targetFileLocation);
                }
            }
            // get the template data for rendering
            String templateLocation = DataResourceWorker
                    .getContentFile(dataResource.getString("dataResourceTypeId"),
                            dataResource.getString("objectInfo"), (String) templateContext.get("contextRoot"))
                    .toString();
            // render the XSLT template and file
            String outDoc = null;
            try {
                outDoc = XslTransform.renderTemplate(templateLocation, (String) templateContext.get("docFile"));
            } catch (TransformerException c) {
                Debug.logError("XSL TransformerException: " + c.getMessage(), module);
            }
            out.append(outDoc);

            // Screen Widget template
        } else if ("SCREEN_COMBINED".equals(dataTemplateTypeId)) {
            try {
                MapStack<String> context = MapStack.create(templateContext);
                context.put("locale", locale);
                // prepare the map for preRenderedContent
                String textData = (String) context.get("textData");
                if (UtilValidate.isNotEmpty(textData)) {
                    Map<String, Object> prc = new HashMap<String, Object>();
                    String mapKey = (String) context.get("mapKey");
                    if (mapKey != null) {
                        prc.put(mapKey, mapKey);
                    }
                    prc.put("body", textData); // used for default screen defs
                    context.put("preRenderedContent", prc);
                }
                // get the screen renderer; or create a new one
                ScreenRenderer screens = (ScreenRenderer) context.get("screens");
                if (screens == null) {
                    // TODO: replace "screen" to support dynamic rendering of different output
                    ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(
                            EntityUtilProperties.getPropertyValue("widget", "screen.name", delegator),
                            EntityUtilProperties.getPropertyValue("widget", "screen.screenrenderer",
                                    delegator));
                    screens = new ScreenRenderer(out, context, screenStringRenderer);
                    screens.getContext().put("screens", screens);
                }
                // render the screen
                ModelScreen modelScreen = null;
                ScreenStringRenderer renderer = screens.getScreenStringRenderer();
                String combinedName = dataResource.getString("objectInfo");
                if ("URL_RESOURCE".equals(dataResource.getString("dataResourceTypeId"))
                        && UtilValidate.isNotEmpty(combinedName) && combinedName.startsWith("component://")) {
                    modelScreen = ScreenFactory.getScreenFromLocation(combinedName);
                } else { // stored in  a single file, long or short text
                    Document screenXml = UtilXml.readXmlDocument(getDataResourceText(dataResource,
                            targetMimeTypeId, locale, templateContext, delegator, cache), true, true);
                    Map<String, ModelScreen> modelScreenMap = ScreenFactory.readScreenDocument(screenXml,
                            "DataResourceId: " + dataResource.getString("dataResourceId"));
                    if (UtilValidate.isNotEmpty(modelScreenMap)) {
                        Map.Entry<String, ModelScreen> entry = modelScreenMap.entrySet().iterator().next(); // get first entry, only one screen allowed per file
                        modelScreen = entry.getValue();
                    }
                }
                if (UtilValidate.isNotEmpty(modelScreen)) {
                    modelScreen.renderScreenString(out, context, renderer);
                } else {
                    throw new GeneralException(
                            "The dataResource file [" + dataResourceId + "] could not be found");
                }
            } catch (SAXException e) {
                throw new GeneralException("Error rendering Screen template", e);
            } catch (ParserConfigurationException e) {
                throw new GeneralException("Error rendering Screen template", e);
            } catch (TemplateException e) {
                throw new GeneralException("Error creating Screen renderer", e);
            }
        } else {
            throw new GeneralException(
                    "The dataTemplateTypeId [" + dataTemplateTypeId + "] is not yet supported");
        }
    }
}

From source file:com.npower.dm.processor.RegistryItem.java

/**
 * //from   w  w  w.ja  v a2  s .c  om
 * Return path of item.
 * Eg:
 *   ./a/b
 *   ./
 *   ./a
 *   ./a/${NodeName:bbbb}/c
 *   ./a/d/${NodeName}/c
 *   
 * @return
 */
private String getDDFPath() {
    RegistryItem parent = this.getParent();
    if (parent == null) {
        return this.getName();
    }

    StringBuffer result = new StringBuffer();
    if (StringUtils.isEmpty(this.getDdfNode().getName())) {
        // Dynamic Node
        if (StringUtils.isEmpty(this.getName())) {
            result.append("${NodeName}");
        } else {
            result.append("${NodeName:" + this.getName() + "}");
        }
    } else {
        // Static Node
        result.append(this.getName());
    }

    if (parent != null) {
        result.insert(0, '/');
        result.insert(0, parent.getDDFPath());
    }
    return result.toString();
}

From source file:com.sfs.whichdoctor.xml.event.PersonXmlEventImpl.java

/**
 * Gets the rotation event./*  w ww . j a v a2 s. c om*/
 *
 * @param rotation the rotation
 * @param preferences the preferences
 *
 * @return the rotation event
 */
private XmlEvent getRotationEvent(final RotationBean rotation, final PreferencesBean preferences) {

    XmlEvent event = new XmlEvent();
    event.setStartDate(rotation.getStartDate());
    event.setEndDate(rotation.getEndDate());
    event.setTitle(rotation.getRotationType() + ": " + rotation.getDescription());

    // Training details
    StringBuffer trgb = new StringBuffer();
    trgb.append(rotation.getTotalMonths());
    trgb.append(" months (");
    trgb.append(rotation.getTotalDays());
    trgb.append(" days @ ");
    trgb.append(Formatter.toPercent(rotation.getTrainingTime(), 0, "%"));
    trgb.append(" time)<br/>");

    // Build organisation description
    StringBuffer orgb = new StringBuffer();
    if (StringUtils.isNotBlank(rotation.getOrganisation1Name())) {
        orgb.append(rotation.getOrganisation1Name());
    }
    if (StringUtils.isNotBlank(rotation.getOrganisation2Name())) {
        if (orgb.length() > 0) {
            orgb.append(" and ");
        }
        orgb.append(rotation.getOrganisation2Name());
    }
    if (orgb.length() > 0) {
        orgb.insert(0, "Undertaken at ");
        orgb.append(".<br/>");
    }
    // Build supervisor description
    StringBuffer supb = new StringBuffer();
    if (rotation.getSupervisors() != null) {
        for (SupervisorBean supervisor : rotation.getSupervisors()) {
            if (supb.length() > 0) {
                supb.append(", ");
            }
            supb.append(OutputFormatter.toCasualName(supervisor.getPerson()));
        }
    }
    if (supb.length() > 0) {
        supb.insert(0, "Supervised by ");
        supb.append(".");
    }
    event.setDescription(trgb.toString() + orgb.toString() + supb.toString());
    event.setUrl(this.getRotationUrl(rotation.getGUID(), preferences));

    return event;
}

From source file:com.esofthead.mycollab.vaadin.ui.registry.AuditLogRegistry.java

public String generatorDetailChangeOfActivity(SimpleActivityStream activityStream) {
    if (activityStream.getAssoAuditLog() != null) {
        FieldGroupFormatter groupFormatter = auditPrinters.get(activityStream.getType());
        if (groupFormatter != null) {
            StringBuffer str = new StringBuffer("");
            boolean isAppended = false;
            List<AuditChangeItem> changeItems = activityStream.getAssoAuditLog().getChangeItems();
            if (CollectionUtils.isNotEmpty(changeItems)) {
                for (AuditChangeItem item : changeItems) {
                    String fieldName = item.getField();
                    DefaultFieldDisplayHandler fieldDisplayHandler = groupFormatter
                            .getFieldDisplayHandler(fieldName);
                    if (fieldDisplayHandler != null) {
                        isAppended = true;
                        str.append(fieldDisplayHandler.generateLogItem(item));
                    }//from  ww  w  .  j ava 2s. c  o m
                }

            }
            if (isAppended) {
                str.insert(0, "<p>").insert(0, "<ul>");
                str.append("</ul>").append("</p>");
            }
            return str.toString();
        }

    }
    return "";
}

From source file:com.meiah.core.util.StringUtil.java

/**
  * /*from  w w  w  .j  a  va 2 s . c  o  m*/
  * @description ?strSplit
  * @author zhangj
  * @date Jun 15, 2012
  */
 public static void insertEngKeyword(List<String> engKeyword, StringBuffer sb, String strSplit) {
     if (Validator.isNull(strSplit)) {
         strSplit = "\"";
     }
     int index = 0, i = 0, increase = 0, count = 1;
     int start = sb.indexOf(strSplit);
     while (index != -1) {
         index = sb.indexOf(strSplit, index + increase);
         if (index != -1) {
             if (count % 2 != 0) {
                 start = index;
                 if (engKeyword.size() > i) {
                     String keyword = engKeyword.get(i++);
                     increase = keyword.length();
                     sb.insert(start + 1, keyword);
                 }
             } else {
                 increase = 1;
             }
         }
         count++;
     }
 }

From source file:com.npower.dm.processor.ProfileAssignmentProcessor.java

/**
 * caculate the nodePath. If the node's name is null, will instead with Map of
 * this.nameMaps. The path will start with "./"
 * //from   ww w.  ja  v  a  2s .  c o  m
 * @return
 */
private String caculateNodePath(DDFNode node) {

    StringBuffer result = new StringBuffer();
    String name = node.getName();
    if (name == null) {
        name = this.generateNodeName(node);
    }
    result.append(name);
    DDFNode parent = node.getParentDDFNode();
    while (parent != null) {
        result.insert(0, "/");
        name = parent.getName();
        if (name == null) {
            if (this.nameMaps.containsKey(parent)) {
                name = this.nameMaps.get(parent);
            } else {
                throw new RuntimeException("Parent node haven't been specified name.");
            }
        }
        result.insert(0, name);
        parent = parent.getParentDDFNode();
    }
    String path = result.toString();
    if (!path.startsWith("./")) {
        return "./" + path;
    } else {
        return path;
    }
}