src/org/sonews/storage/DrupalMessage.java
author František Kučera <franta-hg@frantovo.cz>
Wed, 12 Oct 2011 23:10:31 +0200
changeset 74 e1244384cc6f
parent 72 aae4b4688700
child 75 41d6c0cac8b3
permissions -rw-r--r--
Drupal: XSL transformace XHTML části
     1 /*
     2  *   SONEWS News Server
     3  *   see AUTHORS for the list of contributors
     4  *
     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.
     9  *
    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.
    14  *
    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/>.
    17  */
    18 package org.sonews.storage;
    19 
    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;
    45 
    46 /**
    47  * This is MimeMessage which enables custom Message-ID header
    48  * (this header will not be overwritten by the default one like in MimeMessage).
    49  * 
    50  * Also add header and body separate serialization.
    51  * 
    52  * And can be deserialized from SQL ResultSet
    53  * 
    54  * @author František Kučera (frantovo.cz)
    55  */
    56 public class DrupalMessage extends MimeMessage {
    57 
    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;
    64 
    65 	/**
    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).
    69 	 */
    70 	public DrupalMessage(ResultSet rs, String myDomain, boolean constructBody) throws SQLException, UnsupportedEncodingException, MessagingException {
    71 		super(Session.getDefaultInstance(System.getProperties()));
    72 
    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")));
    78 
    79 		int parentID = rs.getInt("parent_id");
    80 		if (parentID > 0) {
    81 			String parentMessageID = constructMessageId(parentID, rs.getInt("group_id"), rs.getString("group_name"), myDomain);
    82 			addHeader("In-Reply-To", parentMessageID);
    83 			addHeader("References", parentMessageID);
    84 		}
    85 
    86 		if (constructBody) {
    87 			Multipart multipart = new MimeMultipart("alternative");
    88 			setContent(multipart);
    89 
    90 			/** Plain text part */
    91 			MimeBodyPart textPart = new MimeBodyPart();
    92 			multipart.addBodyPart(textPart);
    93 			textPart.setText(readPlainText(rs));
    94 
    95 			/** XHTML part */
    96 			MimeBodyPart htmlPart = new MimeBodyPart();
    97 			multipart.addBodyPart(htmlPart);
    98 			htmlPart.setContent(readXhtmlText(rs), XHTML_CONTENT_TYPE);
    99 		} else {
   100 			setText("");
   101 		}
   102 	}
   103 
   104 	private String readPlainText(ResultSet rs) {
   105 		/**
   106 		 * TODO: převést na prostý text
   107 		 */
   108 		return "TODO: obyčejný text";
   109 	}
   110 
   111 	private String readXhtmlText(ResultSet rs) {
   112 		/**
   113 		 * TODO: znovupoužívat XSL transformér
   114 		 */
   115 		try {
   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));
   127 			
   128 			return output.toString();
   129 		} catch (Exception e) {
   130 			/**
   131 			 * TODO: lepší ošetření chyby
   132 			 */
   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>";
   135 		}
   136 	}
   137 
   138 	private static String constructMessageId(int articleID, int groupID, String groupName, String domainName) {
   139 		StringBuilder sb = new StringBuilder();
   140 		sb.append("<");
   141 		sb.append(articleID);
   142 		sb.append("-");
   143 		sb.append(groupID);
   144 		sb.append("-");
   145 		sb.append(groupName);
   146 		sb.append("@");
   147 		sb.append(domainName);
   148 		sb.append(">");
   149 		return sb.toString();
   150 	}
   151 
   152 	@Override
   153 	public void setHeader(String name, String value) throws MessagingException {
   154 		super.setHeader(name, value);
   155 
   156 		if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
   157 			messageID = value;
   158 		}
   159 	}
   160 
   161 	@Override
   162 	public final void addHeader(String name, String value) throws MessagingException {
   163 		super.addHeader(name, value);
   164 
   165 		if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
   166 			messageID = value;
   167 		}
   168 	}
   169 
   170 	@Override
   171 	public void removeHeader(String name) throws MessagingException {
   172 		super.removeHeader(name);
   173 
   174 		if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
   175 			messageID = null;
   176 		}
   177 	}
   178 
   179 	public void setMessageID(String messageID) {
   180 		this.messageID = messageID;
   181 	}
   182 
   183 	@Override
   184 	protected void updateMessageID() throws MessagingException {
   185 		if (messageID == null) {
   186 			super.updateMessageID();
   187 		} else {
   188 			setHeader(MESSAGE_ID_HEADER, messageID);
   189 		}
   190 	}
   191 
   192 	/**
   193 	 * Call {@link #saveChanges()} before this method, if you want all headers including such ones like:
   194 	 * 
   195 	 * <pre>MIME-Version: 1.0
   196 	 *Content-Type: multipart/alternative;</pre>
   197 	 * 
   198 	 * @return serialized headers
   199 	 * @throws MessagingException if getAllHeaders() fails
   200 	 */
   201 	public String getHeaders() throws MessagingException {
   202 		StringBuilder sb = new StringBuilder();
   203 		for (Enumeration eh = getAllHeaderLines(); eh.hasMoreElements();) {
   204 			sb.append(eh.nextElement());
   205 			sb.append(CRLF);
   206 		}
   207 		return sb.toString();
   208 	}
   209 
   210 	public byte[] getBody() throws IOException, MessagingException {
   211 		saveChanges();
   212 
   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());
   217 		}
   218 
   219 		ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
   220 		writeTo(baos, skipHeaders.toArray(new String[skipHeaders.size()]));
   221 		return baos.toByteArray();
   222 	}
   223 }