3 * see AUTHORS for the list of contributors
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package org.sonews.storage;
20 import java.io.BufferedReader;
21 import java.io.ByteArrayOutputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.InputStreamReader;
25 import java.io.PrintStream;
26 import java.io.StringReader;
27 import java.io.StringWriter;
28 import java.io.UnsupportedEncodingException;
29 import java.sql.ResultSet;
30 import java.sql.SQLException;
31 import java.util.ArrayList;
32 import java.util.Date;
33 import java.util.Enumeration;
34 import java.util.logging.Level;
35 import java.util.logging.Logger;
36 import javax.mail.Header;
37 import javax.mail.MessagingException;
38 import javax.mail.Multipart;
39 import javax.mail.Session;
40 import javax.mail.internet.InternetAddress;
41 import javax.mail.internet.MimeBodyPart;
42 import javax.mail.internet.MimeMessage;
43 import javax.mail.internet.MimeMultipart;
44 import javax.xml.transform.Transformer;
45 import javax.xml.transform.TransformerFactory;
46 import javax.xml.transform.stream.StreamResult;
47 import javax.xml.transform.stream.StreamSource;
48 import org.sonews.util.io.Resource;
51 * This is MimeMessage which enables custom Message-ID header
52 * (this header will not be overwritten by the default one like in MimeMessage).
54 * Also add header and body separate serialization.
56 * And can be deserialized from SQL ResultSet
58 * @author František Kučera (frantovo.cz)
60 public class DrupalMessage extends MimeMessage {
62 private static final Logger log = Logger.getLogger(DrupalMessage.class.getName());
63 private static final String MESSAGE_ID_HEADER = "Message-ID";
64 private static final String CRLF = "\r\n";
65 public static final String CHARSET = "UTF-8";
66 private static final String XHTML_CONTENT_TYPE = "text/html; charset=" + CHARSET;
67 private String messageID;
70 * Constructs MIME message from SQL result.
71 * @param rs ResultSet containing message data. No {@link ResultSet#next()} will be called, just values from current row will be read.
72 * @param constructBody true if whole message should be constructed | false if we need only message headers (body will be dummy).
74 public DrupalMessage(ResultSet rs, String myDomain, boolean constructBody) throws SQLException, UnsupportedEncodingException, MessagingException {
75 super(Session.getDefaultInstance(System.getProperties()));
77 addHeader("Message-id", constructMessageId(rs.getInt("id"), rs.getInt("group_id"), rs.getString("group_name"), myDomain));
78 addHeader("Newsgroups", rs.getString("group_name"));
79 setFrom(new InternetAddress(rs.getString("sender_email"), rs.getString("sender_name")));
80 setSubject(rs.getString("subject"));
81 setSentDate(new Date(rs.getLong("created")));
83 int parentID = rs.getInt("parent_id");
85 String parentMessageID = constructMessageId(parentID, rs.getInt("group_id"), rs.getString("group_name"), myDomain);
86 addHeader("In-Reply-To", parentMessageID);
87 addHeader("References", parentMessageID);
91 Multipart multipart = new MimeMultipart("alternative");
92 setContent(multipart);
95 MimeBodyPart htmlPart = new MimeBodyPart();
96 multipart.addBodyPart(htmlPart);
97 String xhtmlText = readXhtmlText(rs);
98 htmlPart.setContent(xhtmlText, XHTML_CONTENT_TYPE);
100 /** Plain text part */
101 MimeBodyPart textPart = new MimeBodyPart();
102 multipart.addBodyPart(textPart);
103 textPart.setText(readPlainText(rs, xhtmlText));
105 /** empty body, just headers */
110 private String readPlainText(ResultSet rs, String xhtmlText) {
112 * TODO: převést na prostý text
114 return "TODO: obyčejný text\n\n\n" + xhtmlText;
117 private String readXhtmlText(ResultSet rs) {
120 * - znovupoužívat XSL transformér
121 * - používat cache, ukládat si vygenerované články
124 String inputText = "<html><body>" + rs.getString("text") + "</body></html>";
126 TransformerFactory tf = TransformerFactory.newInstance();
127 Transformer paragraphTransformer = tf.newTransformer(new StreamSource(Resource.getAsStream("helpers/mimeXhtmlPart-make-paragraphs.xsl")));
129 String paragraphedText;
130 boolean tidyWasUsed = false;
132 StringReader input = new StringReader(inputText);
133 StringWriter output = new StringWriter(2 * inputText.length());
134 paragraphTransformer.transform(new StreamSource(input), new StreamResult(output));
135 paragraphedText = output.toString();
136 } catch (Exception e) {
137 log.log(Level.FINER, "HTML input was shitty – Tidy had to be called.", e);
138 StringReader input = new StringReader(tidyXhtml(inputText));
139 StringWriter output = new StringWriter(2 * inputText.length());
140 paragraphTransformer.transform(new StreamSource(input), new StreamResult(output));
141 paragraphedText = output.toString();
145 Transformer xhtmlTransformer = tf.newTransformer(new StreamSource(Resource.getAsStream("helpers/mimeXhtmlPart.xsl")));
146 xhtmlTransformer.setParameter("isRoot", (rs.getInt("parent_id") == 0));
147 xhtmlTransformer.setParameter("title", rs.getString("subject"));
148 xhtmlTransformer.setParameter("urlBase", rs.getString("urlBase"));
149 xhtmlTransformer.setParameter("wwwRead", rs.getString("wwwRead"));
150 xhtmlTransformer.setParameter("wwwPost", rs.getString("wwwPost"));
151 xhtmlTransformer.setParameter("headComment", String.format("Drupal-NNTP bridge. Transformed: %1$tc. Tidy had to be used: %2$b", new Date(), tidyWasUsed));
152 StringReader input = new StringReader(paragraphedText);
153 StringWriter output = new StringWriter(2 * paragraphedText.length());
154 xhtmlTransformer.transform(new StreamSource(input), new StreamResult(output));
156 return output.toString();
157 } catch (Exception e) {
159 * TODO: lepší ošetření chyby
161 log.log(Level.WARNING, "Error while transforming article to XHTML", e);
162 return "<html><body><p>Při transformaci příspěvku bohužel došlo k chybě.</p></body></html>";
167 * TODO: refaktorovat, přesunout
169 private static String tidyXhtml(String inputText) throws IOException {
170 // https://sourceforge.net/tracker/index.php?func=detail&aid=3424437&group_id=27659&atid=390966
171 inputText = inputText.replaceAll("\\n", "◆\n");
173 Runtime r = Runtime.getRuntime();
174 Process p = r.exec(new String[]{"tidy", // http://tidy.sourceforge.net
175 "-asxml", // well formed XHTML
176 "-numeric", // číselné entity
178 "--show-warnings", "false", // žádná varování nás nezajímají
179 "--show-errors", "0", // ani chyby
180 "--doctype", "omit", // doctype nepotřebujeme (doplníme si případně vlastní v XSLT)
181 "--logical-emphasis", "true", // em a strong místo i a b
182 "--literal-attributes", "true", // zachovat mezery a konce řádků v atributech
183 "--force-output", "true" // neznámé značky zahodíme, vložíme jen jejich obsah
186 PrintStream vstupProcesu = new PrintStream(p.getOutputStream());
187 vstupProcesu.print(inputText);
188 vstupProcesu.close();
190 String outputText = streamToString(p.getInputStream());
192 outputText = outputText.replaceAll("◆\\n", "\n");
193 outputText = outputText.replaceAll("◆", "\n");
199 * TODO: refaktorovat, přesunout
201 private static String streamToString(InputStream proud) throws IOException {
202 StringBuilder výsledek = new StringBuilder();
203 BufferedReader buf = new BufferedReader(new InputStreamReader(proud));
205 String radek = buf.readLine();
209 výsledek.append(radek);
210 výsledek.append("\n");
213 return výsledek.toString();
216 private static String constructMessageId(int articleID, int groupID, String groupName, String domainName) {
217 StringBuilder sb = new StringBuilder();
219 sb.append(articleID);
223 sb.append(groupName);
225 sb.append(domainName);
227 return sb.toString();
231 public void setHeader(String name, String value) throws MessagingException {
232 super.setHeader(name, value);
234 if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
240 public final void addHeader(String name, String value) throws MessagingException {
241 super.addHeader(name, value);
243 if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
249 public void removeHeader(String name) throws MessagingException {
250 super.removeHeader(name);
252 if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
257 public void setMessageID(String messageID) {
258 this.messageID = messageID;
262 protected void updateMessageID() throws MessagingException {
263 if (messageID == null) {
264 super.updateMessageID();
266 setHeader(MESSAGE_ID_HEADER, messageID);
271 * Call {@link #saveChanges()} before this method, if you want all headers including such ones like:
273 * <pre>MIME-Version: 1.0
274 *Content-Type: multipart/alternative;</pre>
276 * @return serialized headers
277 * @throws MessagingException if getAllHeaders() fails
279 public String getHeaders() throws MessagingException {
280 StringBuilder sb = new StringBuilder();
281 for (Enumeration eh = getAllHeaderLines(); eh.hasMoreElements();) {
282 sb.append(eh.nextElement());
285 return sb.toString();
288 public byte[] getBody() throws IOException, MessagingException {
291 ArrayList<String> skipHeaders = new ArrayList<String>();
292 for (Enumeration eh = getAllHeaders(); eh.hasMoreElements();) {
293 Header h = (Header) eh.nextElement();
294 skipHeaders.add(h.getName());
297 ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
298 writeTo(baos, skipHeaders.toArray(new String[skipHeaders.size()]));
299 return baos.toByteArray();