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.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 ava  2 s . c  o m
    if (templateContext == null) {
        templateContext = FastMap.newInstance();
    }
    if (UtilValidate.isEmpty(targetMimeTypeId)) {
        targetMimeTypeId = "text/html";
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }

    // check for a cached template
    if (cache) {
        String disableCache = EntityUtilProperties.getPropertyValue("content", "disable.ftl.template.cache",
                delegator);
        if (disableCache == null || !disableCache.equalsIgnoreCase("true")) {
            try {
                Template cachedTemplate = FreeMarkerWorker.getTemplate("DataResource:" + dataResourceId);
                if (cachedTemplate != null) {
                    String subContentId = (String) templateContext.get("subContentId");
                    if (UtilValidate.isNotEmpty(subContentId)) {
                        templateContext.put("contentId", subContentId);
                        templateContext.put("subContentId", null);
                        templateContext.put("globalNodeTrail", null); // Force getCurrentContent to query for subContent
                    }
                    FreeMarkerWorker.renderTemplate(cachedTemplate, templateContext, out);
                }
            } catch (TemplateException e) {
                Debug.logError("Error rendering FTL template. " + e.getMessage(), module);
                throw new GeneralException("Error rendering FTL template", e);
            }
            return;
        }
    }

    // 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, true);
    } 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
                FreeMarkerWorker.renderTemplate("DataResource:" + dataResourceId, templateText, templateContext,
                        out);
            } 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 = FastMap.newInstance();
                    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.cloud.bridge.util.RestAuth.java

/**
 * Used as part of the CanonalizedResource element of the StringToSign.
 * CanonicalizedResource = [ "/" + Bucket ] +
 * <HTTP-Request-URI, from the protocol name up to the query string> + [sub-resource]
 * The list of sub-resources that must be included when constructing the CanonicalizedResource Element are: acl, lifecycle, location, 
 * logging, notification, partNumber, policy, requestPayment, torrent, uploadId, uploads, versionId, versioning, versions and website.
 * (http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAuthentication.html)
 * @param query - results from calling "HttpServletRequest req.getQueryString()"
 *//*  ww w  .j a va  2 s.  c o m*/
public void setQueryString(String query) {
    if (null == query) {
        this.queryString = null;
        return;
    }

    // Sub-resources (i.e.: query params) must be lex sorted
    Set<String> subResources = new TreeSet<String>();

    String[] queryParams = query.split("&");
    StringBuffer builtQuery = new StringBuffer();
    for (String queryParam : queryParams) {
        // lookup parameter name
        String paramName = queryParam.split("=")[0];
        if (allowedQueryParams.contains(paramName)) {
            subResources.add(queryParam);
        }
    }
    for (String subResource : subResources) {
        builtQuery.append(subResource + "&");
    }
    // If anything inside the string buffer, add a "?" at the beginning, 
    // and then remove the last '&'
    if (builtQuery.length() > 0) {
        builtQuery.insert(0, "?");
        builtQuery.deleteCharAt(builtQuery.length() - 1);
    }
    this.queryString = builtQuery.toString();
}

From source file:com.googlecode.fascinator.indexer.SolrWrapperQueueConsumer.java

/**
 * Submit all documents currently in the buffer to Solr, then purge
 * //from   w  ww .j ava  2 s . c  o  m
 */
private void submitBuffer(boolean forceCommit) {
    int size = docBuffer.size();
    if (size > 0) {
        // Debugging
        // String age = String.valueOf(
        // ((new Date().getTime()) - bufferOldest) / 1000);
        // String length = String.valueOf(bufferSize);
        // log.debug("Submitting buffer: " + size + " documents, " + length
        // +
        // " bytes, " + age + "s");
        log.debug("=== Submitting buffer: " + size + " documents");

        // Concatenate all documents in the buffer
        StringBuffer submissionBuffer = new StringBuffer();
        for (String doc : docBuffer.keySet()) {
            submissionBuffer.append(docBuffer.get(doc));
            // log.debug("DOC: {}", doc);
        }

        // Submit if the result is valid
        if (submissionBuffer.length() > 0) {
            // Wrap in the basic Solr 'add' node
            String submission = submissionBuffer.insert(0, "<add>").append("</add>").toString();
            // And submit
            try {
                solr.request(new DirectXmlRequest("/update", submission));
            } catch (Exception ex) {
                log.error("Error submitting documents to Solr!", ex);
            }
            // Commit if required
            if (autoCommit || forceCommit) {
                log.info("Running forced commit!");
                try {
                    // HTTP commits for embedded
                    if (commit != null) {
                        solr.commit();
                        commit.commit();
                        // or just HTTP on it's own
                    } else {
                        solr.commit();
                    }
                } catch (Exception e) {
                    log.warn("Solr forced commit failed. Document will"
                            + " not be visible until Solr autocommit fires." + " Error message: {}", e);
                }
            }
        }
    }
    purgeBuffer();
}

From source file:org.agnitas.web.ExportWizardAction.java

/**
 * Separates special characters from input string.
 * @param input   input string/*from   w  w  w. ja  v  a2 s .co  m*/
 * @param sepChar separation string
 * @return input string with separations
 */
protected String escapeChars(String input, String sepChar) {
    int pos = 0;
    StringBuffer tmp = new StringBuffer(input);
    while ((pos = input.indexOf(sepChar, pos)) != -1) {
        tmp = new StringBuffer(input);
        tmp.insert(pos, sepChar);
        pos += sepChar.length() + 1;
        input = tmp.toString();
    }
    return input;
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Construct the XPath of the supplied DOM Node.
 * <p/>/*from   www  . j  a v  a 2  s  .com*/
 * 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) {
    AssertArgument.isNotNull(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.jboss.dashboard.commons.text.StringUtil.java

/**
 * Converts the given string to a Java valid identifier.
 *
 * @param str string to process/*from   w  ww. j  av  a2s.c om*/
 * @return A java based identifier.
 */
public static String toJavaIdentifier(String str) {
    if (str == null || str.trim().equals(""))
        return null;
    StringBuffer buf = new StringBuffer(str);
    int bufIdx = 0;
    while (bufIdx < buf.length()) {
        char c = buf.charAt(bufIdx);

        // Replace tilded by non-tilded chars.
        int tilded = TILDED_CHARS.indexOf(c);
        if (tilded != -1 && tilded < NON_TILDED_CHARS.length()) {
            buf.deleteCharAt(bufIdx);
            c = NON_TILDED_CHARS.charAt(tilded);
            buf.insert(bufIdx++, c);
            continue;
        }
        // Discard special chars and non-valid java identifiers.
        int special = SPECIAL_CHARS.indexOf(c);
        if (special != -1 || !Character.isJavaIdentifierPart(c)) {
            buf.deleteCharAt(bufIdx);
            continue;
        }
        // Adjust buffer index.
        bufIdx++;
    }
    if (buf.length() == 0)
        return "";
    while (buf.length() > 0 && !Character.isJavaIdentifierStart(buf.charAt(0)))
        buf.deleteCharAt(0);

    // Avoid reserved java keywords.
    String javaId = buf.toString();
    if (isJavaKeyword(javaId)) {
        if (javaId.equals("class"))
            javaId = "clazz";
        else
            javaId = '_' + javaId;
    }
    return javaId;
}

From source file:org.jboss.dashboard.ui.config.components.sections.SectionsPropertiesHandler.java

protected String getSectionIds(Section section) throws Exception {
    StringBuffer sb = new StringBuffer();
    while (section != null) {
        sb.insert(0, section.getId());
        section = section.getParent();//from w w  w.  jav a 2s .co m
        if (section != null) {
            sb.insert(0, "/");
        }
    }
    return sb.toString();
}

From source file:ldap.UserAccountImpl.java

public String toString() {
    StringBuffer buffer = new StringBuffer();
    String name = null;/*from   w w  w .  j  a  va  2 s  .  c  om*/
    try {
        NamingEnumeration attList = getAll();
        while (attList.hasMore()) {
            Attribute att = (Attribute) attList.next();
            //if (att.getID().equals(Config.USER_NAMING_ATT))
            if (att.getID().equals(LdapConstants.ldapAttrUid))
                name = att.get().toString() + "\n";

            buffer.append("    ").append(att.getID()).append(": ");

            if (att.size() == 1)
                buffer.append(att.get().toString()).append("\n");
            else {
                NamingEnumeration values = att.getAll();
                buffer.append("\n");
                while (values.hasMore())
                    buffer.append("        ").append(values.next()).append("\n");
            }
        }
        if (name != null)
            buffer.insert(0, name);
    } catch (NamingException e) {
        return "Unexpected Internal Error dumping UserAccount to text.\nError was: " + e.getMessage();
    }
    return buffer.toString();
}

From source file:edu.harvard.i2b2.analysis.security.HighEncryption.java

private String ConvertDecToBaseNClear(UInt64 dValue, long byBase) throws Exception {
    String BaseNums = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    //String sResult = "";
    StringBuffer sResult = new StringBuffer();
    UInt64 dRemainder;//ww w .  j a va  2  s  .c o  m

    //sResult = "";

    if ((byBase >= 2) && (byBase <= 36)) {
        while (dValue.compareTo(0) > 0) // x > 0 
        {
            dRemainder = dValue.divideAndRemainder(byBase);
            //sResult = BaseNums.substring(dRemainder.intValue(), dRemainder.intValue()+1) + sResult;
            sResult.insert(0, BaseNums.substring(dRemainder.intValue(), dRemainder.intValue() + 1));
        }
        return sResult.toString();
    } else {
        throw new Exception("Base should be between 2 and 36.");
    }
}

From source file:edu.harvard.i2b2.im.util.HighEncryption.java

private String ConvertDecToBaseNClear(UInt64 dValue, long byBase) throws Exception {
    String BaseNums = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    // String sResult = "";
    StringBuffer sResult = new StringBuffer();
    UInt64 dRemainder;/*ww  w  .jav a2s  .  c o  m*/

    // sResult = "";

    if ((byBase >= 2) && (byBase <= 36)) {
        while (dValue.compareTo(0) > 0) // x > 0
        {
            dRemainder = dValue.divideAndRemainder(byBase);
            // sResult = BaseNums.substring(dRemainder.intValue(),
            // dRemainder.intValue()+1) + sResult;
            sResult.insert(0, BaseNums.substring(dRemainder.intValue(), dRemainder.intValue() + 1));
        }
        return sResult.toString();
    } else {
        throw new Exception("Base should be between 2 and 36.");
    }
}