Example usage for java.lang StringBuffer indexOf

List of usage examples for java.lang StringBuffer indexOf

Introduction

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

Prototype

@Override
public synchronized int indexOf(String str, int fromIndex) 

Source Link

Usage

From source file:com.openedit.BaseWebPageRequest.java

public String getSiteRoot() {
    String site = (String) getPageValue("siteRoot");
    if (site == null) {
        site = getContentProperty("siteRoot");
    }//from  w w  w .j  av a 2 s .c om
    if (site == null && getRequest() != null) {
        StringBuffer ctx = getRequest().getRequestURL();
        site = ctx.substring(0, ctx.indexOf("/", 8)); //8 comes from https://
    } else if (site == null) {
        site = getRequestParameter("siteRoot");
    }
    return site;
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java

protected void embedOutput(MimeMessageHelper messageHelper, ReportOutput output)
        throws MessagingException, JobExecutionException {
    /***/*from   w  w w  .  j a  v a 2 s .com*/
     try {
     BufferedReader in = new BufferedReader(new FileReader("C:/Users/ichan/Desktop/employee.html"));
     StringBuffer strBuffer = new StringBuffer();
     String strLine;
     while ((strLine = in.readLine()) != null) {
     strBuffer = strBuffer.append(strLine + "\n");
     }
     content = strBuffer.toString();
     } catch (Exception ex) {
     ex.printStackTrace();
     }
     System.out.println("CONTENT = " + content);
     ****/

    // modify content to use inline images
    StringBuffer primaryPage = new StringBuffer(new String(output.getData().getData()));
    for (Iterator it = output.getChildren().iterator(); it.hasNext();) {
        ReportOutput child = (ReportOutput) it.next();
        String childName = child.getFilename();

        // NOTE:  add the ".dat" extension to all image resources
        // email client will automatically append ".dat" extension to all the files with no extension
        // should do it in JasperReport side
        if (output.getFileType().equals(ContentResource.TYPE_HTML)) {
            if (primaryPage == null)
                primaryPage = new StringBuffer(new String(output.getData().getData()));
            int fromIndex = 0;
            while ((fromIndex = primaryPage.indexOf("src=\"" + childName + "\"", fromIndex)) > 0) {
                primaryPage.insert(fromIndex + 5, "cid:");
            }
        }
    }

    messageHelper.setText(primaryPage.toString(), true);
    // add inline images after setting the text in the main body
    for (Iterator it = output.getChildren().iterator(); it.hasNext();) {
        ReportOutput child = (ReportOutput) it.next();
        String childName = child.getFilename();
        DataContainerResource dataContainerResource = new DataContainerResource(child.getData());
        dataContainerResource.setFilename(childName);
        messageHelper.addInline(childName, dataContainerResource);

    }
}

From source file:org.janusgraph.graphdb.database.IndexSerializer.java

public Iterable<RawQuery.Result> executeQuery(IndexQueryBuilder query, final ElementCategory resultType,
        final BackendTransaction backendTx, final StandardJanusGraphTx transaction) {
    MixedIndexType index = getMixedIndex(query.getIndex(), transaction);
    Preconditions.checkArgument(index.getElement() == resultType,
            "Index is not configured for the desired result type: %s", resultType);
    String backingIndexName = index.getBackingIndexName();
    IndexProvider indexInformation = (IndexProvider) mixedIndexes.get(backingIndexName);

    StringBuffer qB = new StringBuffer(query.getQuery());
    final String prefix = query.getPrefix();
    Preconditions.checkNotNull(prefix);//  w  w w . j  a va2s  .  c om
    //Convert query string by replacing
    int replacements = 0;
    int pos = 0;
    while (pos < qB.length()) {
        pos = qB.indexOf(prefix, pos);
        if (pos < 0)
            break;

        int startPos = pos;
        pos += prefix.length();
        StringBuilder keyBuilder = new StringBuilder();
        boolean quoteTerminated = qB.charAt(pos) == '"';
        if (quoteTerminated)
            pos++;
        while (pos < qB.length() && (Character.isLetterOrDigit(qB.charAt(pos))
                || (quoteTerminated && qB.charAt(pos) != '"') || qB.charAt(pos) == '*')) {
            keyBuilder.append(qB.charAt(pos));
            pos++;
        }
        if (quoteTerminated)
            pos++;
        int endPos = pos;
        String keyname = keyBuilder.toString();
        Preconditions.checkArgument(StringUtils.isNotBlank(keyname),
                "Found reference to empty key at position [%s]", startPos);
        String replacement;
        if (keyname.equals("*")) {
            replacement = indexInformation.getFeatures().getWildcardField();
        } else if (transaction.containsRelationType(keyname)) {
            PropertyKey key = transaction.getPropertyKey(keyname);
            Preconditions.checkNotNull(key);
            Preconditions.checkArgument(index.indexesKey(key),
                    "The used key [%s] is not indexed in the targeted index [%s]", key.name(),
                    query.getIndex());
            replacement = key2Field(index, key);
        } else {
            Preconditions.checkArgument(query.getUnknownKeyName() != null,
                    "Found reference to non-existant property key in query at position [%s]: %s", startPos,
                    keyname);
            replacement = query.getUnknownKeyName();
        }
        Preconditions.checkArgument(StringUtils.isNotBlank(replacement));

        qB.replace(startPos, endPos, replacement);
        pos = startPos + replacement.length();
        replacements++;
    }

    String queryStr = qB.toString();
    if (replacements <= 0)
        log.warn("Could not convert given {} index query: [{}]", resultType, query.getQuery());
    log.info("Converted query string with {} replacements: [{}] => [{}]", replacements, query.getQuery(),
            queryStr);
    RawQuery rawQuery = new RawQuery(index.getStoreName(), queryStr, query.getParameters());
    if (query.hasLimit())
        rawQuery.setLimit(query.getLimit());
    rawQuery.setOffset(query.getOffset());
    return Iterables.transform(backendTx.rawQuery(index.getBackingIndexName(), rawQuery),
            new Function<RawQuery.Result<String>, RawQuery.Result>() {
                @Nullable
                @Override
                public RawQuery.Result apply(@Nullable RawQuery.Result<String> result) {
                    return new RawQuery.Result(string2ElementId(result.getResult()), result.getScore());
                }
            });
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java

protected void attachOutput(ReportExecutionJob job, MimeMessageHelper messageHelper, ReportOutput output,
        boolean useZipFormat) throws MessagingException, JobExecutionException {
    String attachmentName;/*  www  .  ja  v a2 s .co m*/
    DataContainer attachmentData;
    if (output.getChildren().isEmpty()) {
        attachmentName = output.getFilename();
        attachmentData = output.getData();
    } else if (useZipFormat) { // use zip format
        attachmentData = job.createDataContainer();
        boolean close = true;
        ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream());
        try {
            zipOutput(job, output, zipOut);
            zipOut.finish();
            zipOut.flush();
            close = false;
            zipOut.close();
        } catch (IOException e) {
            throw new JSExceptionWrapper(e);
        } finally {
            if (close) {
                try {
                    zipOut.close();
                } catch (IOException e) {
                    log.error("Error closing stream", e);
                }
            }
        }

        attachmentName = output.getFilename() + ".zip";
    } else { // NO ZIP FORMAT
        attachmentName = output.getFilename();
        try {
            attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null);
        } catch (UnsupportedEncodingException e) {
            throw new JSExceptionWrapper(e);
        }
        StringBuffer primaryPage = null;
        for (Iterator it = output.getChildren().iterator(); it.hasNext();) {
            ReportOutput child = (ReportOutput) it.next();
            String childName = child.getFilename();

            // NOTE:  add the ".dat" extension to all image resources
            // email client will automatically append ".dat" extension to all the files with no extension
            // should do it in JasperReport side
            if (output.getFileType().equals(ContentResource.TYPE_HTML)) {
                if (primaryPage == null)
                    primaryPage = new StringBuffer(new String(output.getData().getData()));
                int fromIndex = 0;
                while ((fromIndex = primaryPage.indexOf("src=\"" + childName + "\"", fromIndex)) > 0) {
                    primaryPage.insert(fromIndex + 5 + childName.length(), ".dat");
                }
                childName = childName + ".dat";
            }

            try {
                childName = MimeUtility.encodeWord(childName, job.getCharacterEncoding(), null);
            } catch (UnsupportedEncodingException e) {
                throw new JSExceptionWrapper(e);
            }
            messageHelper.addAttachment(childName, new DataContainerResource(child.getData()));
        }
        if (primaryPage == null) {
            messageHelper.addAttachment(attachmentName, new DataContainerResource(output.getData()));
        } else {
            messageHelper.addAttachment(attachmentName,
                    new DataContainerResource(new MemoryDataContainer(primaryPage.toString().getBytes())));
        }
        return;
    }
    try {
        attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null);
    } catch (UnsupportedEncodingException e) {
        throw new JSExceptionWrapper(e);
    }
    messageHelper.addAttachment(attachmentName, new DataContainerResource(attachmentData));
}

From source file:architecture.common.util.TextUtils.java

private final static void linkEmail(StringBuffer str) {
    int lastEndIndex = -1; // Store the index position of the end char of
    // last email address found...

    main: while (true) {
        // get index of '@'...
        int atIndex = str.indexOf("@", lastEndIndex + 1);

        if (atIndex == -1) {
            break;
        } else {//from   ww w . j a va2 s . c om
            // Get the whole email address...
            // Get the part before '@' by moving backwards and taking each
            // character
            // until we encounter an invalid URL char...
            String partBeforeAt = "";
            int linkStartIndex = atIndex;
            boolean reachedStart = false;

            while (!reachedStart) {
                linkStartIndex--;

                if (linkStartIndex < 0) {
                    reachedStart = true;
                } else {
                    char c = str.charAt(linkStartIndex);

                    // if we find these chars in an email, then it's part of
                    // a url, so lets leave it alone
                    // Are there any other chars we should abort email
                    // checking for??
                    if ((c == '?') || (c == '&') || (c == '=') || (c == '/') || (c == '%')) {
                        lastEndIndex = atIndex + 1;

                        continue main;
                    }

                    if (isValidEmailChar(c)) {
                        partBeforeAt = c + partBeforeAt;
                    } else {
                        reachedStart = true;
                    }
                }
            }

            // Increment linkStartIndex back by 1 to reflect the real
            // starting index of the
            // email address...
            linkStartIndex++;

            // Get the part after '@' by doing pretty much the same except
            // moving
            // forward instead of backwards.
            String partAfterAt = "";
            int linkEndIndex = atIndex;
            boolean reachedEnd = false;

            while (!reachedEnd) {
                linkEndIndex++;

                if (linkEndIndex == str.length()) {
                    reachedEnd = true;
                } else {
                    char c = str.charAt(linkEndIndex);

                    if (isValidEmailChar(c)) {
                        partAfterAt += c;
                    } else {
                        reachedEnd = true;
                    }
                }
            }

            // Decrement linkEndIndex back by 1 to reflect the real ending
            // index of the
            // email address...
            linkEndIndex--;

            // Reassemble the whole email address...
            String emailStr = partBeforeAt + '@' + partAfterAt;

            // If the last chars of emailStr is a '.', ':', '-', '/' or '~'
            // then we exclude those chars.
            // The '.' at the end could be just a fullstop to a sentence and
            // we don't want
            // that to be part of an email address (which would then be
            // invalid).
            // Pretty much the same for the other symbols - we don't want
            // them at the end of any email
            // address cos' this would stuff the address up.
            while (true) {
                char lastChar = emailStr.charAt(emailStr.length() - 1);

                if ((lastChar == '.') || (lastChar == ':') || (lastChar == '-') || (lastChar == '/')
                        || (lastChar == '~')) {
                    emailStr = emailStr.substring(0, emailStr.length() - 1);
                    linkEndIndex--;
                } else {
                    break;
                }
            }

            // Verify if email is valid...
            if (verifyEmail(emailStr)) {
                // Construct the hyperlink for the email address...
                String emailLink = "<a href='mailto:" + emailStr + "'>" + emailStr + "</a>";

                // Take the part of the str before the email address, the
                // part after, and add
                // the emailLink between those two parts, so that in effect
                // the original email
                // address is replaced by a hyperlink to it...
                str.replace(linkStartIndex, linkEndIndex + 1, emailLink);

                // Set lastEndIndex to reflect the position of the end of
                // emailLink
                // within the whole string...
                lastEndIndex = (linkStartIndex - 1) + emailLink.length();
            } else {
                // lastEndIndex is different from the one above cos' there's
                // no
                // <a href...> tags added...
                lastEndIndex = (linkStartIndex - 1) + emailStr.length();
            }
        }
    }
}

From source file:org.agnitas.beans.impl.MailingImpl.java

/**
 * Scans a textblock for trackable links and replaces them with encoded
 * rdir-links.//from   w w  w  . j a  v a 2s  .  c  o  m
 */
public String insertTrackableLinks(String aText1, int customerID, ApplicationContext con) {
    if (this.trackableLinks == null) {
        return aText1;
    }

    /*
     * trackableLinks is an unordered HashMap. When there are 2 links in the
     * Map, where one is part of the other, this could lead to an link
     * replacement, depending on the map ordering.
     * 
     * Link 1: http://www.mydomain.de Link 2:
     * http://www.mydomain.de/path/index.htm
     * 
     * If Link 1 is returned before Link 2 from the iterator this resulted
     * in: http://rdir.de/r.html?uid=<uid of Link1>/path/index.htm
     */
    Comparator<String> reverseString = new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o2.compareTo(o1);
        }
    };

    Set<String> sorted = new TreeSet<String>(reverseString);
    sorted.addAll(this.trackableLinks.keySet());

    Iterator<String> i = sorted.iterator();
    String aLink = null;
    int start_link = 0;
    int end_link = 0;
    TrackableLink aLinkObj = null;
    StringBuffer aBuf = new StringBuffer(aText1);
    boolean isHref = false;

    if (aText1 == null) {
        return null;
    }

    while (i.hasNext()) {
        aLink = i.next();
        end_link = 0;
        while ((start_link = aBuf.indexOf(aLink, end_link)) != -1) {
            end_link = start_link + 1;
            isHref = false;
            if (start_link > 5 && (aBuf.substring(start_link - 6, start_link).equalsIgnoreCase("href=\""))) {
                isHref = true;
            }
            if (start_link > 6 && (aBuf.substring(start_link - 7, start_link).equalsIgnoreCase("href=\""))) {
                isHref = true;
            }
            if (aBuf.length() > (start_link + aLink.length())) {
                if (!(aBuf.charAt(start_link + aLink.length()) == ' '
                        || aBuf.charAt(start_link + aLink.length()) == '\''
                        || aBuf.charAt(start_link + aLink.length()) == '"')) {
                    isHref = false;
                }
            }
            if (isHref) {
                aLinkObj = (TrackableLink) this.trackableLinks.get(aLink);
                aBuf.replace(start_link, start_link + aLink.length(),
                        aLinkObj.encodeTagStringLinkTracking(con, customerID));
            }
        }
    }
    return aBuf.toString();
}

From source file:org.talend.designer.runprocess.java.JavaProcessor.java

/**
 * DOC chuang Comment method "computeMethodSizeIfNeeded".
 * /*from ww w  . jav a 2  s.  c om*/
 * @param processCode
 * @return
 */
private String computeMethodSizeIfNeeded(String processCode) {
    // must match TalendDesignerPrefConstants.DISPLAY_METHOD_SIZE
    boolean displayMethodSize = Boolean.parseBoolean(
            CorePlugin.getDefault().getDesignerCoreService().getPreferenceStore("displayMethodSize")); //$NON-NLS-1$
    if (displayMethodSize) {
        StringBuffer code = new StringBuffer(processCode);
        int fromIndex = 0;
        while (fromIndex != -1 && fromIndex < code.length()) {
            int methodStartPos = code.indexOf(METHOD_START_COMMENT, fromIndex);
            if (methodStartPos < 0) {
                break;
            }
            int sizeCommentPos = code.indexOf(SIZE_COMMENT, fromIndex);

            // move ahead to the start position of source code
            methodStartPos = code.indexOf("*/", sizeCommentPos) + 2; //$NON-NLS-1$

            int methodEndPos = code.indexOf(METHOD_END_COMMENT, fromIndex);
            if (methodEndPos < 0) {
                break;
            }
            // start position for next search
            fromIndex = methodEndPos + METHOD_END_COMMENT.length();
            // go back to the end position of source code
            methodEndPos = code.lastIndexOf("/*", methodEndPos); //$NON-NLS-1$
            int size = methodEndPos - methodStartPos;
            code.replace(sizeCommentPos, sizeCommentPos + SIZE_COMMENT.length(), String.valueOf(size));

        }
        return code.toString();
    } else {
        return processCode;
    }
}

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

/**
 * rectify content to adapt its parent's structure
 * @param content/*from www  .  j a  va2 s  . co  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:info.magnolia.cms.beans.config.PropertiesInitializer.java

/**
 * Parse the given String value recursively, to be able to resolve nested placeholders. Partly borrowed from
 * org.springframework.beans.factory.config.PropertyPlaceholderConfigurer (original author: Juergen Hoeller)
 *
 * @deprecated since 4.5 this is now done by {@link info.magnolia.init.AbstractMagnoliaConfigurationProperties#parseStringValue}.
 *///  w ww  . j  a  va2  s.c  o  m
protected String parseStringValue(String strVal, Set<String> visitedPlaceholders) {

    StringBuffer buf = new StringBuffer(strVal);

    int startIndex = strVal.indexOf(PLACEHOLDER_PREFIX);
    while (startIndex != -1) {
        int endIndex = -1;

        int index = startIndex + PLACEHOLDER_PREFIX.length();
        int withinNestedPlaceholder = 0;
        while (index < buf.length()) {
            if (PLACEHOLDER_SUFFIX.equals(buf.subSequence(index, index + PLACEHOLDER_SUFFIX.length()))) {
                if (withinNestedPlaceholder > 0) {
                    withinNestedPlaceholder--;
                    index = index + PLACEHOLDER_SUFFIX.length();
                } else {
                    endIndex = index;
                    break;
                }
            } else if (PLACEHOLDER_PREFIX.equals(buf.subSequence(index, index + PLACEHOLDER_PREFIX.length()))) {
                withinNestedPlaceholder++;
                index = index + PLACEHOLDER_PREFIX.length();
            } else {
                index++;
            }
        }

        if (endIndex != -1) {
            String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex);
            if (!visitedPlaceholders.add(placeholder)) {

                log.warn("Circular reference detected in properties, \"{}\" is not resolvable", strVal);
                return strVal;
            }
            // Recursive invocation, parsing placeholders contained in the placeholder key.
            placeholder = parseStringValue(placeholder, visitedPlaceholders);
            // Now obtain the value for the fully resolved key...
            String propVal = SystemProperty.getProperty(placeholder);
            if (propVal != null) {
                // Recursive invocation, parsing placeholders contained in the
                // previously resolved placeholder value.
                propVal = parseStringValue(propVal, visitedPlaceholders);
                buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal);
                startIndex = buf.indexOf(PLACEHOLDER_PREFIX, startIndex + propVal.length());
            } else {
                // Proceed with unprocessed value.
                startIndex = buf.indexOf(PLACEHOLDER_PREFIX, endIndex + PLACEHOLDER_SUFFIX.length());
            }
            visitedPlaceholders.remove(placeholder);
        } else {
            startIndex = -1;
        }
    }

    return buf.toString();
}

From source file:org.bibsonomy.scraper.url.kde.acm.ACMBasicScraper.java

@Override
protected boolean scrapeInternal(ScrapingContext sc) throws ScrapingException {
    sc.setScraper(this);

    try {/*  www.  j  av a2 s. c  om*/
        /*
         * extract the id from the URL
         */
        final Matcher matcher = URL_PARAM_ID_PATTERN.matcher(sc.getUrl().getQuery());
        if (matcher.find()) {
            String id = matcher.group(1);
            /*
             * If the id contains a dot ".", we use the part after the dot.
             * TODO: Can we do this nicer? 
             */
            final int indexOfDot = id.indexOf(".");
            if (indexOfDot > -1) {
                id = id.substring(indexOfDot + 1);
            }
            /*
             * Scrape entries from popup BibTeX site. BibTeX entry on these
             * pages looks like this: <PRE id="155273">@article{155273,
             * author = {The Author}, title = {This is the title}...}</pre>
             */
            final StringBuffer bibtexEntries = extractBibtexEntries(SITE_URL,
                    "exportformats.cfm?expformat=bibtex&id=" + id);

            /*
             * download the abstract
             * FIXME: 
             * 
             * IDs with a "dot" (e.g., 1082036.1082037 seem to have no abstract:
             * 
             * http://portal.acm.org/tab_abstract.cfm?id=1082036.1082037&usebody=tabbody
             * 
             * We must use only the part after the dot to get it:
             * 
             * http://portal.acm.org/tab_abstract.cfm?id=1082037&usebody=tabbody
             * 
             * This must be done!
             * 
             */
            final String abstrct = WebUtils
                    .getContentAsString(SITE_URL + "/tab_abstract.cfm?usebody=tabbody&id=" + id);
            if (present(abstrct)) {
                /*
                 * extract abstract from HTML
                 */
                final Matcher matcher2 = ABSTRACT_PATTERN.matcher(abstrct);
                if (matcher2.find()) {
                    /*
                     * FIXME: we don't get here for URL 
                     * 
                     * http://doi.acm.org/10.1145/1105664.1105676
                     *  
                     * Thus, the pattern fails for that abstract at
                     * 
                     * http://portal.acm.org/tab_abstract.cfm?id=1105676&usebody=tabbody
                     */
                    final String extractedAbstract = matcher2.group(2);
                    BibTexUtils.addFieldIfNotContained(bibtexEntries, "abstract", extractedAbstract);

                } else {
                    // log if abstract is not available
                    log.info("ACMBasicScraper: Abstract not available");
                }
            } else {
                // log if abstract is not available
                log.info("ACMBasicScraper: Abstract not available");
            }

            /*
             * Some entries (e.g., http://portal.acm.org/citation.cfm?id=500737.500755) seem
             * to have broken BibTeX entries with a "," too much at the end. We remove this
             * here.
             *
             * Some entries have the following end: "},\n} \n" instead of the BROKEN_END String.
             * So we have to adjust the starting index by the additional 2 symbols.
             */
            final int indexOf = bibtexEntries.indexOf(BROKEN_END,
                    bibtexEntries.length() - BROKEN_END.length() - 2);
            if (indexOf > 0) {
                bibtexEntries.replace(indexOf, bibtexEntries.length(), "}\n}");
            }

            final String result = DOIUtils.cleanDOI(bibtexEntries.toString().trim());
            //final String result = bibtexEntries.toString().trim();

            if (!"".equals(result)) {
                sc.setBibtexResult(result);
                return true;
            } else
                throw new ScrapingFailureException("getting bibtex failed");
        }
        return false;

    } catch (Exception e) {
        throw new InternalFailureException(e);
    }
}