com.sun.star.uno.XComponentContext Java Examples

The following examples show how to use com.sun.star.uno.XComponentContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OOPresentation.java    From Quelea with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Connect to an office, if no office is running a new instance is
 * started. A new connection is established and the service manger from
 * the running office is returned.
 *
 * @param path the path to the openoffice install.
 */
private static XComponentContext connect(String path) throws BootstrapException, Exception {
    File progPath = new File(path, "program");
    xOfficeContext = BootstrapSocketConnector.bootstrap(progPath.getAbsolutePath());
    XComponentContext localContext = Bootstrap.createInitialComponentContext(null);
    XMultiComponentFactory localServiceManager = localContext.getServiceManager();
    XConnector connector = UnoRuntime.queryInterface(XConnector.class,
            localServiceManager.createInstanceWithContext("com.sun.star.connection.Connector",
                    localContext));
    connection = connector.connect(RUN_ARGS);
    XBridgeFactory bridgeFactory = UnoRuntime.queryInterface(XBridgeFactory.class,
            localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory", localContext));
    bridge = bridgeFactory.createBridge("", "urp", connection, null);
    bridgeComponent = UnoRuntime.queryInterface(XComponent.class, bridge);
    bridgeComponent.addEventListener(new com.sun.star.lang.XEventListener() {
        @Override
        public void disposing(EventObject eo) {
        }
    });
    return xOfficeContext;

}
 
Example #2
Source File: AbstractInliner.java    From yarg with Apache License 2.0 6 votes vote down vote up
protected void insertImage(XComponent document, OfficeResourceProvider officeResourceProvider, XText destination, XTextRange textRange,
                           Image image) throws Exception {
    XMultiServiceFactory xFactory = as(XMultiServiceFactory.class, document);
    XComponentContext xComponentContext = officeResourceProvider.getXComponentContext();
    XMultiComponentFactory serviceManager = xComponentContext.getServiceManager();

    Object oImage = xFactory.createInstance(TEXT_GRAPHIC_OBJECT);
    Object oGraphicProvider = serviceManager.createInstanceWithContext(GRAPHIC_PROVIDER_OBJECT, xComponentContext);

    XGraphicProvider xGraphicProvider = as(XGraphicProvider.class, oGraphicProvider);

    XPropertySet imageProperties = buildImageProperties(xGraphicProvider, oImage, image.imageContent);
    XTextContent xTextContent = as(XTextContent.class, oImage);
    destination.insertTextContent(textRange, xTextContent, true);
    setImageSize(image.width, image.height, oImage, imageProperties);
}
 
Example #3
Source File: OfficeConnection.java    From yarg with Apache License 2.0 6 votes vote down vote up
public void open() throws OpenOfficeException {
    if (this.closed) {
        try {
            XComponentContext localContext = bsc.connect("127.0.0.1", port);
            String connectionString = "socket,host=127.0.0.1,port=" + port;
            XMultiComponentFactory localServiceManager = localContext.getServiceManager();
            XConnector connector = as(XConnector.class,
                    localServiceManager.createInstanceWithContext("com.sun.star.connection.Connector", localContext));
            XConnection connection = connector.connect(connectionString);
            XBridgeFactory bridgeFactory = as(XBridgeFactory.class,
                    localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory", localContext));
            String bridgeName = "yarg_" + bridgeIndex.incrementAndGet();
            XBridge bridge = bridgeFactory.createBridge(bridgeName, "urp", connection, null);
            XMultiComponentFactory serviceManager = as(XMultiComponentFactory.class, bridge.getInstance("StarOffice.ServiceManager"));
            XPropertySet properties = as(XPropertySet.class, serviceManager);
            xComponentContext = as(XComponentContext.class, properties.getPropertyValue("DefaultContext"));

            officeResourceProvider = new OfficeResourceProvider(xComponentContext, officeIntegration);
            closed = false;
        } catch (Exception e) {
            close();
            throw new OpenOfficeException("Unable to create Open office components.", e);
        }
    }
}
 
Example #4
Source File: RemoteOfficeConnection.java    From noa-libre with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Opens connection to OpenOffice.org.
 * 
 * @return information whether the connection is available
 * 
 * @throws Exception if any error occurs
 */
public boolean openConnection() throws Exception {
  String unoUrl = "uno:socket,host=" + host + ",port=" + port +";urp;StarOffice.ServiceManager";
  XComponentContext xLocalContext = Bootstrap.createInitialComponentContext(null);
  Object connector = xLocalContext.getServiceManager().createInstanceWithContext("com.sun.star.connection.Connector", xLocalContext);
  XConnector xConnector = (XConnector) UnoRuntime.queryInterface(XConnector.class, connector);
  
  String url[] = parseUnoUrl(unoUrl);
  if (null == url) {
    throw new com.sun.star.uno.Exception("Couldn't parse UNO URL "+ unoUrl);
  }
  
  XConnection connection = xConnector.connect(url[0]);
  Object bridgeFactory = xLocalContext.getServiceManager().createInstanceWithContext("com.sun.star.bridge.BridgeFactory", xLocalContext);
  XBridgeFactory xBridgeFactory = (XBridgeFactory) UnoRuntime.queryInterface(XBridgeFactory.class, bridgeFactory);
  xBridge = xBridgeFactory.createBridge("", url[1], connection ,null);
  bridgeFactory = xBridge.getInstance(url[2]);
  xMultiComponentFactory = (XMultiComponentFactory)UnoRuntime.queryInterface(XMultiComponentFactory.class, bridgeFactory);
  XPropertySet xProperySet = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, xMultiComponentFactory);
  Object remoteContext = xProperySet.getPropertyValue("DefaultContext");
  xRemoteContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, remoteContext);
  xMultiServiceFactory = (XMultiServiceFactory)UnoRuntime.queryInterface(XMultiServiceFactory.class, xMultiComponentFactory);
  isConnectionEstablished = true;
  return true;      
}
 
Example #5
Source File: LocalOfficeConnectionGhost.java    From noa-libre with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Establishes the connection to the office.
 * 
 * @return constructed component context
 * 
 * @author Andreas Bröker
 */
private XComponentContext connect() {
	try {
		if (officeProgressMonitor != null)
			officeProgressMonitor
					.beginSubTask(Messages
							.getString("LocalOfficeConnectionGhost_monitor_constructing_initial_context_message")); //$NON-NLS-1$

		XComponentContext xContext = null;
		if (officeArguments != null && officeArguments.length > 0)
			xContext = Bootstrap.bootstrap(officeArguments);
		else
			xContext = Bootstrap.bootstrap();
		return xContext;
	} catch (java.lang.Exception exception) {
		System.out.println("java.lang.Exception: "); //$NON-NLS-1$
		System.out.println(exception);
		exception.printStackTrace();
		System.out.println("--- end."); //$NON-NLS-1$
		throw new com.sun.star.uno.RuntimeException(exception.toString());
	}
}
 
Example #6
Source File: DialogHelper.java    From libreoffice-starter-extension with MIT License 6 votes vote down vote up
public static void showMessageBox(XComponentContext context, XDialog dialog, MessageBoxType type, String sTitle, String sMessage) {
	XToolkit xToolkit;
	try {
		xToolkit = UnoRuntime.queryInterface(XToolkit.class,
					context.getServiceManager().createInstanceWithContext("com.sun.star.awt.Toolkit", context));
	} catch (Exception e) {
		return;
	}
	XMessageBoxFactory xMessageBoxFactory = UnoRuntime.queryInterface(XMessageBoxFactory.class, xToolkit);
	XWindowPeer xParentWindowPeer = UnoRuntime.queryInterface(XWindowPeer.class, dialog);
       XMessageBox xMessageBox = xMessageBoxFactory.createMessageBox(xParentWindowPeer, type,
       		com.sun.star.awt.MessageBoxButtons.BUTTONS_OK, sTitle, sMessage);
       if (xMessageBox == null)
       	return;
       
       xMessageBox.execute();
}
 
Example #7
Source File: DialogHelper.java    From libreoffice-starter-extension with MIT License 6 votes vote down vote up
/** Returns a URL to be used with XDialogProvider to create a dialog */
public static String convertToURL(XComponentContext xContext, File dialogFile) {
	String sURL = null;
	try {
		com.sun.star.ucb.XFileIdentifierConverter xFileConverter = (com.sun.star.ucb.XFileIdentifierConverter) UnoRuntime
				.queryInterface(com.sun.star.ucb.XFileIdentifierConverter.class, xContext.getServiceManager()
						.createInstanceWithContext("com.sun.star.ucb.FileContentProvider", xContext));
		sURL = xFileConverter.getFileURLFromSystemPath("", dialogFile.getAbsolutePath());
	} catch (com.sun.star.uno.Exception ex) {
		return null;
	}
	return sURL;
}
 
Example #8
Source File: OPConnection.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * (non-Javadoc)
 * @see net.heartsome.cat.converter.ooconnect.OPconnect#connect()
 * @throws ConnectException
 */
public void connect() throws ConnectException {
	try {
		XComponentContext localContext;

		localContext = Bootstrap.createInitialComponentContext(null);

		XMultiComponentFactory localServiceManager = localContext.getServiceManager();
		XConnector connector = (XConnector) UnoRuntime.queryInterface(XConnector.class, localServiceManager
				.createInstanceWithContext("com.sun.star.connection.Connector", localContext)); //$NON-NLS-1$
		XConnection connection = connector.connect(strConnection);
		XBridgeFactory bridgeFactory = (XBridgeFactory) UnoRuntime.queryInterface(XBridgeFactory.class,
				localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory", localContext)); //$NON-NLS-1$
		bridge = bridgeFactory.createBridge("ms2ooBridge", "urp", connection, null); //$NON-NLS-1$ //$NON-NLS-2$
		bgComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, bridge);
		// bgComponent.addEventListener(this);
		serviceMg = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class, bridge
				.getInstance("StarOffice.ServiceManager")); //$NON-NLS-1$
		XPropertySet properties = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, serviceMg);
		componentContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, properties
				.getPropertyValue("DefaultContext")); //$NON-NLS-1$
		connected = true;
		if (connected) {
			System.out.println("has already connected"); //$NON-NLS-1$
		} else {
			System.out.println("connect to Openoffice fail,please check OpenOffice service that have to open"); //$NON-NLS-1$
		}

	} catch (NoConnectException connectException) {
		throw new ConnectException(MessageFormat.format(Messages.getString("ooconnect.OPConnection.msg"), strConnection + ": " + connectException.getMessage())); //$NON-NLS-1$ //$NON-NLS-2$
	} catch (Exception exception) {
		throw new OPException(MessageFormat.format(Messages.getString("ooconnect.OPConnection.msg"), strConnection), exception); //$NON-NLS-1$
	} catch (java.lang.Exception e) {
		if (Converter.DEBUG_MODE) {
			e.printStackTrace();
		}
	}
}
 
Example #9
Source File: OPConnection.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * (non-Javadoc)
 * @see net.heartsome.cat.converter.ooconnect.OPconnect#connect()
 * @throws ConnectException
 */
public void connect() throws ConnectException {
	try {
		XComponentContext localContext;

		localContext = Bootstrap.createInitialComponentContext(null);

		XMultiComponentFactory localServiceManager = localContext.getServiceManager();
		XConnector connector = (XConnector) UnoRuntime.queryInterface(XConnector.class, localServiceManager
				.createInstanceWithContext("com.sun.star.connection.Connector", localContext)); //$NON-NLS-1$
		XConnection connection = connector.connect(strConnection);
		XBridgeFactory bridgeFactory = (XBridgeFactory) UnoRuntime.queryInterface(XBridgeFactory.class,
				localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory", localContext)); //$NON-NLS-1$
		bridge = bridgeFactory.createBridge("ms2ooBridge", "urp", connection, null); //$NON-NLS-1$ //$NON-NLS-2$
		bgComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, bridge);
		// bgComponent.addEventListener(this);
		serviceMg = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class, bridge
				.getInstance("StarOffice.ServiceManager")); //$NON-NLS-1$
		XPropertySet properties = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, serviceMg);
		componentContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, properties
				.getPropertyValue("DefaultContext")); //$NON-NLS-1$
		connected = true;
		if (connected) {
			System.out.println("has already connected"); //$NON-NLS-1$
		} else {
			System.out.println("connect to Openoffice fail,please check OpenOffice service that have to open"); //$NON-NLS-1$
		}

	} catch (NoConnectException connectException) {
		throw new ConnectException(MessageFormat.format(Messages.getString("ooconnect.OPConnection.msg"), strConnection + ": " + connectException.getMessage())); //$NON-NLS-1$ //$NON-NLS-2$
	} catch (Exception exception) {
		throw new OPException(MessageFormat.format(Messages.getString("ooconnect.OPConnection.msg"), strConnection), exception); //$NON-NLS-1$
	} catch (java.lang.Exception e) {
		if (Converter.DEBUG_MODE) {
			e.printStackTrace();
		}
	}
}
 
Example #10
Source File: ServiceInterfaceSupplier.java    From noa-libre with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the XDesktop interface from the OpenOffice.org desktop service.
 * 
 * @param componentContext component context to be used
 * 
 * @return XDesktop interface from the OpenOffice.org desktop service
 * 
 * @throws Exception if any error occurs
 */
public static XDesktop getXDesktop(XComponentContext componentContext) throws Exception {
	Object service = componentContext.getServiceManager().createInstanceWithContext("com.sun.star.frame.Desktop", componentContext);
	if(service != null) {
		return (XDesktop)UnoRuntime.queryInterface(XDesktop.class, service);
	}
	else {
		return null;
	}
}
 
Example #11
Source File: OfficeConnection.java    From kkFileViewOfficeEdit with Apache License 2.0 5 votes vote down vote up
public void connect() throws ConnectException {
    logger.fine(String.format("connecting with connectString '%s'", unoUrl));
    try {
        XComponentContext localContext = Bootstrap.createInitialComponentContext(null);
        XMultiComponentFactory localServiceManager = localContext.getServiceManager();
        XConnector connector = OfficeUtils.cast(XConnector.class, localServiceManager.createInstanceWithContext("com.sun.star.connection.Connector", localContext));
        XConnection connection = connector.connect(unoUrl.getConnectString());
        XBridgeFactory bridgeFactory = OfficeUtils.cast(XBridgeFactory.class, localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory", localContext));
        String bridgeName = "jodconverter_" + bridgeIndex.getAndIncrement();
        XBridge bridge = bridgeFactory.createBridge(bridgeName, "urp", connection, null);
        bridgeComponent = OfficeUtils.cast(XComponent.class, bridge);
        bridgeComponent.addEventListener(bridgeListener);
        serviceManager = OfficeUtils.cast(XMultiComponentFactory.class, bridge.getInstance("StarOffice.ServiceManager"));
        XPropertySet properties = OfficeUtils.cast(XPropertySet.class, serviceManager);
        componentContext = OfficeUtils.cast(XComponentContext.class, properties.getPropertyValue("DefaultContext"));
        connected = true;
        logger.info(String.format("connected: '%s'", unoUrl));
        OfficeConnectionEvent connectionEvent = new OfficeConnectionEvent(this);
        for (OfficeConnectionEventListener listener : connectionEventListeners) {
            listener.connected(connectionEvent);
        }
    } catch (NoConnectException connectException) {
        throw new ConnectException(String.format("connection failed: '%s'; %s", unoUrl, connectException.getMessage()));
    } catch (Exception exception) {
        throw new OfficeException("connection failed: "+ unoUrl, exception);
    }
}
 
Example #12
Source File: BootstrapConnector.java    From yarg with Apache License 2.0 5 votes vote down vote up
/**
 * Disconnects from an OOo server using the connection string from the
 * previous connect.
 * 
 * If there has been no previous connect, the disconnects does nothing.
 * 
 * If there has been a previous connect, disconnect tries to terminate
 * the OOo server and kills the OOo server process the connect started.
 */
public void disconnect() {

    if (oooConnectionString == null)
        return;

    // call office to terminate itself
    try {
        // get local context
        XComponentContext xLocalContext = getLocalContext();

        // create a URL resolver
        XUnoUrlResolver xUrlResolver = UnoUrlResolver.create(xLocalContext);

        // get remote context
        XComponentContext xRemoteContext = getRemoteContext(xUrlResolver);

        // get desktop to terminate office
        Object desktop = xRemoteContext.getServiceManager().createInstanceWithContext("com.sun.star.frame.Desktop",xRemoteContext);
        XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktop);
        xDesktop.terminate();
    }
    catch (Exception e) {
        // Bad luck, unable to terminate office
    }

    oooServer.kill();
    oooConnectionString = null;
}
 
Example #13
Source File: BootstrapConnector.java    From yarg with Apache License 2.0 5 votes vote down vote up
/**
 * Create default local component context.
 * 
 * @return      The default local component context
 */
protected XComponentContext getLocalContext() throws BootstrapException, Exception {

    XComponentContext xLocalContext = Bootstrap.createInitialComponentContext(null);
    if (xLocalContext == null) {
        throw new BootstrapException("no local component context!");
    }
    return xLocalContext;
}
 
Example #14
Source File: BootstrapConnector.java    From yarg with Apache License 2.0 5 votes vote down vote up
/**
 * Try to connect to office.
 * 
 * @return      The remote component context
 */
protected XComponentContext getRemoteContext(XUnoUrlResolver xUrlResolver) throws BootstrapException, ConnectionSetupException, IllegalArgumentException, NoConnectException {

    Object context = xUrlResolver.resolve(oooConnectionString);
    XComponentContext xContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, context);
    if (xContext == null) {
        throw new BootstrapException("no component context!");
    }
    return xContext;
}
 
Example #15
Source File: OfficeConnection.java    From wenku with MIT License 5 votes vote down vote up
public void connect() throws ConnectException {
    logger.fine(String.format("connecting with connectString '%s'", unoUrl));
    try {
        XComponentContext localContext = Bootstrap.createInitialComponentContext(null);
        XMultiComponentFactory localServiceManager = localContext.getServiceManager();
        XConnector connector = OfficeUtils.cast(XConnector.class, localServiceManager.createInstanceWithContext("com.sun.star.connection.Connector", localContext));
        XConnection connection = connector.connect(unoUrl.getConnectString());
        XBridgeFactory bridgeFactory = OfficeUtils.cast(XBridgeFactory.class, localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory", localContext));
        String bridgeName = "jodconverter_" + bridgeIndex.getAndIncrement();
        XBridge bridge = bridgeFactory.createBridge(bridgeName, "urp", connection, null);
        bridgeComponent = OfficeUtils.cast(XComponent.class, bridge);
        bridgeComponent.addEventListener(bridgeListener);
        serviceManager = OfficeUtils.cast(XMultiComponentFactory.class, bridge.getInstance("StarOffice.ServiceManager"));
        XPropertySet properties = OfficeUtils.cast(XPropertySet.class, serviceManager);
        componentContext = OfficeUtils.cast(XComponentContext.class, properties.getPropertyValue("DefaultContext"));
        connected = true;
        logger.info(String.format("connected: '%s'", unoUrl));
        OfficeConnectionEvent connectionEvent = new OfficeConnectionEvent(this);
        for (OfficeConnectionEventListener listener : connectionEventListeners) {
            listener.connected(connectionEvent);
        }
    } catch (NoConnectException connectException) {
        throw new ConnectException(String.format("connection failed: '%s'; %s", unoUrl, connectException.getMessage()));
    } catch (Exception exception) {
        throw new OfficeException("connection failed: "+ unoUrl, exception);
    }
}
 
Example #16
Source File: OOPresentation.java    From Quelea with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates and instantiates a new document
 *
 * @throws Exception if something goes wrong creating the document.
 */
private static XComponent createDocument(XComponentContext xOfficeContext, String sURL, String sTargetFrame, int nSearchFlags, PropertyValue[] aArgs) throws Exception {
    XComponentLoader aLoader = UnoRuntime.queryInterface(XComponentLoader.class, xOfficeContext.getServiceManager().createInstanceWithContext("com.sun.star.frame.Desktop", xOfficeContext));
    XComponent xComponent = UnoRuntime.queryInterface(XComponent.class, aLoader.loadComponentFromURL(sURL, sTargetFrame, nSearchFlags, aArgs));

    if (xComponent == null) {
        throw new Exception("Could not create document: " + sURL);
    }
    return xComponent;
}
 
Example #17
Source File: DialogHelper.java    From libreoffice-starter-extension with MIT License 5 votes vote down vote up
/**
 * Create a dialog from an xdl file.
 *
 * @param xdlFile
 *            The filename in the `dialog` folder
 * @param context
 * @return XDialog
 */
public static XDialog createDialog(String xdlFile, XComponentContext context, XDialogEventHandler handler) {
	Object oDialogProvider;
	try {
		oDialogProvider = context.getServiceManager().createInstanceWithContext("com.sun.star.awt.DialogProvider2",
				context);
		XDialogProvider2 xDialogProv = (XDialogProvider2) UnoRuntime.queryInterface(XDialogProvider2.class,
				oDialogProvider);
		File dialogFile = FileHelper.getDialogFilePath(xdlFile, context);
		return xDialogProv.createDialogWithHandler(convertToURL(context, dialogFile), handler);
	} catch (Exception e) {
		return null;
	}
}
 
Example #18
Source File: OfficeConnection.java    From kkFileView with Apache License 2.0 5 votes vote down vote up
public void connect() throws ConnectException {
    logger.fine(String.format("connecting with connectString '%s'", unoUrl));
    try {
        XComponentContext localContext = Bootstrap.createInitialComponentContext(null);
        XMultiComponentFactory localServiceManager = localContext.getServiceManager();
        XConnector connector = OfficeUtils.cast(XConnector.class, localServiceManager.createInstanceWithContext("com.sun.star.connection.Connector", localContext));
        XConnection connection = connector.connect(unoUrl.getConnectString());
        XBridgeFactory bridgeFactory = OfficeUtils.cast(XBridgeFactory.class, localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory", localContext));
        String bridgeName = "jodconverter_" + bridgeIndex.getAndIncrement();
        XBridge bridge = bridgeFactory.createBridge(bridgeName, "urp", connection, null);
        bridgeComponent = OfficeUtils.cast(XComponent.class, bridge);
        bridgeComponent.addEventListener(bridgeListener);
        serviceManager = OfficeUtils.cast(XMultiComponentFactory.class, bridge.getInstance("StarOffice.ServiceManager"));
        XPropertySet properties = OfficeUtils.cast(XPropertySet.class, serviceManager);
        componentContext = OfficeUtils.cast(XComponentContext.class, properties.getPropertyValue("DefaultContext"));
        connected = true;
        logger.info(String.format("connected: '%s'", unoUrl));
        OfficeConnectionEvent connectionEvent = new OfficeConnectionEvent(this);
        for (OfficeConnectionEventListener listener : connectionEventListeners) {
            listener.connected(connectionEvent);
        }
    } catch (NoConnectException connectException) {
        throw new ConnectException(String.format("connection failed: '%s'; %s", unoUrl, connectException.getMessage()));
    } catch (Exception exception) {
        throw new OfficeException("connection failed: "+ unoUrl, exception);
    }
}
 
Example #19
Source File: OpenOfficeWorker.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public static List<String> getFilterNames(XMultiComponentFactory xmulticomponentfactory) throws Exception {
    XPropertySet xPropertySet = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, xmulticomponentfactory);
    Object oDefaultContext = xPropertySet.getPropertyValue("DefaultContext");
    XComponentContext xComponentContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, oDefaultContext);


    Object filterFactory = xmulticomponentfactory.createInstanceWithContext("com.sun.star.document.FilterFactory", xComponentContext);
    XNameAccess xNameAccess = (XNameAccess)UnoRuntime.queryInterface(XNameAccess.class, filterFactory);
    String [] filterNames = xNameAccess.getElementNames();

    //String [] serviceNames = filterFactory.getAvailableServiceNames();
    for (int i=0; i < filterNames.length; i++) {
        String s = filterNames[i];
        Debug.logInfo(s, module);
        /*
        if (s.toLowerCase().indexOf("filter") >= 0) {
            Debug.logInfo("FILTER: " + s, module);
        }
        if (s.toLowerCase().indexOf("desktop") >= 0) {
            Debug.logInfo("DESKTOP: " + s, module);
        }
        */
    }

    List<String> filterNameList = UtilMisc.toListArray(filterNames);
    return filterNameList;
}
 
Example #20
Source File: DocumentHelper.java    From libreoffice-starter-extension with MIT License 5 votes vote down vote up
/** Returns the curerent XDesktop */
public static XDesktop getCurrentDesktop(XComponentContext xContext) {
	XMultiComponentFactory xMCF = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class,
			xContext.getServiceManager());
       Object desktop = null;
	try {
		desktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
	} catch (Exception e) {
		return null;
	}
       return (XDesktop) UnoRuntime.queryInterface(com.sun.star.frame.XDesktop.class, desktop);
}
 
Example #21
Source File: OpenOfficeWorker.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public static String convertToUrl(String filePath, XComponentContext xComponentContext) throws MalformedURLException {

        String returnUrl = null;
        File f = new File(filePath);
        // SCIPIO: Bad java
        //URL u = f.toURL();
        URL u = f.toURI().toURL();
        returnUrl =  ExternalUriReferenceTranslator.create(xComponentContext).translateToInternal(u.toExternalForm());

        return returnUrl;
    }
 
Example #22
Source File: DialogHelper.java    From libreoffice-starter-extension with MIT License 4 votes vote down vote up
public static void showWarningMessage(XComponentContext context, XDialog dialog, String message) {
	showMessageBox(context, dialog, MessageBoxType.WARNINGBOX, "Warnung", message);
}
 
Example #23
Source File: TerminationOpenoffice.java    From tmxeditor8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Gets the current component.
 * @return the current component
 * @throws Exception
 *             the exception
 */
public static XComponent getCurrentComponent() throws Exception {
	XComponentContext xRemoteContext = com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null);
	// XComponentContext xRemoteContext =
	// com.sun.star.comp.helper.Bootstrap.bootstrap();

	XMultiComponentFactory xRemoteServiceManager = xRemoteContext.getServiceManager();

	Object desktop = xRemoteServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xRemoteContext); //$NON-NLS-1$

	XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktop);

	XComponent currentComponent = xDesktop.getCurrentComponent();

	return currentComponent;
}
 
Example #24
Source File: TerminationOpenoffice.java    From translationstudio8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Gets the current component.
 * @return the current component
 * @throws Exception
 *             the exception
 */
public static XComponent getCurrentComponent() throws Exception {
	XComponentContext xRemoteContext = com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null);
	// XComponentContext xRemoteContext =
	// com.sun.star.comp.helper.Bootstrap.bootstrap();

	XMultiComponentFactory xRemoteServiceManager = xRemoteContext.getServiceManager();

	Object desktop = xRemoteServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xRemoteContext); //$NON-NLS-1$

	XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktop);

	XComponent currentComponent = xDesktop.getCurrentComponent();

	return currentComponent;
}
 
Example #25
Source File: OpenOfficeWorker.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static void convertOODocToFile(XMultiComponentFactory xmulticomponentfactory, String fileInPath, String fileOutPath, String outputMimeType) throws FileNotFoundException, IOException, MalformedURLException, Exception {
    // Converting the document to the favoured type
    // 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 = (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. */

    Object desktopObj = xmulticomponentfactory.createInstanceWithContext("com.sun.star.frame.Desktop", xcomponentcontext);
    //XDesktop desktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktopObj);
    XComponentLoader xcomponentloader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, desktopObj);


    // Preparing properties for loading the document
    PropertyValue propertyvalue[] = new PropertyValue[ 2 ];
    // Setting the flag for hidding the open document
    propertyvalue[ 0 ] = new PropertyValue();
    propertyvalue[ 0 ].Name = "Hidden";
    propertyvalue[ 0 ].Value = Boolean.valueOf(false);

    propertyvalue[ 1 ] = new PropertyValue();
    propertyvalue[ 1 ].Name = "UpdateDocMode";
    propertyvalue[ 1 ].Value = "1";

    // Loading the wanted document
    String stringUrl = convertToUrl(fileInPath, xcomponentcontext);
    Debug.logInfo("stringUrl:" + stringUrl, module);
    Object objectDocumentToStore = xcomponentloader.loadComponentFromURL(stringUrl, "_blank", 0, propertyvalue);

    // 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 = new PropertyValue[ 3 ];
    // Setting the flag for overwriting
    propertyvalue[ 0 ] = new PropertyValue();
    propertyvalue[ 0 ].Name = "Overwrite";
    propertyvalue[ 0 ].Value = Boolean.valueOf(true);
    // Setting the filter name
    // Preparing properties for converting the document
    String filterName = getFilterNameFromMimeType(outputMimeType);

    propertyvalue[ 1 ] = new PropertyValue();
    propertyvalue[ 1 ].Name = "FilterName";
    propertyvalue[ 1 ].Value = filterName;

    propertyvalue[2] = new PropertyValue();
    propertyvalue[2].Name = "CompressionMode";
    propertyvalue[2].Value = "1";

    // Storing and converting the document
    //File newFile = new File(stringConvertedFile);
    //newFile.createNewFile();

    String stringConvertedFile = convertToUrl(fileOutPath, xcomponentcontext);
    Debug.logInfo("stringConvertedFile: "+stringConvertedFile, module);
    xstorable.storeToURL(stringConvertedFile, propertyvalue);

    // Getting the method dispose() for closing the document
    XComponent xcomponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, xstorable);

    // Closing the converted document
    xcomponent.dispose();
    return;
}
 
Example #26
Source File: LocalOfficeConnection.java    From noa-libre with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Returns OpenOffice.org frame integrated into the submitted native view. 
 * 
 * @param nativeView native view
 * 
 * @return OpenOffice.org frame integrated into the submitted Java AWT container
 * 
 * @author Markus Krüger
 * @date 08.12.2006
 */
public XFrame getOfficeFrame(NativeView nativeView) {
  if(officeConnection != null) {
    try {
      //TODO needs to be changed in later version as the dispose listener can be used.
      if(!isConnected())
        openConnection();

      if(LOGGER.isLoggable(Level.FINEST))
        LOGGER.finest("Creating local office window.");
      XComponentContext xComponentContext = getXComponentContext();
      Object object = null;
      // Create the document frame from UNO window. (<= 6.0 => Task, >= 6.1 => Frame)
      if(LOGGER.isLoggable(Level.FINEST))
        LOGGER.finest("Creating UNO XWindow interface.");

      XToolkit xToolkit = (XToolkit) UnoRuntime.queryInterface(
          XToolkit.class, getXMultiServiceFactory().createInstance(
              "com.sun.star.awt.Toolkit"));

      //      initialise le xChildFactory
      XSystemChildFactory xChildFactory = (XSystemChildFactory) UnoRuntime
          .queryInterface(XSystemChildFactory.class, xToolkit);

      Integer handle = nativeView.getHWND();
      short systeme = (short) nativeView.getNativeWindowSystemType();
      byte[] procID = new byte[0];

      XWindowPeer xWindowPeer = xChildFactory.createSystemChild(
          (Object) handle, procID, systeme);

      XWindow xWindow = (XWindow) UnoRuntime.queryInterface(XWindow.class,
          xWindowPeer);

      object = getXMultiServiceFactory().createInstance(
          "com.sun.star.frame.Task"); //$NON-NLS-1$
      if(object == null)
        object = getXMultiServiceFactory().createInstance(
            "com.sun.star.frame.Frame"); //$NON-NLS-1$
      if(LOGGER.isLoggable(Level.FINEST))
        LOGGER.finest("Creating UNO XFrame interface.");
      XFrame xFrame = (XFrame) UnoRuntime
          .queryInterface(XFrame.class, object);
      xFrame.getContainerWindow();
      xFrame.initialize(xWindow);
      xFrame.setName(xFrame.toString());
      if(LOGGER.isLoggable(Level.FINEST))
        LOGGER.finest("Creating desktop service.");
      Object desktop = getXMultiServiceFactory().createInstance(
          "com.sun.star.frame.Desktop"); //$NON-NLS-1$
      com.sun.star.frame.XFrames xFrames = ((com.sun.star.frame.XFramesSupplier) UnoRuntime
          .queryInterface(com.sun.star.frame.XFramesSupplier.class, desktop))
          .getFrames();
      xFrames.append(xFrame);
      return xFrame;
    }
    catch(Exception exception) {
      LOGGER.throwing(this.getClass().getName(), "getOfficeFrame", exception);
      //exception.printStackTrace();
      return null;
    }
  }
  else {
    return null;
  }
}
 
Example #27
Source File: OfficeResourceProvider.java    From yarg with Apache License 2.0 4 votes vote down vote up
public OfficeResourceProvider(XComponentContext xComponentContext, OfficeIntegration officeIntegration) throws Exception {
    this.xComponentContext = xComponentContext;
    this.officeIntegration = officeIntegration;
}
 
Example #28
Source File: OfficeResourceProvider.java    From yarg with Apache License 2.0 4 votes vote down vote up
public XComponentContext getXComponentContext() {
    return xComponentContext;
}
 
Example #29
Source File: OpenOfficeWorker.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static OpenOfficeByteArrayOutputStream convertOODocByteStreamToByteStream(XMultiComponentFactory xmulticomponentfactory,
        OpenOfficeByteArrayInputStream is, String inputMimeType, String outputMimeType) throws Exception {

    // 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 = (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. */

    Object desktopObj = xmulticomponentfactory.createInstanceWithContext("com.sun.star.frame.Desktop", xcomponentcontext);
    //XDesktop desktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktopObj);
    XComponentLoader xcomponentloader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, desktopObj);

    // Preparing properties for loading the document
    PropertyValue propertyvalue[] = new PropertyValue[2];
    // Setting the flag for hidding the open document
    propertyvalue[0] = new PropertyValue();
    propertyvalue[0].Name = "Hidden";
    propertyvalue[0].Value = Boolean.TRUE;
    //
    propertyvalue[1] = new PropertyValue();
    propertyvalue[1].Name = "InputStream";
    propertyvalue[1].Value = is;

    // Loading the wanted document
    Object objectDocumentToStore = xcomponentloader.loadComponentFromURL("private:stream", "_blank", 0, propertyvalue);
    if (objectDocumentToStore == null) {
        Debug.logError("Could not get objectDocumentToStore object from xcomponentloader.loadComponentFromURL", module);
    }

    // Getting an object that will offer a simple way to store a document to a URL.
    XStorable xstorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, objectDocumentToStore);
    if (xstorable == null) {
        Debug.logError("Could not get XStorable object from UnoRuntime.queryInterface", module);
    }

    // Preparing properties for converting the document
    String filterName = getFilterNameFromMimeType(outputMimeType);
    propertyvalue = new PropertyValue[4];

    propertyvalue[0] = new PropertyValue();
    propertyvalue[0].Name = "OutputStream";
    OpenOfficeByteArrayOutputStream os = new OpenOfficeByteArrayOutputStream();
    propertyvalue[0].Value = os;
    // Setting the filter name
    propertyvalue[1] = new PropertyValue();
    propertyvalue[1].Name = "FilterName";
    propertyvalue[1].Value = filterName;
    // Setting the flag for overwriting
    propertyvalue[3] = new PropertyValue();
    propertyvalue[3].Name = "Overwrite";
    propertyvalue[3].Value = Boolean.TRUE;
    // For PDFs
    propertyvalue[2] = new PropertyValue();
    propertyvalue[2].Name = "CompressionMode";
    propertyvalue[2].Value = "1";

    xstorable.storeToURL("private:stream", propertyvalue);
    //xstorable.storeToURL("file:///home/byersa/testdoc1_file.pdf", propertyvalue);

    // Getting the method dispose() for closing the document
    XComponent xcomponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, xstorable);

    // Closing the converted document
    xcomponent.dispose();

    return os;
}
 
Example #30
Source File: ActionOneDialog.java    From libreoffice-starter-extension with MIT License 4 votes vote down vote up
public ActionOneDialog(XComponentContext xContext) {
	this.dialog = DialogHelper.createDialog("ActionOneDialog.xdl", xContext, this);
}