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:org.kuali.ole.select.document.OlePurchaseOrderAmendmentDocument.java

/**
 * This method will set copies into list of copies for LineItem.
 *
 * @param singleItem//www. j  a v  a 2s .c  o  m
 * @param workBibDocument
 * @return
 */
public List<OleCopies> setCopiesToLineItem(OlePurchaseOrderItem singleItem, WorkBibDocument workBibDocument) {
    List<WorkInstanceDocument> instanceDocuments = workBibDocument.getWorkInstanceDocumentList();
    List<OleCopies> copies = new ArrayList<OleCopies>();
    for (WorkInstanceDocument workInstanceDocument : instanceDocuments) {
        List<WorkItemDocument> itemDocuments = workInstanceDocument.getItemDocumentList();
        StringBuffer enumeration = new StringBuffer();
        for (int itemDocs = 0; itemDocs < itemDocuments.size(); itemDocs++) {
            if (itemDocs + 1 == itemDocuments.size()) {
                enumeration = enumeration.append(itemDocuments.get(itemDocs).getEnumeration());
            } else {
                enumeration = enumeration.append(itemDocuments.get(itemDocs).getEnumeration() + ",");
            }

        }
        int startingCopy = 0;
        if (singleItem.getItemNoOfParts().intValue() != 0 && null != enumeration) {
            String enumerationSplit = enumeration.substring(1, 2);
            boolean isint = checkIsEnumerationSplitIsIntegerOrNot(enumerationSplit);
            if (isint) {
                startingCopy = Integer.parseInt(enumerationSplit);
            }
        }
        if (singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
                || singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
            boolean isValid = checkForEnumeration(enumeration);
            if (isValid) {
                int noOfCopies = workInstanceDocument.getItemDocumentList().size()
                        / singleItem.getItemNoOfParts().intValue();
                OleRequisitionCopies copy = new OleRequisitionCopies();
                copy.setParts(singleItem.getItemNoOfParts());
                copy.setLocationCopies(workInstanceDocument.getHoldingsDocument().getLocationName());
                copy.setItemCopies(new KualiDecimal(noOfCopies));
                copy.setPartEnumeration(enumeration.toString());
                copy.setStartingCopyNumber(new KualiInteger(startingCopy));
                copies.add(copy);
            }
        }
    }
    return copies;
}

From source file:org.apache.ivory.latedata.LateDataHandler.java

public String detectChanges(Path file, Map<String, Long> map, Configuration conf) throws Exception {

    StringBuffer buffer = new StringBuffer();
    BufferedReader in = new BufferedReader(new InputStreamReader(file.getFileSystem(conf).open(file)));
    String line;/*from w w w . j a v  a2  s  .c  o m*/
    try {
        Map<String, Long> recorded = new LinkedHashMap<String, Long>();
        while ((line = in.readLine()) != null) {
            if (line.isEmpty())
                continue;
            int index = line.indexOf('=');
            String key = line.substring(0, index);
            long size = Long.parseLong(line.substring(index + 1));
            recorded.put(key, size);
        }

        for (Map.Entry<String, Long> entry : map.entrySet()) {
            if (recorded.get(entry.getKey()) == null) {
                LOG.info("No matching key " + entry.getKey());
                continue;
            }
            if (!recorded.get(entry.getKey()).equals(entry.getValue())) {
                LOG.info("Recorded size:" + recorded.get(entry.getKey()) + "  is different from new size"
                        + entry.getValue());
                buffer.append(entry.getKey()).append(',');
            }
        }
        if (buffer.length() == 0) {
            return "";
        } else {
            return buffer.substring(0, buffer.length() - 1);
        }

    } finally {
        in.close();
    }

}

From source file:org.exoplatform.ecm.webui.component.explorer.UIWorkingArea.java

public String getActionsExtensionList(Node node) throws Exception {
    StringBuffer actionsList = new StringBuffer(1024);
    List<UIExtension> uiExtensionList = getUIExtensionList();
    UIComponent uiAddedActionManage;//from www .jav  a  2  s .  c om
    try {
        NodeFinder nodeFinder = getApplicationComponent(NodeFinder.class);
        nodeFinder.getItem(getAncestorOfType(UIJCRExplorer.class).getSession(), node.getPath());
    } catch (PathNotFoundException pne) {
        return "";
    }
    for (UIExtension uiextension : uiExtensionList) {
        if (uiextension.getCategory().startsWith(ITEM_CONTEXT_MENU)
                || ITEM_GROUND_CONTEXT_MENU.equals(uiextension.getCategory())) {
            uiAddedActionManage = addUIExtension(uiextension, createContext(node));
            if (uiAddedActionManage != null) {
                actionsList.append(uiextension.getName()).append(",");
            }
        }
    }
    if (actionsList.length() > 0) {
        return actionsList.substring(0, actionsList.length() - 1);
    }
    return actionsList.toString();
}

From source file:com.doculibre.constellio.wicket.pages.SearchResultsPage.java

private void initComponents() {
    final SimpleSearch simpleSearch = getSimpleSearch();
    String collectionName = simpleSearch.getCollectionName();
    ConstellioUser currentUser = ConstellioSession.get().getUser();
    RecordCollectionServices recordCollectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordCollection collection = recordCollectionServices.get(collectionName);
    boolean userHasPermission = false;
    if (collection != null) {
        userHasPermission = (!collection.hasSearchPermission())
                || (currentUser != null && currentUser.hasSearchPermission(collection));
    }// w  ww  .  j  av a2  s.co  m
    if (StringUtils.isEmpty(collectionName) || !userHasPermission) {
        setResponsePage(ConstellioApplication.get().getHomePage());
    } else {

        final IModel suggestedSearchKeyListModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                ListOrderedMap suggestedSearch = new ListOrderedMap();
                if (simpleSearch.isQueryValid() && simpleSearch.getQuery() != null) {
                    SpellChecker spellChecker = new SpellChecker(ConstellioApplication.get().getDictionaries());
                    try {
                        if (!simpleSearch.getQuery().equals("*:*")) {
                            suggestedSearch = spellChecker.suggest(simpleSearch.getQuery(),
                                    simpleSearch.getCollectionName());
                        }
                    } catch (RuntimeException e) {
                        e.printStackTrace();
                        // chec du spellchecker, pas besoin de faire planter la page
                    }
                }
                return suggestedSearch;
            }
        };

        BaseSearchResultsPageHeaderPanel headerPanel = (BaseSearchResultsPageHeaderPanel) getHeaderComponent();
        headerPanel.setAdvancedForm(simpleSearch.getAdvancedSearchRule() != null);
        SearchFormPanel searchFormPanel = headerPanel.getSearchFormPanel();

        final ThesaurusSuggestionPanel thesaurusSuggestionPanel = new ThesaurusSuggestionPanel(
                "thesaurusSuggestion", simpleSearch, getLocale());
        add(thesaurusSuggestionPanel);

        SpellCheckerPanel spellCheckerPanel = new SpellCheckerPanel("spellChecker",
                searchFormPanel.getSearchTxtField(), searchFormPanel.getSearchButton(),
                suggestedSearchKeyListModel) {
            @SuppressWarnings("unchecked")
            public boolean isVisible() {
                boolean visible = false;
                if (dataProvider != null && !thesaurusSuggestionPanel.isVisible()) {
                    RecordCollectionServices collectionServices = ConstellioSpringUtils
                            .getRecordCollectionServices();
                    RecordCollection collection = collectionServices.get(simpleSearch.getCollectionName());
                    if (collection != null && collection.isSpellCheckerActive()
                            && simpleSearch.getAdvancedSearchRule() == null) {
                        ListOrderedMap spell = (ListOrderedMap) suggestedSearchKeyListModel.getObject();
                        if (spell.size() > 0/* && dataProvider.size() == 0 */) {
                            for (String key : (List<String>) spell.keyList()) {
                                if (spell.get(key) != null) {
                                    return visible = true;
                                }
                            }
                        }
                    }
                }
                return visible;
            }
        };
        add(spellCheckerPanel);

        dataProvider = new SearchResultsDataProvider(simpleSearch, 10);

        WebMarkupContainer searchResultsSection = new WebMarkupContainer("searchResultsSection") {
            @Override
            public boolean isVisible() {
                return StringUtils.isNotBlank(simpleSearch.getLuceneQuery());
            }
        };
        add(searchResultsSection);

        IModel detailsLabelModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                String detailsLabel;
                QueryResponse queryResponse = dataProvider.getQueryResponse();
                long start;
                long nbRes;
                double elapsedTimeSeconds;
                if (queryResponse != null) {
                    start = queryResponse.getResults().getStart();
                    nbRes = dataProvider.size();
                    elapsedTimeSeconds = (double) queryResponse.getElapsedTime() / 1000;
                } else {
                    start = 0;
                    nbRes = 0;
                    elapsedTimeSeconds = 0;
                }
                long end = start + 10;
                if (nbRes < end) {
                    end = nbRes;
                }

                String pattern = "#.####";
                DecimalFormat elapsedTimeFormatter = new DecimalFormat(pattern);
                String elapsedTimeStr = elapsedTimeFormatter.format(elapsedTimeSeconds);

                String forTxt = new StringResourceModel("for", SearchResultsPage.this, null).getString();
                String noResultTxt = new StringResourceModel("noResult", SearchResultsPage.this, null)
                        .getString();
                String resultsTxt = new StringResourceModel("results", SearchResultsPage.this, null)
                        .getString();
                String ofTxt = new StringResourceModel("of", SearchResultsPage.this, null).getString();
                String secondsTxt = new StringResourceModel("seconds", SearchResultsPage.this, null)
                        .getString();

                String queryTxt = " ";
                if (simpleSearch.isQueryValid() && simpleSearch.getQuery() != null
                        && simpleSearch.getAdvancedSearchRule() == null) {
                    queryTxt = " " + forTxt + " " + simpleSearch.getQuery() + " ";
                }

                if (nbRes > 0) {
                    Locale locale = getLocale();
                    detailsLabel = resultsTxt + " " + NumberFormatUtils.format(start + 1, locale) + " - "
                            + NumberFormatUtils.format(end, locale) + " " + ofTxt + " "
                            + NumberFormatUtils.format(nbRes, locale) + queryTxt + "(" + elapsedTimeStr + " "
                            + secondsTxt + ")";
                } else {
                    detailsLabel = noResultTxt + " " + queryTxt + "(" + elapsedTimeStr + " " + secondsTxt + ")";
                }

                String collectionName = dataProvider.getSimpleSearch().getCollectionName();
                if (collectionName != null) {
                    RecordCollectionServices collectionServices = ConstellioSpringUtils
                            .getRecordCollectionServices();
                    RecordCollection collection = collectionServices.get(collectionName);
                    Locale displayLocale = collection.getDisplayLocale(getLocale());
                    String collectionTitle = collection.getTitle(displayLocale);
                    detailsLabel = collectionTitle + " > " + detailsLabel;
                }
                return detailsLabel;
            }
        };
        Label detailsLabel = new Label("detailsRes", detailsLabelModel);
        add(detailsLabel);

        final IModel sortOptionsModel = new LoadableDetachableModel() {

            @Override
            protected Object load() {
                List<SortChoice> choices = new ArrayList<SortChoice>();
                choices.add(new SortChoice(null, null, null));
                String collectionName = dataProvider.getSimpleSearch().getCollectionName();
                if (collectionName != null) {
                    IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices();
                    RecordCollectionServices collectionServices = ConstellioSpringUtils
                            .getRecordCollectionServices();
                    RecordCollection collection = collectionServices.get(collectionName);
                    for (IndexField indexField : indexFieldServices.getSortableIndexFields(collection)) {
                        String label = indexField.getLabel(IndexField.LABEL_TITLE,
                                ConstellioSession.get().getLocale());
                        if (label == null || label.isEmpty()) {
                            label = indexField.getName();
                        }
                        choices.add(new SortChoice(indexField.getName(), label, "asc"));
                        choices.add(new SortChoice(indexField.getName(), label, "desc"));
                    }
                }
                return choices;
            }
        };

        IChoiceRenderer triChoiceRenderer = new ChoiceRenderer() {
            @Override
            public Object getDisplayValue(Object object) {
                SortChoice choice = (SortChoice) object;
                String displayValue;
                if (choice.title == null) {
                    displayValue = new StringResourceModel("sort.relevance", SearchResultsPage.this, null)
                            .getString();
                } else {
                    String order = new StringResourceModel("sortOrder." + choice.order, SearchResultsPage.this,
                            null).getString();
                    displayValue = choice.title + " " + order;
                }
                return displayValue;
            }
        };
        IModel value = new Model(new SortChoice(simpleSearch.getSortField(), simpleSearch.getSortField(),
                simpleSearch.getSortOrder()));
        DropDownChoice sortField = new DropDownChoice("sortField", value, sortOptionsModel, triChoiceRenderer) {
            @Override
            protected boolean wantOnSelectionChangedNotifications() {
                return true;
            }

            @Override
            protected void onSelectionChanged(Object newSelection) {
                SortChoice choice = (SortChoice) newSelection;
                if (choice.name == null) {
                    simpleSearch.setSortField(null);
                    simpleSearch.setSortOrder(null);
                } else {
                    simpleSearch.setSortField(choice.name);
                    simpleSearch.setSortOrder(choice.order);
                }
                simpleSearch.setPage(0);

                PageFactoryPlugin pageFactoryPlugin = PluginFactory.getPlugin(PageFactoryPlugin.class);
                RequestCycle.get().setResponsePage(pageFactoryPlugin.getSearchResultsPage(),
                        SearchResultsPage.getParameters(simpleSearch));
            }

            @Override
            public boolean isVisible() {
                return ((List<?>) sortOptionsModel.getObject()).size() > 1;
            }
        };
        searchResultsSection.add(sortField);
        sortField.setNullValid(false);

        add(new AjaxLazyLoadPanel("facetsPanel") {
            @Override
            public Component getLazyLoadComponent(String markupId) {
                return new FacetsPanel(markupId, dataProvider);
            }
        });

        final IModel featuredLinkModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                FeaturedLink suggestion;
                RecordCollectionServices collectionServices = ConstellioSpringUtils
                        .getRecordCollectionServices();
                FeaturedLinkServices featuredLinkServices = ConstellioSpringUtils.getFeaturedLinkServices();
                Long featuredLinkId = simpleSearch.getFeaturedLinkId();
                if (featuredLinkId != null) {
                    suggestion = featuredLinkServices.get(featuredLinkId);
                } else {
                    String collectionName = simpleSearch.getCollectionName();
                    if (simpleSearch.getAdvancedSearchRule() == null) {
                        String text = simpleSearch.getQuery();
                        RecordCollection collection = collectionServices.get(collectionName);
                        suggestion = featuredLinkServices.suggest(text, collection);
                        if (suggestion == null) {
                            SynonymServices synonymServices = ConstellioSpringUtils.getSynonymServices();
                            List<String> synonyms = synonymServices.getSynonyms(text, collectionName);
                            if (!synonyms.isEmpty()) {
                                for (String synonym : synonyms) {
                                    if (!synonym.equals(text)) {
                                        suggestion = featuredLinkServices.suggest(synonym, collection);
                                    }
                                    if (suggestion != null) {
                                        break;
                                    }
                                }
                            }
                        }
                    } else {
                        suggestion = new FeaturedLink();
                    }
                }
                return suggestion;
            }
        };
        IModel featuredLinkTitleModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                FeaturedLink featuredLink = (FeaturedLink) featuredLinkModel.getObject();
                return featuredLink.getTitle(getLocale());
            }
        };
        final IModel featuredLinkDescriptionModel = new LoadableDetachableModel() {
            @Override
            protected Object load() {
                FeaturedLink featuredLink = (FeaturedLink) featuredLinkModel.getObject();
                StringBuffer descriptionSB = new StringBuffer();
                String description = featuredLink.getDescription(getLocale());
                if (description != null) {
                    descriptionSB.append(description);
                    String lookFor = "${";
                    int indexOfLookFor = -1;
                    while ((indexOfLookFor = descriptionSB.indexOf(lookFor)) != -1) {
                        int indexOfEnclosingQuote = descriptionSB.indexOf("}", indexOfLookFor);
                        String featuredLinkIdStr = descriptionSB.substring(indexOfLookFor + lookFor.length(),
                                indexOfEnclosingQuote);

                        int indexOfTagBodyStart = descriptionSB.indexOf(">", indexOfEnclosingQuote) + 1;
                        int indexOfTagBodyEnd = descriptionSB.indexOf("</a>", indexOfTagBodyStart);
                        String capsuleQuery = descriptionSB.substring(indexOfTagBodyStart, indexOfTagBodyEnd);
                        if (capsuleQuery.indexOf("<br/>") != -1) {
                            capsuleQuery = StringUtils.remove(capsuleQuery, "<br/>");
                        }
                        if (capsuleQuery.indexOf("<br />") != -1) {
                            capsuleQuery = StringUtils.remove(capsuleQuery, "<br />");
                        }

                        try {
                            String linkedCapsuleURL = getFeaturedLinkURL(new Long(featuredLinkIdStr));
                            descriptionSB.replace(indexOfLookFor, indexOfEnclosingQuote + 1, linkedCapsuleURL);
                        } catch (NumberFormatException e) {
                            // Ignore
                        }
                    }
                }
                return descriptionSB.toString();
            }

            private String getFeaturedLinkURL(Long featuredLinkId) {
                SimpleSearch clone = simpleSearch.clone();
                clone.setFeaturedLinkId(featuredLinkId);
                PageFactoryPlugin pageFactoryPlugin = PluginFactory.getPlugin(PageFactoryPlugin.class);
                String url = RequestCycle.get()
                        .urlFor(pageFactoryPlugin.getSearchResultsPage(), getParameters(clone)).toString();
                return url;
            }
        };

        WebMarkupContainer featuredLink = new WebMarkupContainer("featuredLink", featuredLinkModel) {
            @Override
            public boolean isVisible() {
                boolean visible = super.isVisible();
                if (visible) {
                    if (featuredLinkModel.getObject() != null) {
                        String description = (String) featuredLinkDescriptionModel.getObject();
                        visible = StringUtils.isNotEmpty(description);
                    } else {
                        visible = false;
                    }
                }
                DataView dataView = (DataView) searchResultsPanel.getDataView();
                return visible && dataView.getCurrentPage() == 0;
            }
        };
        searchResultsSection.add(featuredLink);
        featuredLink.add(new Label("title", featuredLinkTitleModel));
        featuredLink.add(new WebMarkupContainer("description", featuredLinkDescriptionModel) {
            @Override
            protected void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) {
                String descriptionHTML = (String) getModel().getObject();
                replaceComponentTagBody(markupStream, openTag, descriptionHTML);
            }
        });

        searchResultsSection
                .add(searchResultsPanel = new SearchResultsPanel("resultatsRecherchePanel", dataProvider));
    }
}

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

/**
 * /*w  w w . jav  a  2 s  .c  o  m*/
 * @param in
 * @param line
 * @throws HttpException
 * @throws IOException
 */
@SuppressWarnings("unused")
private void readChunkedContent(PushbackInputStream in, StringBuffer line) throws HttpException, IOException {
    boolean doneChunks = false;
    int contentBytesRead = 0;
    byte[] bytes = new byte[Http.BUFFER_SIZE];
    ByteArrayOutputStream out = new ByteArrayOutputStream(Http.BUFFER_SIZE);

    while (!doneChunks) {
        if (Http.LOG.isTraceEnabled()) {
            Http.LOG.trace("Http: starting chunk");
        }

        readLine(in, line, false);

        String chunkLenStr;
        // if (LOG.isTraceEnabled()) { LOG.trace("chunk-header: '" + line + "'");
        // }

        int pos = line.indexOf(";");
        if (pos < 0) {
            chunkLenStr = line.toString();
        } else {
            chunkLenStr = line.substring(0, pos);
            // if (LOG.isTraceEnabled()) { LOG.trace("got chunk-ext: " +
            // line.substring(pos+1)); }
        }
        chunkLenStr = chunkLenStr.trim();
        int chunkLen;
        try {
            chunkLen = Integer.parseInt(chunkLenStr, 16);
        } catch (NumberFormatException e) {
            throw new HttpException("bad chunk length: " + line.toString());
        }

        if (chunkLen == 0) {
            doneChunks = true;
            break;
        }

        if (http.getMaxContent() >= 0 && (contentBytesRead + chunkLen) > http.getMaxContent())
            chunkLen = http.getMaxContent() - contentBytesRead;

        // read one chunk
        int chunkBytesRead = 0;
        while (chunkBytesRead < chunkLen) {

            int toRead = (chunkLen - chunkBytesRead) < Http.BUFFER_SIZE ? (chunkLen - chunkBytesRead)
                    : Http.BUFFER_SIZE;
            int len = in.read(bytes, 0, toRead);

            if (len == -1)
                throw new HttpException("chunk eof after " + contentBytesRead + " bytes in successful chunks"
                        + " and " + chunkBytesRead + " in current chunk");

            // DANGER!!! Will printed GZIPed stuff right to your
            // terminal!
            // if (LOG.isTraceEnabled()) { LOG.trace("read: " + new String(bytes, 0,
            // len)); }

            out.write(bytes, 0, len);
            chunkBytesRead += len;
        }

        readLine(in, line, false);
    }

    if (!doneChunks) {
        if (contentBytesRead != http.getMaxContent())
            throw new HttpException("chunk eof: !doneChunk && didn't max out");
        return;
    }

    content = out.toByteArray();
    parseHeaders(in, line);

}

From source file:org.kuali.ole.select.document.service.impl.OlePurchaseOrderDocumentHelperServiceImpl.java

public List<OleCopies> setCopiesToLineItem(OlePurchaseOrderItem singleItem, BibTree bibTree) {
    List<HoldingsTree> instanceDocuments = bibTree.getHoldingsTrees();
    List<OleCopies> copies = new ArrayList<OleCopies>();
    for (HoldingsTree holdingsTree : instanceDocuments) {
        List<Item> itemDocuments = holdingsTree.getItems();
        StringBuffer enumeration = new StringBuffer();
        for (int itemDocs = 0; itemDocs < itemDocuments.size(); itemDocs++) {
            if (itemDocs + 1 == itemDocuments.size()) {
                enumeration = enumeration.append(itemDocuments.get(itemDocs).getEnumeration());
            } else {
                enumeration = enumeration.append(itemDocuments.get(itemDocs).getEnumeration() + ";");
            }//from   w w w.j  ava  2  s  .  co  m

        }
        int startingCopy = 0;
        if (singleItem.getItemNoOfParts().intValue() != 0 && null != enumeration
                && StringUtils.isNotEmpty(enumeration.toString())) {
            String enumerationSplit = enumeration.substring(1, 2);
            boolean isint = checkIsEnumerationSplitIsIntegerOrNot(enumerationSplit);
            if (isint) {
                startingCopy = Integer.parseInt(enumerationSplit);
            }
        }
        if (singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
                || singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
            int noOfCopies = holdingsTree.getItems().size() / singleItem.getItemNoOfParts().intValue();
            OleRequisitionCopies copy = new OleRequisitionCopies();
            copy.setParts(singleItem.getItemNoOfParts());
            copy.setLocationCopies(holdingsTree.getHoldings().getLocationName());
            copy.setItemCopies(new KualiDecimal(noOfCopies));
            copy.setPartEnumeration(enumeration.toString());
            copy.setStartingCopyNumber(new KualiInteger(startingCopy));
            copies.add(copy);
        }
    }
    return copies;
}

From source file:org.ebayopensource.turmeric.tools.library.utils.TypeLibraryUtilities.java

public static String getContentFromSunEpisodeForMasterEpisode(InputStream inputStream, boolean isFirstFile)
        throws IOException {

    Charset defaultCharset = Charset.defaultCharset();
    InputStreamReader isr = null;
    BufferedReader reader = null;

    StringBuffer strBuff = new StringBuffer();
    String lineStr = "";
    boolean startOfContentReached = false;
    try {//  w w  w .ja va  2 s  .  c o  m
        isr = new InputStreamReader(inputStream, defaultCharset);
        reader = new BufferedReader(isr);
        while ((lineStr = reader.readLine()) != null) {
            if (lineStr.trim().contains(TypeLibraryConstants.MASTER_EPISODE_TURMERIC_START_COMMNENT)) {
                startOfContentReached = true;

                if (!isFirstFile) {
                    // if this sun-jaxb.episode file is not the first episode file then we will have to skip two more lines
                    reader.readLine();
                    reader.readLine();
                }

                break;
            }
        }

        if (startOfContentReached) {
            while ((lineStr = reader.readLine()) != null) {
                if (lineStr.trim().contains(TypeLibraryConstants.MASTER_EPISODE_TURMERIC_END_COMMNENT)) {

                    int index = strBuff.lastIndexOf("</bindings>");
                    if (index > 0)
                        strBuff = new StringBuffer(strBuff.substring(0, index));
                    break;
                }

                strBuff.append(lineStr + "\n");
            }
        }
    } finally {
        CodeGenUtil.closeQuietly(reader);
        CodeGenUtil.closeQuietly(isr);
    }

    return strBuff.toString();
}

From source file:org.ambraproject.article.service.BrowseServiceImpl.java

/**
 * Returns list of articles in a given date range, from newest to oldest
 * @param params the collection class of parameters.
 * @return the articles//from  www .  ja  v a 2  s  .  co m
 */
private BrowseResult getArticlesByDateViaSolr(BrowseParameters params) {
    BrowseResult result = new BrowseResult();
    ArrayList<SearchHit> articles = new ArrayList<SearchHit>();
    long totalSize = 0;

    SolrQuery query = createCommonQuery(params.getJournalKey());

    query.addField("title_display");
    query.addField("author_display");
    query.addField("article_type");
    query.addField("publication_date");
    query.addField("id");
    query.addField("abstract_primary_display");
    query.addField("eissn");

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String sDate = sdf.format(params.getStartDate().getTime());
    String eDate = sdf.format(params.getEndDate().getTime());

    sDate = sDate + "T00:00:00Z";
    eDate = eDate + "T00:00:00Z";

    query.addFilterQuery("publication_date:[" + sDate + " TO " + eDate + "]");

    StringBuffer sb = new StringBuffer();
    if (params.getArticleTypes() != null && params.getArticleTypes().size() > 0) {
        for (URI uri : params.getArticleTypes()) {
            String path = uri.getPath();
            int index = path.lastIndexOf("/");
            if (index != -1) {
                String articleType = path.substring(index + 1);
                sb.append("\"").append(articleType).append("\"").append(" OR ");
            }
        }
        String articleTypesQuery = sb.substring(0, sb.length() - 4);

        if (articleTypesQuery.length() > 0) {
            query.addFilterQuery("article_type_facet:" + articleTypesQuery);
        }
    }

    setSort(query, params);

    query.setStart(params.getPageNum() * params.getPageSize());
    query.setRows(params.getPageSize());

    log.info("getArticlesByDate Solr Query:" + query.toString());

    try {
        QueryResponse response = this.serverFactory.getServer().query(query);
        SolrDocumentList documentList = response.getResults();
        totalSize = documentList.getNumFound();

        for (SolrDocument document : documentList) {
            SearchHit sh = createArticleBrowseDisplay(document, query.toString());
            articles.add(sh);
        }

    } catch (SolrServerException e) {
        log.error("Unable to execute a query on the Solr Server.", e);
    }

    result.setArticles(articles);
    result.setTotal(totalSize);

    return result;
}

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

protected String enumerateCronVals(SortedSet vals, int totalCount) {
    if (vals == null || vals.isEmpty()) {
        throw new JSException("jsexception.no.values.to.enumerate");
    }/*w ww. j  a  v  a2 s  .c om*/

    if (vals.size() == totalCount) {
        return "*";
    }

    StringBuffer enumStr = new StringBuffer();
    for (Iterator it = vals.iterator(); it.hasNext();) {
        Byte val = (Byte) it.next();
        enumStr.append(val.byteValue());
        enumStr.append(',');
    }
    return enumStr.substring(0, enumStr.length() - 1);
}

From source file:com.clustercontrol.collect.util.CollectGraphUtil.java

/**
 * ID??????/*from w w w.  j  a  v  a  2 s .  co m*/
 * 
 * @return
 */
private static String orderItemInfoSelection() {
    String selectInfoStr = getInstance().selectInfoStr.substring(0, getInstance().selectInfoStr.length() - 1);
    String selectInfoArr[] = selectInfoStr.split(SQUARE_SEPARATOR);
    StringBuffer sb = new StringBuffer();
    int count = 0;
    for (String select : selectInfoArr) {
        for (CollectKeyInfoPK collectInfo : getInstance().m_collectKeyInfoList) {
            String itemNameLocale = HinemosMessage.replace(collectInfo.getItemName());
            if (!collectInfo.getDisplayName().equals("")
                    && !itemNameLocale.endsWith("[" + collectInfo.getDisplayName() + "]")) {
                itemNameLocale += "[" + collectInfo.getDisplayName() + "]";
            }
            String str = itemNameLocale + "(" + collectInfo.getMonitorId() + ")";
            if (str.equals(select)) {
                String param = "{" + "\'count\':" + count + ", " + "\'itemname\':\'" + itemNameLocale + "\', "
                        + "\'monitorid\':\'" + collectInfo.getMonitorId() + "\', " + "\'displayname\':\'"
                        + collectInfo.getDisplayName() + "\'" + "},";
                sb.append(param);
                count++;
                break;
            }
        }
    }
    String ret = "\'orderitem\':[" + sb.substring(0, sb.toString().length() - 1) + "]";
    m_log.debug("orderItemInfoSelection() ret:" + ret);
    return ret;
}