OpenOffice.org Forum at OOoForum.orgThe OpenOffice.org Forum
 
 [Home]   [FAQ]   [Search]   [Memberlist]   [Usergroups]   [Register
 [Profile]   [Log in to check your private messages]   [Log in

Problem with DocumentConverter.java example

 
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Macros and API
View previous topic :: View next topic  
Author Message
WanaBanana
General User
General User


Joined: 20 Aug 2004
Posts: 7

PostPosted: Fri Aug 20, 2004 7:03 am    Post subject: Problem with DocumentConverter.java example Reply with quote

Hi All,

I'm tring to get the DOcumentConverter example to work properly but my program keeps throwing the following exception:

Code:

com.sun.star.io.IOException:
   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
   at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
   at java.lang.reflect.Constructor.newInstance(Unknown Source)
   at com.sun.star.lib.uno.protocols.urp.Unmarshal.readThrowable(Unmarshal.java:315)
   at com.sun.star.lib.uno.protocols.urp.Unmarshal.readAny(Unmarshal.java:157)
   at com.sun.star.lib.uno.protocols.urp.Unmarshal.readObject(Unmarshal.java:404)
   at com.sun.star.lib.uno.protocols.urp.urp.readReply(urp.java:192)
   at com.sun.star.lib.uno.protocols.urp.urp.readMessage(urp.java:308)
   at com.sun.star.lib.uno.protocols.urp.urp.readMessage(urp.java:607)
   at com.sun.star.lib.uno.bridges.java_remote.java_remote_bridge$MessageDispatcher.invoke(java_remote_bridge.java:184)
   at com.sun.star.lib.uno.bridges.java_remote.java_remote_bridge$MessageDispatcher.run(java_remote_bridge.java:175)


Does anyonw know why this might be happening? The example I am running with my own custom modifications is as follows:
Code:

package wordbuilder.utilities;

/*************************************************************************
*
*  $RCSfile: DocumentConverter.java,v $
*
*  $Revision: 1.3 $
*
*  last change: $Author: hr $ $Date: 2003/06/30 15:54:16 $
*
*  The Contents of this file are made available subject to the terms of
*  the BSD license.

*  Copyright (c) 2003 by Sun Microsystems, Inc.
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*  1. Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*  2. Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*  3. Neither the name of Sun Microsystems, Inc. nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
*  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
*  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
*  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*     
*************************************************************************/

import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;

import java.io.File;
import java.io.FileFilter;


/** The class <CODE>DocumentConverter</CODE> allows you to convert all documents in
* a given directory and in its subdirectories to a given type. A converted
* document will be created in the same directory as the origin document.
*
*/
public class DocumentConverter {
 /** Containing the loaded documents
  */
 static XComponentLoader xcomponentloader = null;

   /** Containing the given type to convert to */ 
   static String stringConvertType = "PDF - Portable Document Format"; 
   
   /** Containing the given extension */ 
   static String stringExtension = "pdf"; 

 static String indent = "";
 
 /** Traversing the given directory recursively and converting their files to the
  * favoured type if possible
  * @param fileDirectory Containing the directory
  */
 static void traverse( File fileDirectory ) {
   // Testing, if the file is a directory, and if so, it throws an exception
   if ( !fileDirectory.isDirectory() ) {
     throw new IllegalArgumentException(
     "not a directory: " + fileDirectory.getName()
     );
   }
   
   System.out.println(indent + "[" + fileDirectory.getName() + "]");
   indent += "  ";
   
   // Getting all files and directories in the current directory
   File[] entries = fileDirectory.listFiles(
   new FileFilter() {
     public boolean accept( File pathname ) {
       return true;
     }
   }
   );
   
   // Iterating for each file and directory
   for ( int i = 0; i < entries.length; ++i ) {
     // Testing, if the entry in the list is a directory
     if ( entries[ i ].isDirectory() ) {
       // Recursive call for the new directory
       traverse( entries[ i ] );
     } else {
       // Converting the document to the favoured type
       try {
         // Composing the URL by replacing all backslashs
         String stringUrl = "file:///"
         + entries[ i ].getAbsolutePath().replace( '\\', '/' );
         
         // Loading the wanted document
         Object objectDocumentToStore =
         DocumentConverter.xcomponentloader.loadComponentFromURL(
         stringUrl, "_blank", 0, new PropertyValue[0] );
         
         // Getting an object that will offer a simple way to store a document to a URL.
         XStorable xstorable =
         ( XStorable ) UnoRuntime.queryInterface( XStorable.class,
         objectDocumentToStore );
         
         // Preparing properties for converting the document
         PropertyValue propertyvalue[] = new PropertyValue[ 2 ];
         // Setting the flag for overwriting
         propertyvalue[ 0 ] = new PropertyValue();
         propertyvalue[ 0 ].Name = "Overwrite";
         propertyvalue[ 0 ].Value = new Boolean(true);
         // Setting the filter name
         propertyvalue[ 1 ] = new PropertyValue();
         propertyvalue[ 1 ].Name = "FilterName";
         propertyvalue[ 1 ].Value = DocumentConverter.stringConvertType;
         
         // Appending the favoured extension to the origin document name
         int index = stringUrl.lastIndexOf('.');
         if (index >= 0)
             stringUrl = stringUrl.substring(0, index + 1);
         stringUrl = stringUrl + DocumentConverter.stringExtension;
         
         // Storing and converting the document
         xstorable.storeAsURL( stringUrl, propertyvalue );
         
         // Getting the method dispose() for closing the document
         XComponent xcomponent =
         ( XComponent ) UnoRuntime.queryInterface( XComponent.class,
         xstorable );
         
         // Closing the converted document
         xcomponent.dispose();
       }
       catch( Exception exception ) {
         exception.printStackTrace();
       }
       
       System.out.println(indent + entries[ i ].getName());
     }
   }
   
   indent = indent.substring(2);
 }
 
 /** Connecting to the office with the component UnoUrlResolver and calling the
  * static method traverse
  * @param args The array of the type String contains the directory, in which all files should be
  * converted, the favoured converting type and the wanted extension
  */
 public static void main( String args[] ) {
   try {
     String sConnectionString = "uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager";

     /*if ( args.length < 3 ) {
       System.out.println(
       "usage: java -classpath <see make> " +
       "DocumentConverter \"<directory to convert>\"" +
       " \"<type to convert to>\" \"<extension>\" [\"<connection>\"]" );
       System.out.println( "\ne.g.:" );
       System.out.println(
       "java -classpath <see make> " +
       "DocumentConverter" + " \"c:/myoffice\" \"swriter: MS Word 97\" \"doc\"" );
       System.exit(1);
     }*/
     
     // It is possible to use a different connection string, passed as argument
     if ( args.length == 4 ) {
           sConnectionString = args[3];
     }
     
     /* Bootstraps a component context with the jurt base components
        registered. Component context to be granted to a component for running.
        Arbitrary values can be retrieved from the context. */
     XComponentContext xComponentContext =
     com.sun.star.comp.helper.Bootstrap.createInitialComponentContext( null );
     
     /* Gets the service manager instance to be used (or null). This method has
        been added for convenience, because the service manager is a often used
        object. */
     XMultiComponentFactory xMultiComponentFactory =
     xComponentContext.getServiceManager();
     
     /* Creates an instance of the component UnoUrlResolver which
        supports the services specified by the factory. */
     Object objectUrlResolver = xMultiComponentFactory.createInstanceWithContext(
     "com.sun.star.bridge.UnoUrlResolver", xComponentContext );
     
     // Create a new url resolver
     XUnoUrlResolver xurlresolver = ( XUnoUrlResolver )
     UnoRuntime.queryInterface( XUnoUrlResolver.class,
     objectUrlResolver );
     
     // Resolves an object that is specified as follow:
     // uno:<connection description>;<protocol description>;<initial object name>
     Object objectInitial = xurlresolver.resolve( sConnectionString );
     
     // Create a service manager from the initial object
     xMultiComponentFactory = ( XMultiComponentFactory )
     UnoRuntime.queryInterface( XMultiComponentFactory.class, objectInitial );
     
     // Query for the XPropertySet interface.
     XPropertySet xpropertysetMultiComponentFactory = ( XPropertySet )
     UnoRuntime.queryInterface( XPropertySet.class, xMultiComponentFactory );
     
     // Get the default context from the office server.
     Object objectDefaultContext =
     xpropertysetMultiComponentFactory.getPropertyValue( "DefaultContext" );
     
     // Query for the interface XComponentContext.
     xComponentContext = ( XComponentContext ) UnoRuntime.queryInterface(
     XComponentContext.class, objectDefaultContext );
     
     /* A desktop environment contains tasks with one or more
        frames in which components can be loaded. Desktop is the
        environment for components which can instanciate within
        frames. */
     xcomponentloader = ( XComponentLoader )
     UnoRuntime.queryInterface( XComponentLoader.class,
     xMultiComponentFactory.createInstanceWithContext(
     "com.sun.star.frame.Desktop", xComponentContext ) );
     
      // Getting the given starting directory     
      File file = new File("C:\\testarea");           
      
      // Getting the given type to convert to     
      stringConvertType = "PDF - Portable Document Format";           
      
      // Getting the given extension that should be appended to the origin document     
      stringExtension = "pdf";     
     
     // Starting the conversion of documents in the given directory and subdirectories
     traverse( file );
     
     System.exit(0);
   }
   catch( Exception exception ) {
     System.err.println( exception );
   }
 }
}


My c:\testarea directory contains a single word document.

Many thanks in advance

Dan
Back to top
View user's profile Send private message
WanaBanana
General User
General User


Joined: 20 Aug 2004
Posts: 7

PostPosted: Fri Aug 20, 2004 7:51 am    Post subject: Reply with quote

Hi again,

I've managed to pinpoint it to this line of code:
Code:
xstorable.storeAsURL( stringUrl, propertyvalue );


Any further than that though and I'm lost Sad

Thanks again!
Back to top
View user's profile Send private message
varungupta
General User
General User


Joined: 18 Aug 2004
Posts: 7

PostPosted: Sat Aug 21, 2004 1:51 am    Post subject: Reply with quote

WanaBanana wrote:
Hi again,

I've managed to pinpoint it to this line of code:
Code:
xstorable.storeAsURL( stringUrl, propertyvalue );


Any further than that though and I'm lost Sad

Thanks again!


Hi WanaBanana

I m also getting the same problem.
I used stringConvertType as "writer_pdf_Export"
And it gives the same exception.

Will someone help us

Thanx again

Varun
Back to top
View user's profile Send private message
Jeroen
General User
General User


Joined: 09 Aug 2004
Posts: 15
Location: The Netherlands

PostPosted: Sat Aug 21, 2004 2:10 am    Post subject: Reply with quote

Hi! I think the XStorable isnīt created correctly... I create the XStorable with a XTextDocument so I think you need to convert the objectDocumentToStore to a XTextDocument

Code:

XStorable xstorable = ( XStorable ) UnoRuntime.queryInterface( XStorable.class, [b]XTextDocument[/b]);


So, you need to use a instance of a XTextDocument in the example code...
Back to top
View user's profile Send private message
varungupta
General User
General User


Joined: 18 Aug 2004
Posts: 7

PostPosted: Sat Aug 21, 2004 2:32 am    Post subject: Reply with quote

Jeroen wrote:
Hi! I think the XStorable isnīt created correctly... I create the XStorable with a XTextDocument so I think you need to convert the objectDocumentToStore to a XTextDocument

Code:

XStorable xstorable = ( XStorable ) UnoRuntime.queryInterface( XStorable.class, [b]XTextDocument[/b]);


So, you need to use a instance of a XTextDocument in the example code...


Hi Jeroen

I tried that but it also does not work
Any other thing that u can suggest

Varun
Back to top
View user's profile Send private message
Jeroen
General User
General User


Joined: 09 Aug 2004
Posts: 15
Location: The Netherlands

PostPosted: Tue Aug 24, 2004 5:24 am    Post subject: Reply with quote

Hi, sorry, I can't suggest anything else at the moment...
Back to top
View user's profile Send private message
Bernie
General User
General User


Joined: 15 Apr 2004
Posts: 28
Location: Grenoble, France

PostPosted: Wed Aug 25, 2004 4:57 am    Post subject: Reply with quote

Hello,
when i want to create a PDF document, i use this :

XStorable xstorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, myXTextDocument);
PropertyValue propertyValue[] = new PropertyValue[2];
propertyValue[0] = new PropertyValue();
propertyValue[0].Name = "FilterName";
propertyValue[0].Value = "writer_pdf_Export";
propertyValue[1] = new PropertyValue();
propertyValue[1].Name = "Overwrite";
propertyValue[1].Value = Boolean.TRUE;
XModel xModel = (XModel) UnoRuntime.queryInterface(XModel.class, myXTextDocument);
XFrame xFrame = xModel.getCurrentController().getFrame();
xFrame.activate();

xstorable.storeToURL(outPdfDocument, propertyValue);

Please note the bolded instructions ! Without them, my program was crashing...

HTH
_________________
Bernie.
Back to top
View user's profile Send private message
DannyB
Moderator
Moderator


Joined: 02 Apr 2003
Posts: 3991
Location: Lawrence, Kansas, USA

PostPosted: Thu Aug 26, 2004 6:31 am    Post subject: Reply with quote

The thing of importance here is storeToURL versus storeAsURL.

storeAsURL stores the document, such that the document is now saved as that file. This is more like File --> Save.

storeToURL is more like File --> Save A Copy As....
(although OOo has no such command.)

You can use either the TO or AS when storing a document into a format that can completely represent the document. i.e a Writer document can be stored either TO or AS a SXW or DOC, for example. But you can only store TO a PDF, for example. There is no capability to read the PDF back in, so you can't store AS a PDF.
_________________
Want to make OOo Drawings like the colored flower design to the left?
Back to top
View user's profile Send private message
johncarl81
Newbie
Newbie


Joined: 05 Aug 2005
Posts: 1

PostPosted: Fri Aug 05, 2005 9:14 am    Post subject: Problem with loadcomponentfromURL Reply with quote

Hello,
First, let me say that this website is a total help. I have been searching for a solution to convert docs to pdfs on our solaris machine forever and I found the solution here. Anwayys, the problem I am having is the following:

I have to read a doc file from an actual http:// url in .loadcomponentfromurl and it simply returns null. It doesnt throw an exception, it just returns null... which made me think that the url could not be read. But I have error checked this problem. I can save this url to disk and it saves as the filename. Also, I can read in a sxw file from a http:// url just fine and it converts it just as it should. In addtion, if the file is on my local drive (file:///) then I can read and convert the .doc file just fine. So, the problem simply comes down to that I cant .loadComponentFromURL when the url is a .doc file. Could anyone help me solve this problem? Thanks.
Back to top
View user's profile Send private message Send e-mail
Display posts from previous:   
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Macros and API All times are GMT - 8 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group