https://issues.apache.org/ooo/show_bug.cgi?id=125309

--- Comment #5 from kpassey <[email protected]> ---
I've put the version in the summary - sorry...

It shows the same behaviour in 3.4.1 and 4.1.0 so I am assuming anything in
between.

The programming language is Java..and this app is running on WIN7 and XP..

Here is my code...I've changed the User and Pwd..and here are the args to run
it - I have it set up in Eclipse so it is easy to test..

Run args - DEBLETRS ALL1.odt all1 AS400 /C:  "\\Asok\epson" 1 KDP

You will need to set up a mailmerg doc and odb to build the qry in the local pc
hence the "/C:" server location - ultimately I want  the docs hosted on a
central server. My printer is a network printer "\\Asok\epson". The qry is the
same name as the doc in lowercase dropping the .odt.. AS400 is the data source
so you can call it what you want..


import java.io.File;
import com.sun.star.beans.NamedValue;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.container.XNameAccess;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.sdbc.XConnection;
import com.sun.star.sdbc.XDataSource;
import com.sun.star.task.XJob;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.XCloseable;
import com.sun.star.view.XPrintable;

public class PrintDoc extends java.lang.Object {

    private XComponentContext xRemoteContext = null;

    private XMultiComponentFactory xRemoteServiceManager = null;

    private static String mDoc;

    private static String mLoc;

    private static String mQRY;

    private static String mSource;

    private static String mPrinter;

    private static String loadUrl;
    private static String tmpUrl;

    private static XComponent xDoc;

    private static String mServer;

    private static int copies;

    private static String letterRef;

    private static String errorText;

    private static boolean OOup = false;

    // constructor

    public PrintDoc(String dsLoc, String dsDoc, String dsQRY, String dsSource,
            String dsServer, String dsPrinter, int num, String ref) {
        mDoc = dsDoc;
        mLoc = dsLoc;
        mQRY = dsQRY;
        mSource = dsSource.trim();
        // mServer = dsServer.trim();
        mServer = "/C:";
        mPrinter = dsPrinter.trim();
        copies = num;
        letterRef = ref;

        System.out.println(" Document " + mDoc);
        System.out.println(" Location " + mLoc);
        System.out.println(" Query Name " + mQRY);
        System.out.println(" DataSource Name " + mSource);
        System.out.println(" OO Server Name " + mServer);
        System.out.println(" Printer Name " + mPrinter);
        System.out.println(" Number of Copies " + copies);
    }

    // /////////////////////////////////////////////////////////////////
    // Main
    // /////////////////////////////////////////////////////////////////
    public static void main(String[] args) {

        if (args.length < 8) {
            System.out.println(" Call this with the following parameters");
            System.out.println(" Document");
            System.out.println(" Location");
            System.out.println(" Query Name");
            System.out.println(" DataSOurce Name");
            System.out.println(" OO Server Name");
            System.out.println(" Printer Name");
            System.out.println(" Copies");
            System.out.println(" Ref");

            System.exit(0);
        }
        // ///////////////////////////////////////////////////////////////////
        // Make sure the letter file exists - otherwise abort
        // ///////////////////////////////////////////////////////////////////
        // ///////////
        // Put the Query name to lower case
        //
        args[2] = args[2].toLowerCase();
        int numCopies = Integer.parseInt(args[6]);

        PrintDoc pd = new PrintDoc(args[0], args[1], args[2], args[3], args[4],
                args[5], numCopies, args[7]);

        try {
            if (pd.testFile()) {
                // only do this if the file is there
                while (!OOup) {
                    pd.useConnection();
                }
                pd.getDocument();
                pd.setOutputDev();
                pd.storeDocument();
                pd.doMerge();
                pd = null;
                System.exit(0);

            } else {
                errorText = "The Letter is missing";

                if (!letterRef.equals("DailyRun")) {
                    ErrorSWT dispDocErr = new ErrorSWT(mDoc, letterRef,
                            errorText);
                    dispDocErr.displayError();
                    dispDocErr = null;
                }

                LogFileEntry lg = new LogFileEntry();
                lg.logDoc = mDoc;
                lg.ref = letterRef;
                lg.comment = errorText;
                lg.writeFile();

            }

        } catch (java.lang.Exception e) {
            ErrorSWT dispConnErr = new ErrorSWT(mDoc, letterRef, errorText);
            dispConnErr.displayError();
            dispConnErr = null;

            LogFileEntry lg = new LogFileEntry();
            lg.logDoc = mDoc;
            lg.ref = letterRef;
            lg.comment = errorText;
            lg.writeFile();

        } finally {
            pd = null;
            System.exit(0);
        }
    }

    // /////////////////////////////////////////////////////////////////
    // Make Sure The file is there
    // ////////////////////////////////////////////////////////////////
    protected boolean testFile() throws java.lang.Exception {

        String dirName = File.separator + File.separator + mServer
                + File.separator + "PJDocs" + File.separator + mLoc;

        File dir = new File(dirName);
        if (dir.isDirectory()) {
            System.out.println(" Directory Found " + dirName);
        } else {
            System.out.println(" Directory Not Found  " + dirName);
        }

        String fileName = File.separator + File.separator + mServer
                + File.separator + "PJDocs" + File.separator + mLoc
                + File.separator + mDoc;
        System.out.println(" Testing for File " + fileName);
        File letterName = new File(fileName);
        if (!letterName.isFile()) {
            errorText = "The open office document has not been created on "
                    + mServer;
            ErrorSWT dispDocErr = new ErrorSWT(mDoc, letterRef, errorText);
            dispDocErr.displayError();
            dispDocErr = null;

            LogFileEntry lg = new LogFileEntry();
            lg.logDoc = mDoc;
            lg.ref = letterRef;
            lg.comment = "The open office document has not been created on "
                    + mServer;
            lg.writeFile();

            System.out.println(" Document " + fileName
                    + " has not been created");
            dir = null;
            letterName = null;
            return false;
        } else {
            dir = null;
            letterName = null;
            return true;
        }

    }

    // /////////////////////////////////////////////////////////////////
    // Make Sure Open Office is Listening
    // /////////////////////////////////////////////////////////////////
    protected void useConnection() throws java.lang.Exception {
        try {

            xRemoteServiceManager = this
                   
.getRemoteServiceManager("uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager");
            //
            // Is Open Office Listening
            //
            OOup = true;
            System.out.println(" Open Office is up on port 8100");
            XNameAccess xNameAccess = (XNameAccess) UnoRuntime.queryInterface(
                    XNameAccess.class, xRemoteServiceManager
                            .createInstanceWithContext(
                                    "com.sun.star.sdb.DatabaseContext",
                                    xRemoteContext));

            String[] elements = xNameAccess.getElementNames();

            for (int i = 0; i < elements.length; i++) {
                System.out.println(" Elements on boot " + elements[i]);
            }

        } catch (com.sun.star.connection.NoConnectException e) {
            System.out.println(" No process listening on the resource");

            OOup = false;

            // Connect or start a OpenOffice instance
            System.out.println(" Starting OO");
            startOffice();
        } catch (com.sun.star.lang.DisposedException e) {

            OOup = false;
            // startOffice();
            startOffice();
        } catch (InterruptedException e) {
            System.out
                    .println(" InterruptedException raised trying to re-start
Office ");

            OOup = false;
            startOffice();
            Thread.sleep(4000);
        }
    }

    // /////////////////////////////////////////////////////////////////
    //
    // /////////////////////////////////////////////////////////////////
    protected XMultiComponentFactory getRemoteServiceManager(String unoUrl)
            throws java.lang.Exception {

        if (xRemoteContext == null) {
            // First step: create local component context, get local
            // servicemanager and
            // ask it to create a UnoUrlResolver object with an XUnoUrlResolver
            // interface
            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);

            XPropertySet xPropertySet = (XPropertySet) UnoRuntime
                    .queryInterface(XPropertySet.class, initialObject);
            Object context = xPropertySet.getPropertyValue("DefaultContext");
            xRemoteContext = (XComponentContext) UnoRuntime.queryInterface(
                    XComponentContext.class, context);
        }
        return xRemoteContext.getServiceManager();
    }

    //
    // Load The Document required to OO
    //
    protected void getDocument() throws java.lang.Exception {
        // document to load

        loadUrl = "file:" + "//" + mServer + "/" + "PJDocs" + "/" + mLoc + "/"
                + mDoc;
        System.out.println(" Loading from " + loadUrl);

        PropertyValue[] loadProps = new PropertyValue[1];
        loadProps[0] = new PropertyValue();
        loadProps[0].Name = "Hidden";
        loadProps[0].Value = new Boolean(true);

        // Create an instance of the desktop service
        Object desktop = xRemoteServiceManager.createInstanceWithContext(
                "com.sun.star.frame.Desktop", xRemoteContext);
        XComponentLoader xComponentLoader = (XComponentLoader) UnoRuntime
                .queryInterface(XComponentLoader.class, desktop);

        // set the document
        xDoc = xComponentLoader.loadComponentFromURL(loadUrl, "_blank", 0,
                loadProps);

        System.out.println(" Document Loaded from " + loadUrl);

        if (xDoc == null) {
            errorText = "Couldn't Load the Document for some reason";

        }
    }

    // //////////////////////////////////////////////////////////////////
    // Set the printer options on the loaded document
    // //////////////////////////////////////////////////////////////////
    protected void setOutputDev() {

        XPrintable xPrintable = (XPrintable) UnoRuntime.queryInterface(
                XPrintable.class, xDoc);

        PropertyValue[] printerDesc = new PropertyValue[1];
        printerDesc[0] = new PropertyValue();
        printerDesc[0].Name = "Name";
        printerDesc[0].Value = mPrinter;

        PropertyValue[] printOpts = new PropertyValue[3];

        printOpts[0] = new PropertyValue();
        printOpts[0].Name = "CopyCount";
        printOpts[0].Value = new Short((short) copies);
        printOpts[1] = new PropertyValue();
        printOpts[1].Name = "Collate";
        printOpts[1].Value = new Boolean((boolean) false);
        printOpts[2] = new PropertyValue();
        printOpts[2].Name = "Wait";
        printOpts[2].Value = new Boolean((boolean) true);

        try {
            xPrintable.setPrinter(printerDesc);
            System.out.println(" Printer Set as " + mPrinter);

        } catch (Exception e) {
            errorText = "Error Setting the printer";
            ErrorSWT dispConnErr = new ErrorSWT(mDoc, letterRef, errorText);
            dispConnErr.displayError();
            dispConnErr = null;
            System.out.println(" There was a problem setting the printer " +
e);
        }
    }

    // //////////////////////////////////////////////////////////////////
    // Save the changed document
    // //////////////////////////////////////////////////////////////////
    protected void storeDocument() throws java.lang.Exception {
        XStorable xStorable = (XStorable) UnoRuntime.queryInterface(
                XStorable.class, xDoc);

        System.out.println(" Document came from " + xStorable.getLocation());
        tmpUrl = "file:" + "//" + mServer + "/" + "PJDocs" + "/" + "Updated"
                + "/" + mDoc;
        PropertyValue[] storeProps = new PropertyValue[1];

        storeProps[0] = new PropertyValue();
        storeProps[0].Name = "Overwrite";
        storeProps[0].Value = new Boolean(true);

        try {

            xStorable.storeAsURL(tmpUrl, storeProps);
            System.out.println(" Document Saved in " + tmpUrl);

        } catch (Exception e) {
            System.out.println(" There was a problem saving the letter " + e);
        }
        // Close the document
        XCloseable xCloseable = (XCloseable) UnoRuntime.queryInterface(
                XCloseable.class, xDoc);

        boolean bClosed = false;

        if (xCloseable != null) {

            try {
                xCloseable.close(true);
                bClosed = true;
                System.out.println(" Closing Document");
                xCloseable = null;
            } catch (com.sun.star.util.CloseVetoException e) {
                System.out.println(e.getLocalizedMessage());
            }
        }
        // check the printer saved ok
        if (!bClosed) {
            XComponent xComponent = (XComponent) UnoRuntime.queryInterface(
                    XComponent.class, xDoc);
            xComponent.dispose();
            System.out.println(" Disposing Component");
            xComponent = null;
        }
        // xDoc = null;
    }

    // end save document as
    // /////////////////////////////////////////////////////////////////
    // Merge
    // /////////////////////////////////////////////////////////////////
    protected void doMerge() {

        Object mmservice = null;
        System.out.println(" Starting the merge");

        try {
            //
            // Connect to the datasource
            //
            XNameAccess xNameAccess = (XNameAccess) UnoRuntime.queryInterface(
                    XNameAccess.class, xRemoteServiceManager
                            .createInstanceWithContext(
                                    "com.sun.star.sdb.DatabaseContext",
                                    xRemoteContext));

            String[] elements = xNameAccess.getElementNames();

            for (int i = 0; i < elements.length; i++) {
                System.out.println(" Elements " + elements[i]);
            }

            XDataSource xDS = (XDataSource) UnoRuntime.queryInterface(
                    XDataSource.class, xNameAccess.getByName(mSource));
            XPropertySet oDsProps = (XPropertySet) UnoRuntime.queryInterface(
                    XPropertySet.class, xDS);

            oDsProps.setPropertyValue("User", "USER");
            oDsProps.setPropertyValue("Password", "PWD");

            try {
                // Create an instance of the MailMerge service
                mmservice = xRemoteServiceManager.createInstanceWithContext(
                        "com.sun.star.text.MailMerge", xRemoteContext);
            } catch (Exception e) {
                LogFileEntry lg = new LogFileEntry();
                lg.logDoc = mDoc;
                lg.ref = letterRef;
                lg.comment = "Could not perform the mail merge for some
reason";
                lg.writeFile();
                errorText = "Error getting MailMerge service";
                System.out.println(" Error getting MailMerge service: " + e);
                return;
            }

            // Set up the properties for the MailMerge command
            XConnection xConnection = xDS.getConnection("USER", "PWD");

            PropertyValue[] printOpts = new PropertyValue[3];
            printOpts[0] = new PropertyValue();
            printOpts[0].Name = "CopyCount";
            printOpts[0].Value = new Short((short) copies);
            printOpts[1] = new PropertyValue();
            printOpts[1].Name = "Collate";
            printOpts[1].Value = new Boolean((boolean) false);
            printOpts[2] = new PropertyValue();
            printOpts[2].Name = "Wait";
            printOpts[2].Value = new Boolean((boolean) true);
            System.out.println(" CopyCount " + copies);

            // Get the XPropertySet interface of the mmservice object
            XPropertySet oObjProps = (XPropertySet) UnoRuntime.queryInterface(
                    XPropertySet.class, mmservice);
            oObjProps.setPropertyValue("DataSourceName", mSource);
            oObjProps.setPropertyValue("ActiveConnection", xConnection);
            oObjProps.setPropertyValue("Command", mQRY);
            oObjProps.setPropertyValue("CommandType", new Integer(
                    com.sun.star.sdb.CommandType.QUERY));
            oObjProps.setPropertyValue("OutputType", new Short(
                    com.sun.star.text.MailMergeType.PRINTER));
            oObjProps.setPropertyValue("DocumentURL", tmpUrl);
            oObjProps.setPropertyValue("PrintOptions", printOpts);
            oObjProps.setPropertyValue("SinglePrintJobs", false);

            System.out.println(" Merge DocumentUrl is " + loadUrl);

            // Get XJob interface from MailMerge service and call execute on it

            System.out.println(" Running the Job");

            XJob job = (XJob) UnoRuntime.queryInterface(XJob.class, mmservice);

            try {
                job.execute(new NamedValue[0]);
                System.out.println(" Finished the Job");

                LogFileEntry lg = new LogFileEntry();
                lg.logDoc = mDoc;
                lg.ref = letterRef;
                lg.comment = "Document ran OK";
                lg.writeFile();
                System.exit(0);

            } catch (com.sun.star.sdbc.SQLException e) {

                System.out.println("Caught UNO SQLException: " + e);
                e.printStackTrace();
                errorText = "SQL Exception conecting to the AS400 Database";
                LogFileEntry lg = new LogFileEntry();
                lg.logDoc = mDoc;
                lg.ref = letterRef;
                lg.comment = e.toString();
                lg.writeFile();

            } catch (com.sun.star.lang.IllegalArgumentException e) {
                System.out.println(" Caught IllegalArgumentException: " + e);
                errorText = "Open Office IllegalArgumentException";
            } catch (com.sun.star.uno.Exception e) {
                System.out.println(" Caught UNO Exception: " + e);
                errorText = "Open Office UNO Exception";
            } catch (Exception e) {
                System.out.println(e.toString());
            }
            xConnection.close();
        } catch (Exception e) {

            LogFileEntry lg = new LogFileEntry();
            lg.logDoc = mDoc;
            lg.ref = letterRef;
            lg.comment = "Could not set some mail merge properties on this
document";
            lg.writeFile();

            System.out.println(" Error setting MailMerge properties:" + e);
            errorText = "Error setting MailMerge properties";
            ErrorSWT dispConnErr = new ErrorSWT(mDoc, letterRef, errorText);
            dispConnErr.displayError();
            dispConnErr = null;

            e.printStackTrace();
            return;
        }
    }

    protected void startOffice() throws java.lang.Exception {

        String cmd2 = "C:\\PJDocs\\StartOffice.bat";

        String cmdOut = cmd2;
        System.out.println(" Trying " + cmdOut);

        Runtime.getRuntime().exec(cmd2);

        Thread.sleep(10000); // Waits 10 seconds, because
        // Runtime.getRuntime().exec("...") does not
        // wait until OOo is really running in Listening
        // Mode
    }

    // /////////////////////////////////////////////////////////////////
    // End
    // /////////////////////////////////////////////////////////////////

}

-- 
You are receiving this mail because:
You are the assignee for the issue.
You are watching all issue changes.

Reply via email to