List of usage examples for org.apache.commons.lang3 StringUtils replace
public static String replace(final String text, final String searchString, final String replacement)
Replaces all occurrences of a String within another String.
A null reference passed to this method is a no-op.
StringUtils.replace(null, *, *) = null StringUtils.replace("", *, *) = "" StringUtils.replace("any", null, *) = "any" StringUtils.replace("any", *, null) = "any" StringUtils.replace("any", "", *) = "any" StringUtils.replace("aba", "a", null) = "aba" StringUtils.replace("aba", "a", "") = "b" StringUtils.replace("aba", "a", "z") = "zbz"
From source file:com.tealcube.minecraft.bukkit.TextUtils.java
/** * Returns a copy of the passed-in String with arguments replaced. The below example will return "I like apples". * <pre>/* w w w .jav a2 s. c o m*/ * <code>String val = TextUtils.args("I like %fruit%", new String[][]{{"%fruit%", "apples"}});</code> * </pre> * * @param pString * String to replace arguments * @param args * Arguments to replace in String * @return copy of the passed-in String with arguments replaced */ public static String args(String pString, String[][] args) { Validate.notNull(pString, "pString cannot be null"); Validate.notNull(args, "args cannot be null"); String ret = pString; for (String[] arg : args) { if (arg.length < 2) { continue; } ret = StringUtils.replace(ret, arg[0], arg[1]); } return ret; }
From source file:com.threadswarm.imagefeedarchiver.processor.RssItemProcessor.java
private void downloadRssMediaContent(ProcessedRssItem processedItem, RssMediaContent mediaContent) { DownloadStatus downloadStatus = DownloadStatus.FAILED; HttpEntity responseEntity = null;/*from www.j ava2 s .co m*/ try { String targetUrlString = mediaContent.getUrlString(); if (forceHttps) targetUrlString = FeedUtils.rewriteUrlStringToHttps(targetUrlString); URI targetURI = FeedUtils.getUriFromUrlString(targetUrlString); boolean freshURI = processedURISet.add(targetURI); if (!freshURI) { LOGGER.warn("Skipping previously processed URI: {}", targetURI); return; //abort processing } LOGGER.info("Attempting to download {}", targetURI); HttpGet imageGet = new HttpGet(targetURI); for (Header header : headerList) imageGet.addHeader(header); HttpResponse imageResponse = httpClient.execute(imageGet); String originalFileName = StringUtils.stripStart(targetURI.toURL().getFile(), "/"); originalFileName = StringUtils.replace(originalFileName, "/", "_"); File outputFile = getOutputFile(originalFileName); long expectedContentLength = FeedUtils.calculateBestExpectedContentLength(imageResponse, mediaContent); responseEntity = imageResponse.getEntity(); BufferedInputStream bis = null; DigestOutputStream fos = null; int bytesRead = 0; try { bis = new BufferedInputStream(responseEntity.getContent()); fos = new DigestOutputStream(new FileOutputStream(outputFile), MessageDigest.getInstance("SHA")); byte[] buffer = new byte[8192]; while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) { fos.write(buffer, 0, bytesRead); } fos.flush(); MessageDigest messageDigest = fos.getMessageDigest(); byte[] digestBytes = messageDigest.digest(); String digestString = Hex.encodeHexString(digestBytes); LOGGER.info("Downloaded - {} (SHA: {})", targetURI, digestString); processedItem.setDownloadDate(new Date()); downloadStatus = DownloadStatus.COMPLETED; processedItem.setHash(digestString); processedItem.setFilename(outputFile.toString()); } catch (ConnectionClosedException e) { LOGGER.error("An Exception was thrown while attempting to read HTTP entity content", e); } catch (NoSuchAlgorithmException e) { LOGGER.error("The SHA-1 hashing algorithm is not available on this JVM", e); } finally { IOUtils.closeQuietly(bis); IOUtils.closeQuietly(fos); EntityUtils.consumeQuietly(responseEntity); if (downloadStatus == DownloadStatus.FAILED || (outputFile.exists() && outputFile.length() != expectedContentLength)) { LOGGER.warn("Deleted partial/failed file: {}", outputFile); outputFile.delete(); processedItem.setDownloadStatus(DownloadStatus.FAILED); } } } catch (IOException e) { LOGGER.error("An Exception was thrown while attempting to download image content", e); } catch (URISyntaxException e) { LOGGER.error("The supplied URI, {}, violates syntax rules", e); } finally { EntityUtils.consumeQuietly(responseEntity); } processedItem.setDownloadStatus(downloadStatus); itemDAO.save(processedItem); }
From source file:com.glaf.core.util.RequestUtils.java
private static Map<String, String> decodeValues(String ip, String value) { Map<String, String> cookieMap = new java.util.HashMap<String, String>(); if (StringUtils.isNotEmpty(value)) { String c_x = decodeString(value); c_x = StringUtils.replace(c_x, DigestUtils.md5Hex(ip), ""); JSONObject jsonObject = null;/*from ww w . ja v a 2 s.c o m*/ try { jsonObject = JSON.parseObject(c_x); } catch (Exception ex) { // Ignore Exception } if (jsonObject != null) { Iterator<Entry<String, Object>> iterator = jsonObject.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, Object> entry = iterator.next(); String key = (String) entry.getKey(); Object val = entry.getValue(); if (val != null) { cookieMap.put(key, val.toString()); } } } } return cookieMap; }
From source file:io.wcm.handler.url.suffix.impl.UrlSuffixUtil.java
/** * Decode key// w w w .j a v a 2s . c om * @param suffixPart Suffix part * @return Decoded key */ public static String decodeKey(String suffixPart) { // key is the part *before* KEY_VALUE_DELIMITER String key = StringUtils.substringBefore(suffixPart, Character.toString(KEY_VALUE_DELIMITER)); // un-escape special chars for (Map.Entry<String, String> entry : SPECIAL_CHARS_ESCAPEMAP.entrySet()) { key = StringUtils.replace(key, entry.getValue(), entry.getKey()); } return key; }
From source file:com.textocat.textokit.eval.event.LoggingEvaluationListener.java
private String escTab(String src) { return StringUtils.replace(src, "\t", " "); }
From source file:io.sugo.grok.api.Discovery.java
/** * Find a pattern from a log./*from w w w . j ava 2s .co m*/ * * @param text witch is the representation of your single * @return Grok pattern %{Foo}... */ public String discover(String text) { if (text == null) { return ""; } Map<String, Grok> groks = new TreeMap<String, Grok>(); Map<String, String> gPatterns = grok.getPatterns(); // Boolean done = false; String texte = text; // Compile the pattern Iterator<Entry<String, String>> it = gPatterns.entrySet().iterator(); while (it.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry pairs = (Map.Entry) it.next(); String key = pairs.getKey().toString(); Grok g = new Grok(); // g.patterns.putAll( gPatterns ); try { g.copyPatterns(gPatterns); g.setSaved_pattern(key); g.compile("%{" + key + "}"); groks.put(key, g); } catch (GrokException e) { // Add logger continue; } } // Sort patterns by complexity Map<String, Grok> patterns = this.sort(groks); // while (!done){ // done = true; Iterator<Entry<String, Grok>> pit = patterns.entrySet().iterator(); while (pit.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry pairs = (Map.Entry) pit.next(); String key = pairs.getKey().toString(); Grok value = (Grok) pairs.getValue(); // We want to search with more complex pattern // We avoid word, small number, space.... if (this.complexity(value.getNamedRegex()) < 20) { continue; } Match m = value.match(text); if (m.isNull()) { continue; } // get the part of the matched text String part = getPart(m, text); // we skip boundary word Pattern pattern = Pattern.compile(".\\b."); Matcher ma = pattern.matcher(part); if (!ma.find()) { continue; } // We skip the part that already include %{Foo} Pattern pattern2 = Pattern.compile("%\\{[^}+]\\}"); Matcher ma2 = pattern2.matcher(part); if (ma2.find()) { continue; } texte = StringUtils.replace(texte, part, "%{" + key + "}"); } // } return texte; }
From source file:de.vandermeer.asciitable.commons.ArrayTransformations.java
/** * Takes an object (used as a string) and returns a string array with all processed lines. * The process is as follows:/*w w w . j a v a2 s.c o m*/ * (1) replace all line breaks (CR LF, CR, LF) into HTML4 line break entity (<br>). * (2) replace all HTML4 line break entities to HTML5 entities (as in self-closing <br/> entity). * (3) use a tokenizer to process the resulting string (not ignoring empty tokens, since they mark required line breaks). * (4) return the array of the tokenizer * * As a result, a string containing 1 line break will be converted into 2 paragraphs (array length 2): * <pre>{@code String: "paragraph 1\nparagraph 2" Array: {paragraph 1,paragraph 2} * }</pre> * A string containing 2 line breaks will be converted into 3 strings (first paragraph, additional line break, second paragraph): * <pre>{@code String: "paragraph 1\n\nparagraph 2" Array: {paragraph 1,,paragraph 2} * }</pre> * * @param content the content to process * @return null if content was null, empty array if content was an empty string, string array with lines otherwise */ public static final String[] PROCESS_CONTENT(Object content) { if (content == null || content.toString() == null) { return null; } if ("".equals(content)) { return new String[] { "" }; } String lfRep = StringUtils.replacePattern(content.toString(), "\\r\\n|\\r|\\n", "<br>"); lfRep = StringUtils.replace(lfRep, "<br>", "<br/>"); StrTokenizer tok = new StrTokenizer(lfRep, "<br/>").setIgnoreEmptyTokens(false); return tok.getTokenArray(); }
From source file:com.xpn.xwiki.util.Util.java
public static String restoreValue(String value) { value = StringUtils.replace(value, "%_N_%", "\n"); value = StringUtils.replace(value, "%_Q_%", "\""); return value; }
From source file:ke.co.tawi.babblesms.server.servlet.export.csv.ExportCsv.java
/** * Returns a zipped MS Excel file of the data specified for exporting. * * @param request// w w w. j a v a2 s. c o m * @param response * @throws ServletException, IOException */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletOutputStream out = response.getOutputStream(); response.setContentType("application/zip"); response.setHeader("Cache-Control", "cache, must-revalidate"); response.setHeader("Pragma", "public"); HttpSession session = request.getSession(false); Account account; String fileName; String exportExcelOption = request.getParameter("exportExcel"); String sessionEmail = (String) session.getAttribute(SessionConstants.ACCOUNT_SIGN_IN_KEY); Element element = accountsCache.get(sessionEmail); account = (Account) element.getObjectValue(); fileName = new StringBuffer(account.getUsername()).append(" ").append(SPREADSHEET_NAME).toString(); response.setHeader("Content-Disposition", "attachment; filename=\"" + StringUtils.replace(fileName, ".xlsx", ".zip") + "\""); File excelFile = new File(FileUtils.getTempDirectoryPath() + File.separator + fileName); File csvFile = new File(StringUtils.replace(excelFile.getCanonicalPath(), ".xlsx", ".csv")); File zippedFile = new File(StringUtils.replace(excelFile.getCanonicalPath(), ".xlsx", ".zip")); // These are to determine whether or not we have created a CSV & Excel file on disk boolean successCSVFile = true, successExcelFile = true; if (StringUtils.equalsIgnoreCase(exportExcelOption, "Export All")) { //export all pages successCSVFile = dbFileUtils.sqlResultToCSV(getExportTopupsSqlQuery(account), csvFile.toString(), '|'); if (successCSVFile) { successExcelFile = AllTopupsExportUtil.createExcelExport(csvFile.toString(), "|", excelFile.toString()); } } else if (StringUtils.equalsIgnoreCase(exportExcelOption, "Export Page")) { //export a single page InboxPage inboxPage = (InboxPage) session.getAttribute("currentInboxPage"); successExcelFile = AllTopupsExportUtil.createExcelExport(inboxPage.getContents(), networkHash, networkHash, "|", excelFile.toString()); } else { //export search results InboxPage topupPage = (InboxPage) session.getAttribute("currentSearchPage"); successExcelFile = AllTopupsExportUtil.createExcelExport(topupPage.getContents(), networkHash, networkHash, "|", excelFile.toString()); } if (successExcelFile) { // If we successfully created the MS Excel File on disk // Zip the Excel file List<File> filesToZip = new ArrayList<>(); filesToZip.add(excelFile); ZipUtil.compressFiles(filesToZip, zippedFile.toString()); // Push the file to the request FileInputStream input = FileUtils.openInputStream(zippedFile); IOUtils.copy(input, out); } out.close(); FileUtils.deleteQuietly(excelFile); FileUtils.deleteQuietly(csvFile); FileUtils.deleteQuietly(zippedFile); }
From source file:io.wcm.devops.conga.resource.ResourceLoaderFilesystemTest.java
private String unifySlashes(String path) { return StringUtils.replace(path, "\\", "/"); }