src/org/sonews/storage/DrupalMessage.java
author František Kučera <franta-hg@frantovo.cz>
Fri, 21 Oct 2011 18:21:30 +0200
changeset 105 d566d08c20d6
parent 104 b4c8a2760d6f
child 106 dc04a3c2c557
permissions -rw-r--r--
Drupal: lepší názvy proměnných.
franta-hg@72
     1
/*
franta-hg@72
     2
 *   SONEWS News Server
franta-hg@72
     3
 *   see AUTHORS for the list of contributors
franta-hg@72
     4
 *
franta-hg@72
     5
 *   This program is free software: you can redistribute it and/or modify
franta-hg@72
     6
 *   it under the terms of the GNU General Public License as published by
franta-hg@72
     7
 *   the Free Software Foundation, either version 3 of the License, or
franta-hg@72
     8
 *   (at your option) any later version.
franta-hg@72
     9
 *
franta-hg@72
    10
 *   This program is distributed in the hope that it will be useful,
franta-hg@72
    11
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
franta-hg@72
    12
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
franta-hg@72
    13
 *   GNU General Public License for more details.
franta-hg@72
    14
 *
franta-hg@72
    15
 *   You should have received a copy of the GNU General Public License
franta-hg@72
    16
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
franta-hg@72
    17
 */
franta-hg@72
    18
package org.sonews.storage;
franta-hg@72
    19
franta-hg@75
    20
import java.io.BufferedReader;
franta-hg@102
    21
import java.io.ByteArrayInputStream;
franta-hg@72
    22
import java.io.ByteArrayOutputStream;
franta-hg@72
    23
import java.io.IOException;
franta-hg@75
    24
import java.io.InputStream;
franta-hg@75
    25
import java.io.InputStreamReader;
franta-hg@75
    26
import java.io.PrintStream;
franta-hg@74
    27
import java.io.StringReader;
franta-hg@74
    28
import java.io.StringWriter;
franta-hg@72
    29
import java.io.UnsupportedEncodingException;
franta-hg@72
    30
import java.sql.ResultSet;
franta-hg@72
    31
import java.sql.SQLException;
franta-hg@72
    32
import java.util.ArrayList;
franta-hg@72
    33
import java.util.Date;
franta-hg@72
    34
import java.util.Enumeration;
franta-hg@74
    35
import java.util.logging.Level;
franta-hg@74
    36
import java.util.logging.Logger;
franta-hg@72
    37
import javax.mail.Header;
franta-hg@72
    38
import javax.mail.MessagingException;
franta-hg@72
    39
import javax.mail.Multipart;
franta-hg@72
    40
import javax.mail.Session;
franta-hg@72
    41
import javax.mail.internet.InternetAddress;
franta-hg@72
    42
import javax.mail.internet.MimeBodyPart;
franta-hg@72
    43
import javax.mail.internet.MimeMessage;
franta-hg@72
    44
import javax.mail.internet.MimeMultipart;
franta-hg@104
    45
import javax.xml.parsers.DocumentBuilder;
franta-hg@104
    46
import javax.xml.parsers.DocumentBuilderFactory;
franta-hg@104
    47
import javax.xml.parsers.ParserConfigurationException;
franta-hg@74
    48
import javax.xml.transform.Transformer;
franta-hg@103
    49
import javax.xml.transform.TransformerException;
franta-hg@74
    50
import javax.xml.transform.TransformerFactory;
franta-hg@104
    51
import javax.xml.transform.dom.DOMSource;
franta-hg@74
    52
import javax.xml.transform.stream.StreamResult;
franta-hg@74
    53
import javax.xml.transform.stream.StreamSource;
franta-hg@102
    54
import org.sonews.daemon.NNTPConnection;
franta-hg@74
    55
import org.sonews.util.io.Resource;
franta-hg@104
    56
import org.w3c.dom.Document;
franta-hg@104
    57
import org.xml.sax.SAXException;
franta-hg@72
    58
franta-hg@72
    59
/**
franta-hg@72
    60
 * This is MimeMessage which enables custom Message-ID header
franta-hg@72
    61
 * (this header will not be overwritten by the default one like in MimeMessage).
franta-hg@72
    62
 * 
franta-hg@72
    63
 * Also add header and body separate serialization.
franta-hg@72
    64
 * 
franta-hg@72
    65
 * And can be deserialized from SQL ResultSet
franta-hg@72
    66
 * 
franta-hg@72
    67
 * @author František Kučera (frantovo.cz)
franta-hg@72
    68
 */
franta-hg@72
    69
public class DrupalMessage extends MimeMessage {
franta-hg@72
    70
franta-hg@74
    71
	private static final Logger log = Logger.getLogger(DrupalMessage.class.getName());
franta-hg@72
    72
	private static final String MESSAGE_ID_HEADER = "Message-ID";
franta-hg@72
    73
	private static final String CRLF = "\r\n";
franta-hg@72
    74
	public static final String CHARSET = "UTF-8";
franta-hg@72
    75
	private static final String XHTML_CONTENT_TYPE = "text/html; charset=" + CHARSET;
franta-hg@100
    76
	private static final String ZNAKČKA_KONCE_ŘÁDKU = "◆";
franta-hg@72
    77
	private String messageID;
franta-hg@102
    78
	private Long parentID;
franta-hg@102
    79
	private Long groupID;
franta-hg@104
    80
	private TransformerFactory transformerFactory;
franta-hg@104
    81
	private DocumentBuilderFactory documentBuilderFactory;
franta-hg@104
    82
franta-hg@104
    83
	/**
franta-hg@104
    84
	 * Initializes XML factories (Transformer, DocumentBuilder).
franta-hg@104
    85
	 */
franta-hg@104
    86
	private void initFactories() {
franta-hg@104
    87
		transformerFactory = TransformerFactory.newInstance();
franta-hg@104
    88
		documentBuilderFactory = DocumentBuilderFactory.newInstance();
franta-hg@104
    89
		/**
franta-hg@104
    90
		 * Komentáře nás nepotřebujeme 
franta-hg@104
    91
		 * (a museli bychom je brát v úvahu při dělení odstavců:
franta-hg@104
    92
		 * v současné verzi XSLT odstavcovače by nám případný komentář
franta-hg@104
    93
		 * rozdělil text na dva odstavce, přestože to má být odstavec jede).
franta-hg@104
    94
		 */
franta-hg@104
    95
		documentBuilderFactory.setIgnoringComments(true);
franta-hg@104
    96
	}
franta-hg@72
    97
franta-hg@72
    98
	/**
franta-hg@72
    99
	 * Constructs MIME message from SQL result.
franta-hg@72
   100
	 * @param rs ResultSet containing message data. No {@link ResultSet#next()} will be called, just values from current row will be read.
franta-hg@72
   101
	 * @param constructBody true if whole message should be constructed | false if we need only message headers (body will be dummy).
franta-hg@72
   102
	 */
franta-hg@104
   103
	public DrupalMessage(ResultSet rs, String myDomain, boolean constructBody) throws SQLException, UnsupportedEncodingException, MessagingException, TransformerException, IOException, ParserConfigurationException, SAXException {
franta-hg@72
   104
		super(Session.getDefaultInstance(System.getProperties()));
franta-hg@104
   105
		initFactories();
franta-hg@72
   106
franta-hg@102
   107
		groupID = rs.getLong("group_id");
franta-hg@102
   108
		addHeader("Message-id", constructMessageId(rs.getInt("id"), groupID, rs.getString("group_name"), myDomain));
franta-hg@72
   109
		addHeader("Newsgroups", rs.getString("group_name"));
franta-hg@74
   110
		setFrom(new InternetAddress(rs.getString("sender_email"), rs.getString("sender_name")));
franta-hg@72
   111
		setSubject(rs.getString("subject"));
franta-hg@72
   112
		setSentDate(new Date(rs.getLong("created")));
franta-hg@74
   113
franta-hg@102
   114
		parentID = rs.getLong("parent_id");
franta-hg@74
   115
		if (parentID > 0) {
franta-hg@72
   116
			String parentMessageID = constructMessageId(parentID, rs.getInt("group_id"), rs.getString("group_name"), myDomain);
franta-hg@72
   117
			addHeader("In-Reply-To", parentMessageID);
franta-hg@72
   118
			addHeader("References", parentMessageID);
franta-hg@72
   119
		}
franta-hg@72
   120
franta-hg@72
   121
		if (constructBody) {
franta-hg@72
   122
			Multipart multipart = new MimeMultipart("alternative");
franta-hg@72
   123
			setContent(multipart);
franta-hg@72
   124
franta-hg@82
   125
			/** XHTML part */
franta-hg@82
   126
			MimeBodyPart htmlPart = new MimeBodyPart();
franta-hg@103
   127
			String xhtmlText = readXhtmlText(
franta-hg@103
   128
					rs.getString("text"),
franta-hg@103
   129
					rs.getString("subject"),
franta-hg@103
   130
					rs.getInt("parent_id"),
franta-hg@103
   131
					rs.getString("urlBase"),
franta-hg@103
   132
					rs.getString("wwwRead"),
franta-hg@103
   133
					rs.getString("wwwPost"));
franta-hg@82
   134
			htmlPart.setContent(xhtmlText, XHTML_CONTENT_TYPE);
franta-hg@84
   135
franta-hg@74
   136
			/** Plain text part */
franta-hg@72
   137
			MimeBodyPart textPart = new MimeBodyPart();
franta-hg@89
   138
			String plainText = readPlainText(rs, xhtmlText);
franta-hg@89
   139
			textPart.setText(plainText);
franta-hg@89
   140
			//addHeader("Lines", String.valueOf(plainText.split("\n").length));
franta-hg@87
   141
franta-hg@87
   142
			/**
franta-hg@87
   143
			 * Thunderbirdu záleží, v jakém pořadí části jsou 
franta-hg@87
   144
			 * (když je prostý text druhý, html se nezobrazí),
franta-hg@87
   145
			 * KNode zobrazuje HTML správně, i když je na prvním místě.
franta-hg@87
   146
			 */
franta-hg@72
   147
			multipart.addBodyPart(textPart);
franta-hg@87
   148
			multipart.addBodyPart(htmlPart);
franta-hg@72
   149
		} else {
franta-hg@82
   150
			/** empty body, just headers */
franta-hg@72
   151
			setText("");
franta-hg@72
   152
		}
franta-hg@72
   153
	}
franta-hg@72
   154
franta-hg@102
   155
	/**
franta-hg@102
   156
	 * Constructs MIME message from article posted by user.
franta-hg@102
   157
	 * @param article article that came through NNTP.
franta-hg@102
   158
	 * @throws MessagingException 
franta-hg@102
   159
	 */
franta-hg@102
   160
	public DrupalMessage(Article article) throws MessagingException {
franta-hg@102
   161
		super(Session.getDefaultInstance(System.getProperties()), serializeArticle(article));
franta-hg@104
   162
		initFactories();
franta-hg@102
   163
franta-hg@102
   164
		String[] parentHeaders = getHeader("In-Reply-To");
franta-hg@104
   165
		if (parentHeaders != null && parentHeaders.length == 1) {
franta-hg@102
   166
			String parentMessageID = parentHeaders[0];
franta-hg@102
   167
			parentID = parseArticleID(parentMessageID);
franta-hg@102
   168
			groupID = parseGroupID(parentMessageID);
franta-hg@102
   169
		} else {
franta-hg@102
   170
			throw new MessagingException("Message posted by user must have exactly one In-Reply-To header.");
franta-hg@102
   171
		}
franta-hg@102
   172
	}
franta-hg@102
   173
franta-hg@102
   174
	private static InputStream serializeArticle(Article a) {
franta-hg@102
   175
		byte articleHeaders[] = a.getHeaderSource().getBytes();
franta-hg@102
   176
		byte delimiter[] = (NNTPConnection.NEWLINE + NNTPConnection.NEWLINE).getBytes();
franta-hg@102
   177
		byte body[] = a.getBody();
franta-hg@102
   178
franta-hg@102
   179
		byte message[] = new byte[articleHeaders.length + delimiter.length + body.length];
franta-hg@102
   180
franta-hg@102
   181
		System.arraycopy(articleHeaders, 0, message, 0, articleHeaders.length);
franta-hg@102
   182
		System.arraycopy(delimiter, 0, message, articleHeaders.length, delimiter.length);
franta-hg@102
   183
		System.arraycopy(body, 0, message, articleHeaders.length + delimiter.length, body.length);
franta-hg@102
   184
franta-hg@102
   185
		return new ByteArrayInputStream(message);
franta-hg@102
   186
	}
franta-hg@102
   187
franta-hg@82
   188
	private String readPlainText(ResultSet rs, String xhtmlText) {
franta-hg@89
   189
		try {
franta-hg@104
   190
			Transformer textTransformer = transformerFactory.newTransformer(new StreamSource(Resource.getAsStream("helpers/mimeTextPart.xsl")));
franta-hg@89
   191
franta-hg@89
   192
			StringReader input = new StringReader(xhtmlText);
franta-hg@89
   193
			StringWriter output = new StringWriter(xhtmlText.length());
franta-hg@89
   194
			textTransformer.transform(new StreamSource(input), new StreamResult(output));
franta-hg@89
   195
franta-hg@89
   196
			return output.toString();
franta-hg@89
   197
		} catch (Exception e) {
franta-hg@89
   198
			/**
franta-hg@89
   199
			 * TODO: lepší ošetření chyby
franta-hg@89
   200
			 */
franta-hg@89
   201
			log.log(Level.WARNING, "Error while transforming article to plain text", e);
franta-hg@89
   202
			return makeSimpleXHTML("Při transformaci příspěvku bohužel došlo k chybě.");
franta-hg@89
   203
		}
franta-hg@72
   204
	}
franta-hg@72
   205
franta-hg@104
   206
	private DOMSource readDOM(String xml) throws ParserConfigurationException, SAXException, IOException {
franta-hg@104
   207
		DocumentBuilder db = documentBuilderFactory.newDocumentBuilder();
franta-hg@104
   208
		Document d = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
franta-hg@104
   209
		return new DOMSource(d);
franta-hg@104
   210
	}
franta-hg@104
   211
franta-hg@105
   212
	private String readXhtmlText(String sourceText, String subject, long parentId, String urlBase, String wwwRead, String wwwPost) throws TransformerException, IOException, ParserConfigurationException, SAXException {
franta-hg@72
   213
		/**
franta-hg@82
   214
		 * TODO: 
franta-hg@104
   215
		 *		- znovupoužívat XSL transformér (nejen v instanci)
franta-hg@82
   216
		 *		- používat cache, ukládat si vygenerované články
franta-hg@72
   217
		 */
franta-hg@105
   218
		String wrappedText = makeSimpleXHTML(sourceText);
franta-hg@103
   219
franta-hg@104
   220
		Transformer paragraphTransformer = transformerFactory.newTransformer(new StreamSource(Resource.getAsStream("helpers/mimeXhtmlPart-make-paragraphs.xsl")));
franta-hg@103
   221
		String paragraphedText;
franta-hg@103
   222
		boolean tidyWasUsed = false;
franta-hg@74
   223
		try {
franta-hg@105
   224
			StringWriter output = new StringWriter(2 * wrappedText.length());
franta-hg@105
   225
			paragraphTransformer.transform(readDOM(wrappedText), new StreamResult(output));
franta-hg@103
   226
			paragraphedText = output.toString();
franta-hg@103
   227
		} catch (Exception e) {
franta-hg@103
   228
			log.log(Level.FINER, "HTML input was shitty – Tidy had to be called.", e);
franta-hg@105
   229
			StringWriter output = new StringWriter(2 * wrappedText.length());
franta-hg@105
   230
			paragraphTransformer.transform(readDOM(tidyXhtml(wrappedText)), new StreamResult(output));
franta-hg@103
   231
			paragraphedText = output.toString();
franta-hg@103
   232
			tidyWasUsed = true;
franta-hg@103
   233
		}
franta-hg@75
   234
franta-hg@104
   235
		Transformer xhtmlTransformer = transformerFactory.newTransformer(new StreamSource(Resource.getAsStream("helpers/mimeXhtmlPart.xsl")));
franta-hg@103
   236
		xhtmlTransformer.setParameter("isRoot", (parentId == 0));
franta-hg@103
   237
		xhtmlTransformer.setParameter("title", subject);
franta-hg@103
   238
		xhtmlTransformer.setParameter("urlBase", urlBase);
franta-hg@103
   239
		xhtmlTransformer.setParameter("wwwRead", wwwRead);
franta-hg@103
   240
		xhtmlTransformer.setParameter("wwwPost", wwwPost);
franta-hg@103
   241
		xhtmlTransformer.setParameter("headComment", String.format("Drupal-NNTP bridge. Transformed: %1$tc. Tidy had to be used: %2$b", new Date(), tidyWasUsed));
franta-hg@105
   242
		StringReader paragraphedReader = new StringReader(paragraphedText);
franta-hg@105
   243
		StringWriter xhtmlWriter = new StringWriter(2 * paragraphedText.length());
franta-hg@105
   244
		xhtmlTransformer.transform(new StreamSource(paragraphedReader), new StreamResult(xhtmlWriter));
franta-hg@75
   245
franta-hg@105
   246
		return xhtmlWriter.toString();
franta-hg@72
   247
	}
franta-hg@72
   248
franta-hg@103
   249
	/**
franta-hg@103
   250
	 * Does not parse XML works just with text.
franta-hg@103
   251
	 * @param body XHTML fragment that should be put between &lt;body&gt; and &lt;/body&gt;
franta-hg@103
   252
	 * @return simple XHTML document (body wrapped in html and body tags)
franta-hg@103
   253
	 */
franta-hg@84
   254
	private static String makeSimpleXHTML(String body) {
franta-hg@84
   255
		return "<html xmlns=\"http://www.w3.org/1999/xhtml\"><body>" + body + "</body></html>";
franta-hg@84
   256
	}
franta-hg@84
   257
franta-hg@75
   258
	/**
franta-hg@103
   259
	 * Does not parse XML works just with text.
franta-hg@103
   260
	 * @param xhtml whole XHTML page
franta-hg@103
   261
	 * @return content between &lt;body&gt; and &lt;/body&gt; tags.
franta-hg@103
   262
	 */
franta-hg@103
   263
	private static String makeFragmentXHTML(String xhtml) {
franta-hg@103
   264
		final String startTag = "<body>";
franta-hg@103
   265
		final String endTag = "</body>";
franta-hg@103
   266
franta-hg@103
   267
		int start = xhtml.indexOf(startTag) + startTag.length();
franta-hg@103
   268
		int end = xhtml.lastIndexOf(endTag);
franta-hg@103
   269
franta-hg@103
   270
		return xhtml.substring(start, end);
franta-hg@103
   271
	}
franta-hg@103
   272
franta-hg@103
   273
	/**
franta-hg@75
   274
	 * TODO: refaktorovat, přesunout
franta-hg@75
   275
	 */
franta-hg@75
   276
	private static String tidyXhtml(String inputText) throws IOException {
franta-hg@89
   277
		/*
franta-hg@89
   278
		 * Viz https://sourceforge.net/tracker/index.php?func=detail&aid=3424437&group_id=27659&atid=390966
franta-hg@89
   279
		 *
franta-hg@89
   280
		 * TODO:
franta-hg@89
   281
		 *		- použít delší zástupný řetězec, ne jen jeden znak
franta-hg@89
   282
		 *		- umísťovat ho jen tam, kde už nějaký text je (ne mezi >\s*<)
franta-hg@89
   283
		 */
franta-hg@100
   284
		inputText = označKonceŘádků(inputText);
franta-hg@82
   285
franta-hg@75
   286
		Runtime r = Runtime.getRuntime();
franta-hg@82
   287
		Process p = r.exec(new String[]{"tidy", // http://tidy.sourceforge.net
franta-hg@82
   288
					"-asxml", // well formed XHTML
franta-hg@82
   289
					"-numeric", // číselné entity
franta-hg@82
   290
					"-utf8", // kódování
franta-hg@82
   291
					"--show-warnings", "false", // žádná varování nás nezajímají
franta-hg@82
   292
					"--show-errors", "0", // ani chyby
franta-hg@82
   293
					"--doctype", "omit", // doctype nepotřebujeme (doplníme si případně vlastní v XSLT)
franta-hg@82
   294
					"--logical-emphasis", "true", // em a strong místo i a b
franta-hg@82
   295
					"--literal-attributes", "true", // zachovat mezery a konce řádků v atributech
franta-hg@82
   296
					"--force-output", "true" // neznámé značky zahodíme, vložíme jen jejich obsah
franta-hg@82
   297
				});
franta-hg@75
   298
franta-hg@75
   299
		PrintStream vstupProcesu = new PrintStream(p.getOutputStream());
franta-hg@75
   300
		vstupProcesu.print(inputText);
franta-hg@75
   301
		vstupProcesu.close();
franta-hg@75
   302
franta-hg@75
   303
		String outputText = streamToString(p.getInputStream());
franta-hg@75
   304
franta-hg@100
   305
		outputText = vraťKonceŘádků(outputText);
franta-hg@82
   306
franta-hg@75
   307
		return outputText;
franta-hg@75
   308
	}
franta-hg@75
   309
franta-hg@100
   310
	private static String označKonceŘádků(String text) {
franta-hg@100
   311
		text = text.replaceAll(">\\s+<", "> <");
franta-hg@100
   312
		text = text.replaceAll("\\n", ZNAKČKA_KONCE_ŘÁDKU + "\n");
franta-hg@100
   313
		return text;
franta-hg@100
   314
	}
franta-hg@100
   315
franta-hg@100
   316
	private static String vraťKonceŘádků(String text) {
franta-hg@100
   317
		text = text.replaceAll(ZNAKČKA_KONCE_ŘÁDKU + "\\n", "\n");
franta-hg@100
   318
		text = text.replaceAll(ZNAKČKA_KONCE_ŘÁDKU, "\n");
franta-hg@100
   319
		return text;
franta-hg@100
   320
	}
franta-hg@100
   321
franta-hg@75
   322
	/**
franta-hg@75
   323
	 * TODO: refaktorovat, přesunout
franta-hg@75
   324
	 */
franta-hg@75
   325
	private static String streamToString(InputStream proud) throws IOException {
franta-hg@75
   326
		StringBuilder výsledek = new StringBuilder();
franta-hg@75
   327
		BufferedReader buf = new BufferedReader(new InputStreamReader(proud));
franta-hg@75
   328
		while (true) {
franta-hg@75
   329
			String radek = buf.readLine();
franta-hg@75
   330
			if (radek == null) {
franta-hg@75
   331
				break;
franta-hg@75
   332
			} else {
franta-hg@75
   333
				výsledek.append(radek);
franta-hg@75
   334
				výsledek.append("\n");
franta-hg@75
   335
			}
franta-hg@75
   336
		}
franta-hg@75
   337
		return výsledek.toString();
franta-hg@75
   338
	}
franta-hg@75
   339
franta-hg@102
   340
	public static String constructMessageId(long articleID, long groupID, String groupName, String domainName) {
franta-hg@72
   341
		StringBuilder sb = new StringBuilder();
franta-hg@72
   342
		sb.append("<");
franta-hg@72
   343
		sb.append(articleID);
franta-hg@72
   344
		sb.append("-");
franta-hg@72
   345
		sb.append(groupID);
franta-hg@72
   346
		sb.append("-");
franta-hg@72
   347
		sb.append(groupName);
franta-hg@72
   348
		sb.append("@");
franta-hg@72
   349
		sb.append(domainName);
franta-hg@72
   350
		sb.append(">");
franta-hg@72
   351
		return sb.toString();
franta-hg@72
   352
	}
franta-hg@72
   353
franta-hg@102
   354
	/**
franta-hg@102
   355
	 * @return article ID of parent of this message | or null, if this is root article and not reply to another one
franta-hg@102
   356
	 */
franta-hg@102
   357
	public Long getParentID() {
franta-hg@102
   358
		return parentID;
franta-hg@102
   359
	}
franta-hg@102
   360
franta-hg@102
   361
	/**
franta-hg@102
   362
	 * @return group ID of this message | or null, if this message is not reply to any other one – which is wrong because we have to know the group
franta-hg@102
   363
	 */
franta-hg@102
   364
	public Long getGroupID() {
franta-hg@102
   365
		return groupID;
franta-hg@102
   366
	}
franta-hg@102
   367
franta-hg@102
   368
	/**
franta-hg@102
   369
	 * 
franta-hg@102
   370
	 * @param messageID &lt;{0}-{1}-{2}@domain.tld&gt; where {0} is nntp_id and {1} is group_id and {2} is group_name
franta-hg@102
   371
	 * @return array where [0] = nntp_id and [1] = group_id and [2] = group_name or returns null if messageID is invalid
franta-hg@102
   372
	 */
franta-hg@102
   373
	private static String[] parseMessageID(String messageID) {
franta-hg@102
   374
		if (messageID.matches("<[0-9]+\\-[0-9]+\\-[a-z0-9\\.]+@.+>")) {
franta-hg@102
   375
			return messageID.substring(1).split("@")[0].split("\\-");
franta-hg@102
   376
		} else {
franta-hg@102
   377
			return null;
franta-hg@102
   378
		}
franta-hg@102
   379
	}
franta-hg@102
   380
franta-hg@102
   381
	public static Long parseArticleID(String messageID) {
franta-hg@102
   382
		String[] localPart = parseMessageID(messageID);
franta-hg@102
   383
		if (localPart == null) {
franta-hg@102
   384
			return null;
franta-hg@102
   385
		} else {
franta-hg@102
   386
			return Long.parseLong(localPart[0]);
franta-hg@102
   387
		}
franta-hg@102
   388
	}
franta-hg@102
   389
franta-hg@102
   390
	public static Long parseGroupID(String messageID) {
franta-hg@102
   391
		String[] localPart = parseMessageID(messageID);
franta-hg@102
   392
		if (localPart == null) {
franta-hg@102
   393
			return null;
franta-hg@102
   394
		} else {
franta-hg@102
   395
			return Long.parseLong(localPart[1]);
franta-hg@102
   396
			// If needed:
franta-hg@102
   397
			// parseGroupName() will be same as this method, just with:
franta-hg@102
   398
			// return localPart[2];
franta-hg@102
   399
		}
franta-hg@102
   400
	}
franta-hg@102
   401
franta-hg@72
   402
	@Override
franta-hg@72
   403
	public void setHeader(String name, String value) throws MessagingException {
franta-hg@72
   404
		super.setHeader(name, value);
franta-hg@72
   405
franta-hg@72
   406
		if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
franta-hg@72
   407
			messageID = value;
franta-hg@72
   408
		}
franta-hg@72
   409
	}
franta-hg@72
   410
franta-hg@72
   411
	@Override
franta-hg@72
   412
	public final void addHeader(String name, String value) throws MessagingException {
franta-hg@72
   413
		super.addHeader(name, value);
franta-hg@72
   414
franta-hg@72
   415
		if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
franta-hg@72
   416
			messageID = value;
franta-hg@72
   417
		}
franta-hg@72
   418
	}
franta-hg@72
   419
franta-hg@72
   420
	@Override
franta-hg@72
   421
	public void removeHeader(String name) throws MessagingException {
franta-hg@72
   422
		super.removeHeader(name);
franta-hg@72
   423
franta-hg@72
   424
		if (MESSAGE_ID_HEADER.equalsIgnoreCase(name)) {
franta-hg@72
   425
			messageID = null;
franta-hg@72
   426
		}
franta-hg@72
   427
	}
franta-hg@72
   428
franta-hg@72
   429
	public void setMessageID(String messageID) {
franta-hg@72
   430
		this.messageID = messageID;
franta-hg@72
   431
	}
franta-hg@72
   432
franta-hg@72
   433
	@Override
franta-hg@72
   434
	protected void updateMessageID() throws MessagingException {
franta-hg@72
   435
		if (messageID == null) {
franta-hg@72
   436
			super.updateMessageID();
franta-hg@72
   437
		} else {
franta-hg@72
   438
			setHeader(MESSAGE_ID_HEADER, messageID);
franta-hg@72
   439
		}
franta-hg@72
   440
	}
franta-hg@72
   441
franta-hg@72
   442
	/**
franta-hg@72
   443
	 * Call {@link #saveChanges()} before this method, if you want all headers including such ones like:
franta-hg@72
   444
	 * 
franta-hg@72
   445
	 * <pre>MIME-Version: 1.0
franta-hg@72
   446
	 *Content-Type: multipart/alternative;</pre>
franta-hg@72
   447
	 * 
franta-hg@72
   448
	 * @return serialized headers
franta-hg@72
   449
	 * @throws MessagingException if getAllHeaders() fails
franta-hg@72
   450
	 */
franta-hg@72
   451
	public String getHeaders() throws MessagingException {
franta-hg@72
   452
		StringBuilder sb = new StringBuilder();
franta-hg@72
   453
		for (Enumeration eh = getAllHeaderLines(); eh.hasMoreElements();) {
franta-hg@72
   454
			sb.append(eh.nextElement());
franta-hg@72
   455
			sb.append(CRLF);
franta-hg@72
   456
		}
franta-hg@72
   457
		return sb.toString();
franta-hg@72
   458
	}
franta-hg@72
   459
franta-hg@72
   460
	public byte[] getBody() throws IOException, MessagingException {
franta-hg@72
   461
		saveChanges();
franta-hg@72
   462
franta-hg@72
   463
		ArrayList<String> skipHeaders = new ArrayList<String>();
franta-hg@72
   464
		for (Enumeration eh = getAllHeaders(); eh.hasMoreElements();) {
franta-hg@72
   465
			Header h = (Header) eh.nextElement();
franta-hg@72
   466
			skipHeaders.add(h.getName());
franta-hg@72
   467
		}
franta-hg@72
   468
franta-hg@72
   469
		ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
franta-hg@72
   470
		writeTo(baos, skipHeaders.toArray(new String[skipHeaders.size()]));
franta-hg@72
   471
		return baos.toByteArray();
franta-hg@72
   472
	}
franta-hg@103
   473
franta-hg@103
   474
	/**
franta-hg@103
   475
	 * Transforms message content to valid XHTML and strips html and body tags.
franta-hg@103
   476
	 * When receiving message from user through NNTP 
franta-hg@103
   477
	 * this method is used to get text that should be saved into databse.
franta-hg@103
   478
	 * @return XHTML fragment – content between &lt;body&gt; and &lt;/body&gt; tags.
franta-hg@103
   479
	 */
franta-hg@103
   480
	public String getBodyXhtmlFragment() throws StorageBackendException {
franta-hg@103
   481
		/**
franta-hg@103
   482
		 * TODO: podporovat i zprávy přímo v HTML a multipart.
franta-hg@103
   483
		 */
franta-hg@103
   484
		try {
franta-hg@103
   485
			Object c = getContent();
franta-hg@103
   486
			if (isMimeType("text/plain") && c instanceof String) {
franta-hg@103
   487
				String xhtml = readXhtmlText(
franta-hg@103
   488
						(String) c,
franta-hg@103
   489
						getSubject(),
franta-hg@103
   490
						getParentID(),
franta-hg@103
   491
						null,
franta-hg@103
   492
						null,
franta-hg@103
   493
						null);
franta-hg@103
   494
				return makeFragmentXHTML(xhtml);
franta-hg@103
   495
			} else {
franta-hg@103
   496
				throw new StorageBackendException("Only text/plain messages are supported for now – post it as plain text please.");
franta-hg@103
   497
			}
franta-hg@103
   498
		} catch (Exception e) {
franta-hg@103
   499
			throw new StorageBackendException(e);
franta-hg@103
   500
		}
franta-hg@103
   501
	}
franta-hg@72
   502
}