KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > cms > util > RemoteCacheUpdater


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.util;
25
26 import java.io.BufferedReader JavaDoc;
27 import java.io.InputStream JavaDoc;
28 import java.io.InputStreamReader JavaDoc;
29 import java.io.PrintWriter JavaDoc;
30 import java.net.URL JavaDoc;
31 import java.net.URLConnection JavaDoc;
32 import java.net.URLEncoder JavaDoc;
33 import java.util.ArrayList JavaDoc;
34 import java.util.Enumeration JavaDoc;
35 import java.util.Hashtable JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.List JavaDoc;
38 import java.util.Map JavaDoc;
39 import java.util.StringTokenizer JavaDoc;
40
41 import org.apache.log4j.Logger;
42
43
44 /**
45  * This class is a class that sends a update-message to all registered instances of delivery-engine.
46  *
47  * @author Mattias Bogeblad
48  *
49  */

50
51 public class RemoteCacheUpdater implements NotificationListener
52 {
53     private final static Logger logger = Logger.getLogger(RemoteCacheUpdater.class.getName());
54
55     //A list of system changes that will either be published upon the next publication or on a manual publishing of them.
56
private static List JavaDoc waitingSystemNotificationMessages = new ArrayList JavaDoc();
57     
58     /**
59      * Default Constructor
60      */

61     
62     public RemoteCacheUpdater()
63     {
64     }
65
66     /**
67      * This method sets the context/arguments the listener should operate with. Could be debuglevels and stuff
68      * like that.
69      */

70     
71     public void setContextParameters(Map JavaDoc map)
72     {
73     }
74     
75     public static List JavaDoc getSystemNotificationMessages()
76     {
77         return waitingSystemNotificationMessages;
78     }
79
80     public static void clearSystemNotificationMessages()
81     {
82         synchronized(waitingSystemNotificationMessages)
83         {
84             waitingSystemNotificationMessages.clear();
85         }
86     }
87
88     /**
89      * This method gets called when a new NotificationMessage is available.
90      * The writer just calls the transactionHistoryController which stores it.
91      */

92     
93     public void notify(NotificationMessage notificationMessage)
94     {
95         try
96         {
97             logger.info("Update Remote caches....");
98             updateRemoteCaches(notificationMessage);
99             logger.info("Done updating remote caches....");
100         }
101         catch(Exception JavaDoc e)
102         {
103             e.printStackTrace();
104         }
105     }
106
107
108     /**
109      * This method serializes the notificationMessage and calls the remote actions.
110      * As a content-tool can have several preview instances we iterate through the instances that have
111      * been indexed in the propertyfile starting with 0.
112      */

113     
114     public void updateRemoteCaches(NotificationMessage notificationMessage) throws Exception JavaDoc
115     {
116         throw new Exception JavaDoc("Wrong - this message handler should not be called...");
117         /*
118         Hashtable hashedMessage = notificationMessageToHashtable(notificationMessage);
119         
120         List urls = new ArrayList();
121         
122         if(notificationMessage.getType() == NotificationMessage.PUBLISHING || notificationMessage.getType() == NotificationMessage.UNPUBLISHING || notificationMessage.getType() == NotificationMessage.SYSTEM)
123         {
124             urls.addAll(CmsPropertyHandler.getPublicDeliveryUrls());
125
126             if(notificationMessage.getType() == NotificationMessage.SYSTEM)
127             {
128                 urls.addAll(CmsPropertyHandler.getInternalDeliveryUrls());
129             }
130
131         }
132         else
133         {
134             urls.addAll(CmsPropertyHandler.getInternalDeliveryUrls());
135         }
136         
137         Iterator urlsIterator = urls.iterator();
138         while(urlsIterator.hasNext())
139         {
140             String deliverUrl = (String)urlsIterator.next();
141             String address = deliverUrl + "/" + CmsPropertyHandler.getCacheUpdateAction();
142             logger.info("Updating cache at " + address);
143             try
144             {
145                 String response = postToUrl(address, hashedMessage);
146             }
147             catch(Exception e)
148             {
149                 logger.warn("Error updating cache at " + address + ":" + e.getMessage(), e);
150             }
151         }
152         */

153     }
154     
155
156     /**
157      * This method serializes the notificationMessage and calls the remote actions.
158      * As a content-tool can have several preview instances we iterate through the instances that have
159      * been indexed in the propertyfile starting with 0.
160      */

161     public void updateRemoteCaches(Hashtable JavaDoc internalMessage, Hashtable JavaDoc publicMessage) throws Exception JavaDoc
162     {
163         List JavaDoc internalUrls = CmsPropertyHandler.getInternalDeliveryUrls();
164         
165         if(internalMessage != null)
166         {
167             Iterator JavaDoc urlsIterator = internalUrls.iterator();
168             while(urlsIterator.hasNext())
169             {
170                 String JavaDoc deliverUrl = (String JavaDoc)urlsIterator.next();
171                 String JavaDoc address = deliverUrl + "/" + CmsPropertyHandler.getCacheUpdateAction();
172                 logger.info("Updating cache at " + address);
173                 try
174                 {
175                     String JavaDoc response = postToUrl(address, internalMessage);
176                 }
177                 catch(Exception JavaDoc e)
178                 {
179                     logger.warn("Error updating cache at " + address + ":" + e.getMessage(), e);
180                 }
181             }
182         }
183
184         List JavaDoc publicUrls = CmsPropertyHandler.getPublicDeliveryUrls();
185
186         if(publicMessage != null)
187         {
188             Iterator JavaDoc urlsIterator = publicUrls.iterator();
189             while(urlsIterator.hasNext())
190             {
191                 String JavaDoc deliverUrl = (String JavaDoc)urlsIterator.next();
192                 String JavaDoc address = deliverUrl + "/" + CmsPropertyHandler.getCacheUpdateAction();
193                 logger.info("Updating cache at " + address);
194                 try
195                 {
196                     String JavaDoc response = postToUrl(address, publicMessage);
197                 }
198                 catch(Exception JavaDoc e)
199                 {
200                     logger.warn("Error updating cache at " + address + ":" + e.getMessage(), e);
201                 }
202             }
203         }
204
205     }
206
207     private Hashtable JavaDoc notificationMessageToHashtable(NotificationMessage notificationMessage)
208     {
209         Hashtable JavaDoc hash = new Hashtable JavaDoc();
210
211         logger.info("Serializing:" + notificationMessage);
212         
213         hash.put("className", notificationMessage.getClassName());
214         hash.put("objectId", notificationMessage.getObjectId());
215         hash.put("objectName", notificationMessage.getObjectName());
216         hash.put("typeId", "" + notificationMessage.getType());
217                 
218         return hash;
219     }
220     
221
222     /**
223      * This method post information to an URL and returns a string.It throws
224      * an exception if anything goes wrong.
225      * (Works like most 'doPost' methods)
226      *
227      * @param urlAddress The address of the URL you would like to post to.
228      * @param inHash The parameters you would like to post to the URL.
229      * @return The result of the postToUrl method as a string.
230      * @exception java.lang.Exception
231      */

232     
233     private String JavaDoc postToUrl(String JavaDoc urlAddress, Hashtable JavaDoc inHash) throws Exception JavaDoc
234     {
235         URL JavaDoc url = new URL JavaDoc(urlAddress);
236         URLConnection JavaDoc urlConn = url.openConnection();
237         urlConn.setAllowUserInteraction(false);
238         urlConn.setDoOutput (true);
239         urlConn.setDoInput (true);
240         urlConn.setUseCaches (false);
241         urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
242         PrintWriter JavaDoc printout = new PrintWriter JavaDoc(urlConn.getOutputStream(), true);
243         String JavaDoc argString = "";
244         if(inHash != null)
245         {
246             argString = toEncodedString(inHash);
247         }
248         printout.print(argString);
249         printout.flush();
250         printout.close ();
251         InputStream JavaDoc inStream = null;
252         inStream = urlConn.getInputStream();
253         InputStreamReader JavaDoc inStreamReader = new InputStreamReader JavaDoc(inStream);
254         BufferedReader JavaDoc buffer = new BufferedReader JavaDoc(inStreamReader);
255         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
256         String JavaDoc line;
257         while((line = buffer.readLine()) != null)
258         {
259             strbuf.append(line);
260         }
261         String JavaDoc readData = strbuf.toString();
262         buffer.close();
263         return readData;
264     }
265   
266   
267     /**
268      * Encodes a hash table to an URL encoded string.
269      *
270      * @param inHash The hash table you would like to encode
271      * @return A URL encoded string.
272      */

273         
274     private String JavaDoc toEncodedString(Hashtable JavaDoc inHash) throws Exception JavaDoc
275     {
276         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
277         Enumeration JavaDoc names = inHash.keys();
278         while(names.hasMoreElements())
279         {
280             String JavaDoc name = names.nextElement().toString();
281             String JavaDoc value = inHash.get(name).toString();
282             buffer.append(URLEncoder.encode(name, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"));
283             if(names.hasMoreElements())
284             {
285                 buffer.append("&");
286             }
287         }
288         return buffer.toString();
289     }
290     
291     
292     /**
293      * As the name indicates, this method takes a URL-encoded string and
294      * converts it to a normal javastring. That is, all Mime-encoding is
295      * removed.
296      *
297      * @param encoded The encoded string.
298      * @return An decoded string.
299      */

300         
301     public String JavaDoc decodeHTTPEncodedString(String JavaDoc encoded)
302     {
303         StringBuffer JavaDoc decoded = new StringBuffer JavaDoc(encoded.length());
304         int i = 0;
305         int j = 0;
306
307         while (i < encoded.length()) {
308             char tecken = encoded.charAt(i);
309             i++;
310
311             if (tecken == '+')
312                 tecken = ' ';
313             else if (tecken == '%') {
314                 tecken = (char)Integer.parseInt(encoded.substring(i,i+2), 16);
315                 i+=2;
316                 }
317             decoded.append(tecken);
318             j++;
319             }
320         return new String JavaDoc(decoded);
321     }
322
323
324     /**
325      * Converts a serialized hashtable in the url-encoded format to
326      * a Hashtable that one can use within the program.
327      * A good technique when exchanging information between different
328      * applications.
329      *
330      * @param encodedstrang The url-encoded string.
331      * @return A Hashtable.
332      */

333
334     public Hashtable JavaDoc httpEncodedStringToHashtable(String JavaDoc encodedstrang)
335     {
336         Hashtable JavaDoc anropin = new Hashtable JavaDoc();
337         StringTokenizer JavaDoc andsplitter = new StringTokenizer JavaDoc(encodedstrang,"&");
338         while (andsplitter.hasMoreTokens())
339         {
340             String JavaDoc namevaluepair = andsplitter.nextToken();
341             StringTokenizer JavaDoc equalsplitter = new StringTokenizer JavaDoc(namevaluepair,"=");
342             if (equalsplitter.countTokens() == 2)
343             {
344                 String JavaDoc name = equalsplitter.nextToken();
345                 String JavaDoc value = equalsplitter.nextToken();
346                 anropin.put(decodeHTTPEncodedString(name),decodeHTTPEncodedString(value));
347             }
348         }
349         return anropin;
350     }
351
352     
353
354 }
355
Popular Tags