Example usage for java.lang StringBuffer substring

List of usage examples for java.lang StringBuffer substring

Introduction

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

Prototype

@Override
public synchronized String substring(int start, int end) 

Source Link

Usage

From source file:com.ss.language.model.gibblda.Document.java

/**
 * ?//from  w w w  .j  a  v a  2s  .  c o m
 * 
 * @param words
 */
private void storeDoc(Vector<Integer> words) {
    if (words.size() > 0) {
        docId = nextDocId();
        StringBuilder wordIds = new StringBuilder();
        Map<Integer, Integer> maps = new LinkedHashMap<Integer, Integer>();
        for (Integer wordId : words) {
            if (wordId != null) {
                wordIds.append(wordId);
                wordIds.append(",");
                Integer times = maps.get(wordId);
                if (times == null) {
                    times = 1;
                } else {
                    times += 1;
                }
                maps.put(wordId, times);
            }
        }
        LuceneDataAccess.save(DOC_PRE + docId, wordIds.substring(0, wordIds.length() - 1));
        // ???
        LDACmdOption option = LDACmdOption.curOption.get();
        File file = null;
        if (option.eachwords != null && option.eachwords.trim().length() > 0) {
            file = new File(option.dir + File.separator + option.eachwords);
            StringBuffer sb = new StringBuffer();
            for (Integer wordId : maps.keySet()) {
                sb.append(wordId);
                sb.append(":");
                sb.append(maps.get(wordId));
                sb.append(", ");
            }
            String line = sb.length() > 0 ? sb.substring(0, sb.length() - 2) : sb.toString();
            line += IOUtils.LINE_SEPARATOR;
            try {
                FileUtils.write(file, line, "UTF-8", true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.netspective.sparx.fileupload.FileUpload.java

/**
 * Reads the form field and puts it in to a table
 *//*from www  . j  av a  2  s .c o  m*/
private void readParam() throws IOException {
    String line = null;
    StringBuffer buf = new StringBuffer();
    while (!(line = readLine()).startsWith(boundary)) {
        buf.append(line);
    }
    line = buf.substring(0, buf.length() - 2);
    if (map.containsKey(paramName)) {
        Object existingValue = map.get(paramName);
        List valueList = null;
        if (existingValue instanceof List) {
            valueList = (List) existingValue;
        } else {
            valueList = new ArrayList();
            valueList.add(existingValue);
        }
        valueList.add(line);
        map.put(paramName, valueList);
    }
    map.put(paramName, line);
}

From source file:org.wso2.carbon.appmgt.sample.deployer.http.HttpHandler.java

/**
 * This method is used to do a http post request
 *
 * @param url         request url/*  w  ww  .j  ava 2 s .co m*/
 * @param payload     Content of the post request
 * @param sessionId   sessionId for authentication
 * @param contentType content type of the post request
 * @return response
 * @throws java.io.IOException - Throws this when failed to fulfill a http post request
 */
public String doPostHttp(String url, String payload, String sessionId, String contentType) throws IOException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    //con.setRequestProperty("User-Agent", USER_AGENT);
    if (!sessionId.equals("") && !sessionId.equals("none")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
    }
    con.setRequestProperty("Content-Type", contentType);
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (sessionId.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (sessionId.equals("appmSamlSsoTokenId")) {
            return con.getHeaderField("Set-Cookie").split(";")[0].split("=")[1];
        } else if (sessionId.equals("header")) {
            return con.getHeaderField("Set-Cookie").split("=")[1].split(";")[0];
        } else {
            return response.toString();
        }
    }
    return null;
}

From source file:org.wso2.carbon.appmgt.sample.deployer.http.HttpHandler.java

/**
 * This method is used to do a https post request
 *
 * @param url         request url//  www.j  a v a 2  s .  c  o  m
 * @param payload     Content of the post request
 * @param sessionId   sessionId for authentication
 * @param contentType content type of the post request
 * @return response
 * @throws java.io.IOException - Throws this when failed to fulfill a https post request
 */
public String doPostHttps(String url, String payload, String sessionId, String contentType) throws IOException {
    URL obj = new URL(url);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    if (!sessionId.equals("")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
    }
    if (!contentType.equals("")) {
        con.setRequestProperty("Content-Type", contentType);
    }
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (sessionId.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (sessionId.equals("header")) {
            return con.getHeaderField("Set-Cookie");
        }

        return response.toString();
    }
    return null;
}

From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java

@Override
public String getFingerPrint(byte[] data) {
    try {/*  w  w  w .  j  a va 2s.c  o  m*/
        byte[] fp = Digest.SHA1.get().digest(data);
        StringBuffer sb = new StringBuffer();
        for (byte b : fp)
            sb.append(String.format("%02X:", b));
        return sb.substring(0, sb.length() - 1).toLowerCase();
    } catch (Exception e) {
        LOG.error(e, e);
        return null;
    }
}

From source file:org.jbpm.formModeler.fieldTypes.document.handling.JBPMDocumentFieldTypeHandler.java

@Override
public Object getValue(Field field, String inputName, Map parametersMap, Map filesMap, String desiredClassName,
        Object previousValue) throws Exception {
    Document oldDoc = (Document) previousValue;

    // Expecting a delete parameter, if we receive that the current file will be deleted from the system
    String[] deleteParam = (String[]) parametersMap.get(inputName + "_delete");
    boolean delete = oldDoc != null && (deleteParam != null && deleteParam.length > 0 && deleteParam[0] != null
            && Boolean.valueOf(deleteParam[0]).booleanValue());

    // if there is an uploaded file for that field we will delete the previous one (if existed) and will return the uploaded file path.
    File file = (File) filesMap.get(inputName);
    if (file != null) {
        // Getting the DocumentMarshallingStrategy for this project if exists any we build the document
        AbstractDocumentMarshallingStrategy marshallingStrategy = getDocumentMarshallingStrategy(inputName);
        if (marshallingStrategy != null) {
            StringBuffer url = RequestContext.getCurrentContext().getRequest().getRequestObject()
                    .getRequestURL();/*from w w w  . j a v a  2 s .  c  o m*/

            Map<String, String> params = new HashMap<String, String>();
            params.put("app.url", url.substring(0, url.indexOf("/Controller")));

            Document doc = marshallingStrategy.buildDocument(file.getName(), file.length(),
                    new Date(file.lastModified()), params);
            doc.setContent(FileUtils.readFileToByteArray(file));
            return doc;
        } else {
            Document doc = new DocumentImpl(file.getName(), file.length(), new Date(file.lastModified()));
            doc.setContent(FileUtils.readFileToByteArray(file));
            return doc;
        }
    }

    // If we receive the delete parameter or we are uploading a new file the current file will be deleted
    if (delete) {
        return null;
    }

    return oldDoc;
}

From source file:XMLUtils.java

/**
 * Returns the text value of an element.
 * @param el/*from  w ww  . j av a  2  s. c  om*/
 * @return
 */
public static String getTextValue(Element el) {
    StringBuffer b = new StringBuffer();
    // retrieve the text node child
    NodeList nl = el.getChildNodes();
    int len = nl.getLength();
    for (int i = 0; i < len; i++) {
        Node n = nl.item(i);
        if (n instanceof Text) {
            Text t = (Text) n;
            b.append(t.getData());
        }
    }
    // trim the result, ignoring the first spaces and cariage return
    int iFirst = 0;
    for (; iFirst < b.length(); iFirst++) {
        char c = b.charAt(iFirst);
        if (c != ' ' && c != '\r' && c != '\n' && c != '\t') {
            break;
        }
    }
    // start by the end as well
    int iLast = b.length() - 1;
    for (; iLast >= 0; iLast--) {
        char c = b.charAt(iLast);
        if (c != ' ' && c != '\r' && c != '\n' && c != '\t') {
            break;
        }
    }
    return b.substring(iFirst, iLast + 1);
}

From source file:org.nuxeo.connect.packages.dependencies.DependencyResolution.java

private String removeLineReturn(StringBuffer sb) {
    if (sb.length() > 0) { // remove ending \n
        return sb.substring(0, sb.length() - 1);
    } else {//from   w w w .j  av  a  2  s . c  o  m
        return "";
    }
}

From source file:org.scilla.Request.java

/**
 * @return request description/*  ww w . j  a  va 2 s  .com*/
 */
public String toString() {
    StringBuffer b = new StringBuffer();
    b.append("source=" + source + ", ");
    b.append("type=" + type + ", ");
    for (Iterator it = param.iterator(); it.hasNext();) {
        RequestParameter rp = (RequestParameter) it.next();
        b.append(rp.key + "=" + rp.val + ", ");
    }
    return b.substring(0, b.length() - 2);
}

From source file:org.ambraproject.feed.service.FeedServiceImpl.java

/**
 * Queries for a list of articles from solr using the parameters set in cacheKey
 *
 * @param cacheKey//from   w w w.  jav  a 2  s .com
 * @return solr search result that contains list of articles
 */
@Override
public Document getArticles(final ArticleFeedCacheKey cacheKey) {
    Map<String, String> params = new HashMap<String, String>();
    // result format
    params.put("wt", "xml");
    // what I want returned, the fields needed for rss feed
    params.put("fl",
            "id,title_display,publication_date,author_without_collab_display,author_collab_only_display,"
                    + "author_display,volume,issue,article_type,subject_hierarchy,abstract_primary_display,copyright");

    // filters
    String fq = "doc_type:full " + "AND !article_type_facet:\"Issue Image\" "
            + "AND cross_published_journal_key:" + cacheKey.getJournal();

    String[] categories = cacheKey.getCategories();
    if (categories != null && categories.length > 0) {
        StringBuffer sb = new StringBuffer();
        for (String category : categories) {
            sb.append("\"").append(category).append("\" AND ");
        }
        params.put("q", "subject_level_1:(" + sb.substring(0, sb.length() - 5) + ")");
    }

    if (cacheKey.getAuthor() != null) {
        fq = fq + " AND author:\"" + cacheKey.getAuthor() + "\"";
    }

    String startDate = "*";
    String endDate = "*";
    boolean addDateRange = false;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    if (cacheKey.getSDate() != null) {
        startDate = sdf.format(cacheKey.getSDate().getTime());
        startDate = startDate + "T00:00:00Z";
        addDateRange = true;
    }
    if (cacheKey.getEDate() != null) {
        endDate = sdf.format(cacheKey.getEDate().getTime());
        endDate = endDate + "T00:00:00Z";
        addDateRange = true;
    }

    if (addDateRange == true) {
        fq = fq + " AND publication_date:[" + startDate + " TO " + endDate + "]";
    }

    params.put("fq", fq);

    // number of results
    params.put("rows", Integer.toString(cacheKey.getMaxResults()));

    // sort the result

    if (cacheKey.isMostViewed()) {
        // Sorts RSS Feed for the most viewed articles linked from the most viewed tab.
        String mostViewedKey = "ambra.virtualJournals." + journalService.getCurrentJournalName()
                + ".mostViewedArticles";
        Integer days = configuration.getInt(mostViewedKey + ".timeFrame");
        String sortField = (days != null) ? solrFieldConverter.getViewCountingFieldName(days)
                : solrFieldConverter.getAllTimeViewsField();
        params.put("sort", sortField + " desc");
    } else {
        params.put("sort", "publication_date desc");
    }

    Document result = null;
    try {
        result = solrHttpService.makeSolrRequest(params);
    } catch (SolrException e) {
        e.printStackTrace();
    }

    return result;
}