1 /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
4 * The Contents of this file are made available subject to the terms of
7 * Copyright 2000, 2010 Oracle and/or its affiliates.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of Sun Microsystems, Inc. nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
29 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
31 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
32 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 import java
.io
.IOException
;
38 import java
.io
.PrintWriter
;
40 import java
.util
.Enumeration
;
43 import javax
.servlet
.ServletException
;
44 import javax
.servlet
.http
.HttpServlet
;
45 import javax
.servlet
.http
.HttpServletRequest
;
46 import javax
.servlet
.http
.HttpServletResponse
;
48 import com
.oreilly
.servlet
.MultipartRequest
;
49 import com
.oreilly
.servlet
.MultipartResponse
;
50 import com
.oreilly
.servlet
.ServletUtils
;
53 import com
.sun
.star
.bridge
.XUnoUrlResolver
;
54 import com
.sun
.star
.uno
.XComponentContext
;
55 import com
.sun
.star
.uno
.UnoRuntime
;
56 import com
.sun
.star
.frame
.XComponentLoader
;
57 import com
.sun
.star
.frame
.XStorable
;
58 import com
.sun
.star
.util
.XCloseable
;
59 import com
.sun
.star
.beans
.PropertyValue
;
60 import com
.sun
.star
.beans
.XPropertySet
;
61 import com
.sun
.star
.lang
.XComponent
;
62 import com
.sun
.star
.lang
.XMultiComponentFactory
;
65 /** This class implements a http servlet in order to convert an incoming document
66 * with help of a running OpenOffice.org and to push the converted file back
69 public class ConverterServlet
extends HttpServlet
{
70 /** Specifies the temporary directory on the web server.
72 private String stringWorkingDirectory
= System
.getProperty( "java.io.tmpdir" ).replace( '\\', '/' );
74 /** Specifies the host for the office server.
76 private static final String stringHost
= "localhost";
78 /** Specifies the port for the office server.
80 private static final String stringPort
= "2083";
82 /** Called by the server (via the service method) to allow a servlet to handle
83 * a POST request. The file from the client will be uploaded to the web server
84 * and converted on the web server and after all pushed to the client.
85 * @param request Object that contains the request the client has made of the servlet.
86 * @param response Object that contains the response the servlet sends to the client.
87 * @throws ServletException If the request for the POST could not be handled.
88 * @throws IOException If an input or output error is detected when the servlet handles the request.
91 protected void doPost( HttpServletRequest request
,
92 HttpServletResponse response
) throws ServletException
, java
.io
.IOException
{
94 // If necessary, add a slash to the end of the string.
95 if ( !stringWorkingDirectory
.endsWith( "/" ) ) {
96 stringWorkingDirectory
+= "/";
99 // Construct a MultipartRequest to help read the information.
100 // Pass in the request, a directory to save files to, and the
101 // maximum POST size we should attempt to handle.
102 MultipartRequest multipartrequest
=
103 new MultipartRequest( request
, stringWorkingDirectory
, 5 * 1024 * 1024 );
105 // Getting all file names from the request
106 Enumeration files
= multipartrequest
.getFileNames();
108 // Every received file will be converted to the specified type
109 while (files
.hasMoreElements()) {
110 // Getting the name from the element
111 String stringName
= (String
)files
.nextElement();
113 // Getting the filename from the request
114 String stringFilename
=
115 multipartrequest
.getFilesystemName( stringName
);
117 // Converting the given file on the server to the specified type and
118 // append a special extension
119 File cleanupFile
= null;
120 String stringSourceFile
= stringWorkingDirectory
+ stringFilename
;
123 String stringConvertedFile
= convertDocument(stringSourceFile
,
124 multipartrequest
.getParameter( "converttype" ),
125 multipartrequest
.getParameter( "extension" ));
127 String shortFileName
= stringConvertedFile
.substring(
128 stringConvertedFile
.lastIndexOf('/') + 1);
130 // Set the response header
131 // Set the filename, is used when the file will be saved (problem with mozilla)
132 response
.addHeader( "Content-Disposition",
133 "attachment; filename=" + shortFileName
);
135 // Constructing the multi part response to the client
136 MultipartResponse multipartresponse
= new MultipartResponse(response
);
138 // Is the convert type HTML?
139 if ( ( multipartrequest
.getParameter( "converttype" ).equals(
140 "swriter: HTML (StarWriter)" ) )
141 || ( multipartrequest
.getParameter( "converttype" ).equals(
142 "scalc: HTML (StarCalc)" ) ) ) {
143 // Setting the content type of the response being sent to the client
145 multipartresponse
.startResponse( "text/html" );
147 // Setting the content type of the response being sent to the client
148 // to application/octet-stream so that file will open a dialog box
149 // at the client in order to save the converted file
150 multipartresponse
.startResponse( "application/octet-stream" );
153 // Pushing the converted file to the client
154 ServletUtils
.returnFile( stringConvertedFile
,
155 response
.getOutputStream() );
157 // Finishing the multi part response
158 multipartresponse
.finish();
160 // clean up the working directory
161 cleanupFile
= new File(stringConvertedFile
);
162 if ( cleanupFile
.exists() )
163 cleanupFile
.delete();
165 } catch (Exception exc
) {
166 response
.setContentType( "text/html;charset=8859-1" );
167 PrintWriter out
= response
.getWriter();
169 exc
.printStackTrace();
171 out
.println( "<html><head>" );
172 out
.println( " <title>" + "SDK Converter Servlet" + "</title>" );
173 out
.println( "</head>" );
174 out
.println( "<body><br><p>");
175 out
.println( "<b>Sorry, the conversion failed!</b></p>");
176 out
.println( "<p><b>Error Message:</b><br>" + exc
.getMessage() + "<br>");
177 exc
.printStackTrace(out
);
178 out
.println( "</p></body><html>");
181 // clean up the working directory
182 cleanupFile
= new File(stringSourceFile
);
183 if ( cleanupFile
.exists() )
184 cleanupFile
.delete();
187 catch (Exception exception
) {
188 System
.err
.println( exception
.toString() );
192 /** This method converts a document to a given type by using a running
193 * OpenOffice.org and saves the converted document to the specified
195 * @param stringDocumentName The full path name of the file on the server to be converted.
196 * @param stringConvertType Type to convert to.
197 * @param stringExtension This string will be appended to the file name of the converted file.
198 * @return The full path name of the converted file will be returned.
199 * @see stringWorkingDirectory
201 private String
convertDocument( String stringDocumentName
,
202 String stringConvertType
,
203 String stringExtension
)
206 String stringConvertedFile
= "";
208 // Converting the document to the favoured type
211 String stringUrl
= "file:///" + stringDocumentName
;
213 /* Bootstraps a component context with the jurt base components
214 registered. Component context to be granted to a component for running.
215 Arbitrary values can be retrieved from the context. */
216 XComponentContext xcomponentcontext
=
217 com
.sun
.star
.comp
.helper
.Bootstrap
.createInitialComponentContext( null );
219 /* Gets the service manager instance to be used (or null). This method has
220 been added for convenience, because the service manager is an often used
222 XMultiComponentFactory xmulticomponentfactory
=
223 xcomponentcontext
.getServiceManager();
225 /* Creates an instance of the component UnoUrlResolver which
226 supports the services specified by the factory. */
227 Object objectUrlResolver
=
228 xmulticomponentfactory
.createInstanceWithContext(
229 "com.sun.star.bridge.UnoUrlResolver", xcomponentcontext
);
231 // Create a new url resolver
232 XUnoUrlResolver xurlresolver
= UnoRuntime
.queryInterface( XUnoUrlResolver
.class,
235 // Resolves an object that is specified as follow:
236 // uno:<connection description>;<protocol description>;<initial object name>
237 Object objectInitial
= xurlresolver
.resolve(
238 "uno:socket,host=" + stringHost
+ ",port=" + stringPort
+
239 ";urp;StarOffice.ServiceManager" );
241 // Create a service manager from the initial object
242 xmulticomponentfactory
= UnoRuntime
.queryInterface( XMultiComponentFactory
.class, objectInitial
);
244 // Query for the XPropertySet interface.
245 XPropertySet xpropertysetMultiComponentFactory
= UnoRuntime
.queryInterface( XPropertySet
.class, xmulticomponentfactory
);
247 // Get the default context from the office server.
248 Object objectDefaultContext
=
249 xpropertysetMultiComponentFactory
.getPropertyValue( "DefaultContext" );
251 // Query for the interface XComponentContext.
252 xcomponentcontext
= UnoRuntime
.queryInterface(
253 XComponentContext
.class, objectDefaultContext
);
255 /* A desktop environment contains tasks with one or more
256 frames in which components can be loaded. Desktop is the
257 environment for components which can instantiate within
259 XComponentLoader xcomponentloader
= UnoRuntime
.queryInterface( XComponentLoader
.class,
260 xmulticomponentfactory
.createInstanceWithContext(
261 "com.sun.star.frame.Desktop", xcomponentcontext
) );
263 // Preparing properties for loading the document
264 PropertyValue propertyvalue
[] = new PropertyValue
[ 1 ];
265 // Setting the flag to hide the open document
266 propertyvalue
[ 0 ] = new PropertyValue();
267 propertyvalue
[ 0 ].Name
= "Hidden";
268 propertyvalue
[ 0 ].Value
= Boolean
.TRUE
;
270 // Loading the wanted document
271 Object objectDocumentToStore
=
272 xcomponentloader
.loadComponentFromURL(
273 stringUrl
, "_blank", 0, propertyvalue
);
275 // Getting an object that will offer a simple way to store a document to a URL.
276 XStorable xstorable
=
277 UnoRuntime
.queryInterface( XStorable
.class,
278 objectDocumentToStore
);
280 // Preparing properties for converting the document
281 propertyvalue
= new PropertyValue
[ 2 ];
282 // Setting the flag for overwriting
283 propertyvalue
[ 0 ] = new PropertyValue();
284 propertyvalue
[ 0 ].Name
= "Overwrite";
285 propertyvalue
[ 0 ].Value
= Boolean
.TRUE
;
286 // Setting the filter name
287 propertyvalue
[ 1 ] = new PropertyValue();
288 propertyvalue
[ 1 ].Name
= "FilterName";
289 propertyvalue
[ 1 ].Value
= stringConvertType
;
291 // Appending the favoured extension to the origin document name
292 int index
= stringUrl
.lastIndexOf('.');
294 stringConvertedFile
= stringUrl
.substring(0, index
) + "." + stringExtension
;
296 stringConvertedFile
= stringUrl
+ "." + stringExtension
;
299 // Storing and converting the document
300 xstorable
.storeAsURL( stringConvertedFile
, propertyvalue
);
302 XCloseable xcloseable
= UnoRuntime
.queryInterface( XCloseable
.class,xstorable
);
304 // Closing the converted document
305 if ( xcloseable
!= null )
306 xcloseable
.close(false);
308 // If Xcloseable is not supported (older versions,
309 // use dispose() for closing the document
310 XComponent xComponent
= UnoRuntime
.queryInterface(
311 XComponent
.class, xstorable
);
312 xComponent
.dispose();
315 if ( stringConvertedFile
.startsWith( "file:///" ) ) {
316 // Truncating the beginning of the file name
317 stringConvertedFile
= stringConvertedFile
.substring( 8 );
320 // Returning the name of the converted file
321 return stringConvertedFile
;
325 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */