KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > content > openoffice > OpenOfficeWorker


1 /*
2  * $Id: $
3  *
4  * Copyright 2005-2006 The Apache Software Foundation
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
7  * use this file except in compliance with the License. You may obtain a copy of
8  * the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15  * License for the specific language governing permissions and limitations
16  * under the License.
17  */

18 package org.ofbiz.content.openoffice;
19
20 import java.io.IOException JavaDoc;
21 import java.io.FileNotFoundException JavaDoc;
22 import java.io.File JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.Hashtable JavaDoc;
25 import java.util.Properties JavaDoc;
26 import java.util.Enumeration JavaDoc;
27
28 import javax.servlet.http.HttpServletRequest JavaDoc;
29 import javax.servlet.http.HttpServletResponse JavaDoc;
30
31 import org.ofbiz.base.util.Debug;
32 import org.ofbiz.base.util.UtilMisc;
33 import org.ofbiz.base.util.UtilProperties;
34 import org.ofbiz.base.util.UtilValidate;
35
36 import com.sun.star.beans.PropertyValue;
37 import com.sun.star.beans.XPropertySet;
38 import com.sun.star.bridge.XUnoUrlResolver;
39 import com.sun.star.container.XNameAccess;
40 import com.sun.star.frame.XComponentLoader;
41 import com.sun.star.frame.XStorable;
42 import com.sun.star.lang.XComponent;
43 import com.sun.star.lang.XMultiComponentFactory;
44 import com.sun.star.uno.UnoRuntime;
45 import com.sun.star.uno.XComponentContext;
46
47 /**
48  * OpenOfficeWorker Class
49  *
50  * Note that for this to work you must start OpenOffice with a command such as the following:
51  * <code>soffice -accept=socket,host=localhost,port=8100;urp;</code>
52  *
53  * @author <a HREF="mailto:byersa@automationgroups.com">Al Byers</a>
54  */

55 public class OpenOfficeWorker{
56
57     public static final String JavaDoc module = OpenOfficeWorker.class.getName();
58     
59     /**
60      * Use OpenOffice to convert documents between types
61      */

62     public static XMultiComponentFactory getRemoteServer(String JavaDoc host, String JavaDoc port) throws IOException JavaDoc, Exception JavaDoc {
63         
64         if (UtilValidate.isEmpty(host)) host = UtilProperties.getPropertyValue("openoffice-uno", "oo.host", "localhost");
65         if (UtilValidate.isEmpty(port)) port = UtilProperties.getPropertyValue("openoffice-uno", "oo.port", "8100");
66         
67         XMultiComponentFactory xmulticomponentfactory = null;
68         XComponentContext xcomponentcontext = null;
69         Object JavaDoc objectUrlResolver = null;
70         XUnoUrlResolver xurlresolver = null;
71         Object JavaDoc objectInitial = null;
72         // Converting the document to the favoured type
73
try {
74             /* Bootstraps a component context with the jurt base components
75             registered. Component context to be granted to a component for running.
76             Arbitrary values can be retrieved from the context. */

77             xcomponentcontext = com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null);
78          
79             /* Gets the service manager instance to be used (or null). This method has
80             been added for convenience, because the service manager is a often used
81             object. */

82             xmulticomponentfactory = xcomponentcontext.getServiceManager();
83          
84             /* Creates an instance of the component UnoUrlResolver which
85             supports the services specified by the factory. */

86             objectUrlResolver = xmulticomponentfactory.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", xcomponentcontext);
87          
88             // Create a new url resolver
89
xurlresolver = (XUnoUrlResolver) UnoRuntime.queryInterface(XUnoUrlResolver.class, objectUrlResolver);
90          
91             // Resolves an object that is specified as follow:
92
// uno:<connection description>;<protocol description>;<initial object name>
93
String JavaDoc url = "uno:socket,host=" + host + ",port=" + port + ";urp;StarOffice.ServiceManager";
94             objectInitial = xurlresolver.resolve(url);
95          
96             // Create a service manager from the initial object
97
xmulticomponentfactory = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class, objectInitial);
98         } catch(Exception JavaDoc e) {
99             // TODO: None of this works. Need a programmable start solution.
100
//String ooxvfb = UtilProperties.getPropertyValue("openoffice-uno", "oo.start.xvfb");
101
//String ooexport = UtilProperties.getPropertyValue("openoffice-uno", "oo.start.export");
102
// String oosoffice = UtilProperties.getPropertyValue("openoffice-uno", "oo.start.soffice");
103
//Process procXvfb = Runtime.getRuntime().exec(ooxvfb);
104
//Process procExport = Runtime.getRuntime().exec(ooexport);
105
/*
106             Process procSoffice = Runtime.getRuntime().exec(oosoffice);
107             Thread.sleep(3000);
108             objectInitial = xurlresolver.resolve("uno:socket,host=" + host + ",port=" + port + ";urp;StarOffice.ServiceManager");
109             xmulticomponentfactory = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class, objectInitial);
110             Debug.logInfo("soffice started. " + procSoffice, module);
111             */

112             String JavaDoc errMsg = "Error connecting to OpenOffice with host [" + host + "] and port [" + port + "]: " + e.toString();
113             Debug.logError(e, errMsg, module);
114             throw new IllegalArgumentException JavaDoc(errMsg);
115         }
116         
117         return xmulticomponentfactory;
118     }
119  
120     public static String JavaDoc listFilterNamesEvent(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
121         XMultiComponentFactory factory = null;
122         
123         try {
124             factory = getRemoteServer("localhost", "8100");
125             List JavaDoc filterList = getFilterNames(factory);
126             request.setAttribute("filterList", filterList);
127         } catch(IOException JavaDoc e) {
128             request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
129             return "error";
130         } catch(Exception JavaDoc e) {
131             request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
132             return "error";
133         }
134         return "success";
135     }
136     
137     public static List JavaDoc getFilterNames(XMultiComponentFactory xmulticomponentfactory) throws Exception JavaDoc {
138         XPropertySet xPropertySet = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, xmulticomponentfactory);
139         Object JavaDoc oDefaultContext = xPropertySet.getPropertyValue("DefaultContext");
140         XComponentContext xComponentContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, oDefaultContext);
141
142
143         Object JavaDoc filterFactory = xmulticomponentfactory.createInstanceWithContext("com.sun.star.document.FilterFactory", xComponentContext);
144         XNameAccess xNameAccess = (XNameAccess)UnoRuntime.queryInterface(XNameAccess.class, filterFactory);
145         String JavaDoc [] filterNames = xNameAccess.getElementNames();
146         
147         //String [] serviceNames = filterFactory.getAvailableServiceNames();
148
for (int i=0; i < filterNames.length; i++) {
149             String JavaDoc s = filterNames[i];
150             Debug.logInfo(s, module);
151             /*
152             if (s.toLowerCase().indexOf("filter") >= 0) {
153                 Debug.logInfo("FILTER: " + s, module);
154             }
155             if (s.toLowerCase().indexOf("desktop") >= 0) {
156                 Debug.logInfo("DESKTOP: " + s, module);
157             }
158             */

159         }
160
161         List JavaDoc filterNameList = UtilMisc.toListArray(filterNames);
162         return filterNameList;
163     }
164     
165     public static void convertOODocToFile(XMultiComponentFactory xmulticomponentfactory, String JavaDoc stringUrl, String JavaDoc stringConvertedFile, String JavaDoc outputMimeType) throws FileNotFoundException JavaDoc, IOException JavaDoc, Exception JavaDoc {
166         // Converting the document to the favoured type
167
// Query for the XPropertySet interface.
168
XPropertySet xpropertysetMultiComponentFactory = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xmulticomponentfactory);
169         
170         // Get the default context from the office server.
171
Object JavaDoc objectDefaultContext = xpropertysetMultiComponentFactory.getPropertyValue("DefaultContext");
172         
173         // Query for the interface XComponentContext.
174
XComponentContext xcomponentcontext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, objectDefaultContext);
175         
176         /* A desktop environment contains tasks with one or more
177            frames in which components can be loaded. Desktop is the
178            environment for components which can instanciate within
179            frames. */

180         
181         Object JavaDoc desktopObj = xmulticomponentfactory.createInstanceWithContext("com.sun.star.frame.Desktop", xcomponentcontext);
182         //XDesktop desktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktopObj);
183
XComponentLoader xcomponentloader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, desktopObj);
184        
185         
186         // Preparing properties for loading the document
187
PropertyValue propertyvalue[] = new PropertyValue[ 2 ];
188         // Setting the flag for hidding the open document
189
propertyvalue[ 0 ] = new PropertyValue();
190         propertyvalue[ 0 ].Name = "Hidden";
191         propertyvalue[ 0 ].Value = new Boolean JavaDoc(true);
192
193         propertyvalue[ 1 ] = new PropertyValue();
194         propertyvalue[ 1 ].Name = "UpdateDocMode";
195         propertyvalue[ 1 ].Value = "1";
196
197         // Loading the wanted document
198
Object JavaDoc objectDocumentToStore = xcomponentloader.loadComponentFromURL(stringUrl, "_blank", 0, propertyvalue);
199         
200         // Getting an object that will offer a simple way to store a document to a URL.
201
XStorable xstorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, objectDocumentToStore);
202         
203         // Preparing properties for converting the document
204
propertyvalue = new PropertyValue[ 3 ];
205         // Setting the flag for overwriting
206
propertyvalue[ 0 ] = new PropertyValue();
207         propertyvalue[ 0 ].Name = "Overwrite";
208         propertyvalue[ 0 ].Value = new Boolean JavaDoc(true);
209         // Setting the filter name
210
// Preparing properties for converting the document
211
String JavaDoc filterName = getFilterNameFromMimeType(outputMimeType);
212         
213         propertyvalue[ 1 ] = new PropertyValue();
214         propertyvalue[ 1 ].Name = "FilterName";
215         propertyvalue[ 1 ].Value = filterName;
216         
217         propertyvalue[2] = new PropertyValue();
218         propertyvalue[2].Name = "CompressionMode";
219         propertyvalue[2].Value = "1";
220         
221         Debug.logInfo("stringConvertedFile: "+stringConvertedFile, module);
222         // Storing and converting the document
223
//File newFile = new File(stringConvertedFile);
224
//newFile.createNewFile();
225

226         xstorable.storeToURL(stringConvertedFile, propertyvalue);
227         
228         // Getting the method dispose() for closing the document
229
XComponent xcomponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, xstorable);
230         
231         // Closing the converted document
232
xcomponent.dispose();
233         return;
234     }
235     
236     public static OpenOfficeByteArrayOutputStream convertOODocByteStreamToByteStream(XMultiComponentFactory xmulticomponentfactory,
237             OpenOfficeByteArrayInputStream is, String JavaDoc inputMimeType, String JavaDoc outputMimeType) throws Exception JavaDoc {
238         
239         // Query for the XPropertySet interface.
240
XPropertySet xpropertysetMultiComponentFactory = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xmulticomponentfactory);
241         
242         // Get the default context from the office server.
243
Object JavaDoc objectDefaultContext = xpropertysetMultiComponentFactory.getPropertyValue("DefaultContext");
244         
245         // Query for the interface XComponentContext.
246
XComponentContext xcomponentcontext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, objectDefaultContext);
247         
248         /* A desktop environment contains tasks with one or more
249            frames in which components can be loaded. Desktop is the
250            environment for components which can instanciate within
251            frames. */

252         
253         Object JavaDoc desktopObj = xmulticomponentfactory.createInstanceWithContext("com.sun.star.frame.Desktop", xcomponentcontext);
254         //XDesktop desktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktopObj);
255
XComponentLoader xcomponentloader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, desktopObj);
256         
257         // Preparing properties for loading the document
258
PropertyValue propertyvalue[] = new PropertyValue[2];
259         // Setting the flag for hidding the open document
260
propertyvalue[0] = new PropertyValue();
261         propertyvalue[0].Name = "Hidden";
262         propertyvalue[0].Value = Boolean.TRUE;
263         //
264
propertyvalue[1] = new PropertyValue();
265         propertyvalue[1].Name = "InputStream";
266         propertyvalue[1].Value = is;
267         
268         // Loading the wanted document
269
Object JavaDoc objectDocumentToStore = xcomponentloader.loadComponentFromURL("private:stream", "_blank", 0, propertyvalue);
270         if (objectDocumentToStore == null) {
271             Debug.logError("Could not get objectDocumentToStore object from xcomponentloader.loadComponentFromURL", module);
272         }
273         
274         // Getting an object that will offer a simple way to store a document to a URL.
275
XStorable xstorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, objectDocumentToStore);
276         if (xstorable == null) {
277             Debug.logError("Could not get XStorable object from UnoRuntime.queryInterface", module);
278         }
279         
280         // Preparing properties for converting the document
281
String JavaDoc filterName = getFilterNameFromMimeType(outputMimeType);
282         propertyvalue = new PropertyValue[4];
283         
284         propertyvalue[0] = new PropertyValue();
285         propertyvalue[0].Name = "OutputStream";
286         OpenOfficeByteArrayOutputStream os = new OpenOfficeByteArrayOutputStream();
287         propertyvalue[0].Value = os;
288         // Setting the filter name
289
propertyvalue[1] = new PropertyValue();
290         propertyvalue[1].Name = "FilterName";
291         propertyvalue[1].Value = filterName;
292         // Setting the flag for overwriting
293
propertyvalue[3] = new PropertyValue();
294         propertyvalue[3].Name = "Overwrite";
295         propertyvalue[3].Value = Boolean.TRUE;
296         // For PDFs
297
propertyvalue[2] = new PropertyValue();
298         propertyvalue[2].Name = "CompressionMode";
299         propertyvalue[2].Value = "1";
300         
301         xstorable.storeToURL("private:stream", propertyvalue);
302         //xstorable.storeToURL("file:///home/byersa/testdoc1_file.pdf", propertyvalue);
303

304         // Getting the method dispose() for closing the document
305
XComponent xcomponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, xstorable);
306         
307         // Closing the converted document
308
xcomponent.dispose();
309       
310         return os;
311     }
312     
313     public static String JavaDoc getFilterNameFromMimeType(String JavaDoc mimeType) {
314         String JavaDoc filterName = "";
315         if (UtilValidate.isEmpty(mimeType)) {
316             filterName = "HTML";
317         } else if (mimeType.equalsIgnoreCase("application/pdf")) {
318             filterName = "writer_pdf_Export";
319         } else if (mimeType.equalsIgnoreCase("application/msword")) {
320             filterName = "MS Word 97";
321         } else if (mimeType.equalsIgnoreCase("text/html")) {
322             filterName = "HTML (StarWriter)";
323         } else {
324             filterName = "HTML";
325         }
326         return filterName;
327
328     }
329     
330     public static String JavaDoc getExtensionFromMimeType(String JavaDoc mimeType) {
331         String JavaDoc extension = "";
332         if (UtilValidate.isEmpty(mimeType)) {
333             extension = "html";
334         } else if (mimeType.equalsIgnoreCase("application/pdf")) {
335             extension = "pdf";
336         } else if (mimeType.equalsIgnoreCase("application/msword")) {
337             extension = "doc";
338         } else if (mimeType.equalsIgnoreCase("text/html")) {
339             extension = "html";
340         } else {
341             extension = "html";
342         }
343         return extension;
344
345     }
346 }
347
Popular Tags