Monday, January 17, 2011

Starting Open Office from shell

I ran across this excellent reference on how to start OO from shell. instead of that silly file name I just opened it on my desktop and dumped the code. What it worth mentioning is that it opens whatever release you currently have. for completion the code it below:

################
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;

import java.io.IOException;
import java.io.InputStream;

/**
 *
 * @author bobohead2
 */
public class StartOpenOffice {
   
    private String unoUrl =
            "uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager";
   
    /** Creates a new instance of StartOpenOffice */
    public StartOpenOffice() {
    }
   
    public boolean startOpenOffice(String p_scriptpfad){
        boolean loaded = false;
        try {
          // loads the script
            String cmd = p_scriptpfad     //home/bobohead2/OpenOffice.org1.1/ListenOffice.sh";
            Process process = Runtime.getRuntime().exec(cmd);
            InputStream processOut = process.getInputStream();
            InputStream processErr = process.getErrorStream();
           
        } catch (IOException ioe) {
            ioe.printStackTrace(System.out);
        }
        while(loaded == false){
            try{
               // open Office may take a while to open
                XComponentContext xLocalContext =
                       com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null);
               
                XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager();
               
                Object urlResolver  = xLocalServiceManager.createInstanceWithContext(
                        "com.sun.star.bridge.UnoUrlResolver", xLocalContext );
                // query XUnoUrlResolver interface from urlResolver object
                XUnoUrlResolver xUnoUrlResolver = (XUnoUrlResolver) UnoRuntime.queryInterface(
                        XUnoUrlResolver.class, urlResolver );
               
                // Second step: use xUrlResolver interface to import the remote StarOffice.ServiceManager,
                // retrieve its property DefaultContext and get the remote servicemanager
                Object initialObject = xUnoUrlResolver.resolve( unoUrl );
                loaded = true;
            }catch(Exception e){
                // open office is not ready yet
                loaded = false;
                // wait a liitle bit and try again
                for(int i=0;i< 10000;i++){
                   
                }
            }
        }
        return loaded;
    }
}
##########################

and to run it just type:
#!/bin/sh
/opt/openoffice.org2.0/program/soffice "-accept=socket,port=8100;urp;"