KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > webtools > print > rmi > FopPrintServer


1 /*
2  * $Id: FopPrintServer.java 6590 2006-01-26 07:21:36Z jaz $
3  *
4  * Copyright (c) 2001-2006 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 package org.ofbiz.webtools.print.rmi;
26
27 import java.io.IOException JavaDoc;
28 import java.io.Writer JavaDoc;
29 import java.rmi.Naming JavaDoc;
30 import java.rmi.RemoteException JavaDoc;
31 import java.rmi.server.RMIClientSocketFactory JavaDoc;
32 import java.rmi.server.RMIServerSocketFactory JavaDoc;
33 import java.rmi.server.UID JavaDoc;
34 import java.util.Locale JavaDoc;
35 import java.util.Map JavaDoc;
36 import javax.naming.InitialContext JavaDoc;
37 import javax.naming.NamingException JavaDoc;
38 import javax.servlet.http.Cookie JavaDoc;
39 import javax.servlet.http.HttpServletRequest JavaDoc;
40 import javax.servlet.http.HttpServletResponse JavaDoc;
41
42 import javolution.util.FastMap;
43 import org.apache.commons.codec.binary.Base64;
44 import org.apache.commons.collections.map.LinkedMap;
45
46 import org.ofbiz.base.container.Container;
47 import org.ofbiz.base.container.ContainerConfig;
48 import org.ofbiz.base.container.ContainerException;
49 import org.ofbiz.base.util.Debug;
50 import org.ofbiz.base.util.UtilHttp;
51 import org.ofbiz.base.util.UtilValidate;
52 import org.ofbiz.base.util.cache.UtilCache;
53 import org.ofbiz.entity.GenericDelegator;
54 import org.ofbiz.service.GenericDispatcher;
55 import org.ofbiz.service.LocalDispatcher;
56
57 /**
58  * FopPrintServer
59  *
60  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
61  * @version $Rev: 6590 $
62  * @since 3.5
63  */

64 public class FopPrintServer implements Container {
65
66     public static final String JavaDoc module = FopPrintServer.class.getName();
67     private static UtilCache settingsCache = new UtilCache("printer.applet.settings", 50, 50, 0, false, true);
68
69     protected static FopPrintServer instance = null;
70     protected FopPrintRemote remote = null;
71     protected String JavaDoc configFile = null;
72     protected String JavaDoc name = null;
73
74     // Container methods
75

76     /**
77      * @see org.ofbiz.base.container.Container#init(String[], String)
78      */

79     public void init(String JavaDoc[] args, String JavaDoc configFile) {
80         this.configFile = configFile;
81         instance = this;
82     }
83
84     public boolean start() throws ContainerException {
85         // get the container config
86
ContainerConfig.Container cfg = ContainerConfig.getContainer("rmi-print-server", configFile);
87         ContainerConfig.Container.Property initialCtxProp = cfg.getProperty("use-initial-context");
88         ContainerConfig.Container.Property lookupHostProp = cfg.getProperty("bound-host");
89         ContainerConfig.Container.Property lookupPortProp = cfg.getProperty("bound-port");
90         ContainerConfig.Container.Property lookupNameProp = cfg.getProperty("bound-name");
91         ContainerConfig.Container.Property delegatorProp = cfg.getProperty("delegator-name");
92         ContainerConfig.Container.Property clientProp = cfg.getProperty("client-factory");
93         ContainerConfig.Container.Property serverProp = cfg.getProperty("server-factory");
94
95         // check the required lookup-name property
96
if (lookupNameProp == null || lookupNameProp.value == null || lookupNameProp.value.length() == 0) {
97             throw new ContainerException("Invalid lookup-name defined in container configuration");
98         } else {
99             this.name = lookupNameProp.value;
100         }
101
102         // check the required delegator-name property
103
if (delegatorProp == null || delegatorProp.value == null || delegatorProp.value.length() == 0) {
104             throw new ContainerException("Invalid delegator-name defined in container configuration");
105         }
106
107         String JavaDoc useCtx = initialCtxProp == null || initialCtxProp.value == null ? "false" : initialCtxProp.value;
108         String JavaDoc host = lookupHostProp == null || lookupHostProp.value == null ? "localhost" : lookupHostProp.value;
109         String JavaDoc port = lookupPortProp == null || lookupPortProp.value == null ? "1099" : lookupPortProp.value;
110         boolean clientAuth = ContainerConfig.getPropertyValue(cfg, "ssl-client-auth", false);
111
112         // setup the factories
113
RMIClientSocketFactory JavaDoc csf = null;
114         RMIServerSocketFactory JavaDoc ssf = null;
115
116         // get the classloader
117
ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
118
119         // load the factories
120
if (clientProp != null && clientProp.value != null && clientProp.value.length() > 0) {
121             try {
122                 Class JavaDoc c = loader.loadClass(clientProp.value);
123                 csf = (RMIClientSocketFactory JavaDoc) c.newInstance();
124             } catch (Exception JavaDoc e) {
125                 throw new ContainerException(e);
126             }
127         }
128         if (serverProp != null && serverProp.value != null && serverProp.value.length() > 0) {
129             try {
130                 Class JavaDoc c = loader.loadClass(serverProp.value);
131                 ssf = (RMIServerSocketFactory JavaDoc) c.newInstance();
132             } catch (Exception JavaDoc e) {
133                 throw new ContainerException(e);
134             }
135         }
136
137         // set the client auth flag on our custom SSL socket factory
138
if (ssf != null && ssf instanceof org.ofbiz.service.rmi.socket.ssl.SSLServerSocketFactory) {
139             ((org.ofbiz.service.rmi.socket.ssl.SSLServerSocketFactory) ssf).setNeedClientAuth(clientAuth);
140         }
141
142         // get the delegator for this container
143
GenericDelegator delegator = GenericDelegator.getGenericDelegator(delegatorProp.value);
144
145         // create the LocalDispatcher
146
LocalDispatcher dispatcher = new GenericDispatcher(name, delegator);
147
148         // create the RemoteDispatcher
149
try {
150             remote = new FopPrintRemoteImpl(dispatcher.getDispatchContext(), Locale.getDefault(), csf, ssf);
151         } catch (RemoteException JavaDoc e) {
152             throw new ContainerException("Unable to start the RMI Print Server", e);
153         }
154
155         if (!useCtx.equalsIgnoreCase("true")) {
156             // bind RMIDispatcher to RMI Naming (Must be JRMP protocol)
157
try {
158                 Naming.rebind("//" + host + ":" + port + "/" + name, remote);
159             } catch (RemoteException JavaDoc e) {
160                 throw new ContainerException("Unable to bind RMI Print Server", e);
161             } catch (java.net.MalformedURLException JavaDoc e) {
162                 throw new ContainerException("Invalid URL for binding", e);
163             }
164         } else {
165             // bind RMIDispatcher to InitialContext (must be RMI protocol not IIOP)
166
try {
167                 InitialContext JavaDoc ic = new InitialContext JavaDoc();
168                 ic.rebind(name, remote);
169             } catch (NamingException JavaDoc e) {
170                 throw new ContainerException("Unable to bind RMI Print Server to JNDI", e);
171             }
172
173             // check JNDI
174
try {
175                 InitialContext JavaDoc ic = new InitialContext JavaDoc();
176                 Object JavaDoc o = ic.lookup(name);
177                 if (o == null) {
178                     throw new NamingException JavaDoc("Object came back null");
179                 }
180             } catch (NamingException JavaDoc e) {
181                 throw new ContainerException("Unable to lookup bound objects", e);
182             }
183         }
184
185         return true;
186     }
187
188     public void stop() throws ContainerException {
189     }
190
191     public FopPrintRemote getRemote() {
192         return this.remote;
193     }
194
195     public static String JavaDoc getXslFo(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp) {
196         FopPrintRemote remote = instance.getRemote();
197         Map JavaDoc reqParams = UtilHttp.getParameterMap(req);
198         reqParams.put("locale", UtilHttp.getLocale(req));
199
200         String JavaDoc screenUri = (String JavaDoc) reqParams.remove("screenUri");
201         if (screenUri != null && reqParams.size() > 0) {
202             String JavaDoc base64String = null;
203             try {
204                 byte[] bytes = remote.getXslFo(screenUri, reqParams);
205                 base64String = new String JavaDoc(Base64.encodeBase64(bytes));
206             } catch (RemoteException JavaDoc e) {
207                 Debug.logError(e, module);
208                 try {
209                     resp.sendError(500);
210                 } catch (IOException JavaDoc e1) {
211                     Debug.logError(e1, module);
212                 }
213             }
214             if (base64String != null) {
215                 try {
216                     Writer JavaDoc out = resp.getWriter();
217                     out.write(base64String);
218                 } catch (IOException JavaDoc e) {
219                     try {
220                         resp.sendError(500);
221                     } catch (IOException JavaDoc e1) {
222                         Debug.logError(e1, module);
223                     }
224                 }
225             }
226         }
227
228         return null;
229     }
230
231     public static String JavaDoc readFopPrintServerSettings(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp) {
232         Map JavaDoc screenPrinterMap = new LinkedMap();
233         Cookie JavaDoc[] cookies = req.getCookies();
234         String JavaDoc sessionId = null;
235
236         for (int i = 0; i < cookies.length; i++) {
237             if ("ofbiz.print.session".equals(cookies[i].getName())) {
238                 String JavaDoc value = cookies[i].getValue();
239                 if (value.startsWith("\"")) {
240                     value = value.substring(1);
241                 }
242                 if (value.endsWith("\"")) {
243                     value = value.substring(0, value.length() - 1);
244                 }
245                 if (UtilValidate.isNotEmpty(value)) {
246                     sessionId = value;
247                 }
248             }
249         }
250
251         Map JavaDoc settingsMap = null;
252         if (sessionId != null) {
253             settingsMap = (Map JavaDoc) settingsCache.get(sessionId);
254         } else {
255             sessionId = new UID JavaDoc().toString();
256             Debug.log("Created new session ID: " + sessionId, module);
257         }
258
259         if (settingsMap == null) {
260             settingsMap = FastMap.newInstance();
261             Debug.log("Empty settings map created for ID: " + sessionId, module);
262         } else {
263             Debug.log("Found settings [" + settingsMap.size() + "] for ID: " + sessionId, module);
264         }
265
266         String JavaDoc[] screens = req.getParameterValues("screen");
267         for (int i = 0; i < screens.length; i++) {
268             String JavaDoc screen = screens[i].indexOf("?") != -1 ?
269                 screens[i].substring(0, screens[i].indexOf("?")) : screens[i];
270             Debug.log("Checking setting for FOP report: " + screen, module);
271
272             String JavaDoc reportSetting = (String JavaDoc) settingsMap.get(screen);
273             if (reportSetting != null) {
274                 screenPrinterMap.put(screens[i], reportSetting);
275                 Debug.log("Found matching setting", module);
276             }
277
278             if (!screenPrinterMap.containsKey(screens[i])) {
279                Debug.log("No matching setting found; using null");
280                screenPrinterMap.put(screens[i], null);
281             }
282         }
283
284         req.setAttribute("screenPrinterMap", screenPrinterMap);
285         req.setAttribute("sessionId", sessionId);
286         //Debug.log("Screen Printer Map ID [" + sessionId + "] - " + screenPrinterMap, module);
287

288         return "success";
289     }
290
291     public static String JavaDoc writeFopPrintServerSettings(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp) {
292         String JavaDoc sessionId = req.getParameter("sessionId");
293         if (sessionId != null) {
294             Cookie JavaDoc printCookie = new Cookie JavaDoc("ofbiz.print.session", sessionId);
295             printCookie.setMaxAge(60 * 60 * 24 * 365);
296             printCookie.setPath("/");
297             resp.addCookie(printCookie);
298             printCookie(printCookie);
299         } else {
300             Debug.logError("No session ID returned from applet", module);
301         }
302
303         return "success";
304     }
305
306     public static String JavaDoc receiveUpdateAppletSettings(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp) {
307         Map JavaDoc paramMap = UtilHttp.getParameterMap(req);
308         String JavaDoc sessionId = (String JavaDoc) paramMap.remove("sessionId");
309         String JavaDoc message = "OK";
310         if (sessionId != null) {
311             settingsCache.put(sessionId, paramMap);
312             //Debug.log("Received Settings:", module);
313
//Debug.log("" + paramMap, module);
314
Debug.log("Stored settings for session: " + sessionId, module);
315         } else {
316             message = "FAIL";
317         }
318
319         Writer JavaDoc out = null;
320         try {
321             out = resp.getWriter();
322             out.write(message);
323         } catch (IOException JavaDoc e) {
324             Debug.logError(e, module);
325         } finally {
326             if (out != null) {
327                 try {
328                     out.flush();
329                     out.close();
330                 } catch (IOException JavaDoc e) {
331                     Debug.logError(e, module);
332                 }
333             }
334         }
335
336         return null;
337     }
338
339     public static String JavaDoc return404(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp) {
340         try {
341             resp.sendError(404);
342         } catch (IOException JavaDoc e) {
343             Debug.logError(e, module);
344         }
345         return null;
346     }
347
348     private static void printCookie(Cookie JavaDoc cookie) {
349         Debug.log("Cookie - " + cookie.getName() + " = " + cookie.getValue() +
350                 " ; " + cookie.getMaxAge() + " @ " + cookie.getPath(), module);
351     }
352 }
353
Popular Tags