Example usage for java.lang StringBuffer delete

List of usage examples for java.lang StringBuffer delete

Introduction

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

Prototype

@Override
public synchronized StringBuffer delete(int start, int end) 

Source Link

Usage

From source file:org.openlaszlo.servlets.responders.ResponderCompile.java

/**
 * @return File name for temporary LZX file that is the
 *         result of this http pre-processing; null for a bad request
 * @param req request/*  w w w  . java 2  s .  c  om*/
 * @param fileName file name associated with request
 */
private String doPreProcessing(HttpServletRequest req, String fileName) throws IOException {
    // Do an http request for this and see what we get back.
    //
    StringBuffer s = req.getRequestURL();
    int len = s.length();
    // Remove the .lzx from the end of the URL
    if (len <= 4) {
        return null;
    }
    s.delete(len - 4, len);

    // FIXME [2002-12-15 bloch] does any/all of this need to be synchronized on session?

    // First get the temporary file name for this session
    HttpSession session = req.getSession();
    String sid = session.getId();
    String tempFileName = getTempFileName(fileName, sid);
    File tempFile = new File(tempFileName);

    tempFile.deleteOnExit();

    // Now pre-process the request and copy the data to
    // the temporary file that is unique to this session

    // FIXME: query string processing

    String surl = s.toString();

    URL url = new URL(surl);
    mLogger.debug(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="Preprocessing request at " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(ResponderCompile.class.getName(), "051018-263",
                    new Object[] { surl }));
    GetMethod getRequest = new LZGetMethod();
    getRequest.setPath(url.getPath());
    //getRequest.setQueryString(url.getQuery());
    getRequest.setQueryString(req.getQueryString());

    // Copy headers to request
    LZHttpUtils.proxyRequestHeaders(req, getRequest);
    // Mention the last modified time, if the file exists
    if (tempFile.exists()) {
        long lastModified = tempFile.lastModified();
        getRequest.addRequestHeader("If-Modified-Since", LZHttpUtils.getDateString(lastModified));
    } else {
        // Otherwise, create a listener that will clean up the tempfile
        // Note: web server administrators must make sure that their servers are killed
        // gracefully or temporary files will not be handled by the LZBindingListener.
        // Add a binding listener for this session that
        // will remove our temporary files
        LZBindingListener listener = (LZBindingListener) session.getAttribute("tmpl");
        if (listener == null) {
            listener = new LZBindingListener(tempFileName);
            session.setAttribute("tmpl", listener);
        } else {
            listener.addTempFile(tempFileName);
        }
    }

    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(url.getHost(), url.getPort(), url.getProtocol());

    HttpClient htc = new HttpClient();
    htc.setHostConfiguration(hostConfig);

    int rc = htc.executeMethod(getRequest);
    mLogger.debug("Response Status: " + rc);
    if (rc >= 400) {
        // respondWithError(req, res, "HTTP Status code: " + rc + " for url " + surl, rc);
        return null;
    }
    if (rc != HttpServletResponse.SC_NOT_MODIFIED) {
        FileOutputStream output = new FileOutputStream(tempFile);
        try {
            // FIXME:[2002-12-17 bloch] verify that the response body is XML
            FileUtils.sendToStream(getRequest.getResponseBodyAsStream(), output);
            // TODO: [2002-12-15 bloch] What to do with response headers?
        } catch (FileUtils.StreamWritingException e) {
            mLogger.warn(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="StreamWritingException while sending error: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(ResponderCompile.class.getName(),
                            "051018-313", new Object[] { e.getMessage() }));
        } finally {
            FileUtils.close(output);
        }
    }

    return tempFileName;
}

From source file:org.hyperic.hq.product.RtPlugin.java

private void transformUrl(RtStat rs, String transforms) {
    if (transforms == null || transforms.equals("")) {
        return;//ww w  . ja  v  a 2  s  . c  o m
    }

    ArrayList patterns = new ArrayList();
    ArrayList subs = new ArrayList();
    getTransforms(transforms, patterns, subs);

    PatternMatcher matcher = new Perl5Matcher();
    Pattern pattern = null;
    PatternCompiler compiler = new Perl5Compiler();
    StringBuffer sb = new StringBuffer();

    for (Iterator p = patterns.iterator(), s = subs.iterator(); (p.hasNext() && s.hasNext());) {
        String curpat = (String) p.next();
        String cursub = (String) s.next();
        int numsubs;

        try {
            // Make sure the StringBuffer is empty each time we try to 
            // substitute.
            sb.delete(0, sb.length());
        } catch (StringIndexOutOfBoundsException e) {
        }

        Perl5Substitution sub = new Perl5Substitution(cursub);
        try {
            pattern = compiler.compile(curpat);
        } catch (MalformedPatternException e) {
            log.error("Poorly formed pattern " + curpat.toString());
        }

        numsubs = Util.substitute(sb, matcher, pattern, sub, rs.getUrl(), Util.SUBSTITUTE_ALL);

        if (numsubs != 0) {
            // We only let the first regex match.
            break;
        }
    }
    rs.setUrl(sb.toString());
}

From source file:org.jbuiltDemo.managed.view.Xhtml2Jbuilt.java

public ElementNode createTextNode(ElementNode parent, boolean comment, StringBuffer data) {
    ElementNode text = new ElementNode();
    text.parent = parent;/*ww  w .ja va  2  s . c o m*/
    text.textOnly = true;
    if (comment) {
        text.comments = data.toString();
    } else {
        text.text = data.toString();
    }
    data.delete(0, data.length() - 1);
    return text;
}

From source file:org.jsecurity.web.RedirectView.java

/**
 * Append query properties to the redirect URL.
 * Stringifies, URL-encodes and formats model attributes as query properties.
 *
 * @param targetUrl      the StringBuffer to append the properties to
 * @param model          Map that contains model attributes
 * @param encodingScheme the encoding scheme to use
 * @throws java.io.UnsupportedEncodingException
 *          if string encoding failed/*from  w ww.j  a  v  a 2 s  .c om*/
 * @see #queryProperties
 */
protected void appendQueryProperties(StringBuffer targetUrl, Map model, String encodingScheme)
        throws UnsupportedEncodingException {

    // Extract anchor fragment, if any.
    // The following code does not use JDK 1.4's StringBuffer.indexOf(String)
    // method to retain JDK 1.3 compatibility.
    String fragment = null;
    int anchorIndex = targetUrl.toString().indexOf('#');
    if (anchorIndex > -1) {
        fragment = targetUrl.substring(anchorIndex);
        targetUrl.delete(anchorIndex, targetUrl.length());
    }

    // If there aren't already some parameters, we need a "?".
    boolean first = (getUrl().indexOf('?') < 0);
    Map queryProps = queryProperties(model);

    if (queryProps != null) {
        for (Object o : queryProps.entrySet()) {
            if (first) {
                targetUrl.append('?');
                first = false;
            } else {
                targetUrl.append('&');
            }
            Map.Entry entry = (Map.Entry) o;
            String encodedKey = urlEncode(entry.getKey().toString(), encodingScheme);
            String encodedValue = (entry.getValue() != null
                    ? urlEncode(entry.getValue().toString(), encodingScheme)
                    : "");
            targetUrl.append(encodedKey).append('=').append(encodedValue);
        }
    }

    // Append anchor fragment, if any, to end of URL.
    if (fragment != null) {
        targetUrl.append(fragment);
    }
}

From source file:org.exoplatform.services.ecm.publication.REST.presentation.document.edit.GetEditedDocumentRESTService.java

private List<Node> getLastEditedNode(String noOfItem, String showGadgetWs) throws Exception {
    if (showGadgetWs != null && showGadgetWs.length() > 0) {
        show_gadget = Boolean.parseBoolean(showGadgetWs);
    }//  ww  w . j a  v a2s . co m
    ArrayList<Node> lstNode = new ArrayList<Node>();
    StringBuffer bf = new StringBuffer(1024);
    List<String> lstNodeType = templateService.getDocumentTemplates();
    if (lstNodeType != null) {
        for (String nodeType : lstNodeType) {
            bf.append("(").append(JCR_PRIMARYTYPE).append("=").append("'").append(nodeType).append("'")
                    .append(")").append(" OR ");
        }
    }

    if (bf.length() == 1)
        return null;
    bf.delete(bf.lastIndexOf("OR") - 1, bf.length());
    if (noOfItem == null || noOfItem.trim().length() == 0)
        noOfItem = String.valueOf(NO_PER_PAGE);
    String queryStatement = StringUtils.replace(QUERY_STATEMENT, "$0", NT_BASE);
    queryStatement = StringUtils.replace(queryStatement, "$1", bf.toString());
    queryStatement = StringUtils.replace(queryStatement, "$2", DATE_MODIFIED);
    ManageableRepository manageableRepository = repositoryService.getCurrentRepository();
    try {
        String[] workspaces = manageableRepository.getWorkspaceNames();
        List<String> lstWorkspace = new ArrayList<String>();
        //Arrays.asList() return fixed size list;
        lstWorkspace.addAll(Arrays.asList(workspaces));
        if (!show_gadget && lstWorkspace.contains(GADGET)) {
            lstWorkspace.remove(GADGET);
        }
        SessionProvider provider = WCMCoreUtils.createAnonimProvider();
        QueryImpl query = null;
        Session session = null;
        QueryResult queryResult = null;
        QueryManager queryManager = null;
        for (String workspace : lstWorkspace) {
            session = provider.getSession(workspace, manageableRepository);
            queryManager = session.getWorkspace().getQueryManager();
            query = (QueryImpl) queryManager.createQuery(queryStatement, Query.SQL);
            query.setLimit(Integer.parseInt(noOfItem));
            query.setOffset(0);
            queryResult = query.execute();
            puttoList(lstNode, queryResult.getNodes());
            session.logout();
        }
    } catch (RepositoryException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Exception when execute SQL " + queryStatement, e);
        }
    }
    return lstNode;
}

From source file:GIST.IzbirkomExtractor.AbbrList.java

/**
 * Creates a list of all possible expansions of a given streetName.
 * stretName itself will be the first element of the expansion list.
 * //from   ww w.  java 2s  .  com
 * @param streetName
 * @return
 */
public ArrayList<String> createAllExpansions(String streetName) {

    ArrayList<String> expansions = new ArrayList<String>();
    expansions.add(streetName);

    Matcher mat = getAbbreviationsPattern().matcher(streetName);
    if (mat.find()) {
        for (String exp : abbrevs.get(mat.group(1)).getExpansions()) {
            StringBuffer str = new StringBuffer(mat.replaceFirst(exp));

            /* get rid of abbreviations with dash */
            if (streetName.length() > mat.start(1) + 1 && streetName.charAt(mat.start(1) + 1) == '-') {
                str.setCharAt(mat.start(1) + exp.length(), ' ');
            }

            if (exp.endsWith("-")) { // support for ?-, ?-, -; remove space, downcase following letter

                /* skip replacement and the end of string */
                if (str.toString().endsWith(exp))
                    continue;

                str.delete(mat.start(1) + exp.length() - 1, mat.start(1) + exp.length() + 1);
                char upcase = str.charAt(mat.start(1) + exp.length() - 1);
                str.setCharAt(mat.start(1) + exp.length() - 1, Character.toLowerCase(upcase));
            }

            expansions.add(str.toString());
        }
    }

    return expansions;
}

From source file:org.alfresco.repo.bulkimport.impl.AbstractBulkFilesystemImporter.java

protected final String mapToString(Map<?, ?> map) {
    StringBuffer result = new StringBuffer();

    if (map != null) {
        result.append('[');

        if (map.size() > 0) {
            for (Object key : map.keySet()) {
                result.append(String.valueOf(key));
                result.append(" = ");
                result.append(String.valueOf(map.get(key)));
                result.append(",\n");
            }//from   w ww.  ja  v a 2 s .  com

            // Delete final dangling ", " value
            result.delete(result.length() - 2, result.length());
        }

        result.append(']');
    } else {
        result.append("(null)");
    }

    return (result.toString());
}

From source file:org.kuali.rice.kim.lookup.RoleMemberLookupableHelperServiceImpl.java

@SuppressWarnings({ "unchecked" })
protected Map<String, String> buildRoleSearchCriteria(Map<String, String> fieldValues) {
    String assignedToPrincipalName = fieldValues.get(ASSIGNED_TO_PRINCIPAL_NAME);
    Map<String, String> searchCriteria;
    List<Principal> principals = new ArrayList<Principal>();

    if (StringUtils.isNotEmpty(assignedToPrincipalName)) { // if a principal name is specified in the search
        // KULRICE-9153: Analyze IU patch for preventing role member lookup from causing out of memory exceptions
        // Changing to exact match on principal name to prevent blowing up Rice by loading every user into memory
        if (assignedToPrincipalName.contains("*")) {
            return null; // bail out, wild cards are not allowed since
                         // IdentityServiceImpl.getPrincipalByPrincipalName has weird behavior around wildcards
        }//from ww w  .j  a  va2 s .com

        Principal principal = KimApiServiceLocator.getIdentityService()
                .getPrincipalByPrincipalName(assignedToPrincipalName);

        if (principal == null) {
            return null; // bail out, if no principal matched and a principal name was supplied, then there will be
                         // no valid matching roles.
        }

        principals.add(principal);
    }

    String assignedToGroupNamespaceCode = fieldValues.get(ASSIGNED_TO_GROUP_NAMESPACE_CODE);
    String assignedToGroupName = fieldValues.get(ASSIGNED_TO_GROUP_NAME);
    List<Group> groups = null;
    if (StringUtils.isNotEmpty(assignedToGroupNamespaceCode) && StringUtils.isEmpty(assignedToGroupName)
            || StringUtils.isEmpty(assignedToGroupNamespaceCode) && StringUtils.isNotEmpty(assignedToGroupName)
            || StringUtils.isNotEmpty(assignedToGroupNamespaceCode)
                    && StringUtils.isNotEmpty(assignedToGroupName)) {
        QueryByCriteria.Builder builder = QueryByCriteria.Builder.create();
        builder.setPredicates(and(like(NAMESPACE_CODE, getQueryString(assignedToGroupNamespaceCode)),
                like(GROUP_NAME, getQueryString(assignedToGroupName))));
        GroupQueryResults qr = KimApiServiceLocator.getGroupService().findGroups(builder.build());
        if (qr.getResults() == null || qr.getResults().isEmpty()) {
            return null;
        }
        groups = qr.getResults();
    }

    String assignedToRoleNamespaceCode = fieldValues.get(ASSIGNED_TO_NAMESPACE_FOR_LOOKUP);
    String assignedToRoleName = fieldValues.get(ASSIGNED_TO_ROLE_NAME);

    searchCriteria = new HashMap<String, String>();
    if (StringUtils.isNotEmpty(assignedToRoleNamespaceCode)) {
        searchCriteria.put(ASSIGNED_TO_ROLE_NAMESPACE_CODE, WILDCARD + assignedToRoleNamespaceCode + WILDCARD);
    }
    if (StringUtils.isNotEmpty(assignedToRoleName)) {
        searchCriteria.put(ASSIGNED_TO_ROLE_ROLE_NAME, WILDCARD + assignedToRoleName + WILDCARD);
    }

    StringBuffer memberQueryString = null;
    if (!principals.isEmpty()) {
        memberQueryString = new StringBuffer();
        for (Principal principal : principals) {
            memberQueryString.append(principal.getPrincipalId() + KimConstants.KimUIConstants.OR_OPERATOR);
        }
        if (memberQueryString.toString().endsWith(KimConstants.KimUIConstants.OR_OPERATOR)) {
            memberQueryString.delete(
                    memberQueryString.length() - KimConstants.KimUIConstants.OR_OPERATOR.length(),
                    memberQueryString.length());
        }
    }
    if (groups != null) {
        if (memberQueryString == null) {
            memberQueryString = new StringBuffer();
        } else if (StringUtils.isNotEmpty(memberQueryString.toString())) {
            memberQueryString.append(KimConstants.KimUIConstants.OR_OPERATOR);
        }
        for (Group group : groups) {
            memberQueryString.append(group.getId() + KimConstants.KimUIConstants.OR_OPERATOR);
        }
        if (memberQueryString.toString().endsWith(KimConstants.KimUIConstants.OR_OPERATOR)) {
            memberQueryString.delete(
                    memberQueryString.length() - KimConstants.KimUIConstants.OR_OPERATOR.length(),
                    memberQueryString.length());
        }
        searchCriteria.put(ASSIGNED_TO_ROLE_MEMBER_ID, memberQueryString.toString());
    }
    if (memberQueryString != null && StringUtils.isNotEmpty(memberQueryString.toString())) {
        searchCriteria.put(ASSIGNED_TO_ROLE_MEMBER_ID, memberQueryString.toString());
    }

    return searchCriteria;
}

From source file:edu.cmu.lti.f12.hw2.hw2_team01.passage.SentenceBasedPassageCandidateFinder.java

private List<PassageSpan> splitParagraph(String text) {

    StringBuffer temptext = new StringBuffer(text);
    List<PassageSpan> rawSpans = new ArrayList<PassageSpan>();
    List<PassageSpan> splitedSpans = new ArrayList<PassageSpan>();
    List<PassageSpan> sentences = new ArrayList<PassageSpan>();
    int start = 0;
    int startindice = -1;
    int pstart, pend, textend;
    while ((startindice = temptext.toString().toLowerCase().indexOf("<p>")) != -1) {

        temptext.delete(0, startindice + 3);
        start += (startindice + 3);/* w  ww .  jav  a  2 s  .  co m*/

        pstart = temptext.toString().toLowerCase().indexOf("<p>");
        pend = temptext.toString().toLowerCase().indexOf("</p>");
        textend = temptext.toString().toLowerCase().indexOf("</txt>");

        if (textend != -1 && textend * pend < pend * pend && textend * pstart < pstart * pstart) {
            PassageSpan ps = new PassageSpan(start, start + textend);

            rawSpans.add(ps);
            temptext = temptext.delete(0, textend + 6);
            start += (textend + 6);

        }

        else if (pend != -1 && pstart > pend) {
            PassageSpan ps = new PassageSpan(start, start + pend);
            rawSpans.add(ps);
            temptext = temptext.delete(0, pend + 4);
            start += (pend + 4);

        }

        else if (pstart != -1) {
            PassageSpan ps = new PassageSpan(start, start + pstart);
            rawSpans.add(ps);
            temptext = temptext.delete(0, pstart + 3);
            start += pstart + 3;

        } else {
        }
    }

    String substring = new String();
    String subtoken = new String();
    String cleanText = new String();
    PassageSpan rawps;
    int substart, subend, psstart, psend, offset;
    Iterator<PassageSpan> ips = rawSpans.iterator();
    while (ips.hasNext()) {
        sentences.clear();
        rawps = ips.next();
        //REFINE THE PARAGRAPH
        //rawps = RefinePassage(rawps);
        //if(rawps == null)continue;
        substart = rawps.begin;
        subend = rawps.end;
        substring = text.substring(substart, subend);
        int count = StringUtils.countMatches(substring, " ");
        if (substring.length() > 20 && count / (double) substring.length() <= 0.4) {
            cleanText = Jsoup.parse(substring).text().replaceAll("([\177-\377\0-\32]*)", "");
            if ((cleanText.length() / (double) substring.length()) >= 0.6) {
                StringTokenizer tokenizer = new StringTokenizer(substring, ",.?!;");
                psstart = substart;
                psend = psstart;
                offset = 0;
                while (tokenizer.hasMoreTokens()) {
                    psstart = psend;
                    subtoken = tokenizer.nextToken();
                    // offset = noneblankindex(subtoken);
                    // psstart += offset;

                    psend += subtoken.length() + 1;
                    int totallength = subtoken.length();
                    while (totallength <= 50) {
                        if (tokenizer.hasMoreElements()) {
                            subtoken = tokenizer.nextToken();
                            totallength += subtoken.length();
                            psend += subtoken.length() + 1;
                        } else
                            break;
                    }
                    PassageSpan sentence = new PassageSpan(psstart, psend);
                    sentences.add(sentence);
                }
            }
        }

        Iterator<PassageSpan> isentence = sentences.iterator();
        PassageSpan ps1;
        while (isentence.hasNext()) {
            ps1 = isentence.next();
            splitedSpans.add(ps1);

        }

        MergeSentences(substart, subend, sentences, splitedSpans, 2);
        MergeSentences(substart, subend, sentences, splitedSpans, 3);
        MergeSentences(substart, subend, sentences, splitedSpans, 4);
        MergeSentences(substart, subend, sentences, splitedSpans, 5);
        MergeSentences(substart, subend, sentences, splitedSpans, 6);
        MergeSentences(substart, subend, sentences, splitedSpans, 7);
        MergeSentences(substart, subend, sentences, splitedSpans, 8);
        MergeSentences(substart, subend, sentences, splitedSpans, 9);
        MergeSentences(substart, subend, sentences, splitedSpans, 10);
    }

    return splitedSpans;
}

From source file:com.glaf.dts.web.springmvc.MxDtsQueryController.java

@RequestMapping("/chooseQuery")
public ModelAndView chooseQuery(HttpServletRequest request, ModelMap modelMap) {
    RequestUtils.setRequestParameterToAttribute(request);
    String elementValue = request.getParameter("elementValue");
    QueryDefinitionQuery query = new QueryDefinitionQuery();
    query.setOrderBy(" E.TARGETTABLENAME_ asc, E.TITLE_ asc ");
    List<QueryDefinition> list = queryDefinitionService.list(query);
    request.setAttribute("unselecteds", list);

    if (StringUtils.isNotEmpty(elementValue)) {
        StringBuffer sb01 = new StringBuffer();
        StringBuffer sb02 = new StringBuffer();
        List<String> selecteds = new java.util.ArrayList<String>();
        for (QueryDefinition q : list) {
            if (StringUtils.contains(elementValue, q.getId())) {
                selecteds.add(q.getId());
                sb01.append(q.getId()).append(",");
                sb02.append(q.getName()).append(",");
            }/*from   w  w w  .j a  v  a2s.c  om*/
        }
        if (sb01.toString().endsWith(",")) {
            sb01.delete(sb01.length() - 1, sb01.length());
        }
        if (sb02.toString().endsWith(",")) {
            sb02.delete(sb02.length() - 1, sb02.length());
        }
        request.setAttribute("selecteds", selecteds);
        request.setAttribute("queryIds", sb01.toString());
        request.setAttribute("queryNames", sb02.toString());
    }

    String x_view = ViewProperties.getString("dts.chooseQuery");
    if (StringUtils.isNotEmpty(x_view)) {
        return new ModelAndView(x_view, modelMap);
    }

    return new ModelAndView("/bi/dts/query/chooseQuery", modelMap);
}