List of usage examples for java.lang StringBuilder indexOf
@Override public int indexOf(String str)
From source file:io.github.tavernaextras.biocatalogue.model.Util.java
/** * Appends given string at the end of the provided URL just before the list of parameters in the url. * /* w ww. j a v a2 s .c om*/ * For example, appending ".xml" to URL "http://www.sandbox.biocatalogue.org/services?tag=blast" will * yield "http://www.sandbox.biocatalogue.org/services.xml?tag=blast". * * No duplication checking is made - if the URL is already ending (before parameters) with the value of * the string to append, that string will still be appended. * * @param url URL to append the string to. * @param strToAppend The string to append. The value will be url-encode before appending. * @return New string containing modified <code>url</code> with the <code>strToAppend</code> appended * before the "query string" of the URL. */ public static String appendStringBeforeParametersOfURL(String url, String strToAppend, boolean ignoreURLEncoding) { StringBuilder modifiedURL = new StringBuilder(url); int iPositionToInsertProvidedString = modifiedURL.indexOf("?"); if (iPositionToInsertProvidedString == -1) iPositionToInsertProvidedString = modifiedURL.length(); String stringToInsert = (ignoreURLEncoding ? strToAppend : Util.urlEncodeQuery(strToAppend)); modifiedURL.insert(iPositionToInsertProvidedString, stringToInsert); return (modifiedURL.toString()); }
From source file:org.apache.carbondata.processing.csvreaderstep.CsvInput.java
/** * This method is borrowed from TextFileInput * * @param log//from w w w .j av a2s .c o m * @param line * @param delimiter * @param enclosure * @param escapeCharacter * @return * @throws KettleException */ public static final String[] guessStringsFromLine(LogChannelInterface log, String line, String delimiter, String enclosure, String escapeCharacter) throws KettleException { List<String> strings = new ArrayList<String>(CarbonCommonConstants.CONSTANT_SIZE_TEN); String pol; // piece of line try { if (line == null) { return null; } // Split string in pieces, only for CSV! int pos = 0; int length = line.length(); boolean dencl = false; int lenEncl = (enclosure == null ? 0 : enclosure.length()); int lenEsc = (escapeCharacter == null ? 0 : escapeCharacter.length()); while (pos < length) { int from = pos; int next; boolean enclFound; boolean containsEscapedEnclosures = false; boolean containsEscapedSeparators = false; // Is the field beginning with an enclosure? // "aa;aa";123;"aaa-aaa";000;... if (lenEncl > 0 && line.substring(from, from + lenEncl).equalsIgnoreCase(enclosure)) { if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRow", line.substring(from, from + lenEncl))); //$NON-NLS-1$ //$NON-NLS-2$ } enclFound = true; int p = from + lenEncl; boolean isEnclosure = lenEncl > 0 && p + lenEncl < length && line.substring(p, p + lenEncl).equalsIgnoreCase(enclosure); boolean isEscape = lenEsc > 0 && p + lenEsc < length && line.substring(p, p + lenEsc).equalsIgnoreCase(escapeCharacter); boolean enclosureAfter = false; // Is it really an enclosure? See if it's not repeated twice or escaped! if ((isEnclosure || isEscape) && p < length - 1) { String strnext = line.substring(p + lenEncl, p + 2 * lenEncl); if (strnext.equalsIgnoreCase(enclosure)) { p++; enclosureAfter = true; dencl = true; // Remember to replace them later on! if (isEscape) { containsEscapedEnclosures = true; } } } // Look for a closing enclosure! while ((!isEnclosure || enclosureAfter) && p < line.length()) { p++; enclosureAfter = false; isEnclosure = lenEncl > 0 && p + lenEncl < length && line.substring(p, p + lenEncl).equals(enclosure); isEscape = lenEsc > 0 && p + lenEsc < length && line.substring(p, p + lenEsc).equals(escapeCharacter); // Is it really an enclosure? See if it's not repeated twice or escaped! if ((isEnclosure || isEscape) && p < length - 1) // Is { String strnext = line.substring(p + lenEncl, p + 2 * lenEncl); if (strnext.equals(enclosure)) { p++; enclosureAfter = true; dencl = true; // Remember to replace them later on! if (isEscape) { containsEscapedEnclosures = true; // remember } } } } if (p >= length) { next = p; } else { next = p + lenEncl; } if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "CsvInput.Log.EndOfEnclosure", "" + p)); //$NON-NLS-2$ //$NON-NLS-2$ //$NON-NLS-3$ } } else { enclFound = false; boolean found = false; int startpoint = from; do { next = line.indexOf(delimiter, startpoint); // See if this position is preceded by an escape character. if (lenEsc > 0 && next - lenEsc > 0) { String before = line.substring(next - lenEsc, next); if (escapeCharacter != null && escapeCharacter.equals(before)) { // take the next separator, this one is escaped... startpoint = next + 1; containsEscapedSeparators = true; } else { found = true; } } else { found = true; } } while (!found && next >= 0); } if (next == -1) { next = length; } if (enclFound) { pol = line.substring(from + lenEncl, next - lenEncl); if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "CsvInput.Log.EnclosureFieldFound", "" + pol)); //$NON-NLS-2$ //$NON-NLS-2$ //$NON-NLS-3$ } } else { pol = line.substring(from, next); if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "CsvInput.Log.NormalFieldFound", "" + pol)); //$NON-NLS-2$ //$NON-NLS-2$ //$NON-NLS-3$ } } if (dencl) { StringBuilder sbpol = new StringBuilder(pol); int idx = sbpol.indexOf(enclosure + enclosure); while (idx >= 0) { sbpol.delete(idx, idx + (enclosure == null ? 0 : enclosure.length())); idx = sbpol.indexOf(enclosure + enclosure); } pol = sbpol.toString(); } // replace the escaped enclosures with enclosures... if (containsEscapedEnclosures) { String replace = escapeCharacter + enclosure; String replaceWith = enclosure; pol = Const.replace(pol, replace, replaceWith); } //replace the escaped separators with separators... if (containsEscapedSeparators) { String replace = escapeCharacter + delimiter; String replaceWith = delimiter; pol = Const.replace(pol, replace, replaceWith); } // Now add pol to the strings found! strings.add(pol); pos = next + delimiter.length(); } if (pos == length) { if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "CsvInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "CsvInput.Log.EndOfEmptyLineFound")); } strings.add(""); //$NON-NLS-1$ } } catch (Exception e) { throw new KettleException( BaseMessages.getString(PKG, "CsvInput.Log.Error.ErrorConvertingLine", e.toString()), e); //$NON-NLS-1$ } return strings.toArray(new String[strings.size()]); }
From source file:org.eclipse.jubula.client.archive.XmlStorage.java
/** * @param xmlData the contents of the import file * @return the xmlData without the header * @throws XmlException if no header available or the version doesn't match *//* w ww.j ava 2 s . com*/ private static String checkAndReduceXmlHeader(StringBuilder xmlData) throws XmlException { int startPos = xmlData.indexOf(XML_HEADER_START); int endPos = xmlData.indexOf(XML_HEADER_END); if (startPos != 0 || endPos == -1) { // wrong header, probably invalid throw new XmlException(Messages.NoHeaderFound); } endPos += XML_HEADER_END.length(); return xmlData.substring(endPos); }
From source file:eu.dasish.annotation.backend.Helpers.java
public static StringBuilder replaceString(StringBuilder source, String oldFragment, Object newObject) { if (oldFragment != null) { int lengthOld = oldFragment.length(); String newFragment;// w ww.ja va 2 s. com if (newObject != null) { if (newObject instanceof Integer) { newFragment = ((Integer) newObject).toString(); } else { if (newObject instanceof String) { newFragment = (String) newObject; } else { newFragment = newObject.toString(); } } } else { newFragment = " "; } int lengthNew = newFragment.length(); int indexOf = source.indexOf(oldFragment); while (indexOf > 0) { source.delete(indexOf, indexOf + lengthOld); source.insert(indexOf, newFragment); indexOf = source.indexOf(oldFragment, indexOf + lengthNew); } } return source; }
From source file:org.eclipse.wb.internal.core.editor.errors.report2.EnvironmentFileReportInfo.java
/** * Returns the contents of '/etc/lsb-release' (and/or others). *//*from w ww .ja v a2 s. c om*/ private static String getLinuxDescription() { StringBuilder result = new StringBuilder(); if (EnvironmentUtils.IS_LINUX) { String[] files = new String[] { "/etc/lsb-release", "/etc/lsb_release", "/etc/system-release", "/etc/fedora-release", "/etc/SuSE-release", "/etc/redhat-release", "/etc/release", "/proc/version_signature", "/proc/version", "/etc/issue", }; for (int i = 0; i < files.length; i++) { File file = new File(files[i]); if (file.exists() && file.canRead()) { try { String version = IOUtils2.readString(file).trim(); if (version != null && result.indexOf(version) == -1) { result.append(version); result.append("\n"); } } catch (Throwable e) { // just ignore } } } } return result.toString(); }
From source file:ca.uhn.fhir.rest.method.MethodUtil.java
private static void parseTagValue(TagList theTagList, String theCompleteHeaderValue, StringBuilder theBuffer) { int firstSemicolon = theBuffer.indexOf(";"); int deleteTo; if (firstSemicolon == -1) { firstSemicolon = theBuffer.indexOf(","); if (firstSemicolon == -1) { firstSemicolon = theBuffer.length(); deleteTo = theBuffer.length(); } else {//from w w w .j a v a 2 s . c o m deleteTo = firstSemicolon; } } else { deleteTo = firstSemicolon + 1; } String term = theBuffer.substring(0, firstSemicolon); String scheme = null; String label = null; if (isBlank(term)) { return; } theBuffer.delete(0, deleteTo); while (theBuffer.length() > 0 && theBuffer.charAt(0) == ' ') { theBuffer.deleteCharAt(0); } while (theBuffer.length() > 0) { boolean foundSomething = false; if (theBuffer.length() > SCHEME.length() && theBuffer.substring(0, SCHEME.length()).equals(SCHEME)) { int closeIdx = theBuffer.indexOf("\"", SCHEME.length()); scheme = theBuffer.substring(SCHEME.length(), closeIdx); theBuffer.delete(0, closeIdx + 1); foundSomething = true; } if (theBuffer.length() > LABEL.length() && theBuffer.substring(0, LABEL.length()).equals(LABEL)) { int closeIdx = theBuffer.indexOf("\"", LABEL.length()); label = theBuffer.substring(LABEL.length(), closeIdx); theBuffer.delete(0, closeIdx + 1); foundSomething = true; } // TODO: support enc2231-string as described in // http://tools.ietf.org/html/draft-johnston-http-category-header-02 // TODO: support multiple tags in one header as described in // http://hl7.org/implement/standards/fhir/http.html#tags while (theBuffer.length() > 0 && (theBuffer.charAt(0) == ' ' || theBuffer.charAt(0) == ';')) { theBuffer.deleteCharAt(0); } if (!foundSomething) { break; } } if (theBuffer.length() > 0 && theBuffer.charAt(0) == ',') { theBuffer.deleteCharAt(0); while (theBuffer.length() > 0 && theBuffer.charAt(0) == ' ') { theBuffer.deleteCharAt(0); } theTagList.add(new Tag(scheme, term, label)); parseTagValue(theTagList, theCompleteHeaderValue, theBuffer); } else { theTagList.add(new Tag(scheme, term, label)); } if (theBuffer.length() > 0) { ourLog.warn("Ignoring extra text at the end of " + Constants.HEADER_CATEGORY + " tag '" + theBuffer.toString() + "' - Complete tag value was: " + theCompleteHeaderValue); } }
From source file:org.wildfly.test.manual.elytron.seccontext.AbstractSecurityContextPropagationTestBase.java
private static void addQueryParam(StringBuilder sb, String paramName, String paramValue) { final String encodedPair = Utils.encodeQueryParam(paramName, paramValue); if (encodedPair != null) { sb.append(sb.indexOf("?") < 0 ? "?" : "&").append(encodedPair); }/*from w w w . j a v a 2 s . c o m*/ }
From source file:pl.nask.hsn2.normalizers.URLNormalizerUtils.java
public static String normalizeQuery(StringBuilder sb, int startIndx, int endIndx) throws URLMalformedInputException { if (sb.indexOf("?") != 0) { throw new URLMalformedInputException("Query should start with '?'"); }//from w w w. j a v a 2 s . c o m int end = findFirstMatch(sb, "#", startIndx); if (end < 0 || end > endIndx) { end = endIndx; } StringBuilder enc = new StringBuilder(sb.substring(startIndx, end)); removeObfuscatedEncoding(enc, new EncodingType[] { EncodingType.PLUS_AS_SPACE, EncodingType.QUERY_ALLOWED }); int i = findFirstMatch(enc, "%", 0); try { if (i < 0) { String tmp = URIUtil.encodeQuery(enc.toString(), DEFAULT_CHARSET); enc.replace(0, enc.length(), tmp); } else { int start = 0; String tmp = ""; while ((i = findFirstMatch(enc, "%", start)) > 0) { if (percentEnc.matcher(enc.substring(i)).matches()) { tmp = URIUtil.encodeQuery(enc.substring(start, i), DEFAULT_CHARSET); enc.replace(start, i, tmp); start = i + 1 - (tmp.length() - (i - start)); } else { enc.replace(i, i + 1, "%25"); start = i + 1; } } tmp = URIUtil.encodeQuery(enc.substring(start), DEFAULT_CHARSET); enc.replace(start, enc.length(), tmp); } } catch (URIException e) { throw new URLMalformedInputException(e); } i = 0; while ((i = findFirstMatch(enc, ";", i)) > 0) { enc.replace(i, i + 1, "&"); } i = 0; while ((i = findFirstMatch(enc, "+ ", i)) > 0) { enc.replace(i, i + 1, "%20"); } sb.replace(startIndx, end, enc.toString()); return enc.toString(); }
From source file:pl.nask.hsn2.normalizers.URLNormalizerUtils.java
private static int getIPv6EndIndex(StringBuilder sb) throws URLHostParseException { int beg, end; if (findFirstMatch(sb, "[]", 0) >= 0) { beg = sb.indexOf("["); end = sb.indexOf("]"); if (beg * end < 0 || beg >= end) { throw new URLHostParseException("Brackets '[]' dont match" + sb.toString()); }//w w w . j a v a 2 s. c o m if (end < 0) { end = sb.length(); } } else { beg = -1; int tmp = findFirstMatch(sb, "/?#", 1); if (tmp > 0) { end = tmp; } else { end = sb.length(); } } int dc = sb.indexOf("::", beg + 1); if (dc > end - 2) { dc = -1; } String t[] = sb.substring(beg + 1, end).split(":"); if (t[0].isEmpty() && dc != beg + 1) { throw new URLHostParseException("Incorrect IPv6:" + sb.substring(beg + 1, end)); } if (dc == -1) { int dot = findFirstMatch(sb, ".", beg + 1, end); if (dot == -1 && t.length != 8) { throw new URLHostParseException(); } } return end; }
From source file:fr.paris.lutece.plugins.search.solr.web.SolrSearchApp.java
/** * Performs a search and fills the model (useful when a page needs to remind * search parameters/results)//from w ww.java 2s .c om * * @param request the request * @param conf the configuration * @return the model * @throws SiteMessageException if an error occurs */ public static Map<String, Object> getSearchResultModel(HttpServletRequest request, SolrSearchAppConf conf) throws SiteMessageException { String strQuery = request.getParameter(PARAMETER_QUERY); String[] facetQuery = request.getParameterValues(PARAMETER_FACET_QUERY); String sort = request.getParameter(PARAMETER_SORT_NAME); String order = request.getParameter(PARAMETER_SORT_ORDER); String strCurrentPageIndex = request.getParameter(PARAMETER_PAGE_INDEX); String fname = StringUtils.isBlank(request.getParameter(PARAMETER_FACET_NAME)) ? null : request.getParameter(PARAMETER_FACET_LABEL).trim(); String flabel = StringUtils.isBlank(request.getParameter(PARAMETER_FACET_LABEL)) ? null : request.getParameter(PARAMETER_FACET_LABEL).trim(); String strConfCode = request.getParameter(PARAMETER_CONF); Locale locale = request.getLocale(); if (conf == null) { //Use default conf if not provided conf = SolrSearchAppConfService.loadConfiguration(null); } StringBuilder sbFacetQueryUrl = new StringBuilder(); SolrFieldManager sfm = new SolrFieldManager(); List<String> lstSingleFacetQueries = new ArrayList<String>(); Hashtable<String, Boolean> switchType = getSwitched(); ArrayList<String> facetQueryTmp = new ArrayList<String>(); if (facetQuery != null) { for (String fq : facetQuery) { if (sbFacetQueryUrl.indexOf(fq) == -1) { String strFqNameIHM = getFacetNameFromIHM(fq); String strFqValueIHM = getFacetValueFromIHM(fq); if (fname == null || !switchType.containsKey(fname) || (strFqNameIHM != null && strFqValueIHM != null && strFqValueIHM.equalsIgnoreCase(flabel) && strFqNameIHM.equalsIgnoreCase(fname))) { sbFacetQueryUrl.append("&fq=" + fq); sfm.addFacet(fq); facetQueryTmp.add(fq); lstSingleFacetQueries.add(fq); } } } // for (String fq : facetQuery) // { // if (sbFacetQueryUrl.indexOf(fq) == -1) // { // // sbFacetQueryUrl.append("&fq=" + fq); // sfm.addFacet(fq); // lstSingleFacetQueries.add(fq); // } // } } facetQuery = new String[facetQueryTmp.size()]; facetQuery = facetQueryTmp.toArray(facetQuery); if (StringUtils.isNotBlank(conf.getFilterQuery())) { int nNewLength = (facetQuery == null) ? 1 : (facetQuery.length + 1); String[] newFacetQuery = new String[nNewLength]; for (int i = 0; i < (nNewLength - 1); i++) { newFacetQuery[i] = facetQuery[i]; } newFacetQuery[newFacetQuery.length - 1] = conf.getFilterQuery(); facetQuery = newFacetQuery; } boolean bEncodeUri = Boolean.parseBoolean( AppPropertiesService.getProperty(PROPERTY_ENCODE_URI, Boolean.toString(DEFAULT_ENCODE_URI))); String strSearchPageUrl = AppPropertiesService.getProperty(PROPERTY_SEARCH_PAGE_URL); String strError = SolrConstants.CONSTANT_EMPTY_STRING; int nLimit = SOLR_RESPONSE_MAX; // Check XSS characters if ((strQuery != null) && (StringUtil.containsXssCharacters(strQuery))) { strError = I18nService.getLocalizedString(MESSAGE_INVALID_SEARCH_TERMS, locale); } if (StringUtils.isNotBlank(strError) || StringUtils.isBlank(strQuery)) { strQuery = ALL_SEARCH_QUERY; String strOnlyFacets = AppPropertiesService.getProperty(PROPERTY_ONLY_FACTES); if (StringUtils.isNotBlank(strError) || (((facetQuery == null) || (facetQuery.length <= 0)) && StringUtils.isNotBlank(strOnlyFacets) && SolrConstants.CONSTANT_TRUE.equals(strOnlyFacets))) { //no request and no facet selected : we show the facets but no result nLimit = 0; } } // paginator & session related elements int nDefaultItemsPerPage = AppPropertiesService.getPropertyInt(PROPERTY_RESULTS_PER_PAGE, DEFAULT_RESULTS_PER_PAGE); String strCurrentItemsPerPage = request.getParameter(PARAMETER_NB_ITEMS_PER_PAGE); int nCurrentItemsPerPage = strCurrentItemsPerPage != null ? Integer.parseInt(strCurrentItemsPerPage) : 0; int nItemsPerPage = Paginator.getItemsPerPage(request, Paginator.PARAMETER_ITEMS_PER_PAGE, nCurrentItemsPerPage, nDefaultItemsPerPage); strCurrentPageIndex = (strCurrentPageIndex != null) ? strCurrentPageIndex : DEFAULT_PAGE_INDEX; SolrSearchEngine engine = SolrSearchEngine.getInstance(); SolrFacetedResult facetedResult = engine.getFacetedSearchResults(strQuery, facetQuery, sort, order, nLimit, Integer.parseInt(strCurrentPageIndex), nItemsPerPage, SOLR_SPELLCHECK); List<SolrSearchResult> listResults = facetedResult.getSolrSearchResults(); List<HashMap<String, Object>> points = null; if (conf.getExtraMappingQuery()) { List<SolrSearchResult> listResultsGeoloc = engine.getGeolocSearchResults(strQuery, facetQuery, nLimit); points = getGeolocModel(listResultsGeoloc); } // The page should not be added to the cache // Notify results infos to QueryEventListeners notifyQueryListeners(strQuery, listResults.size(), request); UrlItem url = new UrlItem(strSearchPageUrl); String strQueryForPaginator = strQuery; if (bEncodeUri) { strQueryForPaginator = SolrUtil.encodeUrl(request, strQuery); } url.addParameter(PARAMETER_QUERY, strQueryForPaginator); url.addParameter(PARAMETER_NB_ITEMS_PER_PAGE, nItemsPerPage); if (strConfCode != null) { url.addParameter(PARAMETER_CONF, strConfCode); } for (String strFacetName : lstSingleFacetQueries) { url.addParameter(PARAMETER_FACET_QUERY, SolrUtil.encodeUrl(strFacetName)); } // nb items per page IPaginator<SolrSearchResult> paginator = new DelegatePaginator<SolrSearchResult>(listResults, nItemsPerPage, url.getUrl(), PARAMETER_PAGE_INDEX, strCurrentPageIndex, facetedResult.getCount()); Map<String, Object> model = new HashMap<String, Object>(); model.put(MARK_RESULTS_LIST, paginator.getPageItems()); // put the query only if it's not *.* model.put(MARK_QUERY, ALL_SEARCH_QUERY.equals(strQuery) ? SolrConstants.CONSTANT_EMPTY_STRING : strQuery); model.put(MARK_FACET_QUERY, sbFacetQueryUrl.toString()); model.put(MARK_PAGINATOR, paginator); model.put(MARK_NB_ITEMS_PER_PAGE, nItemsPerPage); model.put(MARK_ERROR, strError); model.put(MARK_FACETS, facetedResult.getFacetFields()); model.put(MARK_SOLR_FIELDS, SolrFieldManager.getFacetList()); model.put(MARK_FACETS_DATE, facetedResult.getFacetDateList()); model.put(MARK_HISTORIQUE, sfm.getCurrentFacet()); model.put(MARK_FACETS_LIST, lstSingleFacetQueries); model.put(MARK_CONF_QUERY, strConfCode); model.put(MARK_CONF, conf); model.put(MARK_POINTS, points); if (SOLR_SPELLCHECK && (strQuery != null) && (strQuery.compareToIgnoreCase(ALL_SEARCH_QUERY) != 0)) { SpellCheckResponse checkResponse = engine.getSpellChecker(strQuery); if (checkResponse != null) { model.put(MARK_SUGGESTION, checkResponse.getCollatedResults()); //model.put(MARK_SUGGESTION, facetedResult.getSolrSpellCheckResponse().getCollatedResults()); } } model.put(MARK_SORT_NAME, sort); model.put(MARK_SORT_ORDER, order); model.put(MARK_SORT_LIST, SolrFieldManager.getSortList()); model.put(MARK_FACET_TREE, facetedResult.getFacetIntersection()); model.put(MARK_ENCODING, SolrUtil.getEncoding()); String strRequestUrl = request.getRequestURL().toString(); model.put(FULL_URL, strRequestUrl); model.put(SOLR_FACET_DATE_GAP, SolrSearchEngine.SOLR_FACET_DATE_GAP); return model; }