1 /*************************************************************************
3 * $RCSfile: ConverterServlet.java,v $
7 * last change: $Author: hr $ $Date: 2004-02-02 20:09:11 $
9 * The Contents of this file are made available subject to the terms of
12 * Copyright (c) 2003 by Sun Microsystems, Inc.
13 * All rights reserved.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
23 * 3. Neither the name of Sun Microsystems, Inc. nor the names of its
24 * contributors may be used to endorse or promote products derived
25 * from this software without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
30 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
31 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *************************************************************************/
42 import java
.io
.IOException
;
43 import java
.io
.PrintWriter
;
45 import java
.io
.FileInputStream
;
46 import java
.io
.BufferedInputStream
;
47 import java
.util
.Enumeration
;
50 import javax
.servlet
.ServletException
;
51 import javax
.servlet
.http
.HttpServlet
;
52 import javax
.servlet
.http
.HttpServletRequest
;
53 import javax
.servlet
.http
.HttpServletResponse
;
54 import javax
.servlet
.ServletOutputStream
;
57 import com
.oreilly
.servlet
.MultipartRequest
;
58 import com
.oreilly
.servlet
.MultipartResponse
;
59 import com
.oreilly
.servlet
.ServletUtils
;
62 import com
.sun
.star
.bridge
.XUnoUrlResolver
;
63 import com
.sun
.star
.uno
.XComponentContext
;
64 import com
.sun
.star
.uno
.UnoRuntime
;
65 import com
.sun
.star
.frame
.XComponentLoader
;
66 import com
.sun
.star
.frame
.XStorable
;
67 import com
.sun
.star
.util
.XCloseable
;
68 import com
.sun
.star
.beans
.PropertyValue
;
69 import com
.sun
.star
.beans
.XPropertySet
;
70 import com
.sun
.star
.lang
.XComponent
;
71 import com
.sun
.star
.lang
.XMultiComponentFactory
;
74 /** This class implements a http servlet in order to convert an incoming document
75 * with help of a running OpenOffice.org and to push the converted file back
78 public class ConverterServlet
extends HttpServlet
{
79 /** Specifies the temporary directory on the web server.
81 private String stringWorkingDirectory
=
82 System
.getProperty( "java.io.tmpdir" ).replace( '\\', '/' );
84 /** Specifies the host for the office server.
86 private String stringHost
= "localhost";
88 /** Specifies the port for the office server.
90 private String stringPort
= "2083";
92 /** Called by the server (via the service method) to allow a servlet to handle
93 * a POST request. The file from the client will be uploaded to the web server
94 * and converted on the web server and after all pushed to the client.
95 * @param request Object that contains the request the client has made of the servlet.
96 * @param response Object that contains the response the servlet sends to the client.
97 * @throws ServletException If the request for the POST could not be handled.
98 * @throws IOException If an input or output error is detected when the servlet handles the request.
100 protected void doPost( HttpServletRequest request
,
101 HttpServletResponse response
) throws ServletException
, java
.io
.IOException
{
103 // If necessary, add a slash to the end of the string.
104 if ( !stringWorkingDirectory
.endsWith( "/" ) ) {
105 stringWorkingDirectory
+= "/";
108 // Construct a MultipartRequest to help read the information.
109 // Pass in the request, a directory to save files to, and the
110 // maximum POST size we should attempt to handle.
111 MultipartRequest multipartrequest
=
112 new MultipartRequest( request
, stringWorkingDirectory
, 5 * 1024 * 1024 );
114 // Getting all file names from the request
115 Enumeration files
= multipartrequest
.getFileNames();
117 // Every received file will be converted to the specified type
118 while (files
.hasMoreElements()) {
119 // Getting the name from the element
120 String stringName
= (String
)files
.nextElement();
122 // Getting the filename from the request
123 String stringFilename
=
124 multipartrequest
.getFilesystemName( stringName
);
126 // Converting the given file on the server to the specified type and
127 // append a special extension
128 File cleanupFile
= null;
129 String stringSourceFile
= stringWorkingDirectory
+ stringFilename
;
132 String stringConvertedFile
= convertDocument(stringSourceFile
,
133 multipartrequest
.getParameter( "converttype" ),
134 multipartrequest
.getParameter( "extension" ));
136 String shortFileName
= stringConvertedFile
.substring(
137 stringConvertedFile
.lastIndexOf('/') + 1);
139 // Set the response header
140 // Set the filename, is used when the file will be saved (problem with mozilla)
141 response
.addHeader( "Content-Disposition",
142 "attachment; filename=" + shortFileName
);
144 // Constructing the multi part response to the client
145 MultipartResponse multipartresponse
= new MultipartResponse(response
);
147 // Is the convert type HTML?
148 if ( ( multipartrequest
.getParameter( "converttype" ).equals(
149 "swriter: HTML (StarWriter)" ) )
150 || ( multipartrequest
.getParameter( "converttype" ).equals(
151 "scalc: HTML (StarCalc)" ) ) ) {
152 // Setting the content type of the response being sent to the client
154 multipartresponse
.startResponse( "text/html" );
156 // Setting the content type of the response being sent to the client
157 // to application/octet-stream so that file will open a dialog box
158 // at the client in order to save the converted file
159 multipartresponse
.startResponse( "application/octet-stream" );
162 // Pushing the converted file to the client
163 ServletUtils
.returnFile( stringConvertedFile
,
164 response
.getOutputStream() );
166 // Finishing the multi part response
167 multipartresponse
.finish();
169 // clean up the working directory
170 cleanupFile
= new File(stringConvertedFile
);
171 if ( cleanupFile
.exists() )
172 cleanupFile
.delete();
174 } catch (Exception exc
) {
175 response
.setContentType( "text/html;charset=8859-1" );
176 PrintWriter out
= response
.getWriter();
178 exc
.printStackTrace();
180 out
.println( "<html><head>" );
181 out
.println( " <title>" + "SDK Converter Servlet" + "</title>" );
182 out
.println( "</head>" );
183 out
.println( "<body><br><p>");
184 out
.println( "<b>Sorry, the conversion failed!</b></p>");
185 out
.println( "<p><b>Error Mesage:</b><br>" + exc
.getMessage() + "<br>");
186 exc
.printStackTrace(out
);
187 out
.println( "</p></body><html>");
190 // clean up the working directory
191 cleanupFile
= new File(stringSourceFile
);
192 if ( cleanupFile
.exists() )
193 cleanupFile
.delete();
196 catch (Exception exception
) {
197 System
.err
.println( exception
.toString() );
201 /** This method converts a document to a given type by using a running
202 * OpenOffice.org and saves the converted document to the specified
204 * @param stringDocumentName The full path name of the file on the server to be converted.
205 * @param stringConvertType Type to convert to.
206 * @param stringExtension This string will be appended to the file name of the converted file.
207 * @return The full path name of the converted file will be returned.
208 * @see stringWorkingDirectory
210 private String
convertDocument( String stringDocumentName
,
211 String stringConvertType
,
212 String stringExtension
)
215 String stringConvertedFile
= "";
217 // Converting the document to the favoured type
220 String stringUrl
= "file:///" + stringDocumentName
;
222 /* Bootstraps a component context with the jurt base components
223 registered. Component context to be granted to a component for running.
224 Arbitrary values can be retrieved from the context. */
225 XComponentContext xcomponentcontext
=
226 com
.sun
.star
.comp
.helper
.Bootstrap
.createInitialComponentContext( null );
228 /* Gets the service manager instance to be used (or null). This method has
229 been added for convenience, because the service manager is a often used
231 XMultiComponentFactory xmulticomponentfactory
=
232 xcomponentcontext
.getServiceManager();
234 /* Creates an instance of the component UnoUrlResolver which
235 supports the services specified by the factory. */
236 Object objectUrlResolver
=
237 xmulticomponentfactory
.createInstanceWithContext(
238 "com.sun.star.bridge.UnoUrlResolver", xcomponentcontext
);
240 // Create a new url resolver
241 XUnoUrlResolver xurlresolver
= ( XUnoUrlResolver
)
242 UnoRuntime
.queryInterface( XUnoUrlResolver
.class,
245 // Resolves an object that is specified as follow:
246 // uno:<connection description>;<protocol description>;<initial object name>
247 Object objectInitial
= xurlresolver
.resolve(
248 "uno:socket,host=" + stringHost
+ ",port=" + stringPort
+
249 ";urp;StarOffice.ServiceManager" );
251 // Create a service manager from the initial object
252 xmulticomponentfactory
= ( XMultiComponentFactory
)
253 UnoRuntime
.queryInterface( XMultiComponentFactory
.class, objectInitial
);
255 // Query for the XPropertySet interface.
256 XPropertySet xpropertysetMultiComponentFactory
= ( XPropertySet
)
257 UnoRuntime
.queryInterface( XPropertySet
.class, xmulticomponentfactory
);
259 // Get the default context from the office server.
260 Object objectDefaultContext
=
261 xpropertysetMultiComponentFactory
.getPropertyValue( "DefaultContext" );
263 // Query for the interface XComponentContext.
264 xcomponentcontext
= ( XComponentContext
) UnoRuntime
.queryInterface(
265 XComponentContext
.class, objectDefaultContext
);
267 /* A desktop environment contains tasks with one or more
268 frames in which components can be loaded. Desktop is the
269 environment for components which can instanciate within
271 XComponentLoader xcomponentloader
= ( XComponentLoader
)
272 UnoRuntime
.queryInterface( XComponentLoader
.class,
273 xmulticomponentfactory
.createInstanceWithContext(
274 "com.sun.star.frame.Desktop", xcomponentcontext
) );
276 // Preparing properties for loading the document
277 PropertyValue propertyvalue
[] = new PropertyValue
[ 1 ];
278 // Setting the flag for hidding the open document
279 propertyvalue
[ 0 ] = new PropertyValue();
280 propertyvalue
[ 0 ].Name
= "Hidden";
281 propertyvalue
[ 0 ].Value
= new Boolean(true);
283 // Loading the wanted document
284 Object objectDocumentToStore
=
285 xcomponentloader
.loadComponentFromURL(
286 stringUrl
, "_blank", 0, propertyvalue
);
288 // Getting an object that will offer a simple way to store a document to a URL.
289 XStorable xstorable
=
290 ( XStorable
) UnoRuntime
.queryInterface( XStorable
.class,
291 objectDocumentToStore
);
293 // Preparing properties for converting the document
294 propertyvalue
= new PropertyValue
[ 2 ];
295 // Setting the flag for overwriting
296 propertyvalue
[ 0 ] = new PropertyValue();
297 propertyvalue
[ 0 ].Name
= "Overwrite";
298 propertyvalue
[ 0 ].Value
= new Boolean(true);
299 // Setting the filter name
300 propertyvalue
[ 1 ] = new PropertyValue();
301 propertyvalue
[ 1 ].Name
= "FilterName";
302 propertyvalue
[ 1 ].Value
= stringConvertType
;
304 // Appending the favoured extension to the origin document name
305 int index
= stringUrl
.lastIndexOf('.');
307 stringConvertedFile
= stringUrl
.substring(0, index
) + "." + stringExtension
;
309 stringConvertedFile
= stringUrl
+ "." + stringExtension
;
312 // Storing and converting the document
313 xstorable
.storeAsURL( stringConvertedFile
, propertyvalue
);
315 XCloseable xcloseable
= (XCloseable
)UnoRuntime
.queryInterface( XCloseable
.class,xstorable
);
317 // Closing the converted document
318 if ( xcloseable
!= null )
319 xcloseable
.close(false);
321 // If Xcloseable is not supported (older versions,
322 // use dispose() for closing the document
323 XComponent xComponent
= ( XComponent
) UnoRuntime
.queryInterface(
324 XComponent
.class, xstorable
);
325 xComponent
.dispose();
329 // catch( Exception exception ) {
330 // exception.printStackTrace();
334 if ( stringConvertedFile
.startsWith( "file:///" ) ) {
335 // Truncating the beginning of the file name
336 stringConvertedFile
= stringConvertedFile
.substring( 8 );
339 // Returning the name of the converted file
340 return stringConvertedFile
;