List of usage examples for java.util.regex Matcher replaceFirst
public String replaceFirst(Function<MatchResult, String> replacer)
From source file:com.hichinaschool.flashcards.anki.Reviewer.java
/** * Format question field when it contains typeAnswer or clozes. * If there was an error during type text extraction, a warning is displayed * @param buf The question text/*from w ww. j ava 2s .c o m*/ * @return The formatted question text */ private String typeAnsQuestionFilter(String buf) { Matcher m = sTypeAnsPat.matcher(buf); if (mTypeWarning != null) { return m.replaceFirst(mTypeWarning); } return m.replaceFirst(""); }
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 ww w. j a va2 s . c o 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; }