List of usage examples for org.apache.commons.lang3 StringUtils replacePattern
public static String replacePattern(final String source, final String regex, final String replacement)
From source file:com.sonicle.webtop.mail.TestRegexReplace.java
public static void main(String args[]) throws Exception { String content = FileUtils.readFileToString(new File("/export/home/gbulfon/content2.txt"), "UTF-8"); String regex1 = RegexUtils.escapeRegexSpecialChars( "service-request?service=com.sonicle.webtop.mail&csrf=iakyng66lcbs277m&action=PreviewAttachment&nowriter=true&uploadId="); String regex2 = RegexUtils.escapeRegexSpecialChars("&cid="); String replaced = StringUtils.replacePattern(content, regex1 + ".{36}" + regex2, "cid:"); regex1 = RegexUtils.escapeRegexSpecialChars( "service-request?service=com.sonicle.webtop.mail&csrf=iakyng66lcbs277m&action=PreviewAttachment&nowriter=true&uploadId="); regex2 = RegexUtils.escapeRegexSpecialChars("&cid="); replaced = StringUtils.replacePattern(content, regex1 + ".{36}" + regex2, "cid:"); }
From source file:com.axibase.tsd.plain.AbstractInsertCommand.java
protected static String clean(String value) { AtsdUtil.check(value, "Value is empty: " + value); return StringUtils.replacePattern(value.trim(), "[\\s\'\"]", "_"); }
From source file:de.vandermeer.skb.interfaces.transformers.textformat.Text_To_WrappedFormat.java
@Override default Pair<ArrayList<String>, ArrayList<String>> transform(String input) { Validate.notBlank(input);//ww w . jav a2s . c o m Validate.isTrue(this.getWidth() > 0); ArrayList<String> topList = new ArrayList<>(); ArrayList<String> bottomList = new ArrayList<>(); //an emergency break, counting loops to avoid endless loops int count; String text = StringUtils.replacePattern(input, "\\r\\n|\\r|\\n", LINEBREAK); text = StringUtils.replace(text, "<br>", LINEBREAK); text = StringUtils.replace(text, "<br/>", LINEBREAK); StrBuilder sb = new StrBuilder(text); if (this.getTopSettings() != null) { //we have a top request, do that one first Validate.notNull(this.getTopSettings().getLeft()); Validate.notNull(this.getTopSettings().getRight()); Validate.isTrue(this.getTopSettings().getLeft() > 0); Validate.isTrue(this.getTopSettings().getRight() > 0); int topLines = this.getTopSettings().getLeft(); int topWidth = this.getTopSettings().getRight(); count = 0; while (sb.size() > 0 && topLines > 0 && count++ < 200) { if (sb.startsWith(LINEBREAK)) { sb.replaceFirst(LINEBREAK, ""); } String s = null; boolean wln = false; if (sb.indexOf(LINEBREAK) > 0) { s = sb.substring(0, sb.indexOf(LINEBREAK)); wln = true; //sb.replace(0, sb.indexOf(LINEBREAK) + LINEBREAK.length(), ""); } else { s = sb.toString(); //sb.clear(); } String wrap = WordUtils.wrap(s, topWidth, LINEBREAK, true); StrTokenizer tok = new StrTokenizer(wrap, LINEBREAK).setIgnoreEmptyTokens(false); String[] ar = tok.getTokenArray(); if (ar.length <= topLines) { //all lines done, cleanup for (String str : ar) { topList.add(str.trim()); } if (wln == true) { //if we had a conditional linebreak there might be more text, remove the line we processed sb.replace(0, sb.indexOf(LINEBREAK) + LINEBREAK.length(), ""); } else { //no conditional line break, clean builder sb.clear(); } topLines = 0; } else { //we have more lines than we need, so remove the text we have from the builder and copy processed lines StrBuilder replace = new StrBuilder(); for (int i = 0; i < topLines; i++) { topList.add(ar[i].trim()); replace.appendSeparator(' ').append(ar[i]); } if (wln == true) { replace.append(LINEBREAK); } sb.replaceFirst(replace.toString(), ""); topLines = 0; } } } //no top, simple wrapping with recognition of conditional line breaks count = 0; while (sb.size() > 0 && count++ < 200) { if (sb.startsWith(LINEBREAK)) { sb.replaceFirst(LINEBREAK, ""); } String s = null; if (sb.indexOf(LINEBREAK) > 0) { s = sb.substring(0, sb.indexOf(LINEBREAK)); sb.replace(0, sb.indexOf(LINEBREAK) + LINEBREAK.length(), ""); } else { s = sb.toString(); sb.clear(); } s = WordUtils.wrap(s, this.getWidth(), LINEBREAK, true); StrTokenizer tok = new StrTokenizer(s, LINEBREAK).setIgnoreEmptyTokens(false); for (String str : tok.getTokenArray()) { bottomList.add(str.trim()); } } return Pair.of(topList, bottomList); }
From source file:de.vandermeer.skb.interfaces.transformers.String_To_ConditionalBreak.java
/** * Transforms a String to a String[] processing conditional line breaks. * Conditional line breaks are CR LF, CR, LF, <br>, and <br/>. * //w ww . j av a 2 s . c o m * The method proceeds as follows: * * . replace all line breaks (CR LF, CR, LF) into HTML4 line break entity <br> * . replace all HTML4 line break entities to HTML5 entities (as in self-closing <br/> entity). * . use a `tokenizer` to process the resulting string (not ignoring empty tokens, since they mark required line breaks). * . return the array of the `tokenizer` * * As a result, a string containing 1 line break will be converted into an array length 2: * ---- * String: "paragraph 1\nparagraph 2" * Array: {paragraph 1,paragraph 2} * ---- * * A string containing 2 line breaks will be converted into a string array with 3 entries (first paragraph, additional line break, second paragraph): * ---- * String: "paragraph 1\n\nparagraph 2" * Array: {paragraph 1,,paragraph 2} * ---- * * @param s input string * @return array with conditional line breaks converted to empty entries, `null` if `s` was `null` */ @Override default String[] transform(String s) { IsTransformer.super.transform(s); if ("".equals(s)) { return new String[] { "" }; } String lfRep = StringUtils.replacePattern(s.toString(), "\\r\\n|\\r|\\n", "<br>"); lfRep = StringUtils.replace(lfRep, "<br>", "<br/>"); lfRep = StringUtils.replace(lfRep, "<br/>", "<br />"); StrTokenizer tok = new StrTokenizer(lfRep, "<br />").setIgnoreEmptyTokens(false); return tok.getTokenArray(); }
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:/* ww w . j av a2 s . c om*/ * (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:alfio.util.EventUtil.java
public static Optional<byte[]> getIcalForEvent(Event event, TicketCategory ticketCategory, String description) { ICalendar ical = new ICalendar(); VEvent vEvent = new VEvent(); vEvent.setSummary(event.getDisplayName()); vEvent.setDescription(description);// w w w. j a v a 2s. c om vEvent.setLocation(StringUtils.replacePattern(event.getLocation(), "[\n\r\t]+", " ")); ZonedDateTime begin = Optional.ofNullable(ticketCategory) .map(tc -> tc.getTicketValidityStart(event.getZoneId())).orElse(event.getBegin()); ZonedDateTime end = Optional.ofNullable(ticketCategory) .map(tc -> tc.getTicketValidityEnd(event.getZoneId())).orElse(event.getEnd()); vEvent.setDateStart(Date.from(begin.toInstant())); vEvent.setDateEnd(Date.from(end.toInstant())); vEvent.setUrl(event.getWebsiteUrl()); ical.addEvent(vEvent); StringWriter strWriter = new StringWriter(); try (ICalWriter writer = new ICalWriter(strWriter, ICalVersion.V2_0)) { writer.write(ical); return Optional.of(strWriter.toString().getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { log.warn("was not able to generate iCal for event " + event.getShortName(), e); return Optional.empty(); } }
From source file:com.sonicle.webtop.mail.Service.java
private SimpleMessage prepareMessage(JsMessage jsmsg, long msgId, boolean save, boolean isFax) throws Exception { PrivateEnvironment env = environment; UserProfile profile = env.getProfile(); //expand multiple addresses ArrayList<String> aemails = new ArrayList<>(); ArrayList<String> artypes = new ArrayList<>(); for (JsRecipient jsrcpt : jsmsg.recipients) { String emails[] = StringUtils.split(jsrcpt.email, ';'); for (String email : emails) { aemails.add(email);//from w w w . j av a2 s . co m artypes.add(jsrcpt.rtype); } } String emails[] = new String[aemails.size()]; emails = (String[]) aemails.toArray(emails); String rtypes[] = new String[artypes.size()]; rtypes = (String[]) artypes.toArray(rtypes); //String replyfolder = request.getParameter("replyfolder"); //String inreplyto = request.getParameter("inreplyto"); //String references = request.getParameter("references"); //String forwardedfolder = request.getParameter("forwardedfolder"); //String forwardedfrom = request.getParameter("forwardedfrom"); //String subject = request.getParameter("subject"); //String mime = request.getParameter("mime"); //String sident = request.getParameter("identity"); //String content = request.getParameter("content"); //String msgid = request.getParameter("newmsgid"); //String ssave = request.getParameter("save"); //boolean save = (ssave != null && ssave.equals("true")); //String sreceipt = request.getParameter("receipt"); //boolean receipt = (sreceipt != null && sreceipt.equals("true")); //String spriority = request.getParameter("priority"); //boolean priority = (spriority != null && spriority.equals("true")); //boolean isFax = request.getParameter("fax") != null; String to = null; String cc = null; String bcc = null; for (int i = 0; i < emails.length; ++i) { //String email=decoder.decode(ByteBuffer.wrap(emails[i].getBytes())).toString(); String email = emails[i]; if (email == null || email.trim().length() == 0) { continue; } //Check for list boolean checkemail = true; boolean listdone = false; if (email.indexOf('@') < 0) { if (isFax && StringUtils.isNumeric(email)) { String faxpattern = getEnv().getCoreServiceSettings().getFaxPattern(); String faxemail = faxpattern.replace("{number}", email).replace("{username}", profile.getUserId()); email = faxemail; } } else { //check for list if one email with domain equals one allowed service id InternetAddress ia = null; try { ia = new InternetAddress(email); } catch (AddressException exc) { } if (ia != null) { String iamail = ia.getAddress(); String dom = iamail.substring(iamail.indexOf("@") + 1); CoreManager core = WT.getCoreManager(); if (environment.getSession().isServiceAllowed(dom)) { List<Recipient> rcpts = core.expandVirtualProviderRecipient(iamail); for (Recipient rcpt : rcpts) { String xemail = rcpt.getAddress(); String xpersonal = rcpt.getPersonal(); String xrtype = EnumUtils.toSerializedName(rcpt.getType()); if (xpersonal != null) xemail = xpersonal + " <" + xemail + ">"; try { checkEmail(xemail); InternetAddress.parse(xemail.replace(',', ' '), true); } catch (AddressException exc) { throw new AddressException( lookupResource(MailLocaleKey.ADDRESS_ERROR) + " : " + xemail); } if (rtypes[i].equals("to")) { if (xrtype.equals("to")) { if (to == null) to = xemail; else to += "; " + xemail; } else if (xrtype.equals("cc")) { if (cc == null) cc = xemail; else cc += "; " + xemail; } else if (xrtype.equals("bcc")) { if (bcc == null) bcc = xemail; else bcc += "; " + xemail; } } else if (rtypes[i].equals("cc")) { if (cc == null) cc = xemail; else cc += "; " + xemail; } else if (rtypes[i].equals("bcc")) { if (bcc == null) bcc = xemail; else bcc += "; " + xemail; } listdone = true; checkemail = false; } } } } if (listdone) { continue; } if (checkemail) { try { checkEmail(email); //InternetAddress.parse(email.replace(',', ' '), false); getInternetAddress(email); } catch (AddressException exc) { Service.logger.error("Exception", exc); throw new AddressException(lookupResource(MailLocaleKey.ADDRESS_ERROR) + " : " + email); } } if (rtypes[i].equals("to")) { if (to == null) { to = email; } else { to += "; " + email; } } else if (rtypes[i].equals("cc")) { if (cc == null) { cc = email; } else { cc += "; " + email; } } else if (rtypes[i].equals("bcc")) { if (bcc == null) { bcc = email; } else { bcc += "; " + email; } } } //long id = Long.parseLong(msgid); SimpleMessage msg = new SimpleMessage(msgId); /*int idx = jsmsg.identity - 1; Identity from = null; if (idx >= 0) { from = mprofile.getIdentity(idx); }*/ Identity from = mprofile.getIdentity(jsmsg.identityId); msg.setFrom(from); msg.setTo(to); msg.setCc(cc); msg.setBcc(bcc); msg.setSubject(jsmsg.subject); //TODO: fax coverpage - dismissed /*if (isFax) { String coverpage = request.getParameter("faxcover"); if (coverpage != null) { if (coverpage.equals("none")) { msg.addHeaderLine("X-FAX-AutoCoverPage: No"); } else { msg.addHeaderLine("X-FAX-AutoCoverPage: Yes"); msg.addHeaderLine("X-FAX-Cover-Template: " + coverpage); } } }*/ //TODO: custom headers keys /*String[] headersKeys = request.getParameterValues("headersKeys"); String[] headersValues = request.getParameterValues("headersValues"); if (headersKeys != null && headersValues != null && headersKeys.length == headersValues.length) { for (int i = 0; i < headersKeys.length; i++) { if (!headersKeys[i].equals("")) { msg.addHeaderLine(headersKeys[i] + ": " + headersValues[i]); } } }*/ if (jsmsg.inreplyto != null) { msg.setInReplyTo(jsmsg.inreplyto); } if (jsmsg.references != null) { msg.setReferences(new String[] { jsmsg.references }); } if (jsmsg.replyfolder != null) { msg.setReplyFolder(jsmsg.replyfolder); } if (jsmsg.forwardedfolder != null) { msg.setForwardedFolder(jsmsg.forwardedfolder); } if (jsmsg.forwardedfrom != null) { msg.setForwardedFrom(jsmsg.forwardedfrom); } msg.setReceipt(jsmsg.receipt); msg.setPriority(jsmsg.priority ? 1 : 3); if (jsmsg.format == null || jsmsg.format.equals("plain")) { msg.setContent(jsmsg.content); } else { if (jsmsg.format.equalsIgnoreCase("html")) { //TODO: change this weird matching of cids2urls! //CIDs String content = jsmsg.content; String pattern1 = RegexUtils .escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId="); String pattern2 = RegexUtils.escapeRegexSpecialChars("&cid="); content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, "cid:"); pattern1 = RegexUtils.escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId="); pattern2 = RegexUtils.escapeRegexSpecialChars("&cid="); content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, "cid:"); //URLs pattern1 = RegexUtils .escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId="); pattern2 = RegexUtils.escapeRegexSpecialChars("&url="); content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, ""); pattern1 = RegexUtils.escapeRegexSpecialChars("service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId="); pattern2 = RegexUtils.escapeRegexSpecialChars("&url="); content = StringUtils.replacePattern(content, pattern1 + ".{39}" + pattern2, ""); //My resources as cids? if (ss.isPublicResourceLinksAsInlineAttachments()) { ArrayList<JsAttachment> rescids = new ArrayList<>(); String match = "\"" + URIUtils.concat(getEnv().getCoreServiceSettings().getPublicBaseUrl(), ResourceRequest.URL); while (StringUtils.contains(content, match)) { pattern1 = RegexUtils.escapeRegexSpecialChars(match); Pattern pattern = Pattern.compile(pattern1 + "\\S*"); Matcher matcher = pattern.matcher(content); matcher.find(); String matched = matcher.group(); String url = matched.substring(1, matched.length() - 1); URI uri = new URI(url); // Retrieve macthed URL // and save it locally logger.debug("Downloading resource file as uploaded file from URL [{}]", url); HttpClient httpCli = null; try { httpCli = HttpClientUtils.createBasicHttpClient(HttpClientUtils.configureSSLAcceptAll(), uri); InputStream is = HttpClientUtils.getContent(httpCli, uri); String tag = "" + msgId; String filename = PathUtils.getFileName(uri.getPath()); UploadedFile ufile = addAsUploadedFile(tag, filename, ServletHelper.guessMediaType(filename), is); rescids.add(new JsAttachment(ufile.getUploadId(), filename, ufile.getUploadId(), true, ufile.getSize())); content = matcher.replaceFirst("\"cid:" + ufile.getUploadId() + "\""); } catch (IOException ex) { throw new WTException(ex, "Unable to retrieve webcal [{0}]", uri); } finally { HttpClientUtils.closeQuietly(httpCli); } } //add new resource cids as attachments if (rescids.size() > 0) { if (jsmsg.attachments == null) jsmsg.attachments = new ArrayList<>(); jsmsg.attachments.addAll(rescids); } } String textcontent = MailUtils.HtmlToText_convert(MailUtils.htmlunescapesource(content)); String htmlcontent = MailUtils.htmlescapefixsource(content).trim(); if (htmlcontent.length() < 6 || !htmlcontent.substring(0, 6).toLowerCase().equals("<html>")) { htmlcontent = "<html><header></header><body>" + htmlcontent + "</body></html>"; } msg.setContent(htmlcontent, textcontent, "text/html"); } else { msg.setContent(jsmsg.content, null, "text/" + jsmsg.format); } } return msg; }
From source file:nl.imvertor.Validator.Validator.java
private String mergeParms(String template) { String[] parts = StringUtils.splitPreserveAllTokens(template, "[]"); String releasename = ""; for (int i = 0; i < parts.length; i++) { if (i % 2 == 0) { // even locations are strings releasename += parts[i];/* w ww. j av a2 s .c o m*/ } else if (!parts[i].equals("")) { // uneven are names try { // this is a name, extract from declared application parameters String val = configurator.getParm("appinfo", parts[i], false); if (val == null) val = "[" + parts[i] + "]"; releasename += val; } catch (Exception e) { releasename += parts[i]; } } } return StringUtils.replacePattern(releasename, "[^A-Za-z0-9_\\-.]", ""); }
From source file:org.structr.javaparser.MethodVisitorAdapter.java
@Override public void visit(final MethodCallExpr methodCall, final Object arg) { final Map<String, Object> params = (HashMap) arg; final String clsName = (String) params.get("clsName"); final JavaParserFacade facade = (JavaParserFacade) params.get("facade"); final App app = (App) params.get("app"); logger.info("###### " + clsName + ": " + methodCall.getName()); try {/*from w ww . j a v a 2s . c om*/ ////// !!!!!!!!!!! Methoden-Aufruf kann in den meisten Fllen nicht aufgelst werden!! final SymbolReference<ResolvedMethodDeclaration> ref = facade.solve(methodCall); if (ref.isSolved()) { final String qualifiedSignature = ref.getCorrespondingDeclaration().getQualifiedSignature(); //final String scopeString = scope.toString(); final String parentNodeAsString = methodCall.getParentNode().toString(); //logger.info("Resolved to " + qualifiedSignature + ", scope: " + scopeString + ", parent node: " + parentNodeAsString); logger.info("Resolved to " + qualifiedSignature + ", parent node: " + parentNodeAsString); final String calledMethodQualifiedName = StringUtils.replacePattern(qualifiedSignature, "\\(.*\\)", ""); final String calledMethodQualifiedClassName = StringUtils .substringBeforeLast(calledMethodQualifiedName, "."); final String calledMethodName = StringUtils.substringAfterLast(calledMethodQualifiedName, "."); Method calledMethod = null; final JavaClass calledMethodClass = (JavaClass) app.nodeQuery(JavaClass.class) .and(JavaClass.name, calledMethodQualifiedClassName).getFirst(); if (calledMethodClass != null) { logger.info(" Found called class in graph: " + calledMethodClass.getName()); calledMethod = (Method) app.nodeQuery(Method.class).and(Method.name, calledMethodName) .and(Method.classOrInterface, calledMethodClass).getFirst(); if (calledMethod != null) { logger.info(" Found called method in graph: " + calledMethod.getProperty(Method.declaration)); final Optional<MethodDeclaration> callingMethod = methodCall .getAncestorOfType(MethodDeclaration.class); if (callingMethod.isPresent()) { final String callingMethodDeclaration = callingMethod.get().getDeclarationAsString(); logger.info(" Calling method: " + callingMethodDeclaration); final String callingMethodName = callingMethod.get().getNameAsString(); final Optional<TypeDeclaration> typeDecl = callingMethod.get() .getAncestorOfType(TypeDeclaration.class); if (typeDecl.isPresent()) { final String callingMethodClassName = typeDecl.get().getNameAsString(); // Find compilation unit final Optional<CompilationUnit> localCU = typeDecl.get() .getAncestorOfType(CompilationUnit.class); if (localCU.isPresent()) { // Does it have a package declaration? final Optional<PackageDeclaration> packageDecl = localCU.get() .getPackageDeclaration(); if (packageDecl.isPresent()) { // Assemble qualified class name final String packageName = packageDecl.get().getNameAsString(); final String fqcn = packageName + "." + callingMethodClassName; // Find class in graph final JavaClass callingClass = (JavaClass) app.nodeQuery(JavaClass.class) .and(JavaClass.name, fqcn).getFirst(); if (callingClass != null) { final Method method = (Method) app.nodeQuery(Method.class) .and(Method.name, callingMethodName) .and(Method.classOrInterface, callingClass).getFirst(); if (method != null) { logger.info("Found calling method in graph: " + method.getName()); final List<Method> methodsCalled = method .getProperty(Method.methodsCalled); methodsCalled.add(calledMethod); method.setProperty(Method.methodsCalled, methodsCalled); logger.info("Added " + calledMethod.getName() + " to list of methods called in " + method.getName()); } } } } } } } } } } catch (final Throwable t) { logger.info("Unable to resolve " + clsName, t); } }
From source file:org.talend.daikon.properties.property.EnumProperty.java
String convertToInnerClassString(String type) {
return StringUtils.replacePattern(type, "([a-z0-9]*\\\\.[A-Z][^.]*)?((\\\\.)([A-Z][a-z0-9]*))", "$1\\$$4");
}