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