public static void sendSmtpMessage(Session session, Message message, Address[] recipients) throws MessagingException { // message = cloneMimeMessage(message); message.setSentDate(new Date()); setHeaderFieldValue(message, HEADER_X_MAILER, X_MAILER); message.saveChanges(); LOG.info( "Sending message '" + message.getSubject() + "' from '" + Str.format(message.getFrom()) + "' to '" + Str.format(recipients) + "'."); Transport trans = session.getTransport("smtp"); Properties properties = session.getProperties(); trans.connect( properties.getProperty("mail.smtp.host"), properties.getProperty("mail.smtp.auth.user"), properties.getProperty("mail.smtp.auth.password")); trans.sendMessage(message, recipients); trans.close(); }
private String postComment( String projectId, String entityId, String text, String name, String email) { if (projectId == null) throw new RuntimeException("projectId == null"); if (Str.isBlank(text)) throw new RuntimeException("Comment is empty."); Project project = projectDao.getById(projectId); AEntity entity = daoService.getById(entityId); Comment comment = commentDao.postComment(entity, "<nowiki>" + text + "</nowiki>", name, email, true); String message = "New comment posted"; if (!Str.isBlank(name)) message += " by " + name; subscriptionService.notifySubscribers(entity, message, project, email); project.updateHomepage(entity, true); String reference = ((ReferenceSupport) entity).getReference(); String label = ((LabelSupport) entity).getLabel(); ProjectEvent event = projectEventDao.postEvent( project, comment.getAuthorName() + " commented on " + reference + " " + label, entity); if (Str.isEmail(email)) subscriptionService.subscribe(email, entity); transactionService.commit(); webApplication.sendToConversationsByProject(project, event); return "<h2>Comment posted</h2><p>Thank you for your comment! It will be visible in a few minutes.</p><p>Back to <strong>" + KunagiUtl.createExternalRelativeHtmlAnchor(entity) + "</strong>.</p>"; }
public static Session createSmtpSession( String host, Integer port, boolean tls, String user, String password) { if (Str.isBlank(host)) throw new IllegalArgumentException("host ist blank"); if (Str.isBlank(user)) user = null; if (Str.isBlank(password)) password = null; Properties p = new Properties(); p.setProperty("mail.mime.charset", charset); p.setProperty("mail.transport.protocol", "smtp"); p.setProperty("mail.smtp.host", host); if (port != null) p.put("mail.smtp.port", port); p.put("mail.smtp.starttls.enable", String.valueOf(tls)); boolean auth = user != null && password != null; p.setProperty("mail.smtp.auth", String.valueOf(auth)); if (user != null) p.setProperty("mail.smtp.auth.user", user); if (password != null) p.setProperty("mail.smtp.auth.password", password); Session session = Session.getInstance(p); if (auth) { session.setPasswordAuthentication( new URLName("local"), new PasswordAuthentication(user, password)); } return session; }
public static MimeMessage createMessage( Session session, String subject, String html, String text, Address from, Address[] to, Attachment... attachments) { if (text == null) text = Html.convertHtmlToText(html); MimeMessage msg = createEmptyMimeMessage(session); try { msg.setSubject(subject, charset); msg.setFrom(from); msg.setRecipients(Message.RecipientType.TO, to); if ((attachments == null || attachments.length == 0)) { // no attachments if (Str.isBlank(html)) { // no html msg.setText(text, charset); return msg; } msg.setContent(createMultipartAlternative(text, html)); return msg; } MimeMultipart multipartMixed = new MimeMultipart("mixed"); if (Str.isBlank(html)) { // no html MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText(text, charset); multipartMixed.addBodyPart(textBodyPart); } else { // html MimeBodyPart wrapAlternative = new MimeBodyPart(); wrapAlternative.setContent(createMultipartAlternative(text, html)); multipartMixed.addBodyPart(wrapAlternative); } for (Attachment attachment : attachments) { appendAttachment(multipartMixed, attachment); } msg.setContent(multipartMixed); return msg; } catch (MessagingException ex) { throw new RuntimeException(ex); } }
public static List<String> getHeaderListUnsubscribeParsed(Message msg) { String s = getHeaderListUnsubscribe(msg); if (Str.isBlank(s)) return Collections.emptyList(); String[] hrefs = Str.tokenizeToArray(s, ","); List<String> ret = new ArrayList<String>(hrefs.length); for (String href : hrefs) { href = href.trim(); if (href.startsWith("<") && href.endsWith(">")) href = href.substring(1, href.length() - 2); } return ret; }
public static String getSubject(Message msg) { try { return Str.decodeQuotedPrintable(msg.getSubject()); } catch (MessagingException ex) { throw new RuntimeException(ex); } }
private void processDefaultTemplates() { ContextBuilder context = new ContextBuilder(); fillProject(context.putSubContext("project")); fillWiki(context.putSubContext("wiki")); fillBlog(context.putSubContext("blog")); fillSprintBacklog(context.putSubContext("sprintBacklog")); fillProductBacklog(context.putSubContext("productBacklog")); fillBugs(context); fillIdeas(context); fillClosedIssues(context); fillReleases(context); fillIssues(context); fillStories(context); File[] templateFiles = templateDir.listFiles(); if (templateFiles == null) return; for (File templateFile : templateFiles) { String templateName = templateFile.getName(); if (!templateName.endsWith(".vm")) continue; if (templateName.equals(Velocity.LIB_TEMPLATE_NAME)) continue; if (templateName.startsWith("iss.")) continue; if (templateName.startsWith("blg.")) continue; if (templateName.startsWith("sto.")) continue; String outputFileName = Str.removeSuffix(templateName, ".vm"); velocity.processTemplate( templateName, new File(outputDir.getPath() + "/" + outputFileName), context); } }
@Override public String getApplicationName() { if (applicationName != null) return applicationName; String name = super.getApplicationName(); name = Str.removeSuffix(name, "Web"); applicationName = name; return applicationName; }
public static Address[] parseAddresses(String s) throws AddressException { String[] tokens = Str.tokenize(s, ",;:"); InternetAddress[] ads = new InternetAddress[tokens.length]; for (int i = 0; i < ads.length; i++) { ads[i] = new InternetAddress(tokens[i]); } return ads; }
private String submitIssue( String projectId, String label, String text, String additionalInfo, String externalTrackerId, String name, String email, boolean wiki, boolean publish, String remoteHost) { if (projectId == null) throw new RuntimeException("projectId == null"); if (Str.isBlank(label)) throw new RuntimeException( "Subject is empty, but required. Please write a short title for your issue."); if (Str.isBlank(text)) throw new RuntimeException( "Text is empty, but required. Please wirte a short description of your issue."); Project project = projectDao.getById(projectId); String textAsWiki = wiki ? text : "<nowiki>" + text + "</nowiki>"; Issue issue = issueDao.postIssue( project, label, textAsWiki, additionalInfo, externalTrackerId, name, email, publish); if (publish) { project.updateHomepage(issue); } String issuer = issue.getIssuer(); if (Str.isBlank(issuer)) issuer = "anonymous"; ProjectEvent event = projectEventDao.postEvent( project, issuer + " submitted " + issue.getReferenceAndLabel(), issue); if (Str.isEmail(email)) subscriptionService.subscribe(email, issue); transactionService.commit(); webApplication.sendToConversationsByProject(project, issue); webApplication.sendToConversationsByProject(project, event); String issueLink = publish ? KunagiUtl.createExternalRelativeHtmlAnchor(issue) : "<code>" + issue.getReference() + "</code>"; return "<h2>Feedback submitted</h2><p>Thank you for your feedback!</p><p>Your issue is now known as " + issueLink + " and will be reviewed by our Product Owner.</p>"; }
public final void setAuthors(Collection<scrum.server.admin.User> authors) { authors = prepareAuthors(authors); if (authors == null) authors = Collections.emptyList(); java.util.Set<String> ids = getIdsAsSet(authors); if (this.authorsIds.equals(ids)) return; this.authorsIds = ids; updateLastModified(); fireModified("authors=" + Str.format(authors)); }
public final void setReleases(Collection<scrum.server.release.Release> releases) { releases = prepareReleases(releases); if (releases == null) releases = Collections.emptyList(); java.util.Set<String> ids = getIdsAsSet(releases); if (this.releasesIds.equals(ids)) return; this.releasesIds = ids; updateLastModified(); fireModified("releases=" + Str.format(releases)); }
public static String getHeaderFieldValue(Message msg, String fieldName) { String[] header; try { header = msg.getHeader(fieldName); } catch (MessagingException ex) { throw new RuntimeException(ex); } if (header == null) return null; return Str.decodeQuotedPrintable(header[0]); }
private void processEntityTemplate(ContextBuilder context, String reference) { fillProject(context.putSubContext("project")); fillProductBacklog(context.putSubContext("productBacklog")); fillSprintBacklog(context.putSubContext("sprintBacklog")); fillWiki(context.putSubContext("wiki")); String prefix = reference.substring(0, 3); File[] templateFiles = templateDir.listFiles(); if (templateFiles == null) return; for (File templateFile : templateFiles) { String templateName = templateFile.getName(); if (!templateName.endsWith(".vm")) continue; if (!templateName.startsWith(prefix + ".")) continue; String outputFileName = Str.removeSuffix(templateName, ".vm"); outputFileName = Str.removePrefix(outputFileName, prefix + "."); outputFileName = reference + "." + outputFileName; velocity.processTemplate( templateName, new File(outputDir.getPath() + "/" + outputFileName), context); } }
public static String getReplyTo(Message msg) { Address[] aa; try { aa = msg.getReplyTo(); } catch (MessagingException ex) { throw new RuntimeException(ex); } if (aa == null) return null; if (aa.length > 0) { return Str.decodeQuotedPrintable(aa[0].toString()); } return null; }
@SuppressWarnings("unchecked") public ArrayList<AEntity> search(String text) { String[] keys = Str.tokenize(text, " "); ArrayList ret = new ArrayList(); ret.addAll(getMatching(getRequirements(), keys)); ret.addAll(getMatching(getQualitys(), keys)); ret.addAll(getMatching(getTasks(), keys)); ret.addAll(getMatching(getWikipages(), keys)); ret.addAll(getMatching(getIssues(), keys)); ret.addAll(getMatching(getImpediments(), keys)); ret.addAll(getMatching(getRisks(), keys)); ret.addAll(getMatching(getFiles(), keys)); ret.addAll(getMatching(getReleases(), keys)); ret.addAll(getMatching(getBlogEntrys(), keys)); return ret; }
public static Set<String> getRecipientsFormated( Message msg, javax.mail.Message.RecipientType type) { Address[] aa; try { aa = msg.getRecipients(type); } catch (MessagingException ex) { throw new RuntimeException(ex); } Set<String> result = new HashSet<String>(); if (aa != null) { for (Address a : aa) { result.add(Str.decodeQuotedPrintable(a.toString())); } } return result; }
public static String getFromFormated(Message msg) { StringBuffer sb = new StringBuffer(); Address[] aa; try { aa = msg.getFrom(); } catch (MessagingException ex) { throw new RuntimeException(ex); } if (aa == null) { sb.append("<Kein Absender>"); } else { for (int i = 0; i < aa.length; i++) { sb.append(Str.decodeQuotedPrintable(aa[i].toString())); if (i < aa.length - 1) sb.append(", "); } } return sb.toString(); }
public static InputStream getAttachment(Part part, String filename) { try { if (filename.equals(Str.decodeQuotedPrintable(part.getFileName()))) return part.getInputStream(); if (part.getContentType().toLowerCase().startsWith("multipart")) { MimeMultipart multipart; multipart = (MimeMultipart) part.getContent(); int count = multipart.getCount(); for (int i = 0; i < count; i++) { InputStream in = getAttachment(multipart.getBodyPart(i), filename); if (in != null) return in; } } } catch (Throwable ex) { throw new RuntimeException(ex); } return null; }
public static Set<String> getAttachmentFilenames(Part part) { try { Set<String> result = new HashSet<String>(); if (part.getContentType().toLowerCase().startsWith("multipart")) { MimeMultipart multipart; try { multipart = (MimeMultipart) part.getContent(); int count = multipart.getCount(); for (int i = 0; i < count; i++) { result.addAll(getAttachmentFilenames(multipart.getBodyPart(i))); } } catch (NullPointerException ex) { // part.getContent() throws NullPointerException LOG.info(ex); } } else { String filename = part.getFileName(); if (filename != null) result.add(Str.decodeQuotedPrintable(filename)); } return result; } catch (Exception ex) { throw new RuntimeException(ex); } }
@Override protected void onRequest(RequestWrapper<WebSession> req) throws IOException { req.setRequestEncoding(IO.UTF_8); String projectId = req.get("projectId"); String entityId = req.get("entityId"); String text = req.get("text"); String name = Str.cutRight(req.get("name"), 33); if (Str.isBlank(name)) name = null; String email = Str.cutRight(req.get("email"), 33); if (Str.isBlank(email)) email = null; log.info("Comment from the internets"); log.info(" projectId: " + projectId); log.info(" entityId: " + entityId); log.info(" name: " + name); log.info(" email: " + email); log.info(" text: " + text); log.info(" Request-Data:"); log.info(Servlet.toString(req.getHttpRequest(), " ")); String message; try { SpamChecker.check(req); message = postComment(projectId, entityId, text, name, email); } catch (Throwable ex) { log.error("Posting comment failed.", "\n" + Servlet.toString(req.getHttpRequest(), " "), ex); message = "<h2>Failure</h2><p>Posting your comment failed: <strong>" + Str.getRootCauseMessage(ex) + "</strong></p><p>We are sorry, please try again later.</p>"; } String returnUrl = req.get("returnUrl"); if (returnUrl == null) returnUrl = "http://kunagi.org/message.html?#{message}"; returnUrl = returnUrl.replace("{message}", Str.encodeUrlParameter(message)); req.sendRedirect(returnUrl); }
protected java.lang.String prepareText(java.lang.String text) { text = Str.removeUnreadableChars(text); return text; }
@Override public String toString() { return file.getName() + ": " + Str.getRootCauseMessage(exception); }
@Override protected void onRequest(RequestWrapper<WebSession> req) throws IOException { String projectId = req.get("projectId"); String subject = req.get("subject"); String text = req.get("text"); String additionalInfo = req.get("additionalInfo"); String externalTrackerId = req.get("externalTrackerId"); String name = Str.cutRight(req.get("name"), 33); if (Str.isBlank(name)) name = null; String email = Str.cutRight(req.get("email"), 66); if (Str.isBlank(email)) email = null; boolean publish = Str.isTrue(req.get("publish")); boolean wiki = Str.isTrue(req.get("wiki")); log.info("Message from the internets"); log.info(" projectId: " + projectId); log.info(" name: " + name); log.info(" email: " + email); log.info(" publish: " + publish); log.info(" wiki: " + wiki); log.info(" subject: " + subject); log.info(" text: " + text); log.info(" additionalInfo: " + additionalInfo); log.info(" externalTrackerId: " + externalTrackerId); log.info(" Request-Data:"); log.info(Servlet.toString(req.getHttpRequest(), " ")); String message; try { SpamChecker.check(text, name, email, req); message = submitIssue( projectId, subject, text, additionalInfo, externalTrackerId, name, email, wiki, publish, req.getRemoteHost()); } catch (Throwable ex) { log.error( "Submitting issue failed.", "\n" + Servlet.toString(req.getHttpRequest(), " "), ex); message = "<h2>Failure</h2><p>Submitting your feedback failed: <strong>" + Utl.getRootCauseMessage(ex) + "</strong></p><p>We are sorry, please try again later.</p>"; } String returnUrl = req.get("returnUrl"); if (returnUrl != null) { returnUrl = returnUrl.replace("{message}", Str.encodeUrlParameter(message)); req.sendRedirect(returnUrl); return; } req.setContentType("text/html"); PrintWriter out = req.getWriter(); out.print(message); }
public static String getTextContent(Part part, String type) { if (part == null) return null; try { String contentType; try { contentType = part.getContentType(); } catch (Throwable t) { contentType = "unknown"; } if (contentType.toLowerCase().startsWith("text/" + type)) { // ContentType ct = new ContentType(contentType); // String charset = ct.getParameter("charset"); try { Object content = part.getContent(); if (content == null) return null; if (content instanceof String) return (String) content; if (content instanceof InputStream) { String encoding = charset; if (contentType.toLowerCase().contains("UTF")) encoding = IO.UTF_8; if (contentType.toLowerCase().contains("ISO")) encoding = IO.ISO_LATIN_1; return IO.readToString((InputStream) content, encoding); } return Utl.toStringWithType(content); } catch (UnsupportedEncodingException ex) { LOG.warn(ex); return null; } catch (IOException e) { String message = e.getMessage(); if (message != null) { if ("No content".equals(message)) { return null; } if (message.toLowerCase().startsWith("unknown encoding")) { LOG.warn(e); return null; } } throw e; } catch (Throwable t) { LOG.warn(t); return Str.getStackTrace(t); } } if (contentType.toLowerCase().startsWith("multipart")) { MimeMultipart multipart; try { multipart = (MimeMultipart) part.getContent(); } catch (NullPointerException ex) { LOG.warn(ex); return null; } int count = multipart.getCount(); for (int i = 0; i < count; i++) { BodyPart subPart = multipart.getBodyPart(i); String filename = subPart.getFileName(); if (filename != null) continue; String text = getTextContent(subPart, type); if (text != null) return text.trim(); } return null; } return null; } catch (Exception ex) { throw new RuntimeException(ex); } }
public static String getContentAsText(Part part) { String result = getPlainTextContent(part); if (result == null) result = Str.html2text(getHtmlTextContent(part)); return result; }
protected java.lang.String prepareName(java.lang.String name) { name = Str.removeUnreadableChars(name); return name; }
public String wiki2html(String wikitext) { if (Str.isBlank(wikitext)) return null; WikiParser wikiParser = new WikiParser(wikitext); WikiModel model = wikiParser.parse(false); return model.toHtml(htmlContext); }
public static String wiki2text(String wikitext) { if (Str.isBlank(wikitext)) return null; return wikitext; }