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.ByteArrayOutputStream;
21 import java.io.IOException;
22 import java.io.StringReader;
23 import java.io.StringWriter;
24 import java.io.UnsupportedEncodingException;
25 import java.sql.ResultSet;
26 import java.sql.SQLException;
27 import java.util.ArrayList;
28 import java.util.Date;
29 import java.util.Enumeration;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
32 import javax.mail.Header;
33 import javax.mail.MessagingException;
34 import javax.mail.Multipart;
35 import javax.mail.Session;
36 import javax.mail.internet.InternetAddress;
37 import javax.mail.internet.MimeBodyPart;
38 import javax.mail.internet.MimeMessage;
39 import javax.mail.internet.MimeMultipart;
40 import javax.xml.transform.Transformer;
41 import javax.xml.transform.TransformerFactory;
42 import javax.xml.transform.stream.StreamResult;
43 import javax.xml.transform.stream.StreamSource;
44 import org.sonews.util.io.Resource;
47 * This is MimeMessage which enables custom Message-ID header
48 * (this header will not be overwritten by the default one like in MimeMessage).
50 * Also add header and body separate serialization.
52 * And can be deserialized from SQL ResultSet
54 * @author František Kučera (frantovo.cz)
56 public class DrupalMessage extends MimeMessage {
58 private static final Logger log = Logger.getLogger(DrupalMessage.class.getName());
59 private static final String MESSAGE_ID_HEADER = "Message-ID";
60 private static final String CRLF = "\r\n";
61 public static final String CHARSET = "UTF-8";
62 private static final String XHTML_CONTENT_TYPE = "text/html; charset=" + CHARSET;
63 private String messageID;
66 * Constructs MIME message from SQL result.
67 * @param rs ResultSet containing message data. No {@link ResultSet#next()} will be called, just values from current row will be read.
68 * @param constructBody true if whole message should be constructed | false if we need only message headers (body will be dummy).
70 public DrupalMessage(ResultSet rs, String myDomain, boolean constructBody) throws SQLException, UnsupportedEncodingException, MessagingException {
71 super(Session.getDefaultInstance(System.getProperties()));
73 addHeader("Message-id", constructMessageId(rs.getInt("id"), rs.getInt("group_id"), rs.getString("group_name"), myDomain));
74 addHeader("Newsgroups", rs.getString("group_name"));
75 setFrom(new InternetAddress(rs.getString("sender_email"), rs.getString("sender_name")));
76 setSubject(rs.getString("subject"));
77 setSentDate(new Date(rs.getLong("created")));
79 int parentID = rs.getInt("parent_id");
81 String parentMessageID = constructMessageId(parentID, rs.getInt("group_id"), rs.getString("group_name"), myDomain);
82 addHeader("In-Reply-To", parentMessageID);
83 addHeader("References", parentMessageID);
87 Multipart multipart = new MimeMultipart("alternative");
88 setContent(multipart);
90 /** Plain text part */
91 MimeBodyPart textPart = new MimeBodyPart();
92 multipart.addBodyPart(textPart);
93 textPart.setText(readPlainText(rs));
96 MimeBodyPart htmlPart = new MimeBodyPart();
97 multipart.addBodyPart(htmlPart);
98 htmlPart.setContent(readXhtmlText(rs), XHTML_CONTENT_TYPE);
104 private String readPlainText(ResultSet rs) {
106 * TODO: převést na prostý text
108 return "TODO: obyčejný text";
111 private String readXhtmlText(ResultSet rs) {
113 * TODO: znovupoužívat XSL transformér
116 String originalText = rs.getString("text");
117 StringReader input = new StringReader("<body>" + originalText + "</body>");
118 StringWriter output = new StringWriter();
119 TransformerFactory tf = TransformerFactory.newInstance();
120 Transformer t = tf.newTransformer(new StreamSource(Resource.getAsStream("helpers/mimeXhtmlPart.xsl")));
121 t.setParameter("isRoot", (rs.getInt("parent_id") == 0));
122 t.setParameter("title", rs.getString("subject"));
123 t.setParameter("urlBase", rs.getString("urlBase"));
124 t.setParameter("wwwRead", rs.getString("wwwRead"));
125 t.setParameter("wwwPost", rs.getString("wwwPost"));
126 t.transform(new StreamSource(input), new StreamResult(output));
128 return output.toString();
129 } catch (Exception e) {
131 * TODO: lepší ošetření chyby
133 log.log(Level.WARNING, "Error while transforming article to XHTML", e);
134 return "<html><body><p>Při transformaci příspěvku bohužel došlo k chybě.</p></body></html>";
138 private static String constructMessageId(int articleID, int groupID, String groupName, String domainName) {
139 StringBuilder sb = new StringBuilder();
141 sb.append(articleID);
145 sb.append(groupName);
147 sb.append(domainName);
149 return sb.toString();
153 public void setHeader(String name, String value) throws MessagingException {
154 super.setHeader(name, value);
156 if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
162 public final void addHeader(String name, String value) throws MessagingException {
163 super.addHeader(name, value);
165 if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
171 public void removeHeader(String name) throws MessagingException {
172 super.removeHeader(name);
174 if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
179 public void setMessageID(String messageID) {
180 this.messageID = messageID;
184 protected void updateMessageID() throws MessagingException {
185 if (messageID == null) {
186 super.updateMessageID();
188 setHeader(MESSAGE_ID_HEADER, messageID);
193 * Call {@link #saveChanges()} before this method, if you want all headers including such ones like:
195 * <pre>MIME-Version: 1.0
196 *Content-Type: multipart/alternative;</pre>
198 * @return serialized headers
199 * @throws MessagingException if getAllHeaders() fails
201 public String getHeaders() throws MessagingException {
202 StringBuilder sb = new StringBuilder();
203 for (Enumeration eh = getAllHeaderLines(); eh.hasMoreElements();) {
204 sb.append(eh.nextElement());
207 return sb.toString();
210 public byte[] getBody() throws IOException, MessagingException {
213 ArrayList<String> skipHeaders = new ArrayList<String>();
214 for (Enumeration eh = getAllHeaders(); eh.hasMoreElements();) {
215 Header h = (Header) eh.nextElement();
216 skipHeaders.add(h.getName());
219 ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
220 writeTo(baos, skipHeaders.toArray(new String[skipHeaders.size()]));
221 return baos.toByteArray();