KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > cms > plugins > opentree > Communicator


1 /* ===============================================================================
2  *
3  * Part of the InfoGlue Content Management Platform (www.infoglue.org)
4  *
5  * ===============================================================================
6  *
7  * Copyright (C)
8  *
9  * This program is free software; you can redistribute it and/or modify it under
10  * the terms of the GNU General Public License version 2, as published by the
11  * Free Software Foundation. See the file LICENSE.html for more information.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
19  * Place, Suite 330 / Boston, MA 02111-1307 / USA.
20  *
21  * ===============================================================================
22  */

23  
24 package org.infoglue.cms.plugins.opentree;
25
26 import java.io.BufferedInputStream JavaDoc;
27 import java.io.BufferedReader JavaDoc;
28 import java.io.InputStream JavaDoc;
29 import java.io.InputStreamReader JavaDoc;
30 import java.io.PrintWriter JavaDoc;
31 import java.net.URL JavaDoc;
32 import java.net.URLConnection JavaDoc;
33 import java.net.URLDecoder JavaDoc;
34 import java.net.URLEncoder JavaDoc;
35 import java.util.ArrayList JavaDoc;
36 import java.util.Enumeration JavaDoc;
37 import java.util.Hashtable JavaDoc;
38 import java.util.Iterator JavaDoc;
39 import java.util.List JavaDoc;
40 import java.util.StringTokenizer JavaDoc;
41
42 import org.infoglue.cms.net.CommunicationEnvelope;
43 import org.infoglue.cms.net.Node;
44
45
46 public class Communicator
47 {
48     private String JavaDoc serverAddress = null;
49     private String JavaDoc entityName = null;
50     private Integer JavaDoc repositoryId = null;
51     
52     public Communicator(String JavaDoc serverAddress, String JavaDoc entityName, Integer JavaDoc repositoryId)
53     {
54         this.serverAddress = serverAddress;
55         this.entityName = entityName;
56         this.repositoryId = repositoryId;
57     }
58      
59     public Node getRootNode() throws Exception JavaDoc
60     {
61         CommunicationEnvelope requestEnvelope = new CommunicationEnvelope();
62         requestEnvelope.setAction("selectRootNode");
63         
64         List JavaDoc arguments = new ArrayList JavaDoc();
65         Node n = new Node();
66         n.setId(this.repositoryId);
67         arguments.add(n);
68         requestEnvelope.setNodes(arguments);
69         
70         CommunicationEnvelope responseEnvelope = callService(requestEnvelope);
71         
72         Node rootNode = null;
73         int status = Integer.parseInt(responseEnvelope.getStatus());
74
75         //System.out.println("status:" + status);
76

77         if(status == 0)
78         {
79             List JavaDoc nodes = responseEnvelope.getNodes();
80             //System.out.println("nodes:" + nodes);
81
rootNode = (Node)nodes.get(0);
82             //System.out.println("Node:" + rootNode);
83
}
84         
85         return rootNode;
86     }
87
88     public Node getNode(Integer JavaDoc nodeId)
89     {
90         CommunicationEnvelope requestEnvelope = new CommunicationEnvelope();
91         requestEnvelope.setAction("selectNode");
92         
93         List JavaDoc arguments = new ArrayList JavaDoc();
94         Node n = new Node();
95         n.setId(nodeId);
96         arguments.add(n);
97         requestEnvelope.setNodes(arguments);
98         
99         CommunicationEnvelope responseEnvelope = callService(requestEnvelope);
100         
101         Node node = null;
102         int status = Integer.parseInt(responseEnvelope.getStatus());
103
104         System.out.println("status:" + status);
105         
106         if(status == 0)
107         {
108             List JavaDoc nodes = responseEnvelope.getNodes();
109             //System.out.println("nodes:" + nodes);
110
node = (Node)nodes.get(0);
111             //System.out.println("Node:" + node);
112
}
113         
114         return node;
115     }
116
117
118     public List JavaDoc getChildNodeList(Integer JavaDoc parentId)
119     {
120         List JavaDoc childContents = null;
121         CommunicationEnvelope requestEnvelope = new CommunicationEnvelope();
122         requestEnvelope.setAction("selectChildNodes");
123
124         List JavaDoc arguments = new ArrayList JavaDoc();
125         Node n = new Node();
126         n.setId(parentId);
127         arguments.add(n);
128         requestEnvelope.setNodes(arguments);
129                 
130         CommunicationEnvelope responseEnvelope = callService(requestEnvelope);
131         
132         Node rootVO = null;
133         int status = Integer.parseInt(responseEnvelope.getStatus());
134
135         //System.out.println("status:" + status);
136

137         if(status == 0)
138         {
139             childContents = responseEnvelope.getNodes();
140         }
141         
142         return childContents;
143     }
144
145     
146
147
148
149     public CommunicationEnvelope callService(CommunicationEnvelope requestEnvelope)
150     {
151         PrintWriter JavaDoc outputToServlet = null;
152         BufferedInputStream JavaDoc inputFromServlet = null;
153         CommunicationEnvelope responseEnvelope = null;
154             
155         try
156         {
157             String JavaDoc url = serverAddress;
158                                    
159             try
160             {
161                 Hashtable JavaDoc hash = serializeEnvelope(requestEnvelope);
162                 //System.out.println("Sending the envelope to the servlet...");
163
String JavaDoc response = postToUrl(serverAddress, hash);
164                 //System.out.println("response:" + response);
165

166                 responseEnvelope = deserializeEnvelope(httpEncodedStringToHashtable(response));
167                 //System.out.println("Status response:" + responseEnvelope.getStatus());
168
}
169             catch (Exception JavaDoc e)
170             {
171                 e.printStackTrace();
172             }
173
174         }
175         catch (Exception JavaDoc e)
176         {
177             System.out.println(e.toString());
178         }
179         
180         return responseEnvelope;
181     }
182
183     
184     /**
185      * This method post information to an URL and returns a string.It throws
186      * an exception if anything goes wrong.
187      * (Works like most 'doPost' methods)
188      *
189      * @param urlAddress The address of the URL you would like to post to.
190      * @param inHash The parameters you would like to post to the URL.
191      * @return The result of the postToUrl method as a string.
192      * @exception java.lang.Exception
193      */

194     
195     private String JavaDoc postToUrl(String JavaDoc urlAddress, Hashtable JavaDoc inHash) throws Exception JavaDoc
196     {
197         URL JavaDoc url = new URL JavaDoc(urlAddress);
198         URLConnection JavaDoc urlConn = url.openConnection();
199         urlConn.setAllowUserInteraction(false);
200         urlConn.setDoOutput (true);
201         urlConn.setDoInput (true);
202         urlConn.setUseCaches (false);
203         urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
204         PrintWriter JavaDoc printout = new PrintWriter JavaDoc(urlConn.getOutputStream(), true);
205         String JavaDoc argString = "";
206         if(inHash != null)
207         {
208             argString = toEncodedString(inHash);
209         }
210         printout.print(argString);
211         printout.flush();
212         printout.close ();
213         InputStream JavaDoc inStream = null;
214         inStream = urlConn.getInputStream();
215         InputStreamReader JavaDoc inStreamReader = new InputStreamReader JavaDoc(inStream);
216         BufferedReader JavaDoc buffer = new BufferedReader JavaDoc(inStreamReader);
217         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
218         String JavaDoc line;
219         while((line = buffer.readLine()) != null)
220         {
221             strbuf.append(line);
222         }
223         String JavaDoc readData = strbuf.toString();
224         buffer.close();
225         return readData;
226     }
227   
228   
229     /**
230      * Encodes a hash table to an URL encoded string.
231      *
232      * @param inHash The hash table you would like to encode
233      * @return A URL encoded string.
234      */

235         
236     private String JavaDoc toEncodedString(Hashtable JavaDoc inHash) throws Exception JavaDoc
237     {
238         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
239         Enumeration JavaDoc names = inHash.keys();
240         while(names.hasMoreElements())
241         {
242             String JavaDoc name = names.nextElement().toString();
243             String JavaDoc value = inHash.get(name).toString();
244             buffer.append(URLEncoder.encode(name, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"));
245             if(names.hasMoreElements())
246             {
247                 buffer.append("&");
248             }
249         }
250         return buffer.toString();
251     }
252     
253     
254
255     /**
256      * Converts a serialized hashtable in the url-encoded format to
257      * a Hashtable that one can use within the program.
258      * A good technique when exchanging information between different
259      * applications.
260      *
261      * @param encodedstrang The url-encoded string.
262      * @return A Hashtable.
263      */

264
265     public Hashtable JavaDoc httpEncodedStringToHashtable(String JavaDoc encodedstrang) throws Exception JavaDoc
266     {
267         Hashtable JavaDoc anropin = new Hashtable JavaDoc();
268         StringTokenizer JavaDoc andsplitter = new StringTokenizer JavaDoc(encodedstrang,"&");
269         while (andsplitter.hasMoreTokens())
270         {
271             String JavaDoc namevaluepair = andsplitter.nextToken();
272             StringTokenizer JavaDoc equalsplitter = new StringTokenizer JavaDoc(namevaluepair,"=");
273             if (equalsplitter.countTokens() == 2)
274             {
275                 String JavaDoc name = equalsplitter.nextToken();
276                 String JavaDoc value = equalsplitter.nextToken();
277                 anropin.put(URLDecoder.decode(URLDecoder.decode(name, "UTF-8"), "UTF-8"),URLDecoder.decode(URLDecoder.decode(value, "UTF-8"), "UTF-8"));
278             }
279         }
280         return anropin;
281     }
282
283
284
285
286     private Hashtable JavaDoc serializeEnvelope(CommunicationEnvelope requestEnvelope)
287     {
288         Hashtable JavaDoc hash = new Hashtable JavaDoc();
289         System.out.println("Serializing:" + requestEnvelope);
290         hash.put("action", requestEnvelope.getAction());
291         hash.put("status", requestEnvelope.getStatus());
292         
293         List JavaDoc nodes = requestEnvelope.getNodes();
294         int i = 0;
295         Iterator JavaDoc iterator = nodes.iterator();
296         while(iterator.hasNext())
297         {
298             Node n = (Node)iterator.next();
299             hash.put("nodeList." + i + ".id", "" + n.getId());
300             hash.put("nodeList." + i + ".name", "" + n.getName());
301             hash.put("nodeList." + i + ".isBranch", "" + n.getIsBranch());
302             i++;
303         }
304                 
305         return hash;
306     }
307
308
309     private CommunicationEnvelope deserializeEnvelope(Hashtable JavaDoc hash)
310     {
311         CommunicationEnvelope communicationEnvelope = new CommunicationEnvelope();
312         communicationEnvelope.setAction("" + hash.get("action"));
313         communicationEnvelope.setStatus("" + hash.get("status"));
314         //System.out.println("Action:" + communicationEnvelope.getAction());
315
//System.out.println("Status:" + communicationEnvelope.getStatus());
316

317         List JavaDoc nodes = new ArrayList JavaDoc();
318         int i = 0;
319         String JavaDoc id = (String JavaDoc)hash.get("nodeList." + i + ".id");
320         while(id != null)
321         {
322             Node n = new Node();
323             n.setId(new Integer JavaDoc(id));
324             n.setName((String JavaDoc)hash.get("nodeList." + i + ".name"));
325             n.setIsBranch(new Boolean JavaDoc((String JavaDoc)hash.get("nodeList." + i + ".isBranch")));
326             nodes.add(n);
327             //System.out.println("Node:" + n);
328
i++;
329             id = (String JavaDoc)hash.get("nodeList." + i + ".id");
330         }
331         communicationEnvelope.setNodes(nodes);
332                 
333         return communicationEnvelope;
334     }
335
336
337 }
Popular Tags