Version 5.4.3.2, tag libreoffice-5.4.3.2
[LibreOffice.git] / stoc / source / javaloader / javaloader.cxx
blobdb850bdb5e6a6f78c5e640debebfbafe6796559e
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <cstdarg>
22 #include <osl/process.h>
24 #include <rtl/process.h>
25 #include <rtl/ustrbuf.hxx>
26 #include <sal/log.hxx>
28 #include <uno/environment.h>
29 #include <uno/lbnames.h>
30 #include <uno/mapping.hxx>
31 #include <com/sun/star/uno/RuntimeException.hpp>
33 #ifdef LINUX
34 #undef minor
35 #undef major
36 #endif
38 #include <com/sun/star/java/XJavaVM.hpp>
40 #include <com/sun/star/lang/XMultiComponentFactory.hpp>
42 #include "jni.h"
44 #include <cppuhelper/factory.hxx>
45 #include <cppuhelper/implementationentry.hxx>
47 #include <cppuhelper/implbase.hxx>
48 #include <cppuhelper/supportsservice.hxx>
50 #include <com/sun/star/loader/XImplementationLoader.hpp>
51 #include <com/sun/star/lang/IllegalArgumentException.hpp>
52 #include <com/sun/star/lang/XServiceInfo.hpp>
53 #include <com/sun/star/lang/XInitialization.hpp>
54 #include <com/sun/star/registry/XRegistryKey.hpp>
56 #include <jvmaccess/unovirtualmachine.hxx>
57 #include <jvmaccess/virtualmachine.hxx>
59 using namespace css::java;
60 using namespace css::lang;
61 using namespace css::loader;
62 using namespace css::uno;
63 using namespace css::registry;
65 using namespace ::cppu;
66 using namespace ::osl;
68 namespace stoc_javaloader {
70 static Mutex & getInitMutex();
72 static Sequence< OUString > loader_getSupportedServiceNames()
74 Sequence< OUString > seqNames(2);
75 seqNames.getArray()[0] = "com.sun.star.loader.Java";
76 seqNames.getArray()[1] = "com.sun.star.loader.Java2";
77 return seqNames;
80 static OUString loader_getImplementationName()
82 return OUString( "com.sun.star.comp.stoc.JavaComponentLoader" );
85 class JavaComponentLoader : public WeakImplHelper<XImplementationLoader, XServiceInfo>
87 css::uno::Reference<XComponentContext> m_xComponentContext;
88 /** Do not use m_javaLoader directly. Instead use getJavaLoader.
90 css::uno::Reference<XImplementationLoader> m_javaLoader;
91 /** The retured Reference contains a null pointer if the office is not configured
92 to run java.
94 @exception css::uno::RuntimeException
95 If the Java implementation of the loader could not be obtained, for reasons other
96 then that java was not configured the RuntimeException is thrown.
98 const css::uno::Reference<XImplementationLoader> & getJavaLoader();
101 public:
102 /// @throws RuntimeException
103 explicit JavaComponentLoader(const css::uno::Reference<XComponentContext> & xCtx);
105 public:
106 // XServiceInfo
107 virtual OUString SAL_CALL getImplementationName() override;
108 virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName) override;
109 virtual Sequence<OUString> SAL_CALL getSupportedServiceNames() override;
111 // XImplementationLoader
112 virtual css::uno::Reference<XInterface> SAL_CALL activate(
113 const OUString& implementationName, const OUString& implementationLoaderUrl,
114 const OUString& locationUrl, const css::uno::Reference<XRegistryKey>& xKey) override;
115 virtual sal_Bool SAL_CALL writeRegistryInfo(
116 const css::uno::Reference<XRegistryKey>& xKey,
117 const OUString& implementationLoaderUrl, const OUString& locationUrl) override;
120 const css::uno::Reference<XImplementationLoader> & JavaComponentLoader::getJavaLoader()
122 MutexGuard aGuard(getInitMutex());
124 if (m_javaLoader.is())
125 return m_javaLoader;
127 uno_Environment * pJava_environment = nullptr;
128 uno_Environment * pUno_environment = nullptr;
129 typelib_InterfaceTypeDescription * pType_XImplementationLoader = nullptr;
131 try {
132 // get a java vm, where we can create a loader
133 css::uno::Reference<XJavaVM> javaVM_xJavaVM(
134 m_xComponentContext->getValueByName(
135 ("/singletons/"
136 "com.sun.star.java.theJavaVirtualMachine")),
137 UNO_QUERY_THROW);
139 // Use the special protocol of XJavaVM.getJavaVM: If the passed in
140 // process ID has an extra 17th byte of value one, the returned any
141 // contains a pointer to a jvmaccess::UnoVirtualMachine, instead of the
142 // underlying JavaVM pointer:
143 Sequence<sal_Int8> processID(17);
144 rtl_getGlobalProcessId(reinterpret_cast<sal_uInt8 *>(processID.getArray()));
145 processID[16] = 1;
147 // We get a non-refcounted pointer to a jvmaccess::UnoVirtualMachine
148 // from the XJavaVM service (the pointer is guaranteed to be valid
149 // as long as our reference to the XJavaVM service lasts), and
150 // convert the non-refcounted pointer into a refcounted one
151 // immediately:
152 static_assert(sizeof (sal_Int64)
153 >= sizeof (jvmaccess::UnoVirtualMachine *), "must be at least the same size");
154 sal_Int64 nPointer = reinterpret_cast< sal_Int64 >(
155 static_cast< jvmaccess::UnoVirtualMachine * >(nullptr));
156 javaVM_xJavaVM->getJavaVM(processID) >>= nPointer;
157 rtl::Reference< jvmaccess::UnoVirtualMachine > xVirtualMachine(
158 reinterpret_cast< jvmaccess::UnoVirtualMachine * >(nPointer));
159 if (!xVirtualMachine.is())
161 //throw RuntimeException(
162 // "javaloader error - JavaVirtualMachine service could not provide a VM",
163 // css::uno::Reference<XInterface>());
164 // We must not throw a RuntimeException, because this might end the applications.
165 // It is ok if java components
166 // are not working because the office can be installed without Java support.
167 SAL_WARN("stoc", "getJavaVM returned null");
168 return m_javaLoader; // null-ref
173 jvmaccess::VirtualMachine::AttachGuard aGuard2(
174 xVirtualMachine->getVirtualMachine());
175 JNIEnv * pJNIEnv = aGuard2.getEnvironment();
177 // instantiate the java JavaLoader
178 jclass jcClassLoader = pJNIEnv->FindClass("java/lang/ClassLoader");
179 if(pJNIEnv->ExceptionOccurred())
180 throw RuntimeException(
181 "javaloader error - could not find class java/lang/ClassLoader");
182 jmethodID jmLoadClass = pJNIEnv->GetMethodID(
183 jcClassLoader, "loadClass",
184 "(Ljava/lang/String;)Ljava/lang/Class;");
185 if(pJNIEnv->ExceptionOccurred())
186 throw RuntimeException(
187 "javaloader error - could not find method java/lang/ClassLoader.loadClass");
188 jvalue arg;
189 arg.l = pJNIEnv->NewStringUTF(
190 "com.sun.star.comp.loader.JavaLoader");
191 if(pJNIEnv->ExceptionOccurred())
192 throw RuntimeException(
193 "javaloader error - could not create string");
194 jclass jcJavaLoader = static_cast< jclass >(
195 pJNIEnv->CallObjectMethodA(
196 static_cast< jobject >(xVirtualMachine->getClassLoader()),
197 jmLoadClass, &arg));
198 if(pJNIEnv->ExceptionOccurred())
199 throw RuntimeException(
200 "javaloader error - could not find class com/sun/star/comp/loader/JavaLoader");
201 jmethodID jmJavaLoader_init = pJNIEnv->GetMethodID(jcJavaLoader, "<init>", "()V");
202 if(pJNIEnv->ExceptionOccurred())
203 throw RuntimeException(
204 "javaloader error - instantiation of com.sun.star.comp.loader.JavaLoader failed");
205 jobject joJavaLoader = pJNIEnv->NewObject(jcJavaLoader, jmJavaLoader_init);
206 if(pJNIEnv->ExceptionOccurred())
207 throw RuntimeException(
208 "javaloader error - instantiation of com.sun.star.comp.loader.JavaLoader failed");
210 // map the java JavaLoader to this environment
211 OUString sJava("java");
212 uno_getEnvironment(&pJava_environment, sJava.pData,
213 xVirtualMachine.get());
214 if(!pJava_environment)
215 throw RuntimeException(
216 "javaloader error - no Java environment available");
218 // why is there no convenient constructor?
219 OUString sCppu_current_lb_name(CPPU_CURRENT_LANGUAGE_BINDING_NAME);
220 uno_getEnvironment(&pUno_environment, sCppu_current_lb_name.pData, nullptr);
221 if(!pUno_environment)
222 throw RuntimeException(
223 "javaloader error - no C++ environment available");
225 Mapping java_curr(pJava_environment, pUno_environment);
226 if(!java_curr.is())
227 throw RuntimeException(
228 "javaloader error - no mapping from java to C++ ");
230 // release java environment
231 pJava_environment->release(pJava_environment);
232 pJava_environment = nullptr;
234 // release uno environment
235 pUno_environment->release(pUno_environment);
236 pUno_environment = nullptr;
238 cppu::UnoType<XImplementationLoader>::get().
239 getDescription(reinterpret_cast<typelib_TypeDescription **>(&pType_XImplementationLoader));
240 if(!pType_XImplementationLoader)
241 throw RuntimeException(
242 "javaloader error - no type information for XImplementationLoader");
244 m_javaLoader.set(static_cast<XImplementationLoader *>(java_curr.mapInterface(joJavaLoader, pType_XImplementationLoader)));
245 pJNIEnv->DeleteLocalRef( joJavaLoader );
246 if(!m_javaLoader.is())
247 throw RuntimeException(
248 "javaloader error - mapping of java XImplementationLoader to c++ failed");
250 typelib_typedescription_release(reinterpret_cast<typelib_TypeDescription *>(pType_XImplementationLoader));
251 pType_XImplementationLoader = nullptr;
253 catch (jvmaccess::VirtualMachine::AttachGuard::CreationException &)
255 throw RuntimeException("jvmaccess::VirtualMachine::AttachGuard::CreationException");
258 // set the service manager at the javaloader
259 css::uno::Reference<XInitialization> javaLoader_XInitialization(m_javaLoader, UNO_QUERY_THROW);
261 Any any;
262 any <<= css::uno::Reference<XMultiComponentFactory>(
263 m_xComponentContext->getServiceManager());
265 javaLoader_XInitialization->initialize(Sequence<Any>(&any, 1));
267 catch(RuntimeException &) {
268 if(pJava_environment)
269 pJava_environment->release(pJava_environment);
271 if(pUno_environment)
272 pUno_environment->release(pUno_environment);
274 if(pType_XImplementationLoader)
275 typelib_typedescription_release(
276 reinterpret_cast<typelib_TypeDescription *>(pType_XImplementationLoader));
277 throw;
279 SAL_INFO("stoc", "javaloader.cxx: mapped javaloader - 0x" << m_javaLoader.get());
280 return m_javaLoader;
283 JavaComponentLoader::JavaComponentLoader(const css::uno::Reference<XComponentContext> & xCtx) :
284 m_xComponentContext(xCtx)
290 // XServiceInfo
291 OUString SAL_CALL JavaComponentLoader::getImplementationName()
293 return loader_getImplementationName();
296 sal_Bool SAL_CALL JavaComponentLoader::supportsService(const OUString & ServiceName)
298 return cppu::supportsService(this, ServiceName);
301 Sequence<OUString> SAL_CALL JavaComponentLoader::getSupportedServiceNames()
303 return loader_getSupportedServiceNames();
307 // XImplementationLoader
308 sal_Bool SAL_CALL JavaComponentLoader::writeRegistryInfo(
309 const css::uno::Reference<XRegistryKey> & xKey, const OUString & blabla,
310 const OUString & rLibName)
312 const css::uno::Reference<XImplementationLoader> & loader = getJavaLoader();
313 if (loader.is())
314 return loader->writeRegistryInfo(xKey, blabla, rLibName);
315 else
316 throw CannotRegisterImplementationException("Could not create Java implementation loader");
320 css::uno::Reference<XInterface> SAL_CALL JavaComponentLoader::activate(
321 const OUString & rImplName, const OUString & blabla, const OUString & rLibName,
322 const css::uno::Reference<XRegistryKey> & xKey)
324 const css::uno::Reference<XImplementationLoader> & loader = getJavaLoader();
325 if (loader.is())
326 return loader->activate(rImplName, blabla, rLibName, xKey);
327 else
328 throw CannotActivateFactoryException("Could not create Java implementation loader");
331 static Mutex & getInitMutex()
333 static Mutex * pMutex = nullptr;
334 if( ! pMutex )
336 MutexGuard guard( Mutex::getGlobalMutex() );
337 if( ! pMutex )
339 static Mutex mutex;
340 pMutex = &mutex;
343 return *pMutex;
346 /// @throws Exception
347 css::uno::Reference<XInterface> SAL_CALL JavaComponentLoader_CreateInstance(const css::uno::Reference<XComponentContext> & xCtx)
349 css::uno::Reference<XInterface> xRet;
351 try {
352 MutexGuard guard( getInitMutex() );
353 // The javaloader is never destroyed and there can be only one!
354 // Note that the first context wins ....
355 static css::uno::Reference< XInterface > xStaticRef;
356 if( xStaticRef.is() )
358 xRet = xStaticRef;
360 else
362 xRet = *new JavaComponentLoader(xCtx);
363 xStaticRef = xRet;
366 catch(const RuntimeException & runtimeException) {
367 SAL_INFO(
368 "stoc",
369 "could not init javaloader due to " << runtimeException.Message);
370 throw;
373 return xRet;
376 } //end namespace
379 using namespace stoc_javaloader;
381 static const struct ImplementationEntry g_entries[] =
384 JavaComponentLoader_CreateInstance, loader_getImplementationName,
385 loader_getSupportedServiceNames, createSingleComponentFactory,
386 nullptr , 0
388 { nullptr, nullptr, nullptr, nullptr, nullptr, 0 }
391 extern "C"
393 SAL_DLLPUBLIC_EXPORT void * SAL_CALL javaloader_component_getFactory(
394 const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
396 return component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , g_entries );
400 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */