List of usage examples for org.apache.commons.lang3 StringUtils replaceChars
public static String replaceChars(final String str, final String searchChars, String replaceChars)
Replaces multiple characters in a String in one go.
From source file:cgeo.geocaching.connector.gc.GCParser.java
static SearchResult parseCacheFromText(final String pageIn, final CancellableHandler handler) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_details); if (StringUtils.isBlank(pageIn)) { Log.e("GCParser.parseCache: No page given"); return null; }// w ww . j a v a 2 s . c o m final SearchResult searchResult = new SearchResult(); if (pageIn.contains(GCConstants.STRING_UNPUBLISHED_OTHER) || pageIn.contains(GCConstants.STRING_UNPUBLISHED_FROM_SEARCH)) { searchResult.setError(StatusCode.UNPUBLISHED_CACHE); return searchResult; } if (pageIn.contains(GCConstants.STRING_PREMIUMONLY_1) || pageIn.contains(GCConstants.STRING_PREMIUMONLY_2)) { searchResult.setError(StatusCode.PREMIUM_ONLY); return searchResult; } final String cacheName = Html.fromHtml(TextUtils.getMatch(pageIn, GCConstants.PATTERN_NAME, true, "")) .toString(); if (GCConstants.STRING_UNKNOWN_ERROR.equalsIgnoreCase(cacheName)) { searchResult.setError(StatusCode.UNKNOWN_ERROR); return searchResult; } // first handle the content with line breaks, then trim everything for easier matching and reduced memory consumption in parsed fields String personalNoteWithLineBreaks = ""; MatcherWrapper matcher = new MatcherWrapper(GCConstants.PATTERN_PERSONALNOTE, pageIn); if (matcher.find()) { personalNoteWithLineBreaks = matcher.group(1).trim(); } final String page = TextUtils.replaceWhitespace(pageIn); final Geocache cache = new Geocache(); cache.setDisabled(page.contains(GCConstants.STRING_DISABLED)); cache.setArchived(page.contains(GCConstants.STRING_ARCHIVED)); cache.setPremiumMembersOnly(TextUtils.matches(page, GCConstants.PATTERN_PREMIUMMEMBERS)); cache.setFavorite(TextUtils.matches(page, GCConstants.PATTERN_FAVORITE)); // cache geocode cache.setGeocode(TextUtils.getMatch(page, GCConstants.PATTERN_GEOCODE, true, cache.getGeocode())); // cache id cache.setCacheId(TextUtils.getMatch(page, GCConstants.PATTERN_CACHEID, true, cache.getCacheId())); // cache guid cache.setGuid(TextUtils.getMatch(page, GCConstants.PATTERN_GUID, true, cache.getGuid())); // name cache.setName(cacheName); // owner real name cache.setOwnerUserId(Network .decode(TextUtils.getMatch(page, GCConstants.PATTERN_OWNER_USERID, true, cache.getOwnerUserId()))); cache.setUserModifiedCoords(false); String tableInside = page; final int pos = tableInside.indexOf(GCConstants.STRING_CACHEDETAILS); if (pos == -1) { Log.e("GCParser.parseCache: ID \"cacheDetails\" not found on page"); return null; } tableInside = tableInside.substring(pos); if (StringUtils.isNotBlank(tableInside)) { // cache terrain String result = TextUtils.getMatch(tableInside, GCConstants.PATTERN_TERRAIN, true, null); if (result != null) { try { cache.setTerrain(Float.parseFloat(StringUtils.replaceChars(result, '_', '.'))); } catch (final NumberFormatException e) { Log.e("Error parsing terrain value", e); } } // cache difficulty result = TextUtils.getMatch(tableInside, GCConstants.PATTERN_DIFFICULTY, true, null); if (result != null) { try { cache.setDifficulty(Float.parseFloat(StringUtils.replaceChars(result, '_', '.'))); } catch (final NumberFormatException e) { Log.e("Error parsing difficulty value", e); } } // owner cache.setOwnerDisplayName(StringEscapeUtils.unescapeHtml4(TextUtils.getMatch(tableInside, GCConstants.PATTERN_OWNER_DISPLAYNAME, true, cache.getOwnerDisplayName()))); // hidden try { String hiddenString = TextUtils.getMatch(tableInside, GCConstants.PATTERN_HIDDEN, true, null); if (StringUtils.isNotBlank(hiddenString)) { cache.setHidden(GCLogin.parseGcCustomDate(hiddenString)); } if (cache.getHiddenDate() == null) { // event date hiddenString = TextUtils.getMatch(tableInside, GCConstants.PATTERN_HIDDENEVENT, true, null); if (StringUtils.isNotBlank(hiddenString)) { cache.setHidden(GCLogin.parseGcCustomDate(hiddenString)); } } } catch (final ParseException e) { // failed to parse cache hidden date Log.w("GCParser.parseCache: Failed to parse cache hidden (event) date"); } // favorite try { cache.setFavoritePoints(Integer .parseInt(TextUtils.getMatch(tableInside, GCConstants.PATTERN_FAVORITECOUNT, true, "0"))); } catch (final NumberFormatException e) { Log.e("Error parsing favorite count", e); } // cache size cache.setSize(CacheSize.getById( TextUtils.getMatch(tableInside, GCConstants.PATTERN_SIZE, true, CacheSize.NOT_CHOSEN.id))); } // cache found cache.setFound(TextUtils.matches(page, GCConstants.PATTERN_FOUND) || TextUtils.matches(page, GCConstants.PATTERN_FOUND_ALTERNATIVE)); // cache found date try { final String foundDateString = TextUtils.getMatch(page, GCConstants.PATTERN_FOUND_DATE, true, null); if (StringUtils.isNotBlank(foundDateString)) { cache.setVisitedDate(GCLogin.parseGcCustomDate(foundDateString).getTime()); } } catch (final ParseException e) { // failed to parse cache found date Log.w("GCParser.parseCache: Failed to parse cache found date"); } // cache type cache.setType(CacheType .getByPattern(TextUtils.getMatch(page, GCConstants.PATTERN_TYPE, true, cache.getType().id))); // on watchlist cache.setOnWatchlist(TextUtils.matches(page, GCConstants.PATTERN_WATCHLIST)); // latitude and longitude. Can only be retrieved if user is logged in String latlon = TextUtils.getMatch(page, GCConstants.PATTERN_LATLON, true, ""); if (StringUtils.isNotEmpty(latlon)) { try { cache.setCoords(new Geopoint(latlon)); cache.setReliableLatLon(true); } catch (final Geopoint.GeopointException e) { Log.w("GCParser.parseCache: Failed to parse cache coordinates", e); } } // cache location cache.setLocation(TextUtils.getMatch(page, GCConstants.PATTERN_LOCATION, true, "")); // cache hint final String result = TextUtils.getMatch(page, GCConstants.PATTERN_HINT, false, null); if (result != null) { // replace linebreak and paragraph tags final String hint = GCConstants.PATTERN_LINEBREAK.matcher(result).replaceAll("\n"); cache.setHint(StringUtils.replace(hint, "</p>", "").trim()); } cache.checkFields(); // cache personal note cache.setPersonalNote(personalNoteWithLineBreaks); // cache short description cache.setShortDescription(TextUtils.getMatch(page, GCConstants.PATTERN_SHORTDESC, true, "")); // cache description cache.setDescription(TextUtils.getMatch(page, GCConstants.PATTERN_DESC, true, "")); // cache attributes try { final String attributesPre = TextUtils.getMatch(page, GCConstants.PATTERN_ATTRIBUTES, true, null); if (null != attributesPre) { final MatcherWrapper matcherAttributesInside = new MatcherWrapper( GCConstants.PATTERN_ATTRIBUTESINSIDE, attributesPre); final ArrayList<String> attributes = new ArrayList<String>(); while (matcherAttributesInside.find()) { if (matcherAttributesInside.groupCount() > 1 && !matcherAttributesInside.group(2).equalsIgnoreCase("blank")) { // by default, use the tooltip of the attribute String attribute = matcherAttributesInside.group(2).toLowerCase(Locale.US); // if the image name can be recognized, use the image name as attribute final String imageName = matcherAttributesInside.group(1).trim(); if (StringUtils.isNotEmpty(imageName)) { final int start = imageName.lastIndexOf('/'); final int end = imageName.lastIndexOf('.'); if (start >= 0 && end >= 0) { attribute = imageName.substring(start + 1, end).replace('-', '_') .toLowerCase(Locale.US); } } attributes.add(attribute); } } cache.setAttributes(attributes); } } catch (final RuntimeException e) { // failed to parse cache attributes Log.w("GCParser.parseCache: Failed to parse cache attributes"); } // cache spoilers try { if (CancellableHandler.isCancelled(handler)) { return null; } CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_spoilers); final MatcherWrapper matcherSpoilersInside = new MatcherWrapper(GCConstants.PATTERN_SPOILER_IMAGE, page); while (matcherSpoilersInside.find()) { // the original spoiler URL (include .../display/... contains a low-resolution image // if we shorten the URL we get the original-resolution image final String url = matcherSpoilersInside.group(1).replace("/display", ""); String title = null; if (matcherSpoilersInside.group(3) != null) { title = matcherSpoilersInside.group(3); } String description = null; if (matcherSpoilersInside.group(4) != null) { description = matcherSpoilersInside.group(4); } cache.addSpoiler(new Image(url, title, description)); } } catch (final RuntimeException e) { // failed to parse cache spoilers Log.w("GCParser.parseCache: Failed to parse cache spoilers"); } // cache inventory try { cache.setInventoryItems(0); final MatcherWrapper matcherInventory = new MatcherWrapper(GCConstants.PATTERN_INVENTORY, page); if (matcherInventory.find()) { if (cache.getInventory() == null) { cache.setInventory(new ArrayList<Trackable>()); } if (matcherInventory.groupCount() > 1) { final String inventoryPre = matcherInventory.group(2); if (StringUtils.isNotBlank(inventoryPre)) { final MatcherWrapper matcherInventoryInside = new MatcherWrapper( GCConstants.PATTERN_INVENTORYINSIDE, inventoryPre); while (matcherInventoryInside.find()) { if (matcherInventoryInside.groupCount() > 0) { final Trackable inventoryItem = new Trackable(); inventoryItem.setGuid(matcherInventoryInside.group(1)); inventoryItem.setName(matcherInventoryInside.group(2)); cache.getInventory().add(inventoryItem); cache.setInventoryItems(cache.getInventoryItems() + 1); } } } } } } catch (final RuntimeException e) { // failed to parse cache inventory Log.w("GCParser.parseCache: Failed to parse cache inventory (2)"); } // cache logs counts try { final String countlogs = TextUtils.getMatch(page, GCConstants.PATTERN_COUNTLOGS, true, null); if (null != countlogs) { final MatcherWrapper matcherLog = new MatcherWrapper(GCConstants.PATTERN_COUNTLOG, countlogs); while (matcherLog.find()) { final String typeStr = matcherLog.group(1); final String countStr = getNumberString(matcherLog.group(2)); if (StringUtils.isNotBlank(typeStr) && LogType.UNKNOWN != LogType.getByIconName(typeStr) && StringUtils.isNotBlank(countStr)) { cache.getLogCounts().put(LogType.getByIconName(typeStr), Integer.parseInt(countStr)); } } } } catch (final NumberFormatException e) { // failed to parse logs Log.w("GCParser.parseCache: Failed to parse cache log count"); } // waypoints - reset collection cache.setWaypoints(Collections.<Waypoint>emptyList(), false); // add waypoint for original coordinates in case of user-modified listing-coordinates try { final String originalCoords = TextUtils.getMatch(page, GCConstants.PATTERN_LATLON_ORIG, false, null); if (null != originalCoords) { final Waypoint waypoint = new Waypoint( CgeoApplication.getInstance().getString(R.string.cache_coordinates_original), WaypointType.ORIGINAL, false); waypoint.setCoords(new Geopoint(originalCoords)); cache.addOrChangeWaypoint(waypoint, false); cache.setUserModifiedCoords(true); } } catch (final Geopoint.GeopointException e) { } int wpBegin = page.indexOf("<table class=\"Table\" id=\"ctl00_ContentBody_Waypoints\">"); if (wpBegin != -1) { // parse waypoints if (CancellableHandler.isCancelled(handler)) { return null; } CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_waypoints); String wpList = page.substring(wpBegin); int wpEnd = wpList.indexOf("</p>"); if (wpEnd > -1 && wpEnd <= wpList.length()) { wpList = wpList.substring(0, wpEnd); } if (!wpList.contains("No additional waypoints to display.")) { wpEnd = wpList.indexOf("</table>"); wpList = wpList.substring(0, wpEnd); wpBegin = wpList.indexOf("<tbody>"); wpEnd = wpList.indexOf("</tbody>"); if (wpBegin >= 0 && wpEnd >= 0 && wpEnd <= wpList.length()) { wpList = wpList.substring(wpBegin + 7, wpEnd); } final String[] wpItems = wpList.split("<tr"); for (int j = 1; j < wpItems.length; j++) { String[] wp = wpItems[j].split("<td"); // waypoint name // res is null during the unit tests final String name = TextUtils.getMatch(wp[6], GCConstants.PATTERN_WPNAME, true, 1, CgeoApplication.getInstance().getString(R.string.waypoint), true); // waypoint type final String resulttype = TextUtils.getMatch(wp[3], GCConstants.PATTERN_WPTYPE, null); final Waypoint waypoint = new Waypoint(name, WaypointType.findById(resulttype), false); // waypoint prefix waypoint.setPrefix(TextUtils.getMatch(wp[4], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, true, 2, waypoint.getPrefix(), false)); // waypoint lookup waypoint.setLookup(TextUtils.getMatch(wp[5], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, true, 2, waypoint.getLookup(), false)); // waypoint latitude and longitude latlon = Html.fromHtml(TextUtils.getMatch(wp[7], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, false, 2, "", false)).toString().trim(); if (!StringUtils.startsWith(latlon, "???")) { waypoint.setLatlon(latlon); waypoint.setCoords(new Geopoint(latlon)); } j++; if (wpItems.length > j) { wp = wpItems[j].split("<td"); } // waypoint note waypoint.setNote(TextUtils.getMatch(wp[3], GCConstants.PATTERN_WPNOTE, waypoint.getNote())); cache.addOrChangeWaypoint(waypoint, false); } } } cache.parseWaypointsFromNote(); // logs cache.setLogs(getLogsFromDetails(page, false)); // last check for necessary cache conditions if (StringUtils.isBlank(cache.getGeocode())) { searchResult.setError(StatusCode.UNKNOWN_ERROR); return searchResult; } cache.setDetailedUpdatedNow(); searchResult.addAndPutInCache(Collections.singletonList(cache)); return searchResult; }
From source file:com.edduarte.protbox.core.registry.PReg.java
private String convertEncodedNameToRealName(String encodedName) throws ProtboxException { // perform replacements from a normal name to a RFC 3548 compliant name String rfc3548Name = encodedName; rfc3548Name = StringUtils.replaceChars(rfc3548Name, '-', '/'); rfc3548Name = StringUtils.replaceChars(rfc3548Name, '_', '+'); byte[] decryptedNameData = decrypt(Base64.decodeBase64(rfc3548Name), false); try {/* w w w .ja v a 2s . c o m*/ return new String(decryptedNameData, "UTF-8"); } catch (UnsupportedEncodingException ex) { return new String(decryptedNameData); } }
From source file:com.edduarte.protbox.core.registry.PReg.java
private String convertRealNameToEncodedName(String realName) throws ProtboxException { String encodedName;// w w w .j ava2s . c o m try { byte[] encryptedNameData = encrypt(realName.getBytes("UTF-8"), false); encodedName = new String(Base64.encodeBase64(encryptedNameData), "UTF-8"); } catch (UnsupportedEncodingException ex) { byte[] encryptedNameData = encrypt(realName.getBytes(), false); encodedName = new String(Base64.encodeBase64(encryptedNameData)); } // perform replacements from a RFC 3548 compliant name to a normal name encodedName = StringUtils.replaceChars(encodedName, '/', '-'); encodedName = StringUtils.replaceChars(encodedName, '+', '_'); return encodedName; }
From source file:cgeo.geocaching.connector.gc.GCParser.java
private static String getNumberString(final String numberWithPunctuation) { return StringUtils.replaceChars(numberWithPunctuation, ".,", ""); }
From source file:com.gargoylesoftware.htmlunit.html.HtmlElement.java
/** * Helper for src retrieval and normalization. * * @return the value of the attribute {@code src} with all line breaks removed * or an empty string if that attribute isn't defined. */// w w w. ja v a 2 s. com protected final String getSrcAttributeNormalized() { // at the moment StringUtils.replaceChars returns the org string // if nothing to replace was found but the doc implies, that we // can't trust on this in the future final String attrib = getAttribute("src"); if (ATTRIBUTE_NOT_DEFINED == attrib) { return attrib; } return StringUtils.replaceChars(attrib, "\r\n", ""); }
From source file:com.xpn.xwiki.XWiki.java
public String getSkinFile(String filename, String skin, boolean forceSkinAction, XWikiContext context) { XWikiURLFactory urlf = context.getURLFactory(); try {// w ww. ja v a2 s . co m XWikiDocument doc = getDocument(skin, context); if (!doc.isNew()) { // Look for an object property BaseObject object = doc.getXObject(new DocumentReference( doc.getDocumentReference().getWikiReference().getName(), SYSTEM_SPACE, "XWikiSkins")); if (object != null) { String content = object.getStringValue(filename); if (StringUtils.isNotBlank(content)) { URL url = urlf.createSkinURL(filename, doc.getSpace(), doc.getName(), doc.getDatabase(), context); return urlf.getURL(url, context); } } // Look for an attachment String shortName = StringUtils.replaceChars(filename, '/', '.'); XWikiAttachment attachment = doc.getAttachment(shortName); if (attachment != null) { return doc.getAttachmentURL(shortName, "skin", context); } } // Look for a skin file String path = "/skins/" + skin + "/" + filename; if (resourceExists(path)) { URL url; if (forceSkinAction) { url = urlf.createSkinURL(filename, "skins", skin, context); } else { url = urlf.createSkinURL(filename, skin, context); } return urlf.getURL(url, context); } // Look for a resource file path = "/resources/" + filename; if (resourceExists(path)) { URL url; url = urlf.createResourceURL(filename, forceSkinAction, context); return urlf.getURL(url, context); } } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Exception while getting skin file [" + filename + "] from skin [" + skin + "]", e); } } return null; }
From source file:org.apache.jena.fuseki.servlets.ResponseJson.java
private static void jsonOutput(HttpAction action, final Iterator<JsonObject> jsonItems) { OutputContent proc = new OutputContent() { @Override/*from w w w. ja v a2s .c om*/ public void output(ServletOutputStream out) { if (jsonItems != null) ResultSetFormatter.output(out, jsonItems); } }; try { String callback = ResponseOps.paramCallback(action.request); ServletOutputStream out = action.response.getOutputStream(); if (callback != null) { callback = StringUtils.replaceChars(callback, "\r", ""); callback = StringUtils.replaceChars(callback, "\n", ""); out.print(callback); out.println("("); } output(action, "application/json", WebContent.charsetUTF8, proc); if (callback != null) out.println(")"); } catch (IOException ex) { ServletOps.errorOccurred(ex); } }
From source file:org.apache.jmeter.protocol.http.util.ConversionUtils.java
/** * Extract the encoding (charset) from the Content-Type, e.g. * "text/html; charset=utf-8"./*from w w w. j a v a 2s . c om*/ * * @param contentType * string from which the encoding should be extracted * @return the charset encoding - or <code>null</code>, if none was found or * the charset is not supported * @throws IllegalCharsetNameException * if the found charset is not supported */ public static String getEncodingFromContentType(String contentType) { String charSet = null; if (contentType != null) { int charSetStartPos = contentType.toLowerCase(java.util.Locale.ENGLISH).indexOf(CHARSET_EQ); if (charSetStartPos >= 0) { charSet = contentType.substring(charSetStartPos + CHARSET_EQ_LEN); if (charSet != null) { // Remove quotes from charset name, see bug 55852 charSet = StringUtils.replaceChars(charSet, "\'\"", null); charSet = charSet.trim(); if (charSet.length() > 0) { // See Bug 44784 int semi = charSet.indexOf(';'); if (semi == 0) { return null; } if (semi != -1) { charSet = charSet.substring(0, semi); } if (!Charset.isSupported(charSet)) { return null; } return charSet; } return null; } } } return charSet; }
From source file:org.apache.jmeter.visualizers.backend.graphite.AbstractGraphiteMetricsSender.java
/** * Replaces Graphite reserved chars:// ww w .j a v a 2 s . c o m * <ul> * <li>' ' by '-'</li> * <li>'\\' by '-'</li> * <li>'.' by '_'</li> * </ul> * * @param s * text to be sanitized * @return the sanitized text */ static String sanitizeString(String s) { // String#replace uses regexp return StringUtils.replaceChars(s, "\\ .", "--_"); }
From source file:org.dbgl.util.StringRelatedUtils.java
public static String join(final int[] values) { return StringUtils.replaceChars(Arrays.toString(values), "[,]", ""); }