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.openhie.openempi.report.impl.AbstractReportGenerator.java

private void insertParamValue(StringBuffer queryStr, String paramValue, ReportQueryParameter queryParam) {
    String clause = queryParam.getParameterName() + paramValue;
    if (queryParam.getSubstitutionKey() != null && queryParam.getSubstitutionKey().length() > 0
            && queryStr.indexOf("$" + queryParam.getSubstitutionKey()) >= 0) {
        log.debug("Before replacing substitution key " + queryParam.getSubstitutionKey() + " the query was: "
                + queryStr);/* ww w.  j a v  a 2 s  .co m*/
        int start = queryStr.indexOf("$" + queryParam.getSubstitutionKey());
        int end = start + queryParam.getSubstitutionKey().length() + 2;
        queryStr.replace(start, end, clause);
        log.debug("After replacing substitution key " + queryParam.getSubstitutionKey() + " the query is: "
                + queryStr);
    } else {
        if (queryStr.indexOf("WHERE") < 0 && queryStr.indexOf("where") < 0) {
            queryStr.append(" WHERE 1=1");
        }
        queryStr.append(" AND ").append(clause);
    }
}

From source file:org.kuali.ole.sys.web.struts.KualiBatchInputFileAction.java

/**
 * Sends the uploaded file contents, requested file name, and batch type to the BatchInputTypeService for storage. If errors
 * were encountered, messages will be in GlobalVariables.errorMap, which is checked and set for display by the request
 * processor.//from  w w  w. j av  a 2s  .c om
 */
public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    BatchUpload batchUpload = ((KualiBatchInputFileForm) form).getBatchUpload();
    if (LOG.isDebugEnabled()) {
        LOG.debug("------------BatchInputTypeName---------->" + batchUpload.getBatchInputTypeName());
    }
    BatchInputFileType batchType = retrieveBatchInputFileTypeImpl(batchUpload.getBatchInputTypeName());

    BatchInputFileService batchInputFileService = SpringContext.getBean(BatchInputFileService.class);
    FormFile uploadedFile = ((KualiBatchInputFileForm) form).getUploadFile();

    StringBuffer fileName = new StringBuffer(uploadedFile.getFileName());

    int fileExtensionCount = fileName.indexOf(".");
    String extension = fileName.substring(fileExtensionCount + 1);

    if (uploadedFile == null || uploadedFile.getInputStream() == null
            || uploadedFile.getInputStream().available() == 0) {
        GlobalVariables.getMessageMap().putError(OLEConstants.GLOBAL_ERRORS,
                OLEKeyConstants.ERROR_BATCH_UPLOAD_NO_FILE_SELECTED_SAVE, new String[] {});
        return mapping.findForward(OLEConstants.MAPPING_BASIC);
    }

    if (!batchInputFileService.isFileUserIdentifierProperlyFormatted(batchUpload.getFileUserIdentifer())) {
        GlobalVariables.getMessageMap().putError(OLEConstants.GLOBAL_ERRORS,
                OLEKeyConstants.ERROR_BATCH_UPLOAD_FILE_USER_IDENTIFIER_BAD_FORMAT, new String[] {});
        return mapping.findForward(OLEConstants.MAPPING_BASIC);
    }

    InputStream fileContents = ((KualiBatchInputFileForm) form).getUploadFile().getInputStream();
    byte[] fileByteContent = IOUtils.toByteArray(fileContents);

    Object parsedObject = null;
    try {
        parsedObject = batchInputFileService.parse(batchType, fileByteContent);
    } catch (ParseException e) {
        LOG.error("errors parsing xml " + e.getMessage(), e);
        GlobalVariables.getMessageMap().putError(OLEConstants.GLOBAL_ERRORS,
                OLEKeyConstants.ERROR_BATCH_UPLOAD_PARSING_XML, new String[] { e.getMessage() });
    }

    if (parsedObject != null && GlobalVariables.getMessageMap().hasNoErrors()) {
        boolean validateSuccessful = batchInputFileService.validate(batchType, parsedObject);

        if (validateSuccessful && GlobalVariables.getMessageMap().hasNoErrors()) {
            try {
                InputStream saveStream = new ByteArrayInputStream(fileByteContent);
                String savedFileName = "";
                if (batchUpload.getBatchInputTypeName().equalsIgnoreCase("marcInputFileType")) {
                    if (batchUpload == null || batchUpload.getBatchDestinationFilePath() == null) {
                        GlobalVariables.getMessageMap().putError(OLEConstants.GLOBAL_ERRORS,
                                OLEKeyConstants.ERROR_BATCH_UPLOAD_NO_FILE_PATH_SELECTED_SAVE, new String[] {});
                        return mapping.findForward(OLEConstants.MAPPING_BASIC);
                    }
                    savedFileName = batchInputFileService.save(GlobalVariables.getUserSession().getPerson(),
                            batchType, batchUpload.getFileUserIdentifer(), saveStream, parsedObject,
                            batchUpload.getBatchDestinationFilePath(), extension);
                } else {
                    savedFileName = batchInputFileService.save(GlobalVariables.getUserSession().getPerson(),
                            batchType, batchUpload.getFileUserIdentifer(), saveStream, parsedObject);
                }
                KNSGlobalVariables.getMessageList().add(OLEKeyConstants.MESSAGE_BATCH_UPLOAD_SAVE_SUCCESSFUL);
            } catch (FileStorageException e1) {
                LOG.error("errors saving xml " + e1.getMessage(), e1);
                GlobalVariables.getMessageMap().putError(OLEConstants.GLOBAL_ERRORS,
                        OLEKeyConstants.ERROR_BATCH_UPLOAD_SAVE, new String[] { e1.getMessage() });
            }
        }
    }

    return mapping.findForward(OLEConstants.MAPPING_BASIC);
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * ??/* w  w w. java  2 s.c o  m*/
 * 
 * @param uri
 * @param req
 * @return
 */
public static String toUrl(String uri, HttpServletRequest req) {
    StringBuffer buffer = req.getRequestURL();
    boolean isSsl = buffer.indexOf(URL_SSL_PREFIX) > -1;
    String base = buffer.substring(0, buffer.indexOf(SLASH, URL_SSL_PREFIX.length() - (isSsl ? 0 : 1)));
    return StringUtils.isEmpty(uri) ? base : base + uri;
}

From source file:com.huguesjohnson.sega32xcollector.ebay.EbayUtils.java

private String formatCurrency(String amount, String currencyCode) {
    StringBuffer formattedText = new StringBuffer(amount);
    try {/*w ww  .  j a  v a  2  s .  com*/
        //add trailing zeros
        int indexOf = formattedText.indexOf(".");
        if (indexOf >= 0) {
            if (formattedText.length() - indexOf == 2) {
                formattedText.append("0");
            }
        }
        //add dollar sign
        if (currencyCode.equalsIgnoreCase("USD")) {
            formattedText.insert(0, "$");
        } else {
            formattedText.append(" ");
            formattedText.append(currencyCode);
        }
    } catch (Exception x) {
        Log.e(TAG, "formatCurrency", x);
    }
    return (formattedText.toString());
}

From source file:org.dataone.proto.trove.mn.rest.base.AbstractWebController.java

protected String getRequestPID(HttpServletRequest request, String delimiter) throws DecoderException {
    StringBuffer urlBuffer = request.getRequestURL();
    int objectStart = urlBuffer.indexOf(delimiter);
    String pid = urlBuffer.substring(objectStart + delimiter.length(), urlBuffer.length());
    String decodedPID = null;/*w  w  w.  ja va  2 s . c om*/
    try {
        decodedPID = urlCodec.decode(pid, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        decodedPID = urlCodec.decode(pid);
    }
    logger.info("decoding GUID/PID: " + pid + " to " + decodedPID);
    return decodedPID;
}

From source file:com.panet.imeta.trans.steps.http.HTTP.java

private String determineUrl(RowMetaInterface outputRowMeta, Object[] row)
        throws KettleValueException, KettleException {
    try {/* w  w w  .  j a v  a  2s. co  m*/
        if (meta.isUrlInField()) {
            // get dynamic url
            data.realUrl = outputRowMeta.getString(row, data.indexOfUrlField);
        }
        StringBuffer url = new StringBuffer(data.realUrl); // the base URL with variable substitution

        for (int i = 0; i < data.argnrs.length; i++) {
            if (i == 0 && url.indexOf("?") < 0) {
                url.append('?');
            } else {
                url.append('&');
            }

            url.append(URIUtil.encodeWithinQuery(meta.getArgumentParameter()[i]));
            url.append('=');
            String s = outputRowMeta.getString(row, data.argnrs[i]);
            if (s != null)
                s = URIUtil.encodeWithinQuery(s);
            url.append(s);
        }

        return url.toString();
    } catch (Exception e) {
        throw new KettleException(Messages.getString("HTTP.Log.UnableCreateUrl"), e);
    }
}

From source file:be.ibridge.kettle.trans.step.textfileinput.TextFileInput.java

public static final ArrayList convertLineToStrings(LogWriter log, String line, TextFileInputMeta inf)
        throws KettleException {
    ArrayList strings = new ArrayList();
    int fieldnr;//from   w w  w.  j a v  a2 s  .  c o m
    String pol; // piece of line

    try {
        if (line == null)
            return null;

        if (inf.getFileType().equalsIgnoreCase("CSV")) {
            // Split string in pieces, only for CSV!

            fieldnr = 0;
            int pos = 0;
            int length = line.length();
            boolean dencl = false;

            while (pos < length) {
                int from = pos;
                int next;
                int len_encl = (inf.getEnclosure() == null ? 0 : inf.getEnclosure().length());
                int len_esc = (inf.getEscapeCharacter() == null ? 0 : inf.getEscapeCharacter().length());

                boolean encl_found;
                boolean contains_escaped_enclosures = false;
                boolean contains_escaped_separators = false;

                // Is the field beginning with an enclosure?
                // "aa;aa";123;"aaa-aaa";000;...
                if (len_encl > 0
                        && line.substring(from, from + len_encl).equalsIgnoreCase(inf.getEnclosure())) {
                    if (log.isRowLevel())
                        log.logRowlevel("convert line to row",
                                "encl substring=[" + line.substring(from, from + len_encl) + "]");
                    encl_found = true;
                    int p = from + len_encl;

                    boolean is_enclosure = len_encl > 0 && p + len_encl < length
                            && line.substring(p, p + len_encl).equalsIgnoreCase(inf.getEnclosure());
                    boolean is_escape = len_esc > 0 && p + len_esc < length
                            && line.substring(p, p + len_esc).equalsIgnoreCase(inf.getEscapeCharacter());

                    boolean enclosure_after = false;

                    // Is it really an enclosure? See if it's not repeated twice or escaped!
                    if ((is_enclosure || is_escape) && p < length - 1) {
                        String strnext = line.substring(p + len_encl, p + 2 * len_encl);
                        if (strnext.equalsIgnoreCase(inf.getEnclosure())) {
                            p++;
                            enclosure_after = true;
                            dencl = true;

                            // Remember to replace them later on!
                            if (is_escape)
                                contains_escaped_enclosures = true;
                        }
                    }

                    // Look for a closing enclosure!
                    while ((!is_enclosure || enclosure_after) && p < line.length()) {
                        p++;
                        enclosure_after = false;
                        is_enclosure = len_encl > 0 && p + len_encl < length
                                && line.substring(p, p + len_encl).equals(inf.getEnclosure());
                        is_escape = len_esc > 0 && p + len_esc < length
                                && line.substring(p, p + len_esc).equals(inf.getEscapeCharacter());

                        // Is it really an enclosure? See if it's not repeated twice or escaped!
                        if ((is_enclosure || is_escape) && p < length - 1) // Is
                        {
                            String strnext = line.substring(p + len_encl, p + 2 * len_encl);
                            if (strnext.equals(inf.getEnclosure())) {
                                p++;
                                enclosure_after = true;
                                dencl = true;

                                // Remember to replace them later on!
                                if (is_escape)
                                    contains_escaped_enclosures = true; // remember
                            }
                        }
                    }

                    if (p >= length)
                        next = p;
                    else
                        next = p + len_encl;

                    if (log.isRowLevel())
                        log.logRowlevel("convert line to row", "End of enclosure @ position " + p);
                } else {
                    encl_found = false;
                    boolean found = false;
                    int startpoint = from;
                    int tries = 1;
                    do {
                        next = line.indexOf(inf.getSeparator(), startpoint);

                        // See if this position is preceded by an escape character.
                        if (len_esc > 0 && next - len_esc > 0) {
                            String before = line.substring(next - len_esc, next);

                            if (inf.getEscapeCharacter().equals(before)) {
                                // take the next separator, this one is escaped...
                                startpoint = next + 1;
                                tries++;
                                contains_escaped_separators = true;
                            } else {
                                found = true;
                            }
                        } else {
                            found = true;
                        }
                    } while (!found && next >= 0);
                }
                if (next == -1)
                    next = length;

                if (encl_found) {
                    pol = line.substring(from + len_encl, next - len_encl);
                    if (log.isRowLevel())
                        log.logRowlevel("convert line to row", "Enclosed field found: [" + pol + "]");
                } else {
                    pol = line.substring(from, next);
                    if (log.isRowLevel())
                        log.logRowlevel("convert line to row", "Normal field found: [" + pol + "]");
                }

                if (dencl) {
                    StringBuffer sbpol = new StringBuffer(pol);
                    int idx = sbpol.indexOf(inf.getEnclosure() + inf.getEnclosure());
                    while (idx >= 0) {
                        sbpol.delete(idx, idx + inf.getEnclosure().length());
                        idx = sbpol.indexOf(inf.getEnclosure() + inf.getEnclosure());
                    }
                    pol = sbpol.toString();
                }

                //   replace the escaped enclosures with enclosures... 
                if (contains_escaped_enclosures) {
                    String replace = inf.getEscapeCharacter() + inf.getEnclosure();
                    String replaceWith = inf.getEnclosure();

                    pol = Const.replace(pol, replace, replaceWith);
                }

                //replace the escaped separators with separators... 
                if (contains_escaped_separators) {
                    String replace = inf.getEscapeCharacter() + inf.getSeparator();
                    String replaceWith = inf.getSeparator();

                    pol = Const.replace(pol, replace, replaceWith);
                }

                // Now add pol to the strings found!
                strings.add(pol);

                pos = next + 1;
                fieldnr++;
            }
            if (pos == length) {
                if (log.isRowLevel())
                    log.logRowlevel("convert line to row", "End of line empty field found: []");
                strings.add("");
            }
        } else {
            // Fixed file format: Simply get the strings at the required positions...
            for (int i = 0; i < inf.getInputFields().length; i++) {
                TextFileInputField field = inf.getInputFields()[i];

                int length = line.length();

                if (field.getPosition() + field.getLength() <= length) {
                    strings.add(line.substring(field.getPosition(), field.getPosition() + field.getLength()));
                } else {
                    if (field.getPosition() < length) {
                        strings.add(line.substring(field.getPosition()));
                    } else {
                        strings.add("");
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new KettleException("Error converting line : " + e.toString(), e);
    }

    return strings;
}

From source file:org.displaytag.model.Column.java

/**
 * Calculates the cell content, cropping or linking the value as needed.
 * // ww w . ja v a  2  s.  com
 * @return String
 * @throws ObjectLookupException for errors in bean property lookup
 * @throws DecoratorException if a column decorator is used and an exception is thrown during value decoration
 */
public String createChoppedAndLinkedValue() throws ObjectLookupException, DecoratorException {

    String fullValue = ObjectUtils.toString(this.getValue(true));
    String choppedValue;

    // are we supposed to set up a link to the data being displayed in this column?
    if (this.header.getAutoLink()) {
        fullValue = AutolinkColumnDecorator.INSTANCE.decorate(fullValue);
    }

    // trim the string if a maxLength or maxWords is defined
    if (this.header.getMaxLength() > 0) {
        choppedValue = HtmlTagUtil.abbreviateHtmlString(fullValue, this.header.getMaxLength(), false);
    } else if (this.header.getMaxWords() > 0) {
        choppedValue = HtmlTagUtil.abbreviateHtmlString(fullValue, this.header.getMaxWords(), true);
    } else {
        choppedValue = fullValue;
    }

    // chopped content? add the full content to the column "title" attribute
    if (choppedValue.length() < fullValue.length()) {
        // clone the attribute map, don't want to add title to all the columns
        this.htmlAttributes = (HtmlAttributeMap) this.htmlAttributes.clone();
        // add title
        this.htmlAttributes.put(TagConstants.ATTRIBUTE_TITLE, HtmlTagUtil.stripHTMLTags(fullValue));
    }

    if (this.header.getHref() != null) {
        // generates the href for the link
        Href colHref = this.getColumnHref(fullValue);
        Anchor anchor = new Anchor(colHref, choppedValue);
        choppedValue = anchor.toString();

        // SIGESP verifica se hrefType = replace
        if (this.header.getHrefType() != null && this.header.getHrefType().equals("replace")) {

            String strTmp = choppedValue;

            Object valor = LookupUtil.getBeanProperty(this.row.getObject(), this.header.getParamProperty());
            String strValor = "";
            if (valor == null) {
                strValor = "NULL";
            } else {
                // Tratar aspas simples (retorno do javascript)
                strValor = Conversao.substituirExpressaoString(valor.toString(), "'", "\\u0027");
            }

            int intPosicao = -1;

            StringBuffer stbNovaString = new StringBuffer(strTmp);

            while ((intPosicao = stbNovaString.indexOf(this.header.getParamName())) >= 0) {
                stbNovaString.replace(intPosicao, intPosicao + this.header.getParamName().length(),
                        strValor.toString());
            }

            int intPosicaoIgual = stbNovaString.indexOf(strValor.toString() + "=");

            if (intPosicaoIgual != -1) {
                stbNovaString.replace(intPosicaoIgual - 1,
                        intPosicaoIgual - 1 + stbNovaString.substring(intPosicaoIgual - 1).indexOf(">") - 1,
                        ";");
                // stbNovaString.replace(stbNovaString.indexOf(valor.toString() + "=" + valor.toString()) - 1,
                // stbNovaString.substring(stbNovaString.indexOf(valor.toString() + "=" + valor.toString()) -
                // 1).indexOf(">"), ";");
            } else {
                throw new RuntimeException("Os parmetros informados na display-tag esto incorretos");
            }

            choppedValue = stbNovaString.toString();
        }
    }

    return choppedValue;
}

From source file:eionet.cr.web.util.JstlFunctions.java

/**
 * Returns a string that is constructed by concatenating the given bean request's getRequestURI() + "?" + the given bean
 * request's getQueryString(), and replacing the sort predicate with the given one. The present sort order is replaced by the
 * opposite./*from  w w  w . j  av  a  2 s.  com*/
 *
 * @param request
 * @param sortP
 * @param sortO
 * @return
 */
public static String sortUrl(AbstractActionBean actionBean, SearchResultColumn column) {

    HttpServletRequest request = actionBean.getContext().getRequest();
    StringBuffer buf = new StringBuffer(actionBean.getUrlBinding());
    buf.append("?");
    if (StringUtils.isBlank(column.getActionRequestParameter())) {

        if (!StringUtils.isBlank(request.getQueryString())) {

            QueryString queryString = QueryString.createQueryString(request);
            queryString.removeParameters(actionBean.excludeFromSortAndPagingUrls());
            buf.append(queryString.toURLFormat());
        }
    } else {
        buf.append(column.getActionRequestParameter());
    }

    String sortParamValue = column.getSortParamValue();
    if (sortParamValue == null) {
        sortParamValue = "";
    }

    String curValue = request.getParameter("sortP");
    if (curValue != null && buf.indexOf("sortP=") > 0) {
        buf = new StringBuffer(StringUtils.replace(buf.toString(), "sortP=" + Util.urlEncode(curValue),
                "sortP=" + Util.urlEncode(sortParamValue)));
    } else {
        buf.append("&amp;sortP=").append(Util.urlEncode(sortParamValue));
    }

    curValue = request.getParameter("sortO");
    if (curValue != null && buf.indexOf("sortO=") > 0) {
        buf = new StringBuffer(StringUtils.replace(buf.toString(), "sortO=" + curValue,
                "sortO=" + SortOrder.oppositeSortOrder(curValue)));
    } else {
        buf.append("&amp;sortO=").append(SortOrder.oppositeSortOrder(curValue));
    }

    String result = buf.toString();
    return result.startsWith("/") ? result.substring(1) : result;
}

From source file:StringUtils.java

/**
 * Method return boolean result if particular substring is contained within
 * the list of substrings separated by a separator.
 * // w ww . j a v  a 2s  . co m
 * @param strSearchIn -
 *          string of all substrings separated by separator to search in
 * @param strSearchFor -
 *          string that will be search for
 * @param strSeparator -
 *          item separator
 * @return boolean - true if it contains the ID, false otherwise
 */
public static boolean containsInSeparatedString(String strSearchIn, String strSearchFor, String strSeparator) {
    boolean bReturn = false;

    StringBuffer sbInputString = new StringBuffer();
    StringBuffer sbSearchString = new StringBuffer();

    if (strSearchIn.length() > 0) {
        // add separator at the beginning and end of the input string
        sbInputString.append(strSeparator);
        sbInputString.append(strSearchIn);
        sbInputString.append(strSeparator);

        // add separator at the beginning and end of the search string
        sbSearchString.append(strSeparator);
        sbSearchString.append(strSearchFor);
        sbSearchString.append(strSeparator);

        // search for particular ID
        if (sbInputString.indexOf(sbSearchString.toString()) != -1) {
            bReturn = true;
        }
    }

    return bReturn;
}