xref: /trunk/main/stoc/source/javavm/javavm.cxx (revision e437ce2f)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_stoc.hxx"
26 
27 #include "javavm.hxx"
28 
29 #include "interact.hxx"
30 #include "jvmargs.hxx"
31 
32 #include "com/sun/star/beans/NamedValue.hpp"
33 #include "com/sun/star/beans/PropertyState.hpp"
34 #include "com/sun/star/beans/PropertyValue.hpp"
35 #include "com/sun/star/container/XContainer.hpp"
36 #include "com/sun/star/java/JavaNotFoundException.hpp"
37 #include "com/sun/star/java/InvalidJavaSettingsException.hpp"
38 #include "com/sun/star/java/RestartRequiredException.hpp"
39 #include "com/sun/star/java/JavaDisabledException.hpp"
40 #include "com/sun/star/java/JavaVMCreationFailureException.hpp"
41 #include "com/sun/star/lang/DisposedException.hpp"
42 #include "com/sun/star/lang/IllegalArgumentException.hpp"
43 #include "com/sun/star/lang/XEventListener.hpp"
44 #include "com/sun/star/lang/XMultiComponentFactory.hpp"
45 #include "com/sun/star/lang/XSingleComponentFactory.hpp"
46 #include "com/sun/star/lang/WrappedTargetRuntimeException.hpp"
47 #include "com/sun/star/registry/XRegistryKey.hpp"
48 #include "com/sun/star/registry/XSimpleRegistry.hpp"
49 #include "com/sun/star/task/XInteractionHandler.hpp"
50 #include "com/sun/star/uno/Exception.hpp"
51 #include "com/sun/star/uno/Reference.hxx"
52 #include "com/sun/star/uno/RuntimeException.hpp"
53 #include "com/sun/star/uno/Sequence.hxx"
54 #include "com/sun/star/uno/XComponentContext.hpp"
55 #include "com/sun/star/uno/XCurrentContext.hpp"
56 #include "com/sun/star/uno/XInterface.hpp"
57 #include "com/sun/star/util/XMacroExpander.hpp"
58 #include "com/sun/star/container/XNameAccess.hpp"
59 #include "cppuhelper/exc_hlp.hxx"
60 #include "cppuhelper/factory.hxx"
61 #include "cppuhelper/implbase1.hxx"
62 #include "cppuhelper/implementationentry.hxx"
63 #include "jvmaccess/classpath.hxx"
64 #include "jvmaccess/unovirtualmachine.hxx"
65 #include "jvmaccess/virtualmachine.hxx"
66 #include "osl/file.hxx"
67 #include "osl/thread.h"
68 #include "rtl/bootstrap.hxx"
69 #include "rtl/process.h"
70 #include "rtl/string.h"
71 #include "rtl/ustrbuf.hxx"
72 #include "rtl/ustring.h"
73 #include "rtl/ustring.hxx"
74 #include "rtl/uri.hxx"
75 #include "sal/types.h"
76 #include "uno/current_context.hxx"
77 #include "uno/environment.h"
78 #include "uno/lbnames.h"
79 #include "jvmfwk/framework.h"
80 #include "jni.h"
81 
82 #include <stack>
83 #include <string.h>
84 #include <time.h>
85 #include <memory>
86 #include <vector>
87 #include "boost/scoped_array.hpp"
88 #define OUSTR(x) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( x ))
89 
90 // Properties of the javavm can be put
91 // as a komma separated list in this
92 // environment variable
93 #define PROPERTIES_ENV "OO_JAVA_PROPERTIES"
94 #ifdef UNIX
95 #define INI_FILE "javarc"
96 #ifdef MACOSX
97 #define DEF_JAVALIB "JavaVM.framework"
98 #else
99 #define DEF_JAVALIB "libjvm.so"
100 #endif
101 #define TIMEZONE "MEZ"
102 #else
103 #define	INI_FILE "java.ini"
104 #define DEF_JAVALIB "jvm.dll"
105 #define TIMEZONE "MET"
106 #endif
107 
108 /* Within this implementation of the com.sun.star.java.JavaVirtualMachine
109  * service and com.sun.star.java.theJavaVirtualMachine singleton, the method
110  * com.sun.star.java.XJavaVM.getJavaVM relies on the following:
111  * 1  The string "$URE_INTERNAL_JAVA_DIR/" is expanded via the
112  * com.sun.star.util.theMacroExpander singleton into an internal (see the
113  * com.sun.star.uri.ExternalUriReferenceTranslator service), hierarchical URI
114  * reference relative to which the URE JAR files can be addressed.
115  * 2  The string "$URE_INTERNAL_JAVA_CLASSPATH" is either not expandable via the
116  * com.sun.star.util.theMacroExpander singleton
117  * (com.sun.star.lang.IllegalArgumentException), or is expanded via the
118  * com.sun.star.util.theMacroExpander singleton into a list of zero or more
119  * internal (see the com.sun.star.uri.ExternalUriReferenceTranslator service)
120  * URIs, where any space characters (U+0020) are ignored (and, in particular,
121  * separate adjacent URIs).
122  * If either of these requirements is not met, getJavaVM raises a
123  * com.sun.star.uno.RuntimeException.
124  */
125 
126 namespace css = com::sun::star;
127 
128 using stoc_javavm::JavaVirtualMachine;
129 
130 namespace {
131 
132 
133 
134 class NoJavaIniException: public css::uno::Exception
135 {
136 };
137 
138 class SingletonFactory:
139     private cppu::WeakImplHelper1< css::lang::XEventListener >
140 {
141 public:
142     static css::uno::Reference< css::uno::XInterface > getSingleton(
143         css::uno::Reference< css::uno::XComponentContext > const & rContext);
144 
145 private:
146     SingletonFactory(SingletonFactory &); // not implemented
147     void operator =(SingletonFactory); // not implemented
148 
149     inline SingletonFactory() {}
150 
151     virtual inline ~SingletonFactory() {}
152 
153     virtual void SAL_CALL disposing(css::lang::EventObject const &)
154         throw (css::uno::RuntimeException);
155 
156     static void dispose();
157 
158     // TODO ok to keep these static?
159     static osl::Mutex m_aMutex;
160     static css::uno::Reference< css::uno::XInterface > m_xSingleton;
161     static bool m_bDisposed;
162 };
163 
164 css::uno::Reference< css::uno::XInterface > SingletonFactory::getSingleton(
165     css::uno::Reference< css::uno::XComponentContext > const & rContext)
166 {
167     css::uno::Reference< css::uno::XInterface > xSingleton;
168     css::uno::Reference< css::lang::XComponent > xComponent;
169     {
170         osl::MutexGuard aGuard(m_aMutex);
171         if (!m_xSingleton.is())
172         {
173             if (m_bDisposed)
174                 throw css::lang::DisposedException();
175             xComponent = css::uno::Reference< css::lang::XComponent >(
176                 rContext, css::uno::UNO_QUERY_THROW);
177             m_xSingleton = static_cast< cppu::OWeakObject * >(
178                 new JavaVirtualMachine(rContext));
179         }
180         xSingleton = m_xSingleton;
181     }
182     if (xComponent.is())
183         try
184         {
185             xComponent->addEventListener(new SingletonFactory);
186         }
187         catch (...)
188         {
189             dispose();
190             throw;
191         }
192     return xSingleton;
193 }
194 
195 void SAL_CALL SingletonFactory::disposing(css::lang::EventObject const &)
196     throw (css::uno::RuntimeException)
197 {
198     dispose();
199 }
200 
201 void SingletonFactory::dispose()
202 {
203     css::uno::Reference< css::lang::XComponent > xComponent;
204     {
205         osl::MutexGuard aGuard(m_aMutex);
206         xComponent = css::uno::Reference< css::lang::XComponent >(
207             m_xSingleton, css::uno::UNO_QUERY);
208         m_xSingleton.clear();
209         m_bDisposed = true;
210     }
211     if (xComponent.is())
212         xComponent->dispose();
213 }
214 
215 osl::Mutex SingletonFactory::m_aMutex;
216 css::uno::Reference< css::uno::XInterface > SingletonFactory::m_xSingleton;
217 bool SingletonFactory::m_bDisposed = false;
218 
219 rtl::OUString serviceGetImplementationName()
220 {
221     return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
222                              "com.sun.star.comp.stoc.JavaVirtualMachine"));
223 }
224 
225 css::uno::Sequence< rtl::OUString > serviceGetSupportedServiceNames()
226 {
227     rtl::OUString aServiceName(
228         RTL_CONSTASCII_USTRINGPARAM("com.sun.star.java.JavaVirtualMachine"));
229     return css::uno::Sequence< rtl::OUString >(&aServiceName, 1);
230 }
231 
232 css::uno::Reference< css::uno::XInterface > SAL_CALL serviceCreateInstance(
233     css::uno::Reference< css::uno::XComponentContext > const & rContext)
234     SAL_THROW((css::uno::Exception))
235 {
236     // Only one single instance of this service is ever constructed, and is
237     // available until the component context used to create this instance is
238     // disposed.  Afterwards, this function throws a DisposedException (as do
239     // all relevant methods on the single service instance).
240     return SingletonFactory::getSingleton(rContext);
241 }
242 
243 cppu::ImplementationEntry const aServiceImplementation[]
244     = { { serviceCreateInstance,
245           serviceGetImplementationName,
246           serviceGetSupportedServiceNames,
247           cppu::createSingleComponentFactory,
248           0, 0 },
249         { 0, 0, 0, 0, 0, 0 } };
250 
251 typedef std::stack< jvmaccess::VirtualMachine::AttachGuard * > GuardStack;
252 
253 extern "C" {
254 
255 static void destroyAttachGuards(void * pData)
256 {
257     GuardStack * pStack = static_cast< GuardStack * >(pData);
258     if (pStack != 0)
259     {
260         while (!pStack->empty())
261         {
262             delete pStack->top();
263             pStack->pop();
264         }
265         delete pStack;
266     }
267 }
268 
269 }
270 
271 bool askForRetry(css::uno::Any const & rException)
272 {
273     css::uno::Reference< css::uno::XCurrentContext > xContext(
274         css::uno::getCurrentContext());
275     if (xContext.is())
276     {
277         css::uno::Reference< css::task::XInteractionHandler > xHandler;
278         xContext->getValueByName(rtl::OUString(
279                                      RTL_CONSTASCII_USTRINGPARAM(
280                                          "java-vm.interaction-handler")))
281             >>= xHandler;
282         if (xHandler.is())
283         {
284             rtl::Reference< stoc_javavm::InteractionRequest > xRequest(
285                 new stoc_javavm::InteractionRequest(rException));
286             xHandler->handle(xRequest.get());
287             return xRequest->retry();
288         }
289     }
290     return false;
291 }
292 
293 // Only gets the properties if the "Proxy Server" entry in the option dialog is
294 // set to manual (i.e. not to none)
295 void getINetPropsFromConfig(stoc_javavm::JVM * pjvm,
296                             const css::uno::Reference<css::lang::XMultiComponentFactory> & xSMgr,
297                             const css::uno::Reference<css::uno::XComponentContext> &xCtx ) throw (css::uno::Exception)
298 {
299 	css::uno::Reference<css::uno::XInterface> xConfRegistry = xSMgr->createInstanceWithContext(
300 			rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.configuration.ConfigurationRegistry")),
301 			xCtx );
302 	if(!xConfRegistry.is()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("javavm.cxx: couldn't get ConfigurationRegistry")), 0);
303 
304 	css::uno::Reference<css::registry::XSimpleRegistry> xConfRegistry_simple(xConfRegistry, css::uno::UNO_QUERY);
305 	if(!xConfRegistry_simple.is()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("javavm.cxx: couldn't get ConfigurationRegistry")), 0);
306 
307 	xConfRegistry_simple->open(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.Inet")), sal_True, sal_False);
308 	css::uno::Reference<css::registry::XRegistryKey> xRegistryRootKey = xConfRegistry_simple->getRootKey();
309 
310 //	if ooInetProxyType is not 0 then read the settings
311 	css::uno::Reference<css::registry::XRegistryKey> proxyEnable= xRegistryRootKey->openKey(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Settings/ooInetProxyType")));
312 	if( proxyEnable.is() && 0 != proxyEnable->getLongValue())
313 	{
314 		// read ftp proxy name
315 		css::uno::Reference<css::registry::XRegistryKey> ftpProxy_name = xRegistryRootKey->openKey(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Settings/ooInetFTPProxyName")));
316 		if(ftpProxy_name.is() && ftpProxy_name->getStringValue().getLength()) {
317 			rtl::OUString ftpHost = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ftp.proxyHost="));
318 			ftpHost += ftpProxy_name->getStringValue();
319 
320 			// read ftp proxy port
321 			css::uno::Reference<css::registry::XRegistryKey> ftpProxy_port = xRegistryRootKey->openKey(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Settings/ooInetFTPProxyPort")));
322 			if(ftpProxy_port.is() && ftpProxy_port->getLongValue()) {
323 				rtl::OUString ftpPort = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ftp.proxyPort="));
324 				ftpPort += rtl::OUString::valueOf(ftpProxy_port->getLongValue());
325 
326 				pjvm->pushProp(ftpHost);
327 				pjvm->pushProp(ftpPort);
328 			}
329 		}
330 
331 		// read http proxy name
332 		css::uno::Reference<css::registry::XRegistryKey> httpProxy_name = xRegistryRootKey->openKey(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Settings/ooInetHTTPProxyName")));
333 		if(httpProxy_name.is() && httpProxy_name->getStringValue().getLength()) {
334 			rtl::OUString httpHost = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("http.proxyHost="));
335 			httpHost += httpProxy_name->getStringValue();
336 
337 			// read http proxy port
338 			css::uno::Reference<css::registry::XRegistryKey> httpProxy_port = xRegistryRootKey->openKey(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Settings/ooInetHTTPProxyPort")));
339 			if(httpProxy_port.is() && httpProxy_port->getLongValue()) {
340 				rtl::OUString httpPort = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("http.proxyPort="));
341 				httpPort += rtl::OUString::valueOf(httpProxy_port->getLongValue());
342 
343 				pjvm->pushProp(httpHost);
344 				pjvm->pushProp(httpPort);
345 			}
346 		}
347 
348 		// read https proxy name
349 		css::uno::Reference<css::registry::XRegistryKey> httpsProxy_name = xRegistryRootKey->openKey(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Settings/ooInetHTTPSProxyName")));
350 		if(httpsProxy_name.is() && httpsProxy_name->getStringValue().getLength()) {
351 			rtl::OUString httpsHost = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("https.proxyHost="));
352 			httpsHost += httpsProxy_name->getStringValue();
353 
354 			// read https proxy port
355 			css::uno::Reference<css::registry::XRegistryKey> httpsProxy_port = xRegistryRootKey->openKey(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Settings/ooInetHTTPSProxyPort")));
356 			if(httpsProxy_port.is() && httpsProxy_port->getLongValue()) {
357 				rtl::OUString httpsPort = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("https.proxyPort="));
358 				httpsPort += rtl::OUString::valueOf(httpsProxy_port->getLongValue());
359 
360 				pjvm->pushProp(httpsHost);
361 				pjvm->pushProp(httpsPort);
362 			}
363 		}
364 
365 		// read  nonProxyHosts
366 		css::uno::Reference<css::registry::XRegistryKey> nonProxies_name = xRegistryRootKey->openKey(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Settings/ooInetNoProxy")));
367 		if(nonProxies_name.is() && nonProxies_name->getStringValue().getLength()) {
368 			rtl::OUString httpNonProxyHosts = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("http.nonProxyHosts="));
369 			rtl::OUString ftpNonProxyHosts= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ftp.nonProxyHosts="));
370 			rtl::OUString value= nonProxies_name->getStringValue();
371 			// replace the separator ";" by "|"
372 			value= value.replace((sal_Unicode)';', (sal_Unicode)'|');
373 
374 			httpNonProxyHosts += value;
375 			ftpNonProxyHosts += value;
376 
377 			pjvm->pushProp(httpNonProxyHosts);
378 			pjvm->pushProp(ftpNonProxyHosts);
379 		}
380 
381 		// read socks settings
382 /*		Reference<XRegistryKey> socksProxy_name = xRegistryRootKey->openKey(OUSTR("Settings/ooInetSOCKSProxyName"));
383 		if (socksProxy_name.is() && httpProxy_name->getStringValue().getLength()) {
384 			OUString socksHost = OUSTR("socksProxyHost=");
385 			socksHost += socksProxy_name->getStringValue();
386 
387 			// read http proxy port
388 			Reference<XRegistryKey> socksProxy_port = xRegistryRootKey->openKey(OUSTR("Settings/ooInetSOCKSProxyPort"));
389 			if (socksProxy_port.is() && socksProxy_port->getLongValue()) {
390 				OUString socksPort = OUSTR("socksProxyPort=");
391 				socksPort += OUString::valueOf(socksProxy_port->getLongValue());
392 
393 				pjvm->pushProp(socksHost);
394 				pjvm->pushProp(socksPort);
395 			}
396 		}
397 */	}
398 	xConfRegistry_simple->close();
399 }
400 
401 void getDefaultLocaleFromConfig(
402     stoc_javavm::JVM * pjvm,
403     const css::uno::Reference<css::lang::XMultiComponentFactory> & xSMgr,
404     const css::uno::Reference<css::uno::XComponentContext> &xCtx ) throw(css::uno::Exception)
405 {
406 	css::uno::Reference<css::uno::XInterface> xConfRegistry =
407         xSMgr->createInstanceWithContext(
408 		rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
409                           "com.sun.star.configuration.ConfigurationRegistry")), xCtx );
410 	if(!xConfRegistry.is())
411         throw css::uno::RuntimeException(
412             rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("javavm.cxx: couldn't get ConfigurationRegistry")), 0);
413 
414 	css::uno::Reference<css::registry::XSimpleRegistry> xConfRegistry_simple(
415         xConfRegistry, css::uno::UNO_QUERY);
416 	if(!xConfRegistry_simple.is())
417         throw css::uno::RuntimeException(
418             rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("javavm.cxx: couldn't get ConfigurationRegistry")), 0);
419 
420 	xConfRegistry_simple->open(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.Setup")), sal_True, sal_False);
421 	css::uno::Reference<css::registry::XRegistryKey> xRegistryRootKey = xConfRegistry_simple->getRootKey();
422 
423 	// read locale
424 	css::uno::Reference<css::registry::XRegistryKey> ooLocale = xRegistryRootKey->openKey(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("L10N/ooLocale")));
425 	css::uno::Reference<css::registry::XRegistryKey> ooSetupSystemLocale = xRegistryRootKey->openKey(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("L10N/ooSetupSystemLocale")));
426 	if(ooLocale.is() && ooLocale->getStringValue().getLength()) {
427 		sal_Int32 index = ooLocale->getStringValue().indexOf((sal_Unicode) '-');
428 		if(index >= 0) {
429 			rtl::OUString language = ooLocale->getStringValue().copy(0, index);
430 			if(language.getLength()) {
431 				rtl::OUString prop(RTL_CONSTASCII_USTRINGPARAM("user.language="));
432 				prop += language;
433 				pjvm->pushProp(prop);
434 			}
435 		}
436 	}
437 	if(ooSetupSystemLocale.is() && ooSetupSystemLocale->getStringValue().getLength()) {
438 		sal_Int32 index = ooSetupSystemLocale->getStringValue().indexOf((sal_Unicode) '-');
439 		if(index >= 0) {
440 			rtl::OUString country = ooSetupSystemLocale->getStringValue().copy(index + 1);
441 			if(country.getLength()) {
442 				rtl::OUString prop(RTL_CONSTASCII_USTRINGPARAM("user.country="));
443 				prop += country;
444 				pjvm->pushProp(prop);
445 			}
446 		}
447 	}
448 
449 	xConfRegistry_simple->close();
450 }
451 
452 
453 
454 void getJavaPropsFromSafetySettings(
455     stoc_javavm::JVM * pjvm,
456     const css::uno::Reference<css::lang::XMultiComponentFactory> & xSMgr,
457     const css::uno::Reference<css::uno::XComponentContext> &xCtx) throw(css::uno::Exception)
458 {
459     css::uno::Reference<css::uno::XInterface> xConfRegistry =
460         xSMgr->createInstanceWithContext(
461             rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
462                               "com.sun.star.configuration.ConfigurationRegistry")),
463             xCtx);
464 	if(!xConfRegistry.is())
465         throw css::uno::RuntimeException(
466             rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("javavm.cxx: couldn't get ConfigurationRegistry")), 0);
467 
468 	css::uno::Reference<css::registry::XSimpleRegistry> xConfRegistry_simple(
469         xConfRegistry, css::uno::UNO_QUERY);
470 	if(!xConfRegistry_simple.is())
471         throw css::uno::RuntimeException(
472             rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("javavm.cxx: couldn't get ConfigurationRegistry")), 0);
473 
474 	xConfRegistry_simple->open(
475         rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.Office.Java")),
476         sal_True, sal_False);
477 	css::uno::Reference<css::registry::XRegistryKey> xRegistryRootKey =
478         xConfRegistry_simple->getRootKey();
479 
480 	if (xRegistryRootKey.is())
481 	{
482         css::uno::Reference<css::registry::XRegistryKey> key_NetAccess= xRegistryRootKey->openKey(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VirtualMachine/NetAccess")));
483 		if (key_NetAccess.is())
484 		{
485 			sal_Int32 val= key_NetAccess->getLongValue();
486 			rtl::OUString sVal;
487 			switch( val)
488 			{
489 			case 0: sVal= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("host"));
490 				break;
491 			case 1: sVal= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("unrestricted"));
492 				break;
493 			case 3: sVal= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("none"));
494 				break;
495 			}
496 			rtl::OUString sProperty( RTL_CONSTASCII_USTRINGPARAM("appletviewer.security.mode="));
497 			sProperty= sProperty + sVal;
498 			pjvm->pushProp(sProperty);
499 		}
500 		css::uno::Reference<css::registry::XRegistryKey> key_CheckSecurity= xRegistryRootKey->openKey(
501             rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VirtualMachine/Security")));
502 		if( key_CheckSecurity.is())
503 		{
504 			sal_Bool val= (sal_Bool) key_CheckSecurity->getLongValue();
505 			rtl::OUString sProperty(RTL_CONSTASCII_USTRINGPARAM("stardiv.security.disableSecurity="));
506 			if( val)
507 				sProperty= sProperty + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("false"));
508 			else
509 				sProperty= sProperty + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("true"));
510 			pjvm->pushProp( sProperty);
511 		}
512 	}
513 	xConfRegistry_simple->close();
514 }
515 
516 static void setTimeZone(stoc_javavm::JVM * pjvm) throw() {
517 	/* A Bug in the Java function
518 	** struct Hjava_util_Properties * java_lang_System_initProperties(
519 	** struct Hjava_lang_System *this,
520 	** struct Hjava_util_Properties *props);
521 	** This function doesn't detect MEZ, MET or "W. Europe Standard Time"
522 	*/
523 	struct tm *tmData;
524 	time_t clock = time(NULL);
525 	tzset();
526 	tmData = localtime(&clock);
527 #ifdef MACOSX
528 	char * p = tmData->tm_zone;
529 #else
530 	char * p = tzname[0];
531 #endif
532 
533 	if (!strcmp(TIMEZONE, p))
534 		pjvm->pushProp(rtl::OUString::createFromAscii("user.timezone=ECT"));
535 }
536 
537 void initVMConfiguration(
538     stoc_javavm::JVM * pjvm,
539     const css::uno::Reference<css::lang::XMultiComponentFactory> & xSMgr,
540     const css::uno::Reference<css::uno::XComponentContext > &xCtx) throw(css::uno::Exception)
541 {
542 	stoc_javavm::JVM jvm;
543 	try {
544 		getINetPropsFromConfig(&jvm, xSMgr, xCtx);
545 	}
546 	catch(css::uno::Exception & exception) {
547 #if OSL_DEBUG_LEVEL > 1
548 		rtl::OString message = rtl::OUStringToOString(exception.Message, RTL_TEXTENCODING_ASCII_US);
549 		OSL_TRACE("javavm.cxx: can not get INetProps cause of >%s<", message.getStr());
550 #else
551         (void) exception; // unused
552 #endif
553 	}
554 
555 	try {
556 		getDefaultLocaleFromConfig(&jvm, xSMgr,xCtx);
557 	}
558 	catch(css::uno::Exception & exception) {
559 #if OSL_DEBUG_LEVEL > 1
560 		rtl::OString message = rtl::OUStringToOString(exception.Message, RTL_TEXTENCODING_ASCII_US);
561 		OSL_TRACE("javavm.cxx: can not get locale cause of >%s<", message.getStr());
562 #else
563         (void) exception; // unused
564 #endif
565 	}
566 
567     try
568     {
569 		getJavaPropsFromSafetySettings(&jvm, xSMgr, xCtx);
570 	}
571 	catch(css::uno::Exception & exception) {
572 #if OSL_DEBUG_LEVEL > 1
573 		rtl::OString message = rtl::OUStringToOString(exception.Message, RTL_TEXTENCODING_ASCII_US);
574 		OSL_TRACE("javavm.cxx: couldn't get safety settings because of >%s<", message.getStr());
575 #else
576         (void) exception; // unused
577 #endif
578 	}
579 
580 	*pjvm= jvm;
581 	setTimeZone(pjvm);
582 
583 }
584 
585 class DetachCurrentThread {
586 public:
587     explicit DetachCurrentThread(JavaVM * jvm): m_jvm(jvm) {}
588 
589     ~DetachCurrentThread() {
590         if (m_jvm->DetachCurrentThread() != 0) {
591             OSL_ASSERT(false);
592         }
593     }
594 
595 private:
596     DetachCurrentThread(DetachCurrentThread &); // not defined
597     void operator =(DetachCurrentThread &); // not defined
598 
599     JavaVM * m_jvm;
600 };
601 
602 }
603 
604 extern "C" void SAL_CALL
605 component_getImplementationEnvironment(sal_Char const ** pEnvTypeName,
606                                        uno_Environment **)
607 {
608     *pEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
609 }
610 
611 extern "C" void * SAL_CALL component_getFactory(sal_Char const * pImplName,
612                                                 void * pServiceManager,
613                                                 void * pRegistryKey)
614 {
615     return cppu::component_getFactoryHelper(pImplName, pServiceManager,
616                                             pRegistryKey,
617                                             aServiceImplementation);
618 }
619 
620 // There is no component_canUnload, as the library cannot be unloaded.
621 
622 JavaVirtualMachine::JavaVirtualMachine(
623     css::uno::Reference< css::uno::XComponentContext > const & rContext):
624     JavaVirtualMachine_Impl(*static_cast< osl::Mutex * >(this)),
625     m_xContext(rContext),
626     m_bDisposed(false),
627     m_pJavaVm(0),
628     m_bDontCreateJvm(false),
629     m_aAttachGuards(destroyAttachGuards) // TODO check for validity
630 {}
631 
632 void SAL_CALL
633 JavaVirtualMachine::initialize(css::uno::Sequence< css::uno::Any > const &
634                                    rArguments)
635     throw (css::uno::Exception)
636 {
637     osl::MutexGuard aGuard(*this);
638     if (m_bDisposed)
639         throw css::lang::DisposedException(
640             rtl::OUString(), static_cast< cppu::OWeakObject * >(this));
641     if (m_xUnoVirtualMachine.is())
642         throw css::uno::RuntimeException(
643             rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
644                               "bad call to initialize")),
645             static_cast< cppu::OWeakObject * >(this));
646     css::beans::NamedValue val;
647     if (rArguments.getLength() == 1 && (rArguments[0] >>= val)
648         && val.Name.equalsAsciiL(
649             RTL_CONSTASCII_STRINGPARAM( "UnoVirtualMachine")))
650     {
651         OSL_ENSURE(
652             sizeof (sal_Int64) >= sizeof (jvmaccess::UnoVirtualMachine *),
653             "Pointer cannot be represented as sal_Int64");
654         sal_Int64 nPointer = reinterpret_cast< sal_Int64 >(
655             static_cast< jvmaccess::UnoVirtualMachine * >(0));
656         val.Value >>= nPointer;
657         m_xUnoVirtualMachine =
658             reinterpret_cast< jvmaccess::UnoVirtualMachine * >(nPointer);
659     } else {
660         OSL_ENSURE(
661             sizeof (sal_Int64) >= sizeof (jvmaccess::VirtualMachine *),
662             "Pointer cannot be represented as sal_Int64");
663         sal_Int64 nPointer = reinterpret_cast< sal_Int64 >(
664             static_cast< jvmaccess::VirtualMachine * >(0));
665         if (rArguments.getLength() == 1)
666             rArguments[0] >>= nPointer;
667         rtl::Reference< jvmaccess::VirtualMachine > vm(
668             reinterpret_cast< jvmaccess::VirtualMachine * >(nPointer));
669         if (vm.is()) {
670             try {
671                 m_xUnoVirtualMachine = new jvmaccess::UnoVirtualMachine(vm, 0);
672             } catch (jvmaccess::UnoVirtualMachine::CreationException &) {
673                 throw css::uno::RuntimeException(
674                     rtl::OUString(
675                         RTL_CONSTASCII_USTRINGPARAM(
676                             "jvmaccess::UnoVirtualMachine::CreationException")),
677                     static_cast< cppu::OWeakObject * >(this));
678             }
679         }
680     }
681     if (!m_xUnoVirtualMachine.is()) {
682         throw css::lang::IllegalArgumentException(
683             rtl::OUString(
684                 RTL_CONSTASCII_USTRINGPARAM(
685                     "sequence of exactly one any containing either (a) a"
686                     " com.sun.star.beans.NamedValue with Name"
687                     " \"UnoVirtualMachine\" and Value a hyper representing a"
688                     " non-null pointer to a jvmaccess:UnoVirtualMachine, or (b)"
689                     " a hyper representing a non-null pointer to a"
690                     " jvmaccess::VirtualMachine required")),
691             static_cast< cppu::OWeakObject * >(this), 0);
692     }
693     m_xVirtualMachine = m_xUnoVirtualMachine->getVirtualMachine();
694 }
695 
696 rtl::OUString SAL_CALL JavaVirtualMachine::getImplementationName()
697     throw (css::uno::RuntimeException)
698 {
699     return serviceGetImplementationName();
700 }
701 
702 sal_Bool SAL_CALL
703 JavaVirtualMachine::supportsService(rtl::OUString const & rServiceName)
704     throw (css::uno::RuntimeException)
705 {
706     css::uno::Sequence< rtl::OUString > aNames(getSupportedServiceNames());
707     for (sal_Int32 i = 0; i < aNames.getLength(); ++i)
708         if (aNames[i] == rServiceName)
709             return true;
710     return false;
711 }
712 
713 css::uno::Sequence< rtl::OUString > SAL_CALL
714 JavaVirtualMachine::getSupportedServiceNames()
715     throw (css::uno::RuntimeException)
716 {
717     return serviceGetSupportedServiceNames();
718 }
719 
720 css::uno::Any SAL_CALL
721 JavaVirtualMachine::getJavaVM(css::uno::Sequence< sal_Int8 > const & rProcessId)
722     throw (css::uno::RuntimeException)
723 {
724     osl::MutexGuard aGuard(*this);
725     if (m_bDisposed)
726         throw css::lang::DisposedException(
727             rtl::OUString(), static_cast< cppu::OWeakObject * >(this));
728     css::uno::Sequence< sal_Int8 > aId(16);
729     rtl_getGlobalProcessId(reinterpret_cast< sal_uInt8 * >(aId.getArray()));
730     enum ReturnType {
731         RETURN_JAVAVM, RETURN_VIRTUALMACHINE, RETURN_UNOVIRTUALMACHINE };
732     ReturnType returnType =
733         rProcessId.getLength() == 17 && rProcessId[16] == 0
734         ? RETURN_VIRTUALMACHINE
735         : rProcessId.getLength() == 17 && rProcessId[16] == 1
736         ? RETURN_UNOVIRTUALMACHINE
737         : RETURN_JAVAVM;
738     css::uno::Sequence< sal_Int8 > aProcessId(rProcessId);
739     if (returnType != RETURN_JAVAVM)
740         aProcessId.realloc(16);
741     if (aId != aProcessId)
742         return css::uno::Any();
743 
744     while (!m_xVirtualMachine.is()) // retry until successful
745     {
746         // This is the second attempt to create Java.  m_bDontCreateJvm is
747         // set which means instantiating the JVM might crash.
748         if (m_bDontCreateJvm)
749             //throw css::uno::RuntimeException();
750             return css::uno::Any();
751 
752         stoc_javavm::JVM aJvm;
753         initVMConfiguration(&aJvm, m_xContext->getServiceManager(),
754                             m_xContext);
755         //Create the JavaVMOption array
756         const std::vector<rtl::OUString> & props = aJvm.getProperties();
757         boost::scoped_array<JavaVMOption> sarOptions(
758             new JavaVMOption[props.size()]);
759         JavaVMOption * arOptions = sarOptions.get();
760         //Create an array that contains the strings which are passed
761         //into the options
762         boost::scoped_array<rtl::OString> sarPropStrings(
763              new rtl::OString[props.size()]);
764         rtl::OString * arPropStrings = sarPropStrings.get();
765 
766         rtl::OString sJavaOption("-");
767         typedef std::vector<rtl::OUString>::const_iterator cit;
768         int index = 0;
769         for (cit i = props.begin(); i != props.end(); i++)
770         {
771             rtl::OString sOption = rtl::OUStringToOString(
772                 *i, osl_getThreadTextEncoding());
773 
774             if (!sOption.matchIgnoreAsciiCase(sJavaOption, 0))
775                 arPropStrings[index]= rtl::OString("-D") + sOption;
776             else
777                 arPropStrings[index] = sOption;
778 
779             arOptions[index].optionString = (sal_Char*)arPropStrings[index].getStr();
780             arOptions[index].extraInfo = 0;
781             index ++;
782         }
783 
784         JNIEnv * pMainThreadEnv = 0;
785         javaFrameworkError errcode = JFW_E_NONE;
786         errcode = jfw_startVM(arOptions, index, & m_pJavaVm,
787                                 & pMainThreadEnv);
788 
789         bool bStarted = false;
790         switch (errcode)
791         {
792         case JFW_E_NONE: bStarted = true; break;
793         case JFW_E_NO_SELECT:
794         {
795             // No Java configured. We silenty run the java configuration
796             // Java.
797             javaFrameworkError errFind = jfw_findAndSelectJRE( NULL );
798             if (errFind == JFW_E_NONE)
799             {
800                 continue;
801             }
802             else if (errFind == JFW_E_NO_JAVA_FOUND)
803             {
804 
805                 //Warning MessageBox:
806                 //%PRODUCTNAME requires a Java runtime environment (JRE) to perform this task.
807                 //Please install a JRE and restart %PRODUCTNAME.
808                 css::java::JavaNotFoundException exc(
809                     rtl::OUString(
810                         RTL_CONSTASCII_USTRINGPARAM(
811                             "JavaVirtualMachine::getJavaVM failed because"
812                             " No suitable JRE found!")),
813                     static_cast< cppu::OWeakObject * >(this));
814                 askForRetry(css::uno::makeAny(exc));
815                 return css::uno::Any();
816             }
817             else
818             {
819                 //An unexpected error occurred
820                 throw css::uno::RuntimeException(
821                     rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
822                                       "[JavaVirtualMachine]:An unexpected error occurred"
823                                       " while searching for a Java!")), 0);
824             }
825         }
826         case JFW_E_INVALID_SETTINGS:
827         {
828             //Warning MessageBox:
829             // The %PRODUCTNAME configuration has been changed. Under Tools
830             // - Options - %PRODUCTNAME - Java, select the Java runtime environment
831             // you want to have used by %PRODUCTNAME.
832             css::java::InvalidJavaSettingsException exc(
833                 rtl::OUString(
834                     RTL_CONSTASCII_USTRINGPARAM(
835                         "JavaVirtualMachine::getJavaVM failed because"
836                         " Java settings have changed!")),
837                 static_cast< cppu::OWeakObject * >(this));
838             askForRetry(css::uno::makeAny(exc));
839             return css::uno::Any();
840         }
841         case JFW_E_JAVA_DISABLED:
842         {
843             //QueryBox:
844             //%PRODUCTNAME requires a Java runtime environment (JRE) to perform
845             //this task. However, use of a JRE has been disabled. Do you want to
846             //enable the use of a JRE now?
847             css::java::JavaDisabledException exc(
848                 rtl::OUString(
849                     RTL_CONSTASCII_USTRINGPARAM(
850                         "JavaVirtualMachine::getJavaVM failed because"
851                         " Java is disabled!")),
852                 static_cast< cppu::OWeakObject * >(this));
853             if( ! askForRetry(css::uno::makeAny(exc)))
854                 return css::uno::Any();
855             continue;
856         }
857         case JFW_E_VM_CREATION_FAILED:
858         {
859             //If the creation failed because the JRE has been uninstalled then
860             //we search another one. As long as there is a javaldx, we should
861             //never come into this situation. javaldx checks alway if the JRE
862             //still exist.
863             JavaInfo * pJavaInfo = NULL;
864             if (JFW_E_NONE == jfw_getSelectedJRE(&pJavaInfo))
865             {
866                 sal_Bool bExist = sal_False;
867                 if (JFW_E_NONE == jfw_existJRE(pJavaInfo, &bExist))
868                 {
869                     if (bExist == sal_False
870                         && ! (pJavaInfo->nRequirements & JFW_REQUIRE_NEEDRESTART))
871                     {
872                         javaFrameworkError errFind = jfw_findAndSelectJRE( NULL );
873                         if (errFind == JFW_E_NONE)
874                         {
875                             continue;
876                         }
877                     }
878                 }
879             }
880 
881             jfw_freeJavaInfo(pJavaInfo);
882             //
883             //Error: %PRODUCTNAME requires a Java
884             //runtime environment (JRE) to perform this task. The selected JRE
885             //is defective. Please select another version or install a new JRE
886             //and select it under Tools - Options - %PRODUCTNAME - Java.
887             css::java::JavaVMCreationFailureException exc(
888                 rtl::OUString(
889                     RTL_CONSTASCII_USTRINGPARAM(
890                         "JavaVirtualMachine::getJavaVM failed because"
891                         " Java is defective!")),
892                 static_cast< cppu::OWeakObject * >(this), 0);
893             askForRetry(css::uno::makeAny(exc));
894             return css::uno::Any();
895         }
896         case JFW_E_RUNNING_JVM:
897         {
898             //This service should make sure that we do not start java twice.
899             OSL_ASSERT(0);
900             break;
901         }
902         case JFW_E_NEED_RESTART:
903         {
904             //Error:
905             //For the selected Java runtime environment to work properly,
906             //%PRODUCTNAME must be restarted. Please restart %PRODUCTNAME now.
907             css::java::RestartRequiredException exc(
908                 rtl::OUString(
909                     RTL_CONSTASCII_USTRINGPARAM(
910                         "JavaVirtualMachine::getJavaVM failed because"
911                         "Office must be restarted before Java can be used!")),
912                 static_cast< cppu::OWeakObject * >(this));
913             askForRetry(css::uno::makeAny(exc));
914             return css::uno::Any();
915         }
916         default:
917             //RuntimeException: error is somewhere in the java framework.
918             //An unexpected error occurred
919             throw css::uno::RuntimeException(
920                 rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
921                                   "[JavaVirtualMachine]:An unexpected error occurred"
922                                   " while starting Java!")), 0);
923         }
924 
925         if (bStarted)
926         {
927             {
928                 DetachCurrentThread detach(m_pJavaVm);
929                     // necessary to make debugging work; this thread will be
930                     // suspended when the destructor of detach returns
931                 m_xVirtualMachine = new jvmaccess::VirtualMachine(
932                     m_pJavaVm, JNI_VERSION_1_2, true, pMainThreadEnv);
933                 setUpUnoVirtualMachine(pMainThreadEnv);
934             }
935             // Listen for changes in the configuration (e.g. proxy settings):
936             // TODO this is done too late; changes to the configuration done
937             // after the above call to initVMConfiguration are lost
938             registerConfigChangesListener();
939 
940             break;
941         }
942     }
943     if (!m_xUnoVirtualMachine.is()) {
944         try {
945             jvmaccess::VirtualMachine::AttachGuard guard(m_xVirtualMachine);
946             setUpUnoVirtualMachine(guard.getEnvironment());
947         } catch (jvmaccess::VirtualMachine::AttachGuard::CreationException &) {
948             throw css::uno::RuntimeException(
949                 rtl::OUString(
950                     RTL_CONSTASCII_USTRINGPARAM(
951                         "jvmaccess::VirtualMachine::AttachGuard::"
952                         "CreationException occurred")),
953                 static_cast< cppu::OWeakObject * >(this));
954         }
955     }
956     switch (returnType) {
957     default: // RETURN_JAVAVM
958         if (m_pJavaVm == 0) {
959             throw css::uno::RuntimeException(
960                 rtl::OUString(
961                     RTL_CONSTASCII_USTRINGPARAM(
962                         "JavaVirtualMachine service was initialized in a way"
963                         " that the requested JavaVM pointer is not available")),
964                 static_cast< cppu::OWeakObject * >(this));
965         }
966         return css::uno::makeAny(reinterpret_cast< sal_IntPtr >(m_pJavaVm));
967     case RETURN_VIRTUALMACHINE:
968         OSL_ASSERT(sizeof (sal_Int64) >= sizeof (jvmaccess::VirtualMachine *));
969         return css::uno::makeAny(
970             reinterpret_cast< sal_Int64 >(
971                 m_xUnoVirtualMachine->getVirtualMachine().get()));
972     case RETURN_UNOVIRTUALMACHINE:
973         OSL_ASSERT(sizeof (sal_Int64) >= sizeof (jvmaccess::VirtualMachine *));
974         return css::uno::makeAny(
975             reinterpret_cast< sal_Int64 >(m_xUnoVirtualMachine.get()));
976     }
977 }
978 
979 sal_Bool SAL_CALL JavaVirtualMachine::isVMStarted()
980     throw (css::uno::RuntimeException)
981 {
982     osl::MutexGuard aGuard(*this);
983     if (m_bDisposed)
984         throw css::lang::DisposedException(
985             rtl::OUString(), static_cast< cppu::OWeakObject * >(this));
986     return m_xUnoVirtualMachine.is();
987 }
988 
989 sal_Bool SAL_CALL JavaVirtualMachine::isVMEnabled()
990     throw (css::uno::RuntimeException)
991 {
992     {
993         osl::MutexGuard aGuard(*this);
994         if (m_bDisposed)
995             throw css::lang::DisposedException(
996                 rtl::OUString(), static_cast< cppu::OWeakObject * >(this));
997     }
998 //    stoc_javavm::JVM aJvm;
999 //    initVMConfiguration(&aJvm, m_xContext->getServiceManager(), m_xContext);
1000 //    return aJvm.isEnabled();
1001     //ToDo
1002     sal_Bool bEnabled = sal_False;
1003     if (jfw_getEnabled( & bEnabled) != JFW_E_NONE)
1004         throw css::uno::RuntimeException();
1005     return bEnabled;
1006 }
1007 
1008 sal_Bool SAL_CALL JavaVirtualMachine::isThreadAttached()
1009     throw (css::uno::RuntimeException)
1010 {
1011     osl::MutexGuard aGuard(*this);
1012     if (m_bDisposed)
1013         throw css::lang::DisposedException(
1014             rtl::OUString(), static_cast< cppu::OWeakObject * >(this));
1015     // TODO isThreadAttached only returns true if the thread was attached via
1016     // registerThread:
1017     GuardStack * pStack
1018         = static_cast< GuardStack * >(m_aAttachGuards.getData());
1019     return pStack != 0 && !pStack->empty();
1020 }
1021 
1022 void SAL_CALL JavaVirtualMachine::registerThread()
1023     throw (css::uno::RuntimeException)
1024 {
1025     osl::MutexGuard aGuard(*this);
1026     if (m_bDisposed)
1027         throw css::lang::DisposedException(
1028             rtl::OUString(), static_cast< cppu::OWeakObject * >(this));
1029     if (!m_xUnoVirtualMachine.is())
1030         throw css::uno::RuntimeException(
1031             rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1032                               "JavaVirtualMachine::registerThread:"
1033                               " null VirtualMachine")),
1034             static_cast< cppu::OWeakObject * >(this));
1035     GuardStack * pStack
1036         = static_cast< GuardStack * >(m_aAttachGuards.getData());
1037     if (pStack == 0)
1038     {
1039         pStack = new GuardStack;
1040         m_aAttachGuards.setData(pStack);
1041     }
1042     try
1043     {
1044         pStack->push(
1045             new jvmaccess::VirtualMachine::AttachGuard(
1046                 m_xUnoVirtualMachine->getVirtualMachine()));
1047     }
1048     catch (jvmaccess::VirtualMachine::AttachGuard::CreationException &)
1049     {
1050         throw css::uno::RuntimeException(
1051             rtl::OUString(
1052                 RTL_CONSTASCII_USTRINGPARAM(
1053                     "JavaVirtualMachine::registerThread: jvmaccess::"
1054                     "VirtualMachine::AttachGuard::CreationException")),
1055             static_cast< cppu::OWeakObject * >(this));
1056     }
1057 }
1058 
1059 void SAL_CALL JavaVirtualMachine::revokeThread()
1060     throw (css::uno::RuntimeException)
1061 {
1062     osl::MutexGuard aGuard(*this);
1063     if (m_bDisposed)
1064         throw css::lang::DisposedException(
1065             rtl::OUString(), static_cast< cppu::OWeakObject * >(this));
1066     if (!m_xUnoVirtualMachine.is())
1067         throw css::uno::RuntimeException(
1068             rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1069                               "JavaVirtualMachine::revokeThread:"
1070                               " null VirtualMachine")),
1071             static_cast< cppu::OWeakObject * >(this));
1072     GuardStack * pStack
1073         = static_cast< GuardStack * >(m_aAttachGuards.getData());
1074     if (pStack == 0 || pStack->empty())
1075         throw css::uno::RuntimeException(
1076             rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1077                               "JavaVirtualMachine::revokeThread:"
1078                               " no matching registerThread")),
1079             static_cast< cppu::OWeakObject * >(this));
1080     delete pStack->top();
1081     pStack->pop();
1082 }
1083 
1084 void SAL_CALL
1085 JavaVirtualMachine::disposing(css::lang::EventObject const & rSource)
1086     throw (css::uno::RuntimeException)
1087 {
1088     osl::MutexGuard aGuard(*this);
1089     if (rSource.Source == m_xInetConfiguration)
1090         m_xInetConfiguration.clear();
1091     if (rSource.Source == m_xJavaConfiguration)
1092         m_xJavaConfiguration.clear();
1093 }
1094 
1095 void SAL_CALL JavaVirtualMachine::elementInserted(
1096     css::container::ContainerEvent const &)
1097     throw (css::uno::RuntimeException)
1098 {}
1099 
1100 void SAL_CALL JavaVirtualMachine::elementRemoved(
1101     css::container::ContainerEvent const &)
1102     throw (css::uno::RuntimeException)
1103 {}
1104 
1105 // If a user changes the setting, for example for proxy settings, then this
1106 // function will be called from the configuration manager.  Even if the .xml
1107 // file does not contain an entry yet and that entry has to be inserted, this
1108 // function will be called.  We call java.lang.System.setProperty for the new
1109 // values.
1110 void SAL_CALL JavaVirtualMachine::elementReplaced(
1111     css::container::ContainerEvent const & rEvent)
1112     throw (css::uno::RuntimeException)
1113 {
1114     // TODO Using the new value stored in rEvent is wrong here.  If two threads
1115     // receive different elementReplaced calls in quick succession, it is
1116     // unspecified which changes the JVM's system properties last.  A correct
1117     // solution must atomically (i.e., protected by a mutex) read the latest
1118     // value from the configuration and set it as a system property at the JVM.
1119 
1120     rtl::OUString aAccessor;
1121     rEvent.Accessor >>= aAccessor;
1122     rtl::OUString aPropertyName;
1123     rtl::OUString aPropertyName2;
1124     rtl::OUString aPropertyValue;
1125     bool bSecurityChanged = false;
1126     if (aAccessor.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("ooInetProxyType")))
1127     {
1128         // Proxy none, manually
1129         sal_Int32 value = 0;
1130         rEvent.Element >>= value;
1131         setINetSettingsInVM(value != 0);
1132         return;
1133     }
1134     else if (aAccessor.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(
1135                                         "ooInetHTTPProxyName")))
1136     {
1137         aPropertyName = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1138                                           "http.proxyHost"));
1139         rEvent.Element >>= aPropertyValue;
1140     }
1141     else if (aAccessor.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(
1142                                         "ooInetHTTPProxyPort")))
1143     {
1144         aPropertyName
1145             = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("http.proxyPort"));
1146         sal_Int32 n = 0;
1147         rEvent.Element >>= n;
1148         aPropertyValue = rtl::OUString::valueOf(n);
1149     }
1150     else if (aAccessor.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(
1151                                         "ooInetHTTPSProxyName")))
1152     {
1153         aPropertyName = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1154                                           "https.proxyHost"));
1155         rEvent.Element >>= aPropertyValue;
1156     }
1157     else if (aAccessor.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(
1158                                         "ooInetHTTPSProxyPort")))
1159     {
1160         aPropertyName
1161             = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("https.proxyPort"));
1162         sal_Int32 n = 0;
1163         rEvent.Element >>= n;
1164         aPropertyValue = rtl::OUString::valueOf(n);
1165     }
1166     else if (aAccessor.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(
1167                                         "ooInetFTPProxyName")))
1168     {
1169         aPropertyName = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1170                                           "ftp.proxyHost"));
1171         rEvent.Element >>= aPropertyValue;
1172     }
1173     else if (aAccessor.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(
1174                                         "ooInetFTPProxyPort")))
1175     {
1176         aPropertyName = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1177                                           "ftp.proxyPort"));
1178         sal_Int32 n = 0;
1179         rEvent.Element >>= n;
1180         aPropertyValue = rtl::OUString::valueOf(n);
1181     }
1182     else if (aAccessor.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(
1183                                         "ooInetNoProxy")))
1184     {
1185         aPropertyName = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1186                                           "http.nonProxyHosts"));
1187         aPropertyName2 = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1188                                            "ftp.nonProxyHosts"));
1189         rEvent.Element >>= aPropertyValue;
1190         aPropertyValue = aPropertyValue.replace(';', '|');
1191     }
1192     else if (aAccessor.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("NetAccess")))
1193     {
1194         aPropertyName = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1195                                           "appletviewer.security.mode"));
1196         sal_Int32 n = 0;
1197         if (rEvent.Element >>= n)
1198             switch (n)
1199             {
1200             case 0:
1201                 aPropertyValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1202                                                    "host"));
1203                 break;
1204             case 1:
1205                 aPropertyValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1206                                                    "unrestricted"));
1207                 break;
1208             case 3:
1209                 aPropertyValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1210                                                    "none"));
1211                 break;
1212             }
1213         else
1214             return;
1215         bSecurityChanged = true;
1216     }
1217     else if (aAccessor.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("Security")))
1218     {
1219         aPropertyName = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1220                                           "stardiv.security.disableSecurity"));
1221         sal_Bool b = sal_Bool();
1222         if (rEvent.Element >>= b)
1223             if (b)
1224                 aPropertyValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1225                                                    "false"));
1226             else
1227                 aPropertyValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1228                                                    "true"));
1229         else
1230             return;
1231         bSecurityChanged = true;
1232     }
1233     else
1234         return;
1235 
1236     rtl::Reference< jvmaccess::VirtualMachine > xVirtualMachine;
1237     {
1238         osl::MutexGuard aGuard(*this);
1239         if (m_xUnoVirtualMachine.is()) {
1240             xVirtualMachine = m_xUnoVirtualMachine->getVirtualMachine();
1241         }
1242     }
1243     if (xVirtualMachine.is())
1244     {
1245         try
1246         {
1247             jvmaccess::VirtualMachine::AttachGuard aAttachGuard(
1248                 xVirtualMachine);
1249             JNIEnv * pJNIEnv = aAttachGuard.getEnvironment();
1250 
1251             // call java.lang.System.setProperty
1252             // String setProperty( String key, String value)
1253             jclass jcSystem= pJNIEnv->FindClass("java/lang/System");
1254             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:FindClass java/lang/System")), 0);
1255             jmethodID jmSetProps= pJNIEnv->GetStaticMethodID( jcSystem, "setProperty","(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
1256             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:GetStaticMethodID java.lang.System.setProperty")), 0);
1257 
1258             jstring jsPropName= pJNIEnv->NewString( aPropertyName.getStr(), aPropertyName.getLength());
1259             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1260 
1261             // remove the property if it does not have a value ( user left the dialog field empty)
1262             // or if the port is set to 0
1263             aPropertyValue= aPropertyValue.trim();
1264             if(
1265                aPropertyValue.getLength() == 0 ||
1266                (
1267                 (
1268                  aPropertyName.equals( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ftp.proxyPort"))) ||
1269                  aPropertyName.equals( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("http.proxyPort"))) /*||
1270                  aPropertyName.equals( OUString( RTL_CONSTASCII_USTRINGPARAM("socksProxyPort")))*/
1271                 ) &&
1272                 aPropertyValue.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("0")))
1273                )
1274               )
1275             {
1276                 // call java.lang.System.getProperties
1277                 jmethodID jmGetProps= pJNIEnv->GetStaticMethodID( jcSystem, "getProperties","()Ljava/util/Properties;");
1278                 if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:GetStaticMethodID java.lang.System.getProperties")), 0);
1279                 jobject joProperties= pJNIEnv->CallStaticObjectMethod( jcSystem, jmGetProps);
1280                 if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:CallStaticObjectMethod java.lang.System.getProperties")), 0);
1281                 // call java.util.Properties.remove
1282                 jclass jcProperties= pJNIEnv->FindClass("java/util/Properties");
1283                 if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:FindClass java/util/Properties")), 0);
1284                 jmethodID jmRemove= pJNIEnv->GetMethodID( jcProperties, "remove", "(Ljava/lang/Object;)Ljava/lang/Object;");
1285                 if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:GetMethodID java.util.Properties.remove")), 0);
1286                 pJNIEnv->CallObjectMethod( joProperties, jmRemove, jsPropName);
1287 
1288                 // special calse for ftp.nonProxyHosts and http.nonProxyHosts. The office only
1289                 // has a value for two java properties
1290                 if (aPropertyName2.getLength() > 0)
1291                 {
1292                     jstring jsPropName2= pJNIEnv->NewString( aPropertyName2.getStr(), aPropertyName2.getLength());
1293                     if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1294                     pJNIEnv->CallObjectMethod( joProperties, jmRemove, jsPropName2);
1295                 }
1296             }
1297             else
1298             {
1299                 // Change the Value of the property
1300                 jstring jsPropValue= pJNIEnv->NewString( aPropertyValue.getStr(), aPropertyValue.getLength());
1301                 if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1302                 pJNIEnv->CallStaticObjectMethod( jcSystem, jmSetProps, jsPropName, jsPropValue);
1303                 if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:CallStaticObjectMethod java.lang.System.setProperty")), 0);
1304 
1305                 // special calse for ftp.nonProxyHosts and http.nonProxyHosts. The office only
1306                 // has a value for two java properties
1307                 if (aPropertyName2.getLength() > 0)
1308                 {
1309                     jstring jsPropName2= pJNIEnv->NewString( aPropertyName2.getStr(), aPropertyName2.getLength());
1310                     if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1311                     jsPropValue= pJNIEnv->NewString( aPropertyValue.getStr(), aPropertyValue.getLength());
1312                     if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1313                     pJNIEnv->CallStaticObjectMethod( jcSystem, jmSetProps, jsPropName2, jsPropValue);
1314                     if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:CallStaticObjectMethod java.lang.System.setProperty")), 0);
1315                 }
1316             }
1317 
1318             // If the settings for Security and NetAccess changed then we have to notify the SandboxSecurity
1319             // SecurityManager
1320             // call System.getSecurityManager()
1321             if (bSecurityChanged)
1322             {
1323                 jmethodID jmGetSecur= pJNIEnv->GetStaticMethodID( jcSystem,"getSecurityManager","()Ljava/lang/SecurityManager;");
1324                 if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:GetStaticMethodID java.lang.System.getSecurityManager")), 0);
1325                 jobject joSecur= pJNIEnv->CallStaticObjectMethod( jcSystem, jmGetSecur);
1326                 if (joSecur != 0)
1327                 {
1328                     // Make sure the SecurityManager is our SandboxSecurity
1329                     // FindClass("com.sun.star.lib.sandbox.SandboxSecurityManager" only worked at the first time
1330                     // this code was executed. Maybe it is a security feature. However, all attempts to debug the
1331                     // SandboxSecurity class (maybe the VM invokes checkPackageAccess)  failed.
1332 //                  jclass jcSandboxSec= pJNIEnv->FindClass("com.sun.star.lib.sandbox.SandboxSecurity");
1333 //                  if(pJNIEnv->ExceptionOccurred()) throw RuntimeException(OUSTR("JNI:FindClass com.sun.star.lib.sandbox.SandboxSecurity"), Reference<XInterface>());
1334 //                  jboolean bIsSand= pJNIEnv->IsInstanceOf( joSecur, jcSandboxSec);
1335                     // The SecurityManagers class Name must be com.sun.star.lib.sandbox.SandboxSecurity
1336                     jclass jcSec= pJNIEnv->GetObjectClass( joSecur);
1337                     jclass jcClass= pJNIEnv->FindClass("java/lang/Class");
1338                     if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:FindClass java.lang.Class")), 0);
1339                     jmethodID jmName= pJNIEnv->GetMethodID( jcClass,"getName","()Ljava/lang/String;");
1340                     if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:GetMethodID java.lang.Class.getName")), 0);
1341                     jstring jsClass= (jstring) pJNIEnv->CallObjectMethod( jcSec, jmName);
1342                     const jchar* jcharName= pJNIEnv->GetStringChars( jsClass, NULL);
1343                     rtl::OUString sName( jcharName);
1344                     jboolean bIsSandbox;
1345                     if (sName == rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.lib.sandbox.SandboxSecurity")))
1346                         bIsSandbox= JNI_TRUE;
1347                     else
1348                         bIsSandbox= JNI_FALSE;
1349                     pJNIEnv->ReleaseStringChars( jsClass, jcharName);
1350 
1351                     if (bIsSandbox == JNI_TRUE)
1352                     {
1353                         // call SandboxSecurity.reset
1354                         jmethodID jmReset= pJNIEnv->GetMethodID( jcSec,"reset","()V");
1355                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:GetMethodID com.sun.star.lib.sandbox.SandboxSecurity.reset")), 0);
1356                         pJNIEnv->CallVoidMethod( joSecur, jmReset);
1357                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:CallVoidMethod com.sun.star.lib.sandbox.SandboxSecurity.reset")), 0);
1358                     }
1359                 }
1360             }
1361         }
1362         catch (jvmaccess::VirtualMachine::AttachGuard::CreationException &)
1363         {
1364             throw css::uno::RuntimeException(
1365                 rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1366                                   "jvmaccess::VirtualMachine::AttachGuard::"
1367                                   "CreationException")),
1368                 0);
1369         }
1370     }
1371 }
1372 
1373 JavaVirtualMachine::~JavaVirtualMachine()
1374 {
1375     if (m_xInetConfiguration.is())
1376         // We should never get here, but just in case...
1377         try
1378         {
1379             m_xInetConfiguration->removeContainerListener(this);
1380         }
1381         catch (css::uno::Exception &)
1382         {
1383             OSL_ENSURE(false, "com.sun.star.uno.Exception caught");
1384         }
1385     if (m_xJavaConfiguration.is())
1386         // We should never get here, but just in case...
1387         try
1388         {
1389             m_xJavaConfiguration->removeContainerListener(this);
1390         }
1391         catch (css::uno::Exception &)
1392         {
1393             OSL_ENSURE(false, "com.sun.star.uno.Exception caught");
1394         }
1395 }
1396 
1397 void SAL_CALL JavaVirtualMachine::disposing()
1398 {
1399     css::uno::Reference< css::container::XContainer > xContainer1;
1400     css::uno::Reference< css::container::XContainer > xContainer2;
1401     {
1402         osl::MutexGuard aGuard(*this);
1403         m_bDisposed = true;
1404         xContainer1 = m_xInetConfiguration;
1405         m_xInetConfiguration.clear();
1406         xContainer2 = m_xJavaConfiguration;
1407         m_xJavaConfiguration.clear();
1408     }
1409     if (xContainer1.is())
1410         xContainer1->removeContainerListener(this);
1411     if (xContainer2.is())
1412         xContainer2->removeContainerListener(this);
1413 }
1414 
1415 /*We listen to changes in the configuration. For example, the user changes the proxy
1416   settings in the options dialog (menu tools). Then we are notified of this change and
1417   if the java vm is already running we change the properties (System.lang.System.setProperties)
1418   through JNI.
1419   To receive notifications this class implements XContainerListener.
1420 */
1421 void JavaVirtualMachine::registerConfigChangesListener()
1422 {
1423     try
1424     {
1425         css::uno::Reference< css::lang::XMultiServiceFactory > xConfigProvider(
1426             m_xContext->getServiceManager()->createInstanceWithContext( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
1427                 "com.sun.star.configuration.ConfigurationProvider")), m_xContext), css::uno::UNO_QUERY);
1428 
1429         if (xConfigProvider.is())
1430         {
1431             // We register this instance as listener to changes in org.openoffice.Inet/Settings
1432             // arguments for ConfigurationAccess
1433             css::uno::Sequence< css::uno::Any > aArguments(2);
1434             aArguments[0] <<= css::beans::PropertyValue(
1435                 rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("nodepath")),
1436                 0,
1437                 css::uno::makeAny(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.Inet/Settings"))),
1438                 css::beans::PropertyState_DIRECT_VALUE);
1439             // depth: -1 means unlimited
1440             aArguments[1] <<= css::beans::PropertyValue(
1441                 rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("depth")),
1442                 0,
1443                 css::uno::makeAny( (sal_Int32)-1),
1444                 css::beans::PropertyState_DIRECT_VALUE);
1445 
1446             m_xInetConfiguration
1447                 = css::uno::Reference< css::container::XContainer >(
1448                     xConfigProvider->createInstanceWithArguments(
1449                         rtl::OUString(
1450                             RTL_CONSTASCII_USTRINGPARAM(
1451                              "com.sun.star.configuration.ConfigurationAccess")),
1452                         aArguments),
1453                     css::uno::UNO_QUERY);
1454 
1455             if (m_xInetConfiguration.is())
1456                 m_xInetConfiguration->addContainerListener(this);
1457 
1458             // now register as listener to changes in org.openoffice.Java/VirtualMachine
1459             css::uno::Sequence< css::uno::Any > aArguments2(2);
1460             aArguments2[0] <<= css::beans::PropertyValue(
1461                 rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("nodepath")),
1462                 0,
1463                 css::uno::makeAny(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.Office.Java/VirtualMachine"))),
1464                 css::beans::PropertyState_DIRECT_VALUE);
1465             // depth: -1 means unlimited
1466             aArguments2[1] <<= css::beans::PropertyValue(
1467                 rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("depth")),
1468                 0,
1469                 css::uno::makeAny( (sal_Int32)-1),
1470                 css::beans::PropertyState_DIRECT_VALUE);
1471 
1472             m_xJavaConfiguration
1473                 = css::uno::Reference< css::container::XContainer >(
1474                     xConfigProvider->createInstanceWithArguments(
1475                         rtl::OUString(
1476                             RTL_CONSTASCII_USTRINGPARAM(
1477                              "com.sun.star.configuration.ConfigurationAccess")),
1478                         aArguments2),
1479                     css::uno::UNO_QUERY);
1480 
1481             if (m_xJavaConfiguration.is())
1482                 m_xJavaConfiguration->addContainerListener(this);
1483         }
1484     }catch( css::uno::Exception & e)
1485     {
1486 #if OSL_DEBUG_LEVEL > 1
1487         rtl::OString message = rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US);
1488         OSL_TRACE("javavm.cxx: could not set up listener for Configuration because of >%s<", message.getStr());
1489 #else
1490         (void) e; // unused
1491 #endif
1492     }
1493 }
1494 
1495 // param true: all Inet setting are set as Java Properties on a live VM.
1496 // false: the Java net properties are set to empty value.
1497 void JavaVirtualMachine::setINetSettingsInVM(bool set_reset)
1498 {
1499     osl::MutexGuard aGuard(*this);
1500     try
1501     {
1502         if (m_xUnoVirtualMachine.is())
1503         {
1504             jvmaccess::VirtualMachine::AttachGuard aAttachGuard(
1505                 m_xUnoVirtualMachine->getVirtualMachine());
1506             JNIEnv * pJNIEnv = aAttachGuard.getEnvironment();
1507 
1508             // The Java Properties
1509             rtl::OUString sFtpProxyHost(RTL_CONSTASCII_USTRINGPARAM("ftp.proxyHost") );
1510             rtl::OUString sFtpProxyPort(RTL_CONSTASCII_USTRINGPARAM("ftp.proxyPort") );
1511             rtl::OUString sFtpNonProxyHosts (RTL_CONSTASCII_USTRINGPARAM("ftp.nonProxyHosts"));
1512             rtl::OUString sHttpProxyHost(RTL_CONSTASCII_USTRINGPARAM("http.proxyHost") );
1513             rtl::OUString sHttpProxyPort(RTL_CONSTASCII_USTRINGPARAM("http.proxyPort") );
1514             rtl::OUString sHttpNonProxyHosts(RTL_CONSTASCII_USTRINGPARAM("http.nonProxyHosts"));
1515 
1516             // creat Java Properties as JNI strings
1517             jstring jsFtpProxyHost= pJNIEnv->NewString( sFtpProxyHost.getStr(), sFtpProxyHost.getLength());
1518             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1519             jstring jsFtpProxyPort= pJNIEnv->NewString( sFtpProxyPort.getStr(), sFtpProxyPort.getLength());
1520             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1521             jstring jsFtpNonProxyHosts= pJNIEnv->NewString( sFtpNonProxyHosts.getStr(), sFtpNonProxyHosts.getLength());
1522             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1523             jstring jsHttpProxyHost= pJNIEnv->NewString( sHttpProxyHost.getStr(), sHttpProxyHost.getLength());
1524             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1525             jstring jsHttpProxyPort= pJNIEnv->NewString( sHttpProxyPort.getStr(), sHttpProxyPort.getLength());
1526             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1527             jstring jsHttpNonProxyHosts= pJNIEnv->NewString( sHttpNonProxyHosts.getStr(), sHttpNonProxyHosts.getLength());
1528             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1529 
1530             // prepare java.lang.System.setProperty
1531             jclass jcSystem= pJNIEnv->FindClass("java/lang/System");
1532             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:FindClass java/lang/System")), 0);
1533             jmethodID jmSetProps= pJNIEnv->GetStaticMethodID( jcSystem, "setProperty","(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
1534             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:GetStaticMethodID java.lang.System.setProperty")), 0);
1535 
1536             // call java.lang.System.getProperties
1537             jmethodID jmGetProps= pJNIEnv->GetStaticMethodID( jcSystem, "getProperties","()Ljava/util/Properties;");
1538             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:GetStaticMethodID java.lang.System.getProperties")), 0);
1539             jobject joProperties= pJNIEnv->CallStaticObjectMethod( jcSystem, jmGetProps);
1540             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:CallStaticObjectMethod java.lang.System.getProperties")), 0);
1541             // prepare java.util.Properties.remove
1542             jclass jcProperties= pJNIEnv->FindClass("java/util/Properties");
1543             if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:FindClass java/util/Properties")), 0);
1544 
1545             if (set_reset)
1546             {
1547                 // Set all network properties with the VM
1548                 JVM jvm;
1549                 getINetPropsFromConfig( &jvm, m_xContext->getServiceManager(), m_xContext);
1550                 const ::std::vector< rtl::OUString> & Props = jvm.getProperties();
1551                 typedef ::std::vector< rtl::OUString >::const_iterator C_IT;
1552 
1553                 for( C_IT i= Props.begin(); i != Props.end(); i++)
1554                 {
1555                     rtl::OUString prop= *i;
1556                     sal_Int32 index= prop.indexOf( (sal_Unicode)'=');
1557                     rtl::OUString propName= prop.copy( 0, index);
1558                     rtl::OUString propValue= prop.copy( index + 1);
1559 
1560                     if( propName.equals( sFtpProxyHost))
1561                     {
1562                         jstring jsVal= pJNIEnv->NewString( propValue.getStr(), propValue.getLength());
1563                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1564                         pJNIEnv->CallStaticObjectMethod( jcSystem, jmSetProps, jsFtpProxyHost, jsVal);
1565                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:CallStaticObjectMethod java.lang.System.setProperty")), 0);
1566                     }
1567                     else if( propName.equals( sFtpProxyPort))
1568                     {
1569                         jstring jsVal= pJNIEnv->NewString( propValue.getStr(), propValue.getLength());
1570                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1571                         pJNIEnv->CallStaticObjectMethod( jcSystem, jmSetProps, jsFtpProxyPort, jsVal);
1572                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:CallStaticObjectMethod java.lang.System.setProperty")), 0);
1573                     }
1574                     else if( propName.equals( sFtpNonProxyHosts))
1575                     {
1576                         jstring jsVal= pJNIEnv->NewString( propValue.getStr(), propValue.getLength());
1577                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1578                         pJNIEnv->CallStaticObjectMethod( jcSystem, jmSetProps, jsFtpNonProxyHosts, jsVal);
1579                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:CallStaticObjectMethod java.lang.System.setProperty")), 0);
1580                     }
1581                     else if( propName.equals( sHttpProxyHost))
1582                     {
1583                         jstring jsVal= pJNIEnv->NewString( propValue.getStr(), propValue.getLength());
1584                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1585                         pJNIEnv->CallStaticObjectMethod( jcSystem, jmSetProps, jsHttpProxyHost, jsVal);
1586                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:CallStaticObjectMethod java.lang.System.setProperty")), 0);
1587                     }
1588                     else if( propName.equals( sHttpProxyPort))
1589                     {
1590                         jstring jsVal= pJNIEnv->NewString( propValue.getStr(), propValue.getLength());
1591                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1592                         pJNIEnv->CallStaticObjectMethod( jcSystem, jmSetProps, jsHttpProxyPort, jsVal);
1593                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:CallStaticObjectMethod java.lang.System.setProperty")), 0);
1594                     }
1595                     else if( propName.equals( sHttpNonProxyHosts))
1596                     {
1597                         jstring jsVal= pJNIEnv->NewString( propValue.getStr(), propValue.getLength());
1598                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:NewString")), 0);
1599                         pJNIEnv->CallStaticObjectMethod( jcSystem, jmSetProps, jsHttpNonProxyHosts, jsVal);
1600                         if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:CallStaticObjectMethod java.lang.System.setProperty")), 0);
1601                     }
1602                 }
1603             }
1604             else
1605             {
1606                 // call java.util.Properties.remove
1607                 jmethodID jmRemove= pJNIEnv->GetMethodID( jcProperties, "remove", "(Ljava/lang/Object;)Ljava/lang/Object;");
1608                 if(pJNIEnv->ExceptionOccurred()) throw css::uno::RuntimeException(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("JNI:GetMethodID java.util.Property.remove")), 0);
1609                 pJNIEnv->CallObjectMethod( joProperties, jmRemove, jsFtpProxyHost);
1610                 pJNIEnv->CallObjectMethod( joProperties, jmRemove, jsFtpProxyPort);
1611                 pJNIEnv->CallObjectMethod( joProperties, jmRemove, jsFtpNonProxyHosts);
1612                 pJNIEnv->CallObjectMethod( joProperties, jmRemove, jsHttpProxyHost);
1613                 pJNIEnv->CallObjectMethod( joProperties, jmRemove, jsHttpProxyPort);
1614                 pJNIEnv->CallObjectMethod( joProperties, jmRemove, jsHttpNonProxyHosts);
1615             }
1616         }
1617     }
1618     catch (css::uno::RuntimeException &)
1619     {
1620         OSL_ENSURE(false, "RuntimeException");
1621     }
1622     catch (jvmaccess::VirtualMachine::AttachGuard::CreationException &)
1623     {
1624         OSL_ENSURE(false,
1625                    "jvmaccess::VirtualMachine::AttachGuard::CreationException");
1626     }
1627 }
1628 
1629 void JavaVirtualMachine::setUpUnoVirtualMachine(JNIEnv * environment) {
1630     css::uno::Reference< css::util::XMacroExpander > exp;
1631     if (!(m_xContext->getValueByName(
1632               rtl::OUString(
1633                   RTL_CONSTASCII_USTRINGPARAM(
1634                       "/singletons/com.sun.star.util.theMacroExpander")))
1635           >>= exp)
1636         || !exp.is())
1637     {
1638         throw css::uno::RuntimeException(
1639             rtl::OUString(
1640                 RTL_CONSTASCII_USTRINGPARAM(
1641                     "component context fails to supply singleton"
1642                     " com.sun.star.util.theMacroExpander of type"
1643                     " com.sun.star.util.XMacroExpander")),
1644             m_xContext);
1645     }
1646     rtl::OUString baseUrl;
1647     try {
1648         baseUrl = exp->expandMacros(
1649             rtl::OUString(
1650                 RTL_CONSTASCII_USTRINGPARAM("$URE_INTERNAL_JAVA_DIR/")));
1651     } catch (css::lang::IllegalArgumentException &) {
1652         throw css::uno::RuntimeException(
1653             rtl::OUString(
1654                 RTL_CONSTASCII_USTRINGPARAM(
1655                     "com::sun::star::lang::IllegalArgumentException")),
1656             static_cast< cppu::OWeakObject * >(this));
1657     }
1658     rtl::OUString classPath;
1659     try {
1660         classPath = exp->expandMacros(
1661             rtl::OUString(
1662                 RTL_CONSTASCII_USTRINGPARAM("$URE_INTERNAL_JAVA_CLASSPATH")));
1663     } catch (css::lang::IllegalArgumentException &) {}
1664     jclass class_URLClassLoader = environment->FindClass(
1665         "java/net/URLClassLoader");
1666     if (class_URLClassLoader == 0) {
1667         handleJniException(environment);
1668     }
1669     jmethodID ctor_URLClassLoader = environment->GetMethodID(
1670         class_URLClassLoader, "<init>", "([Ljava/net/URL;)V");
1671     if (ctor_URLClassLoader == 0) {
1672         handleJniException(environment);
1673     }
1674     jclass class_URL = environment->FindClass("java/net/URL");
1675     if (class_URL == 0) {
1676         handleJniException(environment);
1677     }
1678     jmethodID ctor_URL_1 = environment->GetMethodID(
1679         class_URL, "<init>", "(Ljava/lang/String;)V");
1680     if (ctor_URL_1 == 0) {
1681         handleJniException(environment);
1682     }
1683     jvalue args[3];
1684     args[0].l = environment->NewString(
1685         static_cast< jchar const * >(baseUrl.getStr()),
1686         static_cast< jsize >(baseUrl.getLength()));
1687     if (args[0].l == 0) {
1688         handleJniException(environment);
1689     }
1690     jobject base = environment->NewObjectA(class_URL, ctor_URL_1, args);
1691     if (base == 0) {
1692         handleJniException(environment);
1693     }
1694     jmethodID ctor_URL_2 = environment->GetMethodID(
1695         class_URL, "<init>", "(Ljava/net/URL;Ljava/lang/String;)V");
1696     if (ctor_URL_2 == 0) {
1697         handleJniException(environment);
1698     }
1699     jobjectArray classpath = jvmaccess::ClassPath::translateToUrls(
1700         m_xContext, environment, classPath);
1701     if (classpath == 0) {
1702         handleJniException(environment);
1703     }
1704     args[0].l = base;
1705     args[1].l = environment->NewStringUTF("unoloader.jar");
1706     if (args[1].l == 0) {
1707         handleJniException(environment);
1708     }
1709     args[0].l = environment->NewObjectA(class_URL, ctor_URL_2, args);
1710     if (args[0].l == 0) {
1711         handleJniException(environment);
1712     }
1713     args[0].l = environment->NewObjectArray(1, class_URL, args[0].l);
1714     if (args[0].l == 0) {
1715         handleJniException(environment);
1716     }
1717     jobject cl1 = environment->NewObjectA(
1718         class_URLClassLoader, ctor_URLClassLoader, args);
1719     if (cl1 == 0) {
1720         handleJniException(environment);
1721     }
1722     jmethodID method_loadClass = environment->GetMethodID(
1723         class_URLClassLoader, "loadClass",
1724         "(Ljava/lang/String;)Ljava/lang/Class;");
1725     if (method_loadClass == 0) {
1726         handleJniException(environment);
1727     }
1728     args[0].l = environment->NewStringUTF(
1729         "com.sun.star.lib.unoloader.UnoClassLoader");
1730     if (args[0].l == 0) {
1731         handleJniException(environment);
1732     }
1733     jclass class_UnoClassLoader = static_cast< jclass >(
1734         environment->CallObjectMethodA(cl1, method_loadClass, args));
1735     if (class_UnoClassLoader == 0) {
1736         handleJniException(environment);
1737     }
1738     jmethodID ctor_UnoClassLoader = environment->GetMethodID(
1739         class_UnoClassLoader, "<init>",
1740         "(Ljava/net/URL;[Ljava/net/URL;Ljava/lang/ClassLoader;)V");
1741     if (ctor_UnoClassLoader == 0) {
1742         handleJniException(environment);
1743     }
1744     args[0].l = base;
1745     args[1].l = classpath;
1746     args[2].l = cl1;
1747     jobject cl2 = environment->NewObjectA(
1748         class_UnoClassLoader, ctor_UnoClassLoader, args);
1749     if (cl2 == 0) {
1750         handleJniException(environment);
1751     }
1752     try {
1753         m_xUnoVirtualMachine = new jvmaccess::UnoVirtualMachine(
1754             m_xVirtualMachine, cl2);
1755     } catch (jvmaccess::UnoVirtualMachine::CreationException &) {
1756         throw css::uno::RuntimeException(
1757             rtl::OUString(
1758                 RTL_CONSTASCII_USTRINGPARAM(
1759                     "jvmaccess::UnoVirtualMachine::CreationException")),
1760             static_cast< cppu::OWeakObject * >(this));
1761     }
1762 }
1763 
1764 void JavaVirtualMachine::handleJniException(JNIEnv * environment) {
1765     environment->ExceptionClear();
1766     throw css::uno::RuntimeException(
1767         rtl::OUString(
1768             RTL_CONSTASCII_USTRINGPARAM("JNI exception occurred")),
1769         static_cast< cppu::OWeakObject * >(this));
1770 }
1771