Example usage for java.lang StringBuffer indexOf

List of usage examples for java.lang StringBuffer indexOf

Introduction

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

Prototype

@Override
public int indexOf(String str) 

Source Link

Usage

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

/**
 * /*from w ww.  j a va2s  .  c om*/
 * @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 ((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:com.digitalpebble.storm.crawler.protocol.http.HttpResponse.java

private void readChunkedContent(PushbackInputStream in, StringBuffer line) throws HttpException, IOException {
    boolean doneChunks = false;
    int contentBytesRead = 0;
    byte[] bytes = new byte[HttpProtocol.BUFFER_SIZE];
    ByteArrayOutputStream out = new ByteArrayOutputStream(HttpProtocol.BUFFER_SIZE);

    while (!doneChunks) {
        if (HttpProtocol.LOGGER.isTraceEnabled()) {
            HttpProtocol.LOGGER.trace("Http: starting chunk");
        }/*from w  ww .j ava2 s. com*/

        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) < HttpProtocol.BUFFER_SIZE ? (chunkLen - chunkBytesRead)
                    : HttpProtocol.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.apache.nutch.protocol.http.HttpResponse.java

/**
 * @param in/*  w w w  .  j a va 2 s .  c  o  m*/
 * @param line
 * @throws HttpException
 * @throws IOException
 */
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, null);

}

From source file:org.apache.poi.ss.format.CellNumberFormatter.java

private void writeInteger(StringBuffer result, StringBuffer output, List<Special> numSpecials,
        Set<StringMod> mods, boolean showCommas) {

    int pos = result.indexOf(".") - 1;
    if (pos < 0) {
        if (exponent != null && numSpecials == integerSpecials)
            pos = result.indexOf("E") - 1;
        else/*  w w w.  j  ava2  s  . co m*/
            pos = result.length() - 1;
    }

    int strip;
    for (strip = 0; strip < pos; strip++) {
        char resultCh = result.charAt(strip);
        if (resultCh != '0' && resultCh != ',')
            break;
    }

    ListIterator<Special> it = numSpecials.listIterator(numSpecials.size());
    boolean followWithComma = false;
    Special lastOutputIntegerDigit = null;
    int digit = 0;
    while (it.hasPrevious()) {
        char resultCh;
        if (pos >= 0)
            resultCh = result.charAt(pos);
        else {
            // If result is shorter than field, pretend there are leading zeros
            resultCh = '0';
        }
        Special s = it.previous();
        followWithComma = showCommas && digit > 0 && digit % 3 == 0;
        boolean zeroStrip = false;
        if (resultCh != '0' || s.ch == '0' || s.ch == '?' || pos >= strip) {
            zeroStrip = s.ch == '?' && pos < strip;
            output.setCharAt(s.pos, (zeroStrip ? ' ' : resultCh));
            lastOutputIntegerDigit = s;
        }
        if (followWithComma) {
            mods.add(insertMod(s, zeroStrip ? " " : ",", StringMod.AFTER));
            followWithComma = false;
        }
        digit++;
        --pos;
    }
    StringBuffer extraLeadingDigits = new StringBuffer();
    if (pos >= 0) {
        // We ran out of places to put digits before we ran out of digits; put this aside so we can add it later
        ++pos; // pos was decremented at the end of the loop above when the iterator was at its end
        extraLeadingDigits = new StringBuffer(result.substring(0, pos));
        if (showCommas) {
            while (pos > 0) {
                if (digit > 0 && digit % 3 == 0)
                    extraLeadingDigits.insert(pos, ',');
                digit++;
                --pos;
            }
        }
        mods.add(insertMod(lastOutputIntegerDigit, extraLeadingDigits, StringMod.BEFORE));
    }
}

From source file:com.isecpartners.gizmo.HttpRequest.java

public boolean readRequest(Socket clientSock) {
    StringBuffer contents = new StringBuffer();

    try {//from  www  .  j  a v  a2 s . c  o  m
        InputStream input = clientSock.getInputStream();

        contents = readMessage(input);

        if (contents == null) {
            return false;
        }

        setContentEncodings(contents);
        this.interrimContents = contents.toString();
        this.sock = clientSock;

        this.header = contents.substring(0, contents.indexOf("\r\n"));

        workingContents = new StringBuffer(this.interrimContents.toString());

        if (header.contains("CONNECT") && GizmoView.getView().intercepting()) {
            handle_connect_protocol();
            if (!GizmoView.getView().config().terminateSSL()) {
                return false;
            }
            this.header = workingContents.substring(0, workingContents.indexOf("\r\n"));
        }
        if (GizmoView.getView().intercepting()) {
            if (header.contains("http")) {
                url = header.substring(header.indexOf("http"), header.indexOf("HTTP") - 1);
            } else {
                url = header.substring(header.indexOf("/"), header.indexOf("HTTP") - 1);
            }
            if (url.contains("//")) {
                host = url.substring(url.indexOf("//") + 2, url.indexOf("/", url.indexOf("//") + 2));
            } else {
                String upper = workingContents.toString().toUpperCase();
                int host_start = upper.indexOf("HOST:") + 5;
                host = workingContents.substring(host_start, upper.indexOf("\n", host_start)).trim();
            }
        }

        this.addContents(workingContents.toString());

    } catch (Exception e) {
        return false;
    }

    return true;
}

From source file:org.apache.poi.ss.format.CellNumberFormatter.java

private void writeFractional(StringBuffer result, StringBuffer output) {
    int digit;/*www.j a v  a2  s .  c  o  m*/
    int strip;
    ListIterator<Special> it;
    if (fractionalSpecials.size() > 0) {
        digit = result.indexOf(".") + 1;
        if (exponent != null)
            strip = result.indexOf("e") - 1;
        else
            strip = result.length() - 1;
        while (strip > digit && result.charAt(strip) == '0')
            strip--;
        it = fractionalSpecials.listIterator();
        while (it.hasNext()) {
            Special s = it.next();
            char resultCh = result.charAt(digit);
            if (resultCh != '0' || s.ch == '0' || digit < strip)
                output.setCharAt(s.pos, resultCh);
            else if (s.ch == '?') {
                // This is when we're in trailing zeros, and the format is '?'.  We still strip out remaining '#'s later
                output.setCharAt(s.pos, ' ');
            }
            digit++;
        }
    }
}

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));
    }//from   w w w .  java  2s  .c o 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:com.nofuturecorp.www.connector.Database.java

/**
 * Make a post request to the PHP URL for process request and get data in JSON format
 * @param json with data to send/*from www.ja va  2  s  .  c o  m*/
 * @return JSON with data received
 * @throws IOException
 * @throws DatabaseException 
 */
private String makePostRequest(String json) throws IOException, DatabaseException {

    if (json == null) {
        throw new NullPointerException("json cannot be null");
    }
    if (!ignoreSecureProtocol && url.toUpperCase().startsWith("HTTPS")) {
        throw new SecureProtocolException(
                "URL Protocol is not valid. Please use HTTPS or set true ignore secure protocol");
    }

    StringBuffer data = null;
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setDoOutput(true);

    OutputStream os = con.getOutputStream();
    os.write(("isTransaction=" + isTransaction + "&data=" + json).getBytes());
    os.flush();
    os.close();

    int response = con.getResponseCode();
    if (response == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
        String line = null;
        data = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            data.append(line);
        }
        String js = data.substring(data.indexOf("{"));
        return js;
    } else {
        throw new DatabaseException("HTTP connection fails. Response code: " + response);
    }
}

From source file:com.photon.phresco.impl.DrupalApplicationProcessor.java

public void replaceSqlBlock(File versionFile, String fileName, String moduleName, String queryString)
        throws PhrescoException, IOException {
    BufferedReader buff = null;//from   w w w . j  a  v a  2s. c  o m
    try {
        File scriptFile = new File(versionFile + File.separator + fileName);
        StringBuffer sb = new StringBuffer();
        if (scriptFile.isFile()) {
            // if script file is available need to replace the content
            buff = new BufferedReader(new FileReader(scriptFile));
            String readBuff = buff.readLine();
            String sectionStarts = MODULE_START_TAG + moduleName + START_MODULE_END_TAG;
            String sectionEnds = MODULE_START_TAG + moduleName + END_MODULE_END_TAG;

            while (readBuff != null) {
                sb.append(readBuff);
                sb.append(LINE_BREAK);
                readBuff = buff.readLine();
            }

            int cnt1 = sb.indexOf(sectionStarts);
            int cnt2 = sb.indexOf(sectionEnds);
            if (cnt1 != -1 || cnt2 != -1) {
                sb.replace(cnt1 + sectionStarts.length(), cnt2, LINE_BREAK + queryString + LINE_BREAK);
            } else {
                // if this module is not added already in the file and need to add this config alone
                sb.append(LINE_BREAK + DOUBLE_HYPHEN + LINE_BREAK);
                sb.append(MODULE_START_TAG + moduleName + START_MODULE_END_TAG + LINE_BREAK);
                sb.append(queryString);
                sb.append(LINE_BREAK);
                sb.append(MODULE_START_TAG + moduleName + END_MODULE_END_TAG + LINE_BREAK);
                sb.append(DOUBLE_HYPHEN + LINE_BREAK);
            }

        } else {
            // else construct the format and write
            // query string buffer
            sb.append(
                    "CREATE TABLE IF NOT EXISTS `variable` (`name` varchar(128) NOT NULL DEFAULT '' COMMENT 'The name of the variable.', `value` longblob NOT NULL COMMENT 'The value of the variable.', PRIMARY KEY (`name`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Named variable/value pairs created by Drupal core or any...';"
                            + LINE_BREAK);
            sb.append(DOUBLE_HYPHEN + LINE_BREAK);
            sb.append(MODULE_START_TAG + moduleName + START_MODULE_END_TAG + LINE_BREAK);
            sb.append(queryString);
            sb.append(LINE_BREAK);
            sb.append(MODULE_START_TAG + moduleName + END_MODULE_END_TAG + LINE_BREAK);
            sb.append(DOUBLE_HYPHEN + LINE_BREAK);
        }

        FileUtils.writeStringToFile(scriptFile, sb.toString());
    } catch (Exception e) {
        throw new PhrescoException(e);
    } finally {
        if (buff != null) {
            buff.close();
        }
    }
}

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

/**
 * /*ww w . ja v  a2 s .c  om*/
 * @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);

}