comparison flys-aft/src/main/java/de/intevation/aft/Notification.java @ 4095:da9df3641578

Send XML messages via HTTP POST around if the FLYS database has changed. flys-aft/trunk@3614 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Fri, 06 Jan 2012 12:10:40 +0000
parents
children 06891562e633
comparison
equal deleted inserted replaced
4094:b20b710aa86f 4095:da9df3641578
1 package de.intevation.aft;
2
3 import de.intevation.utils.XML;
4
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8
9 import java.net.URL;
10 import java.net.URLConnection;
11 import java.net.HttpURLConnection;
12
13 import org.w3c.dom.Document;
14 import org.w3c.dom.Node;
15 import org.w3c.dom.NodeList;
16
17 import org.apache.log4j.Logger;
18
19 public class Notification
20 {
21 private static Logger log = Logger.getLogger(Notification.class);
22
23 protected Document message;
24
25 public Notification() {
26 }
27
28 public Notification(Document message) {
29 this.message = message;
30 }
31
32 public Notification(Node message) {
33 this(wrap(message));
34 }
35
36 public static Document wrap(Node node) {
37 Document document = XML.newDocument();
38
39 // Send first element as message.
40 // Fall back to root node.
41 Node toImport = node;
42
43 NodeList children = node.getChildNodes();
44 for (int i = 0, N = children.getLength(); i < N; ++i) {
45 Node child = children.item(i);
46 if (child.getNodeType() == Node.ELEMENT_NODE) {
47 toImport = child;
48 break;
49 }
50 }
51
52 toImport = document.importNode(toImport, true);
53 document.appendChild(toImport);
54 document.normalizeDocument();
55 return document;
56 }
57
58 public Document sendPOST(URL url) {
59
60 OutputStream out = null;
61 InputStream in = null;
62 Document result = null;
63
64 try {
65 URLConnection ucon = url.openConnection();
66
67 if (!(ucon instanceof HttpURLConnection)) {
68 log.warn("'" + url + "' is not an HTTP(S) connection.");
69 return null;
70 }
71
72 HttpURLConnection con = (HttpURLConnection)ucon;
73
74 con.setRequestMethod("POST");
75 con.setDoInput(true);
76 con.setDoOutput(true);
77 con.setUseCaches(false);
78 con.setRequestProperty("Content-Type", "text/xml");
79
80 out = con.getOutputStream();
81 XML.toStream(message, out);
82 out.flush();
83 in = con.getInputStream();
84 result = XML.parseDocument(in);
85 }
86 catch (IOException ioe) {
87 log.error("Sending message to '" + url + "' failed.", ioe);
88 }
89 finally {
90 if (out != null) {
91 try { out.close(); } catch (IOException ioe) {}
92 }
93 if (in != null) {
94 try { in.close(); } catch (IOException ioe) {}
95 }
96 }
97
98 return result;
99 }
100 }
101 // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

http://dive4elements.wald.intevation.org