summaryrefslogtreecommitdiffstats
path: root/org/madore/damlengine/WeblogPopulate.java
blob: 9b6694e20e8e26aa92aa001220ea233a3e8ffd2f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package org.madore.damlengine;

import java.util.regex.Pattern;
import java.io.InputStream;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSParser;
import org.w3c.dom.ls.LSSerializer;
import org.w3c.dom.ls.LSInput;

public final class WeblogPopulate {

    private WeblogPopulate() { // Forbid instantiation
	throw new AssertionError("WeblogPopulate cannot be instantiated");
    }

    public static final String toHex(byte[] digest) {
	StringBuilder sb = new StringBuilder();
	for ( byte b : digest )
	    sb.append(String.format("%02x", b));
	return sb.toString();
    }

    public static void populate(InputStream in)
	throws Exception {

	final DOMImplementationLS domils
	    = (DOMImplementationLS)(DamlEngine.IncantDOM.getDOMI());
	LSSerializer ser = domils.createLSSerializer();
	ser.getDomConfig().setParameter("xml-declaration", false);
	LSParser par = domils.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
	par.getDomConfig().setParameter("resource-resolver", new Resolver());
	par.getDomConfig().setParameter("http://xml.org/sax/features/validation", true);
	par.getDomConfig().setParameter("http://xml.org/sax/features/namespaces", true);
	par.getDomConfig().setParameter("http://apache.org/xml/properties/internal/error-handler", new DamlEngine.SelectiveErrorHandler());

	MessageDigest sha1 = MessageDigest.getInstance("SHA-1");

	final Connection conn = WeblogDatabaseConnection.getConnection();

	final PreparedStatement checkSt
	    = conn.prepareStatement("SELECT sha1 FROM entries WHERE id=?");
	final PreparedStatement insertNSt
	    = conn.prepareStatement("INSERT INTO entries(id,edate,lang,title,title_xml,content,sha1) VALUES (?,?,?,?,?::xml,?::xml,?)");
	final PreparedStatement insertCSt
	    = conn.prepareStatement("INSERT INTO entries(id,edate,lang,title,title_xml,content,sha1,cdate) VALUES (?,?,?,?,?::xml,?::xml,?,?::timestamptz)");
	final PreparedStatement updateNSt
	    = conn.prepareStatement("UPDATE entries SET (edate,mdate,lang,title,title_xml,content,sha1)=(?,DEFAULT,?,?,?::xml,?::xml,?) WHERE id=?");
	final PreparedStatement updateCSt
	    = conn.prepareStatement("UPDATE entries SET (edate,mdate,lang,title,title_xml,content,sha1,cdate)=(?,DEFAULT,?,?,?::xml,?::xml,?,?::timestamptz) WHERE id=?");
	final PreparedStatement checkDateSt
	    = conn.prepareStatement("SELECT to_char(cdate,'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') FROM entries WHERE id=?");
	final PreparedStatement clearCatSt
	    = conn.prepareStatement("DELETE FROM incat WHERE id=?");
	final PreparedStatement setCatSt
	    = conn.prepareStatement("INSERT INTO incat(id,code) VALUES (?,?)");

	LSInput input = domils.createLSInput();
	input.setByteStream(in);
	Document doc = par.parse(input);
	XPathFactory xpf = XPathFactory.newInstance();
	XPath xp = xpf.newXPath();
	xp.setNamespaceContext(new DamlEngine.DamlNSMapping());
	XPathExpression expr = xp.compile("//d:weblog/d:entry");
	XPathExpression texpr = xp.compile("d:title");
	NodeList entries = (NodeList)(expr.evaluate(doc, XPathConstants.NODESET));
	for ( int i=0 ; i<entries.getLength() ; i++ ) {
	    Element ent = (Element)(entries.item(i));
	    String idStr = ent.getAttributeNS(null, "number");
	    if ( ! Pattern.matches("^\\d{4}$", idStr) )
		throw new IllegalArgumentException("entry number attribute must be of the form NNNN");
	    int id = Integer.parseInt(idStr);
	    String date = ent.getAttributeNS(null, "date");
	    if ( ! Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", date) )
		throw new IllegalArgumentException("entry date attribute must be of the form YYYY-MM-DD");
	    String cdate;
	    if ( ent.hasAttributeNS(null, "cdate") )
		cdate = ent.getAttributeNS(null, "cdate");
	    else
		cdate = null;
	    String catStr = ent.getAttributeNS(null, "cat");
	    String[] catList = catStr.split("\\s+");
	    String lang = LangHelper.getLangRec(ent);
	    String content = ser.writeToString(ent);
	    sha1.reset();
	    String digest = toHex(sha1.digest(content.getBytes("UTF-8")));

	    checkSt.setInt(1, id);
	    ResultSet checkRes = checkSt.executeQuery();
	    boolean exists = checkRes.next();
	    if ( exists && checkRes.getString(1).equals(digest) )
		continue;
	    Node titleNode = (Node)(texpr.evaluate(ent, XPathConstants.NODE));
	    String titleTxt = (titleNode != null) ? titleNode.getTextContent() : null;
	    String titleXml = (titleNode != null) ? ser.writeToString(titleNode) : null;
	    conn.setAutoCommit(false);
	    if ( exists ) {
		System.err.println("Updating entry "+id);
		PreparedStatement updateSt;
		if ( cdate == null )
		    updateSt = updateNSt;
		else
		    updateSt = updateCSt;
		updateSt.setString(1, date);
		updateSt.setString(2, lang);
		updateSt.setString(3, titleTxt);
		updateSt.setString(4, titleXml);
		updateSt.setString(5, content);
		updateSt.setString(6, digest);
		if ( cdate != null ) {
		    updateSt.setString(7, cdate);
		    updateSt.setInt(8, id);
		} else {
		    updateSt.setInt(7, id);
		}
		updateSt.executeUpdate();
	    } else {
		System.err.println("Registering entry "+id);
		PreparedStatement insertSt;
		if ( cdate == null )
		    insertSt = insertNSt;
		else
		    insertSt = insertCSt;
		insertSt.setInt(1, id);
		insertSt.setString(2, date);
		insertSt.setString(3, lang);
		insertSt.setString(4, titleTxt);
		insertSt.setString(5, titleXml);
		insertSt.setString(6, content);
		insertSt.setString(7, digest);
		if ( cdate != null )
		    insertSt.setString(8, cdate);
		insertSt.executeUpdate();
	    }
	    if ( ! Pattern.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}\\:\\d{2}(?:\\:\\d{2})?(?:Z|[\\+\\-]\\d{2}\\:\\d{2})$", cdate) ) {
		checkDateSt.setInt(1, id);
		ResultSet checkDate = checkDateSt.executeQuery();
		checkDate.next();
		String checkDateStr = checkDate.getString(1);
		System.err.println("cdate for entry "+id+": "
				   +checkDateStr);
	    }
	    clearCatSt.setInt(1, id);
	    clearCatSt.executeUpdate();
	    for ( String cat : catList ) {
		if ( ! cat.equals("") ) {
		    setCatSt.setInt(1, id);
		    setCatSt.setString(2, cat);
		    setCatSt.executeUpdate();
		}
	    }
	    conn.commit();
	}

	checkSt.close();
	insertNSt.close();
	insertCSt.close();
	updateNSt.close();
	updateCSt.close();
	checkDateSt.close();
	clearCatSt.close();
	setCatSt.close();

    }

}