Example usage for java.lang StringBuffer setLength

List of usage examples for java.lang StringBuffer setLength

Introduction

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

Prototype

@Override
public synchronized void setLength(int newLength) 

Source Link

Usage

From source file:com.pureinfo.srm.auth.ShowCheckboxGroupFunctionHandler.java

private String doPerform(String _sName, boolean _bValue, String[] _arrayMaps) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < _arrayMaps.length; i++) {
        String map[] = _arrayMaps[i].split(":");
        if (map == null || map.length < 1) {
            continue;
        }//from   www. j  a v  a2  s  .  c  o m
        String sBoxValue = map[0];
        String sBoxShow = map.length > 1 ? map[1] : " ";
        sb.append("<INPUT type=\"checkbox\" value=\"").append(sBoxValue).append('\"');
        if ((sBoxValue.equals("1") || sBoxValue.equals("true")) && _bValue) {
            sb.append(" checked");
        }
        sb.append(" onClick=\"document.getElementById('").append(_sName)
                .append("').value=this.checked?'1':'0';\"");
        //"onClick=document.getElementById("$_sName").value=this.checked?1:0"
        sb.append('>').append(sBoxShow);
    }
    String sResult = new String(sb);
    sb.setLength(0);
    return sResult;
}

From source file:net.groupbuy.entity.Article.java

/**
 * ?//w ww .j  a va2s  .co  m
 * 
 * @return 
 */
@Transient
public String[] getPageContents() {
    if (StringUtils.isEmpty(content)) {
        return new String[] { "" };
    }
    if (content.contains(PAGE_BREAK_SEPARATOR)) {
        return content.split(PAGE_BREAK_SEPARATOR);
    } else {
        List<String> pageContents = new ArrayList<String>();
        Document document = Jsoup.parse(content);
        List<Node> children = document.body().childNodes();
        if (children != null) {
            int textLength = 0;
            StringBuffer html = new StringBuffer();
            for (Node node : children) {
                if (node instanceof Element) {
                    Element element = (Element) node;
                    html.append(element.outerHtml());
                    textLength += element.text().length();
                    if (textLength >= PAGE_CONTENT_LENGTH) {
                        pageContents.add(html.toString());
                        textLength = 0;
                        html.setLength(0);
                    }
                } else if (node instanceof TextNode) {
                    TextNode textNode = (TextNode) node;
                    String text = textNode.text();
                    String[] contents = PARAGRAPH_SEPARATOR_PATTERN.split(text);
                    Matcher matcher = PARAGRAPH_SEPARATOR_PATTERN.matcher(text);
                    for (String content : contents) {
                        if (matcher.find()) {
                            content += matcher.group();
                        }
                        html.append(content);
                        textLength += content.length();
                        if (textLength >= PAGE_CONTENT_LENGTH) {
                            pageContents.add(html.toString());
                            textLength = 0;
                            html.setLength(0);
                        }
                    }
                }
            }
            String pageContent = html.toString();
            if (StringUtils.isNotEmpty(pageContent)) {
                pageContents.add(pageContent);
            }
        }
        return pageContents.toArray(new String[pageContents.size()]);
    }
}

From source file:org.latticesoft.util.common.FileUtil.java

public static void unzipFile(String src, String target) {
    try {/*from w  w  w.j av a  2  s. c o m*/
        BufferedOutputStream dest = null;
        FileInputStream fis = new FileInputStream(src);
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
        ZipEntry entry = null;
        StringBuffer sb = new StringBuffer();
        byte data[] = new byte[SIZE];
        while ((entry = zis.getNextEntry()) != null) {
            int count;
            sb.setLength(0);
            sb.append(target).append(File.separator).append(entry.getName());
            if (log.isInfoEnabled()) {
                log.info("Unzipping to " + sb.toString());
            }
            FileOutputStream fos = new FileOutputStream(sb.toString());
            dest = new BufferedOutputStream(fos, SIZE);
            while ((count = zis.read(data, 0, SIZE)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
        }
        zis.close();
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e);
        }
    }
}

From source file:org.apache.hadoop.mapreduce.jobhistory.HistoryViewer.java

private void printTasks(TaskType taskType, String status) {
    Map<TaskID, JobHistoryParser.TaskInfo> tasks = job.getAllTasks();
    StringBuffer header = new StringBuffer();
    header.append("\n").append(status).append(" ");
    header.append(taskType).append(" task list for ").append(jobId);
    header.append("\nTaskId\t\tStartTime\tFinishTime\tError");
    if (TaskType.MAP.equals(taskType)) {
        header.append("\tInputSplits");
    }/*from www . j av a  2 s.  com*/
    header.append("\n====================================================");
    StringBuffer taskList = new StringBuffer();
    for (JobHistoryParser.TaskInfo task : tasks.values()) {
        if (taskType.equals(task.getTaskType())
                && (status.equals(task.getTaskStatus()) || status.equalsIgnoreCase("ALL"))) {
            taskList.setLength(0);
            taskList.append(task.getTaskId());
            taskList.append("\t")
                    .append(StringUtils.getFormattedTimeWithDiff(dateFormat, task.getStartTime(), 0));
            taskList.append("\t").append(StringUtils.getFormattedTimeWithDiff(dateFormat, task.getFinishTime(),
                    task.getStartTime()));
            taskList.append("\t").append(task.getError());
            if (TaskType.MAP.equals(taskType)) {
                taskList.append("\t").append(task.getSplitLocations());
            }
            if (taskList != null) {
                System.out.println(header.toString());
                System.out.println(taskList.toString());
            }
        }
    }
}

From source file:com.tremolosecurity.unison.openshiftv3.OpenShiftTarget.java

public String getAuthToken() throws Exception {
    HttpCon con = this.createClient();
    try {/*  ww  w.  j  a va2 s.  com*/

        if (!this.useToken) {

            StringBuffer b = new StringBuffer();
            b.append(this.url)
                    .append("/oauth/authorize?response_type=token&client_id=openshift-challenging-client");
            HttpGet get = new HttpGet(b.toString());
            b.setLength(0);
            b.append(this.userName).append(':').append(this.password);
            String b64 = Base64.encodeBase64String(b.toString().getBytes("UTF-8"));
            b.setLength(0);
            b.append("Basic ").append(b64.substring(0, b64.length() - 2));
            get.addHeader(new BasicHeader("Authorization", b.toString()));

            HttpResponse resp = con.getHttp().execute(get);
            String token = "";
            if (resp.getStatusLine().getStatusCode() == 302) {
                String url = resp.getFirstHeader("Location").getValue();
                int start = url.indexOf("access_token") + "access_token=".length();
                int end = url.indexOf("&", start + 1);
                token = url.substring(start, end);

            } else {
                throw new Exception("Unable to obtain token : " + resp.getStatusLine().toString());
            }

            return token;
        } else {
            return this.osToken;
        }
    } finally {
        if (con != null) {
            con.getBcm().shutdown();
        }
    }
}

From source file:logdruid.util.DataMiner.java

private static Map<Recording, String> getRegexp(Repository repo, Source source) {
    Map<Recording, String> recMatch = new HashMap<Recording, String>();
    Map<Recording, Boolean> activeRecordingOnSourceCache = new HashMap<Recording, Boolean>();
    ArrayList<Recording> recordings;
    recordings = repo.getRecordings(StatRecording.class);
    recordings.addAll(repo.getRecordings(EventRecording.class));
    StringBuffer sb = new StringBuffer(100);

    Iterator<Recording> recordingIterator = recordings.iterator();
    while (recordingIterator.hasNext()) {
        Recording rec = recordingIterator.next();
        if (!activeRecordingOnSourceCache.containsKey(rec)) {
            activeRecordingOnSourceCache.put(rec, source.isActiveRecordingOnSource(rec));
        }/*from w ww  .  ja  v  a 2 s .  com*/
        if (activeRecordingOnSourceCache.get(rec)) {
            if (rec.getIsActive() == true) {
                ArrayList<RecordingItem> recordingItem = ((Recording) rec).getRecordingItem();
                Iterator<RecordingItem> recItemIte = recordingItem.iterator();
                if (logger.isDebugEnabled()) {
                    logger.debug("Record: " + rec.getName());
                }
                sb.setLength(0);
                int cnt = 0;
                while (recItemIte.hasNext()) {
                    RecordingItem recItem = recItemIte.next();
                    String stBefore = (String) recItem.getBefore();
                    String stType = (String) recItem.getType();
                    String stAfter = (String) recItem.getAfter();
                    if (stType.equals("date")) {
                        sb.append(stBefore);
                        sb.append("(");
                        sb.append(repo.getDateFormat(rec.getDateFormatID()).getPattern());
                        sb.append(")");
                        sb.append(stAfter);
                    } else {
                        sb.append(stBefore);
                        sb.append("(");
                        sb.append(getTypeString(stType));
                        sb.append(")");
                        sb.append(stAfter);
                    }
                }
                recMatch.put(rec, sb.toString());

                // logger.info("2**** regexp: "
                // +rec.getRegexp());
                if (logger.isDebugEnabled()) {
                    logger.debug("Pattern: " + sb.toString());
                }
            }
        }
    }
    return recMatch;
}

From source file:org.apache.nutch.protocol.s2jh.HttpResponse.java

private void parseHeaders(PushbackInputStream in, StringBuffer line) throws IOException, HttpException {

    while (readLine(in, line, true) != 0) {

        // handle HTTP responses with missing blank line after headers
        int pos;//  w w  w.  j a  v a2 s.c o m
        if (((pos = line.indexOf("<!DOCTYPE")) != -1) || ((pos = line.indexOf("<HTML")) != -1)
                || ((pos = line.indexOf("<html")) != -1)) {

            in.unread(line.substring(pos).getBytes("UTF-8"));
            line.setLength(pos);

            try {
                // TODO: (CM) We don't know the header names here
                // since we're just handling them generically. It would
                // be nice to provide some sort of mapping function here
                // for the returned header names to the standard metadata
                // names in the ParseData class
                processHeaderLine(line);
            } catch (Exception e) {
                // fixme:
                Http.LOG.error("Failed with the following exception: ", e);
            }
            return;
        }

        processHeaderLine(line);
    }
}

From source file:com.pureinfo.srm.view.function.ShowProductsSelectorFunctionHandler.java

/**
 * @see com.pureinfo.dolphinview.parser.function.FunctionHandlerDVImplBase#perform(java.lang.Object[],
 *      com.pureinfo.dolphinview.context.model.IDVContext)
 *///from   www  . j a v a 2  s. c om
public Object perform(Object[] _args, IDVContext _context) throws PureException {
    SRMUser user = (SRMUser) _context.getObject();
    if (user == null)
        return "";

    IProductMgr mgr = (IProductMgr) ArkContentHelper.getContentMgrOf(Product.class);
    //
    List products = mgr.getMyProduct(user.getId());
    String sWorks = user.getWorks();
    int[] arrIds = MyViewFunctionHelper.split(sWorks);

    //return MyViewFunctionHelper.makeDolphinObjectSelectorOption(products,
    // "id", "productName", listProIds);
    StringBuffer sbuff = new StringBuffer();
    try {
        Product product;
        int nId;
        Date publishDate;
        for (Iterator iter = products.iterator(); iter.hasNext();) {
            product = (Product) iter.next();
            nId = product.getId();
            sbuff.append("<OPTION value=\"").append(nId).append('"');
            if (arrIds != null && ArrayUtils.indexOf(arrIds, nId) >= 0) {
                sbuff.append(" SELECTED");
            }
            sbuff.append('>').append(product.getProductName());
            sbuff.append(" [").append(product.getPublisher()).append(']');

            publishDate = product.getPublishDate();
            if (publishDate != null) {
                sbuff.append(' ').append(ForceConstants.DATE_FORMAT.format(publishDate));
            }
            sbuff.append("</OPTION>");
        }
        return sbuff.toString();
    } finally {
        sbuff.setLength(0);
    }
}

From source file:edu.clemson.lph.utils.CSVParserWrapper.java

private ArrayList<String> readLine(String sLine) throws IOException {
    StringBuffer sb = new StringBuffer();
    ArrayList<String> aFields = new ArrayList<String>();
    boolean bInQuote = false;
    boolean bAfterQuote = false;
    for (int i = 0; i < sLine.trim().length(); i++) {
        char c = sLine.charAt(i);
        if (c == cQuoteChar && !bInQuote) {
            bInQuote = true;/*from   w w  w. j  a  va2  s .  co  m*/
        } else if (bAfterQuote && c != cSepChar) {
            // Ignore
        } else if (c == cQuoteChar && bInQuote) {
            bInQuote = false;
            bAfterQuote = true;
        } else if (!bInQuote && c == cSepChar) {
            bInQuote = false;
            bAfterQuote = false;
            aFields.add(sb.toString());
            sb.setLength(0);
        } else {
            sb.append(c);
        }
    }
    aFields.add(sb.toString());
    return aFields;
}

From source file:com.ikanow.infinit.e.data_model.custom.InfiniteFileInputXmlParser.java

@Override
public BSONObject getNextRecord() throws IOException {
    boolean justIgnored = false;
    boolean hitIdentifier = false;

    BSONObject currObj = null;/*from   w ww . ja  va  2s  . c o m*/

    StringBuffer fullText = new StringBuffer();

    try {
        while (_xmlStreamReader.hasNext()) {
            int eventCode = _xmlStreamReader.next();

            switch (eventCode) {
            case (XMLStreamReader.START_ELEMENT): {
                String tagName = _xmlStreamReader.getLocalName();

                if (null == levelOneFields || levelOneFields.size() == 0) {
                    levelOneFields = new ArrayList<String>();
                    levelOneFields.add(tagName);
                    currObj = new BasicDBObject();
                    _sb.delete(0, _sb.length());
                    fullText.setLength(0);
                    justIgnored = false;
                } else if (levelOneFields.contains(tagName)) {
                    _sb.delete(0, _sb.length());
                    currObj = new BasicDBObject();
                    fullText.setLength(0);
                    justIgnored = false;
                } else if ((null != ignoreFields) && ignoreFields.contains(tagName)) {
                    justIgnored = true;
                } else {
                    if (this.bPreserveCase) {
                        _sb.append("<").append(tagName).append(">");
                    } else {
                        _sb.append("<").append(tagName.toLowerCase()).append(">");
                    }
                    justIgnored = false;
                }
                if (null != currObj) {
                    fullText.append("<").append(tagName);
                    for (int ii = 0; ii < _xmlStreamReader.getAttributeCount(); ++ii) {
                        fullText.append(" ");
                        fullText.append(_xmlStreamReader.getAttributeLocalName(ii)).append("=\"")
                                .append(_xmlStreamReader.getAttributeValue(ii)).append('"');
                    }
                    fullText.append(">");
                } //TESTED

                hitIdentifier = tagName.equalsIgnoreCase(PKElement);

                if (!justIgnored && (null != this.AttributePrefix)) { // otherwise ignore attributes anyway
                    int nAttributes = _xmlStreamReader.getAttributeCount();
                    StringBuffer sb2 = new StringBuffer();
                    for (int i = 0; i < nAttributes; ++i) {
                        sb2.setLength(0);
                        _sb.append('<');

                        sb2.append(this.AttributePrefix);
                        if (this.bPreserveCase) {
                            sb2.append(_xmlStreamReader.getAttributeLocalName(i).toLowerCase());
                        } else {
                            sb2.append(_xmlStreamReader.getAttributeLocalName(i));
                        }
                        sb2.append('>');

                        _sb.append(sb2);
                        _sb.append("<![CDATA[").append(_xmlStreamReader.getAttributeValue(i).trim())
                                .append("]]>");
                        _sb.append("</").append(sb2);
                    }
                }
            }
                break;

            case (XMLStreamReader.CHARACTERS): {
                if (null != currObj) {
                    fullText.append(_xmlStreamReader.getText());
                } //TESTED

                if (_xmlStreamReader.getText().trim().length() > 0 && justIgnored == false)
                    _sb.append("<![CDATA[").append(_xmlStreamReader.getText().trim()).append("]]>");
                if (hitIdentifier) {
                    String tValue = _xmlStreamReader.getText().trim();
                    if (null != XmlSourceName) {
                        if (tValue.length() > 0) {
                            currObj.put(DocumentPojo.url_, XmlSourceName + tValue);
                        }
                    }
                }
            }
                break;
            case (XMLStreamReader.END_ELEMENT): {
                if (null != currObj) {
                    fullText.append("</").append(_xmlStreamReader.getLocalName()).append(">");
                } //TESTED

                hitIdentifier = !_xmlStreamReader.getLocalName().equalsIgnoreCase(PKElement);
                if ((null != ignoreFields) && !ignoreFields.contains(_xmlStreamReader.getLocalName())) {
                    if (levelOneFields.contains(_xmlStreamReader.getLocalName())) {
                        try {
                            JSONObject json = XML.toJSONObject(_sb.toString());
                            BasicDBObject xmlMetadata = convertJsonObjectToBson(json);
                            currObj.put(DocumentPojo.metadata_,
                                    new BasicDBObject("xml", Arrays.asList(xmlMetadata)));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        currObj.put(DocumentPojo.fullText_, fullText.toString());
                        _sb.delete(0, _sb.length());
                        _oneUp++;
                        return currObj;
                    } else {
                        if (this.bPreserveCase) {
                            _sb.append("</").append(_xmlStreamReader.getLocalName()).append(">");
                        } else {
                            _sb.append("</").append(_xmlStreamReader.getLocalName().toLowerCase()).append(">");
                        }

                    }
                }
            } // (end case)
                break;
            } // (end switch)
        }
    } catch (RuntimeException e2) {
        // Don't throw exception, just recover and move onto next split         
        //throw new IOException("record " + _oneUp + ": " + e.getMessage(), e);

    } catch (XMLStreamException e) {
        // Don't throw exception, just recover and move onto next split         
        //throw new IOException("record " + _oneUp + ": " + e.getMessage(), e);
    }
    return null;
}