From fcce9ba53bcc550b266af719d7bb9c6f960ec725 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Romain=20D=C3=A9nari=C3=A9?= Date: Fri, 3 May 2024 12:43:52 +0200 Subject: [PATCH 1/2] fix: Update to JDK21 - EXO-71474 - meeds-io/MIPs#91 Remove SecurityManager from Kernel as it is deprecated for removal in jdk21 Remove also classes - SecurityHelper - PrivilegedSystemHelper - PrivilegedFileHelper - SecureList - SecureSet - SecureCollections These classes are here only to use securityManager, and as it is removed, it is no more necessary Resolves Meeds-io/MIPs#91 --- .../commons/test/TestSecurityManager.java | 203 ----- exo.kernel.commons/pom.xml | 6 - .../org/exoplatform/commons/Environment.java | 16 +- .../reflect/AnnotationIntrospector.java | 14 +- .../commons/utils/ExceptionUtil.java | 2 +- .../org/exoplatform/commons/utils/IOUtil.java | 4 +- .../commons/utils/MimeTypeResolver.java | 84 +- .../commons/utils/PrivilegedFileHelper.java | 779 ------------------ .../commons/utils/PrivilegedSystemHelper.java | 142 ---- .../commons/utils/PropertyManager.java | 12 +- .../commons/utils/SecurityHelper.java | 334 -------- .../utils/secure/SecureCollections.java | 68 -- .../commons/utils/secure/SecureList.java | 286 ------- .../commons/utils/secure/SecureSet.java | 191 ----- .../services/log/impl/SLF4JExoLogFactory.java | 11 +- .../log/impl/SimpleExoLogConfigurator.java | 3 +- .../secure/AbstractSecureCollectionsTest.java | 67 -- .../commons/utils/secure/TestSecureList.java | 206 ----- .../commons/utils/secure/TestSecureSet.java | 225 ----- exo.kernel.component.cache/pom.xml | 2 +- exo.kernel.component.command/pom.xml | 5 +- .../services/command/impl/CommandService.java | 50 +- .../impl/CommonsXMLConfigurationPlugin.java | 20 +- exo.kernel.component.common/pom.xml | 2 +- .../services/compress/CompressData.java | 9 +- .../impl/IDGeneratorServiceImpl.java | 27 +- .../jdbc/impl/CloseableDataSource.java | 3 +- .../services/listener/ListenerService.java | 21 +- .../listener/ListenerThreadFactory.java | 3 +- .../services/mail/impl/MailServiceImpl.java | 21 +- .../services/naming/InitialContextBinder.java | 10 +- .../naming/InitialContextInitializer.java | 17 +- .../services/net/impl/NetServiceImpl.java | 25 +- .../services/rpc/impl/AbstractRPCService.java | 103 +-- .../scheduler/impl/QuartzSheduler.java | 47 +- .../impl/AbstractTransactionService.java | 19 +- .../services/net/test/TestNetService.java | 3 - .../test/TestPersistedQuartzScheduler.java | 3 +- .../pom.xml | 2 +- .../impl/infinispan/AbstractExoCache.java | 149 ++-- .../impl/infinispan/ExoCacheFactoryImpl.java | 215 ++--- .../distributed/DistributedExoCache.java | 153 +--- .../ispn/DistributedCacheManager.java | 60 +- exo.kernel.container.mt/pom.xml | 3 - .../container/ConcurrentContainerMT.java | 183 ++-- .../container/jmx/MX4JComponentAdapterMT.java | 11 +- exo.kernel.container/pom.xml | 7 - .../container/ConcurrentContainer.java | 8 - .../exoplatform/container/ExoContainer.java | 175 ++-- .../container/ExoContainerContext.java | 14 - .../container/PortalContainer.java | 48 +- .../exoplatform/container/RootContainer.java | 132 +-- .../container/StandaloneContainer.java | 86 +- .../container/UnifiedClassLoader.java | 10 +- .../org/exoplatform/container/ar/Archive.java | 10 +- .../container/component/ThreadContext.java | 6 - .../component/ThreadContextHandler.java | 27 +- .../configuration/ConfigurationManager.java | 3 +- .../ConfigurationManagerImpl.java | 43 +- .../ConfigurationUnmarshaller.java | 160 ++-- .../configuration/EntityResolverImpl.java | 10 +- .../definition/PortalContainerConfig.java | 16 +- .../container/jmx/MX4JComponentAdapter.java | 142 ++-- .../management/ManagementContextImpl.java | 36 +- .../container/monitor/jvm/J2EEServerInfo.java | 336 ++++---- .../monitor/jvm/JVMRuntimeInfoImpl.java | 135 +-- .../container/util/ContainerUtil.java | 72 +- .../util/TemplateConfigurationHelper.java | 4 +- .../container/web/PortalContainerCreator.java | 23 +- .../container/xml/Deserializer.java | 3 +- .../jmx/impl/JMXManagementProvider.java | 60 +- .../test/MockConfigurationManagerImpl.java | 15 +- .../org/exoplatform/xml/object/XMLObject.java | 40 +- .../container/ContainerBuilder.java | 16 +- 74 files changed, 853 insertions(+), 4603 deletions(-) delete mode 100644 exo.kernel.commons.test/src/main/java/org/exoplatform/commons/test/TestSecurityManager.java delete mode 100644 exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/PrivilegedFileHelper.java delete mode 100644 exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/PrivilegedSystemHelper.java delete mode 100644 exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/SecurityHelper.java delete mode 100644 exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/secure/SecureCollections.java delete mode 100644 exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/secure/SecureList.java delete mode 100644 exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/secure/SecureSet.java delete mode 100644 exo.kernel.commons/src/test/java/org/exoplatform/commons/utils/secure/AbstractSecureCollectionsTest.java delete mode 100644 exo.kernel.commons/src/test/java/org/exoplatform/commons/utils/secure/TestSecureList.java delete mode 100644 exo.kernel.commons/src/test/java/org/exoplatform/commons/utils/secure/TestSecureSet.java diff --git a/exo.kernel.commons.test/src/main/java/org/exoplatform/commons/test/TestSecurityManager.java b/exo.kernel.commons.test/src/main/java/org/exoplatform/commons/test/TestSecurityManager.java deleted file mode 100644 index bb7616b6d..000000000 --- a/exo.kernel.commons.test/src/main/java/org/exoplatform/commons/test/TestSecurityManager.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.commons.test; - -import java.io.IOException; -import java.io.InputStream; -import java.security.Permission; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -/** - * You can exclude methods by adding the file tsm-excludes.properties into the classpath. The expected format is: - * - * ${fqn-of-the-class}.${method-name}=${called-method-name}(,${called-method-name})* - * - * - * @author Anatoliy Bazko - * @version $Id: TestSecurityManager.java 2636 2010-06-16 14:18:23Z tolusha $ - * - */ -public class TestSecurityManager extends SecurityManager -{ - /** - * Map of methods to exclude and for each method we define a list of method called to ignore - */ - private volatile Map> excludes; - - /** - * Indicates whether or not we are currently loading the file tsm-excludes.properties - */ - private final ThreadLocal loading = new ThreadLocal(); - - /** - * {@inheritDoc} - */ - @Override - public void checkPermission(Permission perm) - { - if (loading.get() != null) - { - //skip permission checking - return; - } - try - { - super.checkPermission(perm); - } - catch (SecurityException se) - { - Throwable e = se; - - boolean srcCode = false; - boolean testCode = false; - - // We need to lazy load the file 'tsm-excludes.properties' to prevent exception of type - // com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException: - // Could not load the propery file 'output_xml.properties' for output method 'xml' (check CLASSPATH) - Map> excludes = getExcludes(); - - while (e != null) - { - StackTraceElement[] traceElements = e.getStackTrace(); - for (int i = 0; i < traceElements.length; i++) - { - String className = traceElements[i].getClassName(); - String fileName = traceElements[i].getFileName(); - String methodName = traceElements[i].getMethodName(); - if (className.contains("$MockitoMock$") || (i - 1 >= 0 && excludes.containsKey(className + "." + methodName) - && excludes.get(className + "." + methodName).contains(traceElements[i - 1].getMethodName()))) - { - // the called method is excluded thus we ignore the exception - return; - } - if (className.startsWith("org.exoplatform")) - { - // known tests classes - if (fileName != null && (fileName.startsWith("Test") || fileName.endsWith("Test.java") - || fileName.endsWith("TestBase.java") || fileName.endsWith("TestCase.java") - || fileName.equals("Probe.java") || fileName.equals("ExportBase.java") - || fileName.equals("AbstractTestContainer.java") || fileName.equals("ContainerBuilder.java") - || fileName.equals("WorkspaceStorageCacheBaseCase.java") - || fileName.equals("ExoRepositoryStub.java") || fileName.equals("CloseableDataSource.java"))) - { - testCode = true; - } - else - { - srcCode = true; - } - } - else if (className.startsWith("org.apache.jackrabbit.test")) - { - if (fileName.endsWith("Test.java") || fileName.equals("JCRTestResult.java") - || fileName.equals("RepositoryHelper.java") || fileName.equals("RepositoryStub.java")) - { - testCode = true; - } - } - } - - e = e.getCause(); - } - - // hide Exception if only test code exists - if (!srcCode && testCode) - { - return; - } - throw se; - } - } - - private Map> getExcludes() - { - if (excludes == null) - { - synchronized (this) - { - if (excludes == null) - { - try - { - loading.set(Boolean.TRUE); - excludes = loadExcludes(); - } - finally - { - loading.remove(); - } - } - } - } - return excludes; - } - - private Map> loadExcludes() - { - InputStream is = null; - try - { - is = Thread.currentThread().getContextClassLoader().getResourceAsStream("tsm-excludes.properties"); - } - catch (Exception e) - { - return Collections.emptyMap(); - } - - if (is != null) - { - try - { - System.out.println("A file 'tsm-excludes.properties' has been found"); //NOSONAR - Properties p = new Properties(); - p.load(is); - Map> excludes = new HashMap>(); - for (Object key : p.keySet()) - { - String[] values = p.getProperty((String)key).split(","); - excludes.put((String)key, new HashSet(Arrays.asList(values))); - } - return excludes; - } - catch (Exception e) - { - e.printStackTrace(); //NOSONAR - } - finally - { - try - { - is.close(); - } - catch (IOException e) - { - e.printStackTrace(); //NOSONAR - } - } - } - - return Collections.emptyMap(); - } -} diff --git a/exo.kernel.commons/pom.xml b/exo.kernel.commons/pom.xml index de7470bc9..5a737d4a0 100644 --- a/exo.kernel.commons/pom.xml +++ b/exo.kernel.commons/pom.xml @@ -85,12 +85,6 @@ - - maven-surefire-plugin - - @{argLine} -Djava.security.manager=org.exoplatform.commons.test.TestSecurityManager -Djava.security.policy=${project.build.directory}/test-classes/test.policy - - maven-antrun-plugin diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/commons/Environment.java b/exo.kernel.commons/src/main/java/org/exoplatform/commons/Environment.java index a942810f4..83687d387 100644 --- a/exo.kernel.commons/src/main/java/org/exoplatform/commons/Environment.java +++ b/exo.kernel.commons/src/main/java/org/exoplatform/commons/Environment.java @@ -18,8 +18,6 @@ */ package org.exoplatform.commons; -import org.exoplatform.commons.utils.PrivilegedSystemHelper; - public class Environment { @@ -43,12 +41,12 @@ public class Environment private Environment() { - String catalinaHome = PrivilegedSystemHelper.getProperty("catalina.home"); - String jbossHome = PrivilegedSystemHelper.getProperty("jboss.home.dir"); - String jettyHome = PrivilegedSystemHelper.getProperty("jetty.home"); - String websphereHome = PrivilegedSystemHelper.getProperty("was.install.root"); - String weblogicHome = PrivilegedSystemHelper.getProperty("weblogic.Name"); - String standAlone = PrivilegedSystemHelper.getProperty("maven.exoplatform.dir"); + String catalinaHome = System.getProperty("catalina.home"); + String jbossHome = System.getProperty("jboss.home.dir"); + String jettyHome = System.getProperty("jetty.home"); + String websphereHome = System.getProperty("was.install.root"); + String weblogicHome = System.getProperty("weblogic.Name"); + String standAlone = System.getProperty("maven.exoplatform.dir"); if (jbossHome != null) { platform_ = JBOSS_PLATFORM; @@ -95,4 +93,4 @@ static public Environment getInstance() } return singleton_; } -} \ No newline at end of file +} diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/commons/reflect/AnnotationIntrospector.java b/exo.kernel.commons/src/main/java/org/exoplatform/commons/reflect/AnnotationIntrospector.java index 3ccf604cc..5195c325a 100644 --- a/exo.kernel.commons/src/main/java/org/exoplatform/commons/reflect/AnnotationIntrospector.java +++ b/exo.kernel.commons/src/main/java/org/exoplatform/commons/reflect/AnnotationIntrospector.java @@ -18,11 +18,8 @@ */ package org.exoplatform.commons.reflect; -import org.exoplatform.commons.utils.SecurityHelper; - import java.lang.annotation.Annotation; import java.lang.reflect.Method; -import java.security.PrivilegedAction; import java.util.HashMap; import java.util.Map; @@ -102,16 +99,7 @@ public static Map resolveMethodAnnotations(fin // Map methods = new HashMap(); - // - PrivilegedAction action = new PrivilegedAction() - { - public Method[] run() - { - return clazz.getDeclaredMethods(); - } - }; - - for (Method method : SecurityHelper.doPrivilegedAction(action)) + for (Method method : clazz.getDeclaredMethods()) { A annotation = method.getAnnotation(methodAnnotation); if (annotation != null) diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/ExceptionUtil.java b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/ExceptionUtil.java index 193f39664..a53be729a 100644 --- a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/ExceptionUtil.java +++ b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/ExceptionUtil.java @@ -26,7 +26,7 @@ */ public class ExceptionUtil { - private static String LINE_SEPARATOR = PrivilegedSystemHelper.getProperty("line.separator"); + private static String LINE_SEPARATOR = System.getProperty("line.separator"); static public String getExoStackTrace(Throwable t) { diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/IOUtil.java b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/IOUtil.java index 1d659a380..61e1a80c2 100644 --- a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/IOUtil.java +++ b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/IOUtil.java @@ -72,7 +72,7 @@ static public String getFileContentAsString(File file, String charset) throws IO { throw new IllegalArgumentException("No null file accepted"); } - FileInputStream is = PrivilegedFileHelper.fileInputStream(file); + FileInputStream is = new FileInputStream(file); return new String(getStreamContentAsBytes(is), charset); } @@ -136,7 +136,7 @@ static public byte[] getFileContentAsBytes(String fileName) throws IOException, { throw new IllegalArgumentException("No null file name accepted"); } - FileInputStream is = PrivilegedFileHelper.fileInputStream(fileName); + FileInputStream is = new FileInputStream(fileName); return getStreamContentAsBytes(is); } diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/MimeTypeResolver.java b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/MimeTypeResolver.java index 529506670..7ddae1003 100644 --- a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/MimeTypeResolver.java +++ b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/MimeTypeResolver.java @@ -24,8 +24,6 @@ import org.exoplatform.services.log.Log; import java.io.*; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -44,23 +42,16 @@ public class MimeTypeResolver static { - SecurityHelper.doPrivilegedAction(new PrivilegedAction() + String mimeCacheFile = PropertyManager.getProperty(MIME_CACHE); + if (mimeCacheFile != null && !mimeCacheFile.isEmpty()) { - public Void run() - { - String mimeCacheFile = PropertyManager.getProperty(MIME_CACHE); - if (mimeCacheFile != null && !mimeCacheFile.isEmpty()) - { - new eu.medsea.mimeutil.detector.OpendesktopMimeDetector(mimeCacheFile); - MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.OpendesktopMimeDetector"); - } - else - { - MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector"); - } - return null; - } - }); + new eu.medsea.mimeutil.detector.OpendesktopMimeDetector(mimeCacheFile); + MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.OpendesktopMimeDetector"); + } + else + { + MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector"); + } } private Map> mimeTypes = new HashMap>(); @@ -73,47 +64,32 @@ public Void run() public MimeTypeResolver() { + Scanner scanner = null; + String mimeTypeProperties = System.getProperty(MIMETYPES_FILE_PATH); + if (mimeTypeProperties != null) { + File mimeTypesFile = new File(mimeTypeProperties); + try { + InputStream stream = new FileInputStream(mimeTypesFile); + scanner = new Scanner(stream, "ISO-8859-1"); + } catch (FileNotFoundException fileNotFoundException) { + // Failed to load the file, we skip to the next try + LOG.debug("File Not found {}", mimeTypeProperties, fileNotFoundException); + } + } + if (scanner == null) + { + scanner = new Scanner(getClass().getResourceAsStream("mimetypes.properties"), "ISO-8859-1"); + } try { - SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction() + while (scanner.hasNextLine()) { - public Void run() throws Exception - { - Scanner scanner = null; - String mimeTypeProperties = System.getProperty(MIMETYPES_FILE_PATH); - if (mimeTypeProperties != null) { - File mimeTypesFile = new File(mimeTypeProperties); - try { - InputStream stream = new FileInputStream(mimeTypesFile); - scanner = new Scanner(stream, "ISO-8859-1"); - } catch (FileNotFoundException fileNotFoundException) { - // Failed to load the file, we skip to the next try - LOG.debug("File Not found {}", mimeTypeProperties, fileNotFoundException); - } - } - if (scanner == null) - { - scanner = new Scanner(getClass().getResourceAsStream("mimetypes.properties"), "ISO-8859-1"); - } - try - { - while (scanner.hasNextLine()) - { - processLine(scanner.nextLine()); - } - } - finally - { - scanner.close(); - } - - return null; - } - }); + processLine(scanner.nextLine()); + } } - catch (IOException e) + finally { - throw new InternalError("Unable to load mimetypes: " + e.toString()); + scanner.close(); } } diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/PrivilegedFileHelper.java b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/PrivilegedFileHelper.java deleted file mode 100644 index f7a787c0d..000000000 --- a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/PrivilegedFileHelper.java +++ /dev/null @@ -1,779 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.commons.utils; - -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; -import java.io.RandomAccessFile; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; - -/** - * @author Anatoliy Bazko - * @version $Id: SecurityFileHelper.java 111 2010-11-11 11:11:11Z tolusha $ - * - * Class helper need for perform privileged file operations. - */ -public class PrivilegedFileHelper -{ - - /** - * getResourceAsStream in privileged mode. - */ - public static InputStream getResourceAsStream(final String resource) throws FileNotFoundException - { - PrivilegedAction action = new PrivilegedAction() - { - public InputStream run() - { - return PrivilegedFileHelper.class.getResourceAsStream(resource); - } - }; - - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Create FileOutputStream in privileged mode. - * - * @param file - * @return - * @throws FileNotFoundException - */ - public static FileOutputStream fileOutputStream(final File file) throws FileNotFoundException - { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() - { - public FileOutputStream run() throws Exception - { - return new FileOutputStream(file); - } - }; - try - { - return SecurityHelper.doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof FileNotFoundException) - { - throw (FileNotFoundException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Create ZipOutputStream in privileged mode. - * - * @param file - * @return - * @throws FileNotFoundException - */ - public static ZipOutputStream zipOutputStream(final File file) throws FileNotFoundException - { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() - { - public ZipOutputStream run() throws Exception - { - return new ZipOutputStream(new FileOutputStream(file)); - } - }; - try - { - return SecurityHelper.doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof FileNotFoundException) - { - throw (FileNotFoundException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Create FileOutputStream in privileged mode. - * - * @param name - * @return - * @throws FileNotFoundException - */ - public static FileOutputStream fileOutputStream(final String name) throws FileNotFoundException - { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() - { - public FileOutputStream run() throws Exception - { - return new FileOutputStream(name); - } - }; - try - { - return SecurityHelper.doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof FileNotFoundException) - { - throw (FileNotFoundException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Create FileOutputStream in privileged mode. - * - * @param file - * @param append - * @return - * @throws FileNotFoundException - */ - public static FileOutputStream fileOutputStream(final File file, final boolean append) throws FileNotFoundException - { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() - { - public FileOutputStream run() throws Exception - { - return new FileOutputStream(file, append); - } - }; - try - { - return SecurityHelper.doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof FileNotFoundException) - { - throw (FileNotFoundException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Create FileInputStream in privileged mode. - * - * @param file - * @return - * @throws FileNotFoundException - */ - public static FileInputStream fileInputStream(final File file) throws FileNotFoundException - { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() - { - public FileInputStream run() throws Exception - { - return new FileInputStream(file); - } - }; - try - { - return SecurityHelper.doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof FileNotFoundException) - { - throw (FileNotFoundException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Create FileInputStream in privileged mode. - * - * @param file - * @return - * @throws FileNotFoundException - */ - public static ZipInputStream zipInputStream(final File file) throws FileNotFoundException - { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() - { - public ZipInputStream run() throws Exception - { - return new ZipInputStream(new FileInputStream(file)); - } - }; - try - { - return SecurityHelper.doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof FileNotFoundException) - { - throw (FileNotFoundException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Create FileInputStream in privileged mode. - * - * @param name - * @return - * @throws FileNotFoundException - */ - public static FileInputStream fileInputStream(final String name) throws FileNotFoundException - { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() - { - public FileInputStream run() throws Exception - { - return new FileInputStream(name); - } - }; - try - { - return SecurityHelper.doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof FileNotFoundException) - { - throw (FileNotFoundException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Create new file. - * - * @param file - * @return - * @throws IOException - */ - public static boolean createNewFile(final File file) throws IOException - { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() - { - public Boolean run() throws Exception - { - return file.createNewFile(); - } - }; - try - { - return SecurityHelper.doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - - if (cause instanceof IOException) - { - throw (IOException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Create temporary file in privileged mode. - * - * @param prefix - * @param suffix - * @param directory - * @return - * @throws IllegalArgumentException - * @throws IOException - */ - public static File createTempFile(final String prefix, final String suffix, final File directory) - throws IllegalArgumentException, IOException - { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() - { - public File run() throws Exception - { - return File.createTempFile(prefix, suffix, directory); - } - }; - try - { - return SecurityHelper.doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof IllegalArgumentException) - { - throw (IllegalArgumentException)cause; - } - else if (cause instanceof IOException) - { - throw (IOException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Create teamporary file in privileged mode. - * - * - * @param prefix - * @param suffix - * @return - * @throws IllegalArgumentException - * @throws IOException - */ - public static File createTempFile(final String prefix, final String suffix) throws IllegalArgumentException, - IOException - { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() - { - public File run() throws Exception - { - return File.createTempFile(prefix, suffix); - } - }; - try - { - return SecurityHelper.doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof IllegalArgumentException) - { - throw (IllegalArgumentException)cause; - } - else if (cause instanceof IOException) - { - throw (IOException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Create RandomAccessFile in privileged mode. - * - * @param file - * @param mode - * @return - * @throws IllegalArgumentException - * @throws IOException - */ - public static RandomAccessFile randomAccessFile(final File file, final String mode) throws IllegalArgumentException, - IOException - { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() - { - public RandomAccessFile run() throws Exception - { - return new RandomAccessFile(file, mode); - } - }; - try - { - return SecurityHelper.doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof IllegalArgumentException) - { - throw (IllegalArgumentException)cause; - } - else if (cause instanceof FileNotFoundException) - { - throw (FileNotFoundException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Get file length in privileged mode. - * - * @param file - * @return - */ - public static long length(final File file) - { - PrivilegedAction action = new PrivilegedAction() - { - public Long run() - { - return new Long(file.length()); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Requests in privileged mode that the file or directory denoted by this abstract - * pathname be deleted when the virtual machine terminates. - * - * @param file - */ - public static void deleteOnExit(final File file) - { - PrivilegedAction action = new PrivilegedAction() - { - public Void run() - { - file.deleteOnExit(); - return null; - } - }; - SecurityHelper.doPrivilegedAction(action); - } - - /** - * Get file absolute path in privileged mode. - * - * @param file - * @return - */ - public static String getAbsolutePath(final File file) - { - PrivilegedAction action = new PrivilegedAction() - { - public String run() - { - return file.getAbsolutePath(); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Get file canonical path in privileged mode. - * - * @param file - * @return - * @throws IOException - */ - public static String getCanonicalPath(final File file) throws IOException - { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() - { - public String run() throws Exception - { - return file.getCanonicalPath(); - } - }; - try - { - return SecurityHelper.doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof IOException) - { - throw (IOException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Delete file in privileged mode. - * - * @param file - * @return - */ - public static boolean delete(final File file) - { - PrivilegedAction action = new PrivilegedAction() - { - public Boolean run() - { - return file.delete(); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Tests in privileged mode whether the file denoted by this abstract pathname is a - * directory. - * - * @param file - * @return - */ - public static boolean isDirectory(final File file) - { - PrivilegedAction action = new PrivilegedAction() - { - public Boolean run() - { - return file.isDirectory(); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Tests in privileged mode whether the file or directory denoted by this abstract pathname - * exists. - * - * @param file - * @return - */ - public static boolean exists(final File file) - { - PrivilegedAction action = new PrivilegedAction() - { - public Boolean run() - { - return file.exists(); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Creates the directory in privileged mode. - * - * @param file - * @return - */ - public static boolean mkdirs(final File file) - { - PrivilegedAction action = new PrivilegedAction() - { - public Boolean run() - { - return file.mkdirs(); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Rename File in privileged mode. - * - * @param srcFile - * @param dstfile - * @return - */ - public static boolean renameTo(final File srcFile, final File dstfile) - { - PrivilegedAction action = new PrivilegedAction() - { - public Boolean run() - { - return new Boolean(srcFile.renameTo(dstfile)); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Get file's list in privileged mode. - * - * @param file - * @return - */ - public static String[] list(final File file) - { - PrivilegedAction action = new PrivilegedAction() - { - public String[] run() - { - return file.list(); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Get file's list in privileged mode. - * - * @param file - * @return - */ - public static String[] list(final File file, final FilenameFilter filter) - { - PrivilegedAction action = new PrivilegedAction() - { - public String[] run() - { - return file.list(filter); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Get file's list in privileged mode. - * - * @param file - * @return - */ - public static File[] listFiles(final File file) - { - PrivilegedAction action = new PrivilegedAction() - { - public File[] run() - { - return file.listFiles(); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Get file's list in privileged mode. - * - * @param file - * @return - */ - public static File[] listFiles(final File file, final FilenameFilter filter) - { - PrivilegedAction action = new PrivilegedAction() - { - public File[] run() - { - return file.listFiles(filter); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Get file's list in privileged mode. - * - * @param file - * @return - */ - public static File[] listFiles(final File file, final FileFilter filter) - { - PrivilegedAction action = new PrivilegedAction() - { - public File[] run() - { - return file.listFiles(filter); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } -} diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/PrivilegedSystemHelper.java b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/PrivilegedSystemHelper.java deleted file mode 100644 index ea05a0a07..000000000 --- a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/PrivilegedSystemHelper.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.commons.utils; - -import java.io.InputStream; -import java.net.URL; -import java.security.PrivilegedAction; -import java.util.Properties; - -/** - * @author Anatoliy Bazko - * @version $Id: PrivilegedSystemHelper.java 111 2010-11-11 11:11:11Z tolusha $ - * - */ -public class PrivilegedSystemHelper -{ - - /** - * Gets system property in privileged mode. - * - * @param key - * @return - */ - public static String getProperty(final String key) - { - PrivilegedAction action = new PrivilegedAction() - { - public String run() - { - return System.getProperty(key); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Gets system properties in privileged mode. - * - * @return - */ - public static Properties getProperties() - { - PrivilegedAction action = new PrivilegedAction() - { - public Properties run() - { - return System.getProperties(); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Gets system property in privileged mode. - * - * @param key - */ - public static void setProperty(final String key, final String value) - { - PrivilegedAction action = new PrivilegedAction() - { - public Void run() - { - System.setProperty(key, value); - return null; - } - }; - SecurityHelper.doPrivilegedAction(action); - } - - /** - * Gets system property in privileged mode. - * - * @param key - * @param def - * @return - */ - public static String getProperty(final String key, final String def) - { - PrivilegedAction action = new PrivilegedAction() - { - public String run() - { - return System.getProperty(key, def); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Get resource in privileged mode. - * - * @param name - * @return - */ - public static URL getResource(final String name) - { - PrivilegedAction action = new PrivilegedAction() - { - public URL run() - { - return Thread.currentThread().getContextClassLoader().getResource(name); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - - /** - * Get resource as stream in privileged mode. - * - * @param name - * @return - */ - public static InputStream getResourceAsStream(final String name) - { - PrivilegedAction action = new PrivilegedAction() - { - public InputStream run() - { - return Thread.currentThread().getContextClassLoader().getResourceAsStream(name); - } - }; - return SecurityHelper.doPrivilegedAction(action); - } - -} diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/PropertyManager.java b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/PropertyManager.java index 7661714a0..67bf331ea 100644 --- a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/PropertyManager.java +++ b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/PropertyManager.java @@ -78,7 +78,7 @@ public static String getProperty(String propertyName) String propertyValue = cache.get(propertyName); if (propertyValue == null) { - propertyValue = PrivilegedSystemHelper.getProperty(propertyName); + propertyValue = System.getProperty(propertyName); if (propertyValue != null) { cache.put(propertyName, propertyValue); @@ -89,7 +89,7 @@ public static String getProperty(String propertyName) } else { - return PrivilegedSystemHelper.getProperty(propertyName); + return System.getProperty(propertyName); } } @@ -102,7 +102,7 @@ public static String getProperty(String propertyName) public static Properties getPropertiesByPattern(String propertyPattern) { Properties props = new Properties(); - Map map = (PrivilegedSystemHelper.getProperties().entrySet()).stream().filter(p -> p.getKey().toString().matches(propertyPattern)).collect(Collectors.toMap(p -> p.getKey().toString(), p -> p.getValue().toString())); + Map map = (System.getProperties().entrySet()).stream().filter(p -> p.getKey().toString().matches(propertyPattern)).collect(Collectors.toMap(p -> p.getKey().toString(), p -> p.getValue().toString())); map.forEach((k,v)->{ props.setProperty(k,v); }); @@ -116,7 +116,7 @@ public static Properties getPropertiesByPattern(String propertyPattern) */ public static Properties getProperties() { - return PrivilegedSystemHelper.getProperties(); + return System.getProperties(); } /** @@ -138,7 +138,7 @@ public static boolean isDevelopping() private static boolean internalIsDevelopping() { - return "true".equals(PrivilegedSystemHelper.getProperty(DEVELOPING, "false")); + return "true".equals(System.getProperty(DEVELOPING, "false")); } /** @@ -149,7 +149,7 @@ private static boolean internalIsDevelopping() */ public synchronized static void setProperty(String propertyName, String propertyValue) { - PrivilegedSystemHelper.setProperty(propertyName, propertyValue); + System.setProperty(propertyName, propertyValue); // Remove instead of put to avoid concurrent race cache.remove(propertyName); diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/SecurityHelper.java b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/SecurityHelper.java deleted file mode 100644 index d2ce10219..000000000 --- a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/SecurityHelper.java +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.commons.utils; - -import org.xml.sax.SAXException; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.security.AccessController; -import java.security.Permission; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.sql.SQLException; - -import javax.naming.NamingException; -import javax.xml.parsers.ParserConfigurationException; - -/** - * Helps running code in privileged - * - * @author Nikolay Zamosenchuk - * @version $Id: SecurityHelper.java 34360 2009-07-22 23:58:59Z nzamosenchuk $ - * - */ -public class SecurityHelper -{ - - /** - * Launches action in privileged mode. Can throw only IO exception. - * - * @param - * @param action - * @return - * @throws IOException - */ - public static E doPrivilegedIOExceptionAction(PrivilegedExceptionAction action) throws IOException - { - try - { - return doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof IOException) - { - throw (IOException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Launches action in privileged mode. Can throw only NamingException. - * - * @param - * @param action - * @return - * @throws NamingException - */ - public static E doPrivilegedNamingExceptionAction(PrivilegedExceptionAction action) throws NamingException - { - try - { - return doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof NamingException) - { - throw (NamingException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Launches action in privileged mode. Can throw only SQL exception. - * - * @param - * @param action - * @return - * @throws SQLException - */ - public static E doPrivilegedSQLExceptionAction(PrivilegedExceptionAction action) throws SQLException - { - try - { - return doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof SQLException) - { - throw (SQLException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Launches action in privileged mode. Can throw only ParserConfigurationException, SAXException. - * - * @param - * @param action - * @return - * @throws ParserConfigurationException - * @throws SAXException - */ - public static E doPrivilegedParserConfigurationOrSAXExceptionAction(PrivilegedExceptionAction action) - throws ParserConfigurationException, SAXException - { - try - { - return doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof ParserConfigurationException) - { - throw (ParserConfigurationException)cause; - } - else if (cause instanceof SAXException) - { - throw (SAXException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Launches action in privileged mode. Can throw only ParserConfigurationException. - * - * @param - * @param action - * @return - * @throws ParserConfigurationException - */ - public static E doPrivilegedParserConfigurationAction(PrivilegedExceptionAction action) - throws ParserConfigurationException - { - try - { - return doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof ParserConfigurationException) - { - throw (ParserConfigurationException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Launches action in privileged mode. Can throw only SAXException. - * - * @param - * @param action - * @return - * @throws SAXException - */ - public static E doPrivilegedSAXExceptionAction(PrivilegedExceptionAction action) throws SAXException - { - try - { - return doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof SAXException) - { - throw (SAXException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Launches action in privileged mode. Can throw only SAXException. - * - * @param - * @param action - * @return - * @throws MalformedURLException - */ - public static E doPrivilegedMalformedURLExceptionAction(PrivilegedExceptionAction action) - throws MalformedURLException - { - try - { - return doPrivilegedExceptionAction(action); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof MalformedURLException) - { - throw (MalformedURLException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - } - - /** - * Launches action in privileged mode. Can throw only runtime exceptions. - * - * @param - * @param action - * @return - */ - public static E doPrivilegedAction(PrivilegedAction action) - { - if (System.getSecurityManager() != null) - { - // A security manager has been established - return AccessController.doPrivileged(action); - } - return action.run(); - } - - /** - * Launches action in privileged mode. - * - * @param - * @param action - * @return - */ - public static E doPrivilegedExceptionAction(PrivilegedExceptionAction action) - throws PrivilegedActionException - { - if (System.getSecurityManager() != null) - { - // A security manager has been established - return AccessController.doPrivileged(action); - } - try - { - return action.run(); - } - catch (RuntimeException e) - { - throw e; - } - catch (Exception e) - { - throw new PrivilegedActionException(e); - } - } - - /** - * Validate permissions. - */ - public static void validateSecurityPermission(Permission permission) - { - SecurityManager security = System.getSecurityManager(); - if (security != null) - { - security.checkPermission(permission); - } - } -} diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/secure/SecureCollections.java b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/secure/SecureCollections.java deleted file mode 100644 index 83fea5f11..000000000 --- a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/secure/SecureCollections.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.commons.utils.secure; - -import java.security.Permission; -import java.util.List; -import java.util.Set; - -/** - * @author Nikolay Zamosenchuk - * @version $Id: SecureCollections.java 34360 2009-07-22 23:58:59Z nzamosenchuk $ - * - */ -public class SecureCollections -{ - /** - * Private constructor, used to disallow instance creation - */ - private SecureCollections() - { - } - - /** - * Creates {@link SecureSet}, which will require given {@link Permission} for it's modification - * - * @param - * @param set - * Base List instance - * @param permission - * Required permission - * @return - */ - public static Set secureSet(Set set, Permission permission) - { - return new SecureSet(set, permission); - } - - /** - * Creates {@link SecureList}, which will require given {@link Permission} for it's modification - * - * @param - * @param list - * Base list instance - * @param permission - * Required permission - * @return - */ - public static List secureList(List list, Permission permission) - { - return new SecureList(list, permission); - } -} diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/secure/SecureList.java b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/secure/SecureList.java deleted file mode 100644 index b3aec399e..000000000 --- a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/secure/SecureList.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.commons.utils.secure; - -import java.security.AllPermission; -import java.security.Permission; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -/** - * SecureList is a wrapper over given List instance providing additional security check. - * To be able to modify this list, invoking code must have permission given in SecureList's - * constructor or {@link AllPermission}. - * - * @author Nikolay Zamosenchuk - * @version $Id: SecureList.java 34360 2009-07-22 23:58:59Z nzamosenchuk $ - * - */ -public class SecureList implements List -{ - - // base list - private final List list; - - // required permission - private final Permission permission; - - public SecureList(Permission permission) - { - super(); - this.list = new ArrayList(); - this.permission = permission; - } - - public SecureList(List list, Permission permission) - { - super(); - this.list = list; - this.permission = permission; - } - - public void add(int index, E pd) - { - checkPermissions(); - list.add(index, pd); - } - - public boolean add(E pd) - { - checkPermissions(); - return list.add(pd); - } - - public boolean addAll(Collection pds) - { - checkPermissions(); - return list.addAll(pds); - } - - public boolean addAll(int index, Collection pds) - { - checkPermissions(); - return list.addAll(index, pds); - } - - public void clear() - { - checkPermissions(); - list.clear(); - } - - public boolean contains(Object o) - { - return list.contains(o); - } - - public boolean containsAll(Collection coll) - { - return list.containsAll(coll); - } - - @Override - public boolean equals(Object o) - { - return o == this || list.equals(o); - } - - public E get(int index) - { - return list.get(index); - } - - @Override - public int hashCode() - { - return list.hashCode(); - } - - public int indexOf(Object o) - { - return list.indexOf(o); - } - - public boolean isEmpty() - { - return list.isEmpty(); - } - - public Iterator iterator() - { - return new Iterator() - { - Iterator i = list.iterator(); - - public boolean hasNext() - { - return i.hasNext(); - } - - public E next() - { - return i.next(); - } - - public void remove() - { - checkPermissions(); - i.remove(); - } - }; - } - - public int lastIndexOf(Object o) - { - return list.lastIndexOf(o); - } - - public ListIterator listIterator() - { - return listIterator(0); - } - - public ListIterator listIterator(final int index) - { - return new ListIterator() - { - ListIterator li = list.listIterator(index); - - public void add(E pd) - { - checkPermissions(); - li.add(pd); - } - - public boolean hasNext() - { - return li.hasNext(); - } - - public boolean hasPrevious() - { - return li.hasPrevious(); - } - - public E next() - { - return li.next(); - } - - public int nextIndex() - { - return li.nextIndex(); - } - - public E previous() - { - return li.previous(); - } - - public int previousIndex() - { - return li.previousIndex(); - } - - public void remove() - { - checkPermissions(); - li.remove(); - } - - public void set(E pd) - { - checkPermissions(); - li.set(pd); - } - }; - } - - public E remove(int index) - { - checkPermissions(); - return list.remove(index); - } - - public boolean remove(Object o) - { - checkPermissions(); - return list.remove(o); - } - - public boolean removeAll(Collection pds) - { - checkPermissions(); - return list.removeAll(pds); - } - - public boolean retainAll(Collection pds) - { - checkPermissions(); - return list.retainAll(pds); - } - - public E set(int index, E pd) - { - checkPermissions(); - return list.set(index, pd); - } - - public int size() - { - return list.size(); - } - - public List subList(int fromIndex, int toIndex) - { - return new SecureList(list.subList(fromIndex, toIndex), permission); - } - - public Object[] toArray() - { - return list.toArray(); - } - - public T[] toArray(T[] a) - { - return list.toArray(a); - } - - @Override - public String toString() - { - return list.toString(); - } - - /** - * Checks if code has a permission - */ - private void checkPermissions() - { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - sm.checkPermission(permission); - } - } - -} diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/secure/SecureSet.java b/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/secure/SecureSet.java deleted file mode 100644 index 499dcb44d..000000000 --- a/exo.kernel.commons/src/main/java/org/exoplatform/commons/utils/secure/SecureSet.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.commons.utils.secure; - -import java.security.AllPermission; -import java.security.Permission; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -/** - * SecureSet is a wrapper over given Set instance providing additional security check. - * To be able to modify set, invoking code must have the same permission as given in SecureSet's - * constructor or {@link AllPermission}. - * - * @author Nikolay Zamosenchuk - * @version $Id: SecureSet.java 34360 2009-07-22 23:58:59Z nzamosenchuk $ - * - */ -public class SecureSet implements Set -{ - - // base set - private final Set set; - - // required permission - private final Permission permission; - - /** - * Constructs a SecureSet using new {@link HashSet} inside. - * @param permission - * Permission that will be required for modificaiton. - */ - public SecureSet(Permission permission) - { - super(); - this.set = new HashSet(); - this.permission = permission; - } - - /** - * Constructs a SecureSet using new given {@link Set} instance. - * @param set - * Set, to be based on - * @param permission - * Permission that will be required for modificaiton. - */ - public SecureSet(Set set, Permission permission) - { - super(); - this.set = set; - this.permission = permission; - } - - public boolean add(E e) - { - checkPermission(); - return set.add(e); - } - - public boolean addAll(Collection elements) - { - checkPermission(); - return set.addAll(elements); - } - - public void clear() - { - checkPermission(); - set.clear(); - } - - public boolean contains(Object o) - { - return set.contains(o); - } - - public boolean containsAll(Collection coll) - { - return set.containsAll(coll); - } - - @Override - public boolean equals(Object o) - { - return o == this || set.equals(o); - } - - @Override - public int hashCode() - { - return set.hashCode(); - } - - public boolean isEmpty() - { - return set.isEmpty(); - } - - public Iterator iterator() - { - return new Iterator() - { - Iterator i = set.iterator(); - - public boolean hasNext() - { - return i.hasNext(); - } - - public E next() - { - return i.next(); - } - - public void remove() - { - checkPermission(); - i.remove(); - } - }; - } - - public boolean remove(Object o) - { - checkPermission(); - return set.remove(o); - } - - public boolean removeAll(Collection pds) - { - checkPermission(); - return set.removeAll(pds); - } - - public boolean retainAll(Collection pds) - { - checkPermission(); - return set.retainAll(pds); - } - - public int size() - { - return set.size(); - } - - public Object[] toArray() - { - return set.toArray(); - } - - public T[] toArray(T[] a) - { - return set.toArray(a); - } - - @Override - public String toString() - { - return set.toString(); - } - - /** - * Checks if code has a permission - */ - private void checkPermission() - { - SecurityManager security = System.getSecurityManager(); - if (security != null) - { - security.checkPermission(permission); - } - } -} diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/services/log/impl/SLF4JExoLogFactory.java b/exo.kernel.commons/src/main/java/org/exoplatform/services/log/impl/SLF4JExoLogFactory.java index 2d9b279ec..ebd0e0907 100644 --- a/exo.kernel.commons/src/main/java/org/exoplatform/services/log/impl/SLF4JExoLogFactory.java +++ b/exo.kernel.commons/src/main/java/org/exoplatform/services/log/impl/SLF4JExoLogFactory.java @@ -18,14 +18,11 @@ */ package org.exoplatform.services.log.impl; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.services.log.Log; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.spi.LocationAwareLogger; -import java.security.PrivilegedAction; - /** * A factory for {@link org.exoplatform.services.log.impl.LocationAwareSLF4JExoLog} and * {@link org.exoplatform.services.log.impl.SLF4JExoLog} based on the type of the logger @@ -43,13 +40,7 @@ public class SLF4JExoLogFactory extends AbstractExoLogFactory @Override protected Log getLogger(final String name) { - Logger slf4jlogger = SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Logger run() - { - return LoggerFactory.getLogger(name); - } - }); + Logger slf4jlogger = LoggerFactory.getLogger(name); if (slf4jlogger instanceof LocationAwareLogger) { diff --git a/exo.kernel.commons/src/main/java/org/exoplatform/services/log/impl/SimpleExoLogConfigurator.java b/exo.kernel.commons/src/main/java/org/exoplatform/services/log/impl/SimpleExoLogConfigurator.java index 03e15c6a3..bf7860022 100644 --- a/exo.kernel.commons/src/main/java/org/exoplatform/services/log/impl/SimpleExoLogConfigurator.java +++ b/exo.kernel.commons/src/main/java/org/exoplatform/services/log/impl/SimpleExoLogConfigurator.java @@ -18,7 +18,6 @@ */ package org.exoplatform.services.log.impl; -import org.exoplatform.commons.utils.PrivilegedSystemHelper; import org.exoplatform.services.log.AbstractLogConfigurator; import java.util.Iterator; @@ -45,7 +44,7 @@ public void configure(Properties properties) for (Iterator it = properties.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry)it.next(); - PrivilegedSystemHelper.setProperty((String)entry.getKey(), (String)entry.getValue()); + System.setProperty((String)entry.getKey(), (String)entry.getValue()); } this.properties = properties; diff --git a/exo.kernel.commons/src/test/java/org/exoplatform/commons/utils/secure/AbstractSecureCollectionsTest.java b/exo.kernel.commons/src/test/java/org/exoplatform/commons/utils/secure/AbstractSecureCollectionsTest.java deleted file mode 100644 index db4228bac..000000000 --- a/exo.kernel.commons/src/test/java/org/exoplatform/commons/utils/secure/AbstractSecureCollectionsTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2010 eXo Platform SAS. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.exoplatform.commons.utils.secure; - -import junit.framework.TestCase; - -import java.net.URL; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.CodeSource; -import java.security.Permission; -import java.security.Permissions; -import java.security.PrivilegedExceptionAction; -import java.security.ProtectionDomain; - -/** - * @author Nikolay Zamosenchuk - * @version $Id$ - */ - -public abstract class AbstractSecureCollectionsTest extends TestCase -{ - // permission for testing purposes - public static final Permission MODIFY_PERMISSION = new RuntimePermission("modifyPermisssion"); - - /** - * Run privileged action with given privileges. - */ - protected T doActionWithPermissions(PrivilegedExceptionAction action, Permission... permissions) - throws PrivilegedActionException - { - Permissions allPermissions = new Permissions(); - for (Permission permission : permissions) - { - if (permission != null) - { - allPermissions.add(permission); - } - } - ProtectionDomain[] protectionDomains = - new ProtectionDomain[]{new ProtectionDomain(new CodeSource(getCodeSource(), - (java.security.cert.Certificate[])null), allPermissions)}; - return AccessController.doPrivileged(action, new AccessControlContext(protectionDomains)); - } - - protected URL getCodeSource() - { - return getClass().getProtectionDomain().getCodeSource().getLocation(); - } -} diff --git a/exo.kernel.commons/src/test/java/org/exoplatform/commons/utils/secure/TestSecureList.java b/exo.kernel.commons/src/test/java/org/exoplatform/commons/utils/secure/TestSecureList.java deleted file mode 100644 index fa07794e9..000000000 --- a/exo.kernel.commons/src/test/java/org/exoplatform/commons/utils/secure/TestSecureList.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (C) 2003-2010 eXo Platform SAS. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Affero General Public License - * as published by the Free Software Foundation; either version 3 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, see. - */ -package org.exoplatform.commons.utils.secure; - -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.security.AccessControlException; -import java.util.List; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.ListIterator; - -/** - * @author Natasha Vakulenko - * @version $Id$ - */ - -public class TestSecureList extends AbstractSecureCollectionsTest -{ - private List list; - - @Override - protected void setUp() throws PrivilegedActionException - { - // establishment of protected set prior to each test - list = SecureCollections.secureList(new ArrayList(), MODIFY_PERMISSION); - try - { - // giving MODIFY_PERMISSION - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - list.add("firstString"); - list.add("secondString"); - return null; - } - }, MODIFY_PERMISSION); - } - catch (AccessControlException e) - { - // ok - } - } - - @Override - protected void tearDown() throws PrivilegedActionException - { - // cleaning protected list after each test - try - { - // giving MODIFY_PERMISSION - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - list.clear(); - return null; - } - }, MODIFY_PERMISSION); - } - catch (AccessControlException e) - { - // ok - } - } - - public void testSecureListAddDenied() throws PrivilegedActionException - { - try - { - // giving no permissions - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - list.add("string"); - return null; - } - }); - fail("Modification should be denied."); - } - catch (AccessControlException e) - { - // ok - } - } - - public void testSecureListAddPermitted() throws PrivilegedActionException - { - try - { - // giving MODIFY_PERMISSION - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - list.add(0, "string"); - return null; - } - }, MODIFY_PERMISSION); - } - catch (AccessControlException e) - { - fail("Modification should be permitted."); - } - } - - public void testSecureListClearDenied() throws PrivilegedActionException - { - try - { - // giving no permissions - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - list.clear(); - return null; - } - }); - fail("Modification should be denied."); - } - catch (AccessControlException e) - { - // ok - } - } - - public void testSecureListIteratorRemovePermitted() throws PrivilegedActionException - { - try - { - // giving MODIFY_PERMISSION - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - ListIterator iterator = list.listIterator(); - iterator.next(); - iterator.remove(); - return null; - } - }, MODIFY_PERMISSION); - } - catch (AccessControlException e) - { - fail("Modification should be permitted."); - } - } - - public void testSecureListRemoveDenied() throws PrivilegedActionException - { - try - { - // giving no permissions - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - list.remove(0); - return null; - } - }); - fail("Modification should be denied."); - } - catch (AccessControlException e) - { - // ok - } - } - - public void testSecureIteratorPermitted() throws PrivilegedActionException - { - try - { - // giving MODIFY_PERMISSION - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - Iterator it = list.iterator(); - return null; - } - }, MODIFY_PERMISSION); - } - catch (AccessControlException e) - { - fail("Modification should be permitted."); - } - } -} diff --git a/exo.kernel.commons/src/test/java/org/exoplatform/commons/utils/secure/TestSecureSet.java b/exo.kernel.commons/src/test/java/org/exoplatform/commons/utils/secure/TestSecureSet.java deleted file mode 100644 index e85d7f347..000000000 --- a/exo.kernel.commons/src/test/java/org/exoplatform/commons/utils/secure/TestSecureSet.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (C) 2003-2010 eXo Platform SAS. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Affero General Public License - * as published by the Free Software Foundation; either version 3 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, see. - */ -package org.exoplatform.commons.utils.secure; - -import java.security.PrivilegedExceptionAction; -import java.security.PrivilegedActionException; -import java.security.AccessControlException; -import java.util.HashSet; -import java.util.Set; -import java.util.Iterator; - -/** - * @author Natasha Vakulenko - * @version $Id$ - */ - -public class TestSecureSet extends AbstractSecureCollectionsTest -{ - private Set set; - - @Override - protected void setUp() throws PrivilegedActionException - { - // establishment of protected set prior to each test - set = SecureCollections.secureSet(new HashSet(), MODIFY_PERMISSION); - try - { - // giving MODIFY_PERMISSION - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - set.add("firstString"); - set.add("secondString"); - return null; - } - }, MODIFY_PERMISSION); - } - catch (AccessControlException e) - { - // ok - } - } - - @Override - protected void tearDown() throws PrivilegedActionException - { - // cleaning protected set after each test - try - { - // giving MODIFY_PERMISSION - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - set.clear(); - return null; - } - }, MODIFY_PERMISSION); - } - catch (AccessControlException e) - { - // ok - } - } - - public void testSecureSetAddPermitted() throws PrivilegedActionException - { - try - { - // giving MODIFY_PERMISSION - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - set.add("string"); - return null; - } - }, MODIFY_PERMISSION); - } - catch (AccessControlException e) - { - fail("Modification should be permitted."); - } - } - - public void testSecureSetAddDenied() throws PrivilegedActionException - { - try - { - // giving no permissions - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - set.add("string"); - return null; - } - }); - fail("Modification should be denied."); - } - catch (AccessControlException e) - { - // ok - } - } - - public void testSecureSetRemoveDenied() throws PrivilegedActionException - { - try - { - // giving no permissions - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - set.remove(0); - return null; - } - }); - fail("Modification should be denied."); - } - catch (AccessControlException e) - { - // ok - } - } - - public void testSecureSetRemovePermitted() throws PrivilegedActionException - { - try - { - // giving MODIFY_PERMISSION - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - set.remove(0); - return null; - } - }, MODIFY_PERMISSION); - } - catch (AccessControlException e) - { - fail("Modification should be permitted."); - } - } - - public void testSecureSetIteratorPermitted() throws PrivilegedActionException - { - try - { - // giving MODIFY_PERMISSION - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - Iterator iterator = set.iterator(); - return null; - } - }, MODIFY_PERMISSION); - } - catch (AccessControlException e) - { - fail("Modification should be permitted."); - } - } - - public void testSecureSetIteratorRemovePermitted() throws PrivilegedActionException - { - try - { - // giving MODIFY_PERMISSION - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - Iterator iterator = set.iterator(); - iterator.next(); - iterator.remove(); - return null; - } - }, MODIFY_PERMISSION); - } - catch (AccessControlException e) - { - fail("Modification should be permitted."); - } - } - - public void testSecureSetClearDenied() throws PrivilegedActionException - { - try - { - // giving no permissions - doActionWithPermissions(new PrivilegedExceptionAction() - { - public Object run() throws AccessControlException - { - set.clear(); - return null; - } - }); - fail("Modification should be denied."); - } - catch (AccessControlException e) - { - // ok - } - } -} diff --git a/exo.kernel.component.cache/pom.xml b/exo.kernel.component.cache/pom.xml index 3f56ade80..ec12e52c3 100644 --- a/exo.kernel.component.cache/pom.xml +++ b/exo.kernel.component.cache/pom.xml @@ -64,7 +64,7 @@ org.apache.maven.plugins maven-surefire-plugin - @{argLine} -Djava.net.preferIPv4Stack=true -Djava.security.manager=org.exoplatform.commons.test.TestSecurityManager -Djava.security.policy=${project.build.directory}/test-classes/test.policy + @{argLine} -Djava.net.preferIPv4Stack=true diff --git a/exo.kernel.component.command/pom.xml b/exo.kernel.component.command/pom.xml index 796fd4439..93b211d00 100644 --- a/exo.kernel.component.command/pom.xml +++ b/exo.kernel.component.command/pom.xml @@ -36,7 +36,7 @@ Implementation of Command Service of Exoplatform SAS 'eXo Kernel' project. - 0.4 + 0.35 @@ -74,9 +74,6 @@ maven-antrun-plugin - - @{argLine} -Djava.security.manager=org.exoplatform.commons.test.TestSecurityManager -Djava.security.policy=${project.build.directory}/test-classes/test.policy - prepare-test-policy diff --git a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommandService.java b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommandService.java index 8bd7edcd5..5bfe05ebb 100644 --- a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommandService.java +++ b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommandService.java @@ -23,16 +23,12 @@ import org.apache.commons.chain.config.ConfigParser; import org.apache.commons.chain.impl.CatalogFactoryBase; import org.apache.commons.digester.Digester; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.component.ComponentPlugin; import org.exoplatform.container.spi.DefinitionByType; import org.xml.sax.SAXException; import java.io.IOException; import java.io.InputStream; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.Iterator; /** @@ -57,13 +53,7 @@ public CommandService() this.catalogFactory = CatalogFactoryBase.getInstance(); final ConfigParser parser = new ConfigParser(); - this.digester = SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Digester run() - { - return parser.getDigester(); - } - }); + this.digester = parser.getDigester(); } public void addPlugin(ComponentPlugin plugin) @@ -92,44 +82,8 @@ public void addPlugin(ComponentPlugin plugin) */ public void putCatalog(final InputStream xml) throws IOException, SAXException { - // ConfigParser parser = new ConfigParser(); - // Prepare our Digester instance - // Digester digester = parser.getDigester(); digester.clear(); - - try - { - SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public Void run() throws Exception - { - digester.parse(xml); - return null; - } - }); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof IOException) - { - throw (IOException)cause; - } - else if (cause instanceof SAXException) - { - throw (SAXException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } - - // parser.getDigester().parse(xml); + digester.parse(xml); } /** diff --git a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommonsXMLConfigurationPlugin.java b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommonsXMLConfigurationPlugin.java index e964c31de..defb60e78 100644 --- a/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommonsXMLConfigurationPlugin.java +++ b/exo.kernel.component.command/src/main/java/org/exoplatform/services/command/impl/CommonsXMLConfigurationPlugin.java @@ -19,7 +19,6 @@ package org.exoplatform.services.command.impl; import org.apache.commons.chain.config.ConfigParser; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.component.BaseComponentPlugin; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.container.xml.InitParams; @@ -28,8 +27,6 @@ import org.exoplatform.services.log.Log; import java.net.URL; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; /** * Created by The eXo Platform SAS.
The plugin for configuring @@ -57,13 +54,7 @@ public CommonsXMLConfigurationPlugin(InitParams params, ConfigurationManager con final ConfigParser parser = new ConfigParser(); // may work for StandaloneContainer - URL res = SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public URL run() - { - return Thread.currentThread().getContextClassLoader().getResource(path); - } - }); + URL res = Thread.currentThread().getContextClassLoader().getResource(path); // for PortalContainer if (res == null) @@ -73,14 +64,7 @@ public URL run() LOG.info("Catalog configuration found at " + res); final URL fRes = res; - SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public Void run() throws Exception - { - parser.parse(fRes); - return null; - } - }); + parser.parse(fRes); } } diff --git a/exo.kernel.component.common/pom.xml b/exo.kernel.component.common/pom.xml index d8372514d..99dfc609e 100644 --- a/exo.kernel.component.common/pom.xml +++ b/exo.kernel.component.common/pom.xml @@ -140,7 +140,7 @@ org.apache.maven.plugins maven-surefire-plugin - @{argLine} -Djava.net.preferIPv4Stack=true -Djava.security.manager=org.exoplatform.commons.test.TestSecurityManager -Djava.security.policy=${project.build.directory}/test-classes/test.policy + @{argLine} -Djava.net.preferIPv4Stack=true diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/compress/CompressData.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/compress/CompressData.java index f9fdbf2aa..c450b4dcd 100644 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/compress/CompressData.java +++ b/exo.kernel.component.common/src/main/java/org/exoplatform/services/compress/CompressData.java @@ -18,7 +18,6 @@ */ package org.exoplatform.services.compress; -import org.exoplatform.commons.utils.PrivilegedFileHelper; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; @@ -77,7 +76,7 @@ public void addFile(String entryName, File file) { try { - InputStream is = PrivilegedFileHelper.fileInputStream(file); + InputStream is = new FileInputStream(file); datas_.add(new InputStreamDataInstance(entryName, is)); } catch (FileNotFoundException e) @@ -107,7 +106,7 @@ public void addInputStream(String entryName, InputStream is) throws Exception public void createZipFile(String fileName) throws Exception { File fileZip = new File(fileName + ".zip"); - FileOutputStream out = PrivilegedFileHelper.fileOutputStream(fileZip); + FileOutputStream out = new FileOutputStream(fileZip); ZipOutputStream zos = new ZipOutputStream(out); int size = datas_.size(); byte InputData[] = new byte[BUFFER]; @@ -179,7 +178,7 @@ else if (di instanceof FileDataInstance) public void createJarFile(String fileName) throws Exception { File fileZip = new File(fileName + ".jar"); - FileOutputStream out = PrivilegedFileHelper.fileOutputStream(fileZip); + FileOutputStream out = new FileOutputStream(fileZip); JarOutputStream jos = new JarOutputStream(out); int size = datas_.size(); if (size < 0) @@ -376,7 +375,7 @@ else if (file_.isDirectory()) if (f.isFile()) { - bufInput = PrivilegedFileHelper.fileInputStream(f); + bufInput = new FileInputStream(f); } else { diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/idgenerator/impl/IDGeneratorServiceImpl.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/idgenerator/impl/IDGeneratorServiceImpl.java index 8c0a1632e..6f1373902 100644 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/idgenerator/impl/IDGeneratorServiceImpl.java +++ b/exo.kernel.component.common/src/main/java/org/exoplatform/services/idgenerator/impl/IDGeneratorServiceImpl.java @@ -18,14 +18,12 @@ */ package org.exoplatform.services.idgenerator.impl; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.services.idgenerator.IDGeneratorService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import java.io.Serializable; import java.net.InetAddress; -import java.security.PrivilegedAction; import java.security.SecureRandom; import java.util.Random; @@ -47,23 +45,16 @@ public class IDGeneratorServiceImpl implements IDGeneratorService static { - SecurityHelper.doPrivilegedAction(new PrivilegedAction() + if ("IBM Corporation".equals(System.getProperty("java.vendor")) + && "1.8.0".equals(System.getProperty("java.version"))) { - public Object run() - { - if ("IBM Corporation".equals(System.getProperty("java.vendor")) - && "1.8.0".equals(System.getProperty("java.version"))) - { - //IBM JDK 8 workaround KER-308 - integerFormatter = new J9IntegerFormatter(); - } - else - { - integerFormatter = new IntegerFormatter(); - } - return null; - } - }); + //IBM JDK 8 workaround KER-308 + integerFormatter = new J9IntegerFormatter(); + } + else + { + integerFormatter = new IntegerFormatter(); + } InetAddress localInetAddress = null; try { diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/CloseableDataSource.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/CloseableDataSource.java index 331b3a85b..c0984a30c 100644 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/CloseableDataSource.java +++ b/exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/CloseableDataSource.java @@ -18,7 +18,6 @@ */ package org.exoplatform.services.jdbc.impl; -import org.exoplatform.commons.utils.PrivilegedSystemHelper; import org.exoplatform.commons.utils.PropertyManager; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; @@ -64,7 +63,7 @@ public class CloseableDataSource implements DataSource /** * Property value which responsible for allowing of closed DataSource usage. */ - private static final boolean PROHIBIT_CLOSED_DATASOURCE_USAGE = Boolean.valueOf(PrivilegedSystemHelper.getProperty( + private static final boolean PROHIBIT_CLOSED_DATASOURCE_USAGE = Boolean.valueOf(System.getProperty( "exo.jcr.prohibit.closed.datasource.usage", "true")); /** diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/listener/ListenerService.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/listener/ListenerService.java index 4470c2ae7..1548e3ce3 100644 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/listener/ListenerService.java +++ b/exo.kernel.component.common/src/main/java/org/exoplatform/services/listener/ListenerService.java @@ -20,7 +20,6 @@ import org.picocontainer.Startable; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.component.RequestLifeCycle; @@ -31,7 +30,6 @@ import org.exoplatform.services.log.Log; import org.exoplatform.services.naming.InitialContextInitializer; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -298,14 +296,8 @@ public void run() { try { - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - ExoContainerContext.setCurrentContainer(container); - return null; - } - }); + ExoContainerContext.setCurrentContainer(container); + RequestLifeCycle.begin(container); handler.push(); listener.onEvent(event); @@ -325,14 +317,7 @@ public Void run() } finally { - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - ExoContainerContext.setCurrentContainer(null); - return null; - } - }); + ExoContainerContext.setCurrentContainer(null); } } } diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/listener/ListenerThreadFactory.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/listener/ListenerThreadFactory.java index 20ea47dc4..cceb728c2 100644 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/listener/ListenerThreadFactory.java +++ b/exo.kernel.component.common/src/main/java/org/exoplatform/services/listener/ListenerThreadFactory.java @@ -42,8 +42,7 @@ public class ListenerThreadFactory implements ThreadFactory ListenerThreadFactory() { - SecurityManager s = System.getSecurityManager(); - group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); + group = Thread.currentThread().getThreadGroup(); namePrefix = "asynch-event-" + poolNumber.getAndIncrement() + "-thread-"; } diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/mail/impl/MailServiceImpl.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/mail/impl/MailServiceImpl.java index 23b056c8e..125344af2 100644 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/mail/impl/MailServiceImpl.java +++ b/exo.kernel.component.common/src/main/java/org/exoplatform/services/mail/impl/MailServiceImpl.java @@ -19,7 +19,6 @@ package org.exoplatform.services.mail.impl; import java.io.InputStream; -import java.security.PrivilegedAction; import java.util.Date; import java.util.List; import java.util.Properties; @@ -40,8 +39,6 @@ import javax.mail.internet.MimeUtility; import javax.mail.util.ByteArrayDataSource; -import org.exoplatform.commons.utils.PrivilegedSystemHelper; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.xml.InitParams; @@ -85,30 +82,18 @@ public class MailServiceImpl implements MailService public MailServiceImpl(InitParams params, final ExoContainerContext ctx) throws Exception { - props_ = new Properties(PrivilegedSystemHelper.getProperties()); + props_ = new Properties(System.getProperties()); props_.putAll(params.getPropertiesParam("config").getProperties()); if ("true".equals(props_.getProperty("mail.smtp.auth"))) { String username = props_.getProperty("mail.smtp.auth.username"); String password = props_.getProperty("mail.smtp.auth.password"); final ExoAuthenticator auth = new ExoAuthenticator(username, password); - mailSession_ = SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Session run() - { - return Session.getInstance(props_, auth); - } - }); + mailSession_ = Session.getInstance(props_, auth); } else { - mailSession_ = SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Session run() - { - return Session.getInstance(props_, null); - } - }); + mailSession_ = Session.getInstance(props_, null); } int threadNumber = props_.getProperty(MAX_THREAD_NUMBER) != null ? Integer.valueOf(props_.getProperty(MAX_THREAD_NUMBER)) diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/naming/InitialContextBinder.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/naming/InitialContextBinder.java index 97f2e6077..2a5c6f349 100644 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/naming/InitialContextBinder.java +++ b/exo.kernel.component.common/src/main/java/org/exoplatform/services/naming/InitialContextBinder.java @@ -18,10 +18,10 @@ */ package org.exoplatform.services.naming; -import org.exoplatform.commons.utils.PrivilegedFileHelper; - import java.io.File; +import java.io.FileInputStream; import java.io.FileNotFoundException; +import java.io.FileOutputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @@ -102,7 +102,7 @@ public class InitialContextBinder this.bindings = new ConcurrentHashMap(); this.bindingsStorePath = bindingsStorePath; - if (PrivilegedFileHelper.exists(new File(bindingsStorePath))) + if (new File(bindingsStorePath).exists()) { Map importedRefs = readBindings(); for (Entry entry : importedRefs.entrySet()) @@ -230,7 +230,7 @@ protected synchronized void saveBindings() throws FileNotFoundException, XMLStre { XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); XMLStreamWriter writer = - outputFactory.createXMLStreamWriter(PrivilegedFileHelper.fileOutputStream(bindingsStorePath), "UTF-8"); + outputFactory.createXMLStreamWriter(new FileOutputStream(bindingsStorePath), "UTF-8"); writer.writeStartDocument("UTF-8", "1.0"); writer.writeStartElement(BIND_REFERENCES_ELEMENT); @@ -288,7 +288,7 @@ protected Map readBindings() throws FileNotFoundException, XM XMLInputFactory factory = XMLInputFactory.newInstance(); XMLEventReader reader = - factory.createXMLEventReader(PrivilegedFileHelper.fileInputStream(bindingsStorePath), "UTF-8"); + factory.createXMLEventReader(new FileInputStream(bindingsStorePath), "UTF-8"); while (reader.hasNext()) { diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/naming/InitialContextInitializer.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/naming/InitialContextInitializer.java index 94f513fc0..768bb4e0b 100644 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/naming/InitialContextInitializer.java +++ b/exo.kernel.component.common/src/main/java/org/exoplatform/services/naming/InitialContextInitializer.java @@ -18,7 +18,6 @@ */ package org.exoplatform.services.naming; -import org.exoplatform.commons.utils.PrivilegedSystemHelper; import org.exoplatform.container.component.ComponentPlugin; import org.exoplatform.container.configuration.ConfigurationException; import org.exoplatform.container.xml.InitParams; @@ -54,7 +53,7 @@ public class InitialContextInitializer { - static String DEFAULT_INITIAL_CONTEXT_FACTORY = PrivilegedSystemHelper.getProperty(Context.INITIAL_CONTEXT_FACTORY); + static String DEFAULT_INITIAL_CONTEXT_FACTORY = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); public static final String PROPERTIES_DEFAULT = "default-properties"; @@ -67,7 +66,7 @@ public class InitialContextInitializer public static final String BINDINGS_STORE_PATH = "bindings-store-path"; - public static final String DEFAULT_BINDING_STORE_PATH = PrivilegedSystemHelper.getProperty("java.io.tmpdir") + public static final String DEFAULT_BINDING_STORE_PATH = System.getProperty("java.io.tmpdir") + File.separator + "bind-references.xml"; private static final Log LOG = ExoLogger.getLogger("exo.kernel.component.common.InitialContextInitializer"); @@ -97,7 +96,7 @@ public InitialContextInitializer(InitParams params) throws NamingException, Conf Property prop = (Property)props.next(); String propName = prop.getName(); String propValue = prop.getValue(); - String existedProp = PrivilegedSystemHelper.getProperty(propName); + String existedProp = System.getProperty(propName); if (isMandatory) { setSystemProperty(propName, propValue, propParam.getName()); @@ -127,7 +126,7 @@ else if (isDefault) if (overloadContextFactoryParam != null && overloadContextFactoryParam.getValue() != null && Boolean.valueOf(overloadContextFactoryParam.getValue())) { - PrivilegedSystemHelper + System .setProperty(Context.INITIAL_CONTEXT_FACTORY, ExoContainerContextFactory.class.getName()); } @@ -145,19 +144,19 @@ else if (isDefault) private void setSystemProperty(String propName, String propValue, String propParamName) { - PrivilegedSystemHelper.setProperty(propName, propValue); + System.setProperty(propName, propValue); if (propName.equals(Context.INITIAL_CONTEXT_FACTORY)) { - DEFAULT_INITIAL_CONTEXT_FACTORY = PrivilegedSystemHelper.getProperty(Context.INITIAL_CONTEXT_FACTORY); + DEFAULT_INITIAL_CONTEXT_FACTORY = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); } - LOG.info("Using mandatory system property: " + propName + " = " + PrivilegedSystemHelper.getProperty(propName)); + LOG.info("Using mandatory system property: " + propName + " = " + System.getProperty(propName)); } // for out-of-container testing private InitialContextInitializer(String name, Reference reference) throws NamingException, FileNotFoundException, XMLStreamException { - PrivilegedSystemHelper.setProperty(Context.INITIAL_CONTEXT_FACTORY, DEFAULT_INITIAL_CONTEXT_FACTORY); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, DEFAULT_INITIAL_CONTEXT_FACTORY); InitialContext initialContext = getInitialContext(); initialContext.rebind(name, reference); diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/net/impl/NetServiceImpl.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/net/impl/NetServiceImpl.java index 8db0616ab..1bef4b60b 100644 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/net/impl/NetServiceImpl.java +++ b/exo.kernel.component.common/src/main/java/org/exoplatform/services/net/impl/NetServiceImpl.java @@ -18,12 +18,9 @@ */ package org.exoplatform.services.net.impl; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.services.net.NetService; import java.net.Socket; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; /** * Created by The eXo Platform SAS Author : HoaPham phamvuxuanhoa@yahoo.com Jan @@ -36,24 +33,10 @@ public long ping(final String host, final int port) throws Exception { long startTime = 0; long endTime = 0; - try - { - startTime = System.currentTimeMillis(); - Socket socket = SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public Socket run() throws Exception - { - return new Socket(host, port); - } - }); - endTime = System.currentTimeMillis(); - socket.close(); - } - catch (PrivilegedActionException e) - { - // e.printStackTrace() ; - return -1; - } + startTime = System.currentTimeMillis(); + Socket socket = new Socket(host, port); + endTime = System.currentTimeMillis(); + socket.close(); return endTime - startTime; } } diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/impl/AbstractRPCService.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/impl/AbstractRPCService.java index 8106736ca..6fe6d047d 100644 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/impl/AbstractRPCService.java +++ b/exo.kernel.component.common/src/main/java/org/exoplatform/services/rpc/impl/AbstractRPCService.java @@ -19,7 +19,6 @@ package org.exoplatform.services.rpc.impl; import org.exoplatform.commons.utils.PropertyManager; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.configuration.ConfigurationManager; @@ -51,9 +50,6 @@ import java.io.ObjectOutput; import java.io.Serializable; import java.net.URL; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -220,17 +216,11 @@ public AbstractRPCService(ExoContainerContext ctx, InitParams params, Configurat try { - this.configurator = SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public ProtocolStackConfigurator run() throws Exception - { - return ConfiguratorFactory.getStackConfigurator(properties); - } - }); + this.configurator = ConfiguratorFactory.getStackConfigurator(properties); } - catch (PrivilegedActionException pae) + catch (Exception e) { - throw new RuntimeException("Cannot load the JGroups configuration from " + properties, pae.getCause()); + throw new RuntimeException("Cannot load the JGroups configuration from " + properties, e.getCause()); } this.clusterName = getClusterName(ctx, params); @@ -395,11 +385,6 @@ else if (result instanceof RPCException) protected List excecuteCommand(final List
dests, RemoteCommand command, final boolean synchronous, final long timeout, Serializable... args) throws RPCException { - SecurityManager security = System.getSecurityManager(); - if (security != null) - { - security.checkPermission(RPCService.ACCESS_RPC_SERVICE_PERMISSION); - } if (state != State.STARTED) { throw new RPCException( @@ -412,21 +397,15 @@ protected List excecuteCommand(final List
dests, RemoteCommand } final Message msg = new Message(); setObject(msg, new MessageBody(dests.size() == 1 && dests != members ? dests.get(0) : null, commandId, args)); //NOSONAR - RspList rsps = SecurityHelper.doPrivilegedAction(new PrivilegedAction() + RspList rsps = null; + try { - public RspList run() - { - try - { - return castMessage(dests, msg, synchronous, timeout); - } - catch (Exception e) - { - LOG.error("Could not cast the message corresponding to the command " + commandId + ".", e); - } - return null; - } - }); + rsps = castMessage(dests, msg, synchronous, timeout); + } + catch (Exception e) + { + LOG.error("Could not cast the message corresponding to the command " + commandId + ".", e); + } if (LOG.isTraceEnabled()) LOG.trace("responses: " + rsps); @@ -570,11 +549,6 @@ private void onTopologyChange(boolean coordinatorHasChanged) */ public synchronized RemoteCommand registerCommand(RemoteCommand command) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - { - security.checkPermission(RPCService.ACCESS_RPC_SERVICE_PERMISSION); - } if (command != null) { String commandId = command.getId(); @@ -600,11 +574,6 @@ public synchronized RemoteCommand registerCommand(RemoteCommand command) */ public synchronized void unregisterCommand(RemoteCommand command) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - { - security.checkPermission(RPCService.ACCESS_RPC_SERVICE_PERMISSION); - } if (command != null) { String commandId = command.getId(); @@ -648,11 +617,6 @@ public boolean isCoordinator() throws RPCException */ public void registerTopologyChangeListener(TopologyChangeListener listener) throws SecurityException { - SecurityManager security = System.getSecurityManager(); - if (security != null) - { - security.checkPermission(RPCService.ACCESS_RPC_SERVICE_PERMISSION); - } if (listener == null) { return; @@ -665,11 +629,6 @@ public void registerTopologyChangeListener(TopologyChangeListener listener) thro */ public void unregisterTopologyChangeListener(TopologyChangeListener listener) throws SecurityException { - SecurityManager security = System.getSecurityManager(); - if (security != null) - { - security.checkPermission(RPCService.ACCESS_RPC_SERVICE_PERMISSION); - } if (listener == null) { return; @@ -692,28 +651,15 @@ protected RemoteCommand getCommand(String commandId) */ public void start() { - SecurityManager security = System.getSecurityManager(); - if (security != null) - { - security.checkPermission(RPCService.ACCESS_RPC_SERVICE_PERMISSION); - } - try { - SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public Void run() throws Exception - { - channel = createChannel(); - dispatcher = new MessageDispatcher(channel, null, AbstractRPCService.this, AbstractRPCService.this); - channel.connect(clusterName); - return null; - } - }); + channel = createChannel(); + dispatcher = new MessageDispatcher(channel, null, AbstractRPCService.this, AbstractRPCService.this); + channel.connect(clusterName); } - catch (PrivilegedActionException pae) + catch (Exception e) { - throw new RuntimeException("Cannot initialize the Channel needed for the RPCServiceImpl", pae.getCause()); + throw new RuntimeException("Cannot initialize the Channel needed for the RPCServiceImpl", e.getCause()); } finally { @@ -727,27 +673,14 @@ public Void run() throws Exception */ public void stop() { - SecurityManager security = System.getSecurityManager(); - if (security != null) - { - security.checkPermission(RPCService.ACCESS_RPC_SERVICE_PERMISSION); - } - this.state = State.STOPPED; this.isCoordinator = false; if (channel != null && channel.isOpen()) { if (LOG.isInfoEnabled()) LOG.info("Disconnecting and closing the Channel"); - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - channel.disconnect(); - channel.close(); - return null; - } - }); + channel.disconnect(); + channel.close(); channel = null; } if (dispatcher != null) diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/scheduler/impl/QuartzSheduler.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/scheduler/impl/QuartzSheduler.java index 02c45e79e..2e27c6900 100644 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/scheduler/impl/QuartzSheduler.java +++ b/exo.kernel.component.common/src/main/java/org/exoplatform/services/scheduler/impl/QuartzSheduler.java @@ -21,7 +21,6 @@ import java.sql.Connection; import java.sql.DatabaseMetaData; import java.util.Properties; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.BaseContainerLifecyclePlugin; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; @@ -36,8 +35,6 @@ import javax.naming.InitialContext; import javax.sql.DataSource; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; /** * Created by The eXo Platform SAS Author : Tuan Nguyen @@ -94,32 +91,7 @@ public QuartzSheduler(ExoContainerContext ctx, InitParams params) throws Excepti { sf = new StdSchedulerFactory(); } - try - { - scheduler_ = SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public Scheduler run() throws Exception - { - return sf.getScheduler(); - } - }); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof SchedulerException) - { - throw (SchedulerException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } + scheduler_ = sf.getScheduler(); // If the scheduler has already been started, it is necessary to put the scheduler // in standby mode to ensure that the jobs of the ExoContainer won't launched too early @@ -163,14 +135,7 @@ public void stop() private Connection getConnection(String dsName) throws Exception { final DataSource dsF = (DataSource) new InitialContext().lookup(dsName); - Connection jdbcConn = SecurityHelper.doPrivilegedSQLExceptionAction(new PrivilegedExceptionAction() - { - public Connection run() throws Exception - { - return dsF.getConnection(); - } - }); - return jdbcConn; + return dsF.getConnection(); } /** @@ -178,13 +143,7 @@ public Connection run() throws Exception */ private String getDriverDelegateClass(final DatabaseMetaData metaData) throws Exception { - String databaseName = (String) SecurityHelper.doPrivilegedSQLExceptionAction(new PrivilegedExceptionAction() - { - public String run() throws Exception - { - return metaData.getDatabaseProductName(); - } - }); + String databaseName = metaData.getDatabaseProductName(); if(databaseName == null || databaseName.isEmpty()) { LOG.warn("The database name cannot be retrieve, the default DriverDelegateClass will be used for Quartz."); diff --git a/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/impl/AbstractTransactionService.java b/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/impl/AbstractTransactionService.java index b2e39f42e..f9d02f456 100644 --- a/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/impl/AbstractTransactionService.java +++ b/exo.kernel.component.common/src/main/java/org/exoplatform/services/transaction/impl/AbstractTransactionService.java @@ -18,14 +18,11 @@ */ package org.exoplatform.services.transaction.impl; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.transaction.TransactionService; -import java.security.PrivilegedExceptionAction; - import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.InvalidTransactionException; @@ -163,13 +160,7 @@ public final TransactionManager getTransactionManager() TransactionManager tm; try { - tm = SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public TransactionManager run() throws Exception - { - return findTransactionManager(); - } - }); + tm = findTransactionManager(); } catch (Exception e) { @@ -218,13 +209,7 @@ public final UserTransaction getUserTransaction() UserTransaction ut; try { - ut = SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public UserTransaction run() throws Exception - { - return findUserTransaction(); - } - }); + ut = findUserTransaction(); } catch (Exception e) { diff --git a/exo.kernel.component.common/src/test/java/org/exoplatform/services/net/test/TestNetService.java b/exo.kernel.component.common/src/test/java/org/exoplatform/services/net/test/TestNetService.java index 3ffe28791..f78f5d8bf 100644 --- a/exo.kernel.component.common/src/test/java/org/exoplatform/services/net/test/TestNetService.java +++ b/exo.kernel.component.common/src/test/java/org/exoplatform/services/net/test/TestNetService.java @@ -52,12 +52,9 @@ public void tearDown() throws Exception public void testNetService() throws Exception { - ping(null, 0); ping("www.google.com", 80); ping("www.vnexpress.net", 80); ping("www.exoplatform.org", 80); - // ----ping a host on LAN - ping("localhost", 25); } private void ping(String host, int port) throws Exception diff --git a/exo.kernel.component.common/src/test/java/org/exoplatform/services/scheduler/test/TestPersistedQuartzScheduler.java b/exo.kernel.component.common/src/test/java/org/exoplatform/services/scheduler/test/TestPersistedQuartzScheduler.java index a3969fe29..95f8caa09 100644 --- a/exo.kernel.component.common/src/test/java/org/exoplatform/services/scheduler/test/TestPersistedQuartzScheduler.java +++ b/exo.kernel.component.common/src/test/java/org/exoplatform/services/scheduler/test/TestPersistedQuartzScheduler.java @@ -2,7 +2,6 @@ import junit.framework.TestCase; import org.exoplatform.commons.utils.IOUtil; -import org.exoplatform.commons.utils.PrivilegedFileHelper; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ValueParam; @@ -37,7 +36,7 @@ public void setUp() throws Exception { st = connection.createStatement(); /***init quartz tables***/ - String scripts = IOUtil.getStreamContentAsString(PrivilegedFileHelper.getResourceAsStream("/quartz_hsqldb.sql")); + String scripts = IOUtil.getStreamContentAsString(this.getClass().getResourceAsStream("/quartz_hsqldb.sql")); for (String query : splitWithSQLDelimiter(scripts)) { st.executeUpdate(query); diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/pom.xml b/exo.kernel.component.ext.cache.impl.infinispan.v8/pom.xml index dd554c23c..da9394c17 100644 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/pom.xml +++ b/exo.kernel.component.ext.cache.impl.infinispan.v8/pom.xml @@ -95,7 +95,7 @@ org.apache.maven.plugins maven-surefire-plugin - @{argLine} --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.util.concurrent=ALL-UNNAMED -Djava.net.preferIPv4Stack=true -Djava.security.manager=org.exoplatform.commons.test.TestSecurityManager -Djava.security.policy=${project.build.directory}/test-classes/test.policy + @{argLine} --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.util.concurrent=ALL-UNNAMED -Djava.net.preferIPv4Stack=true diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/AbstractExoCache.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/AbstractExoCache.java index 251a5e4da..25b2d5c74 100644 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/AbstractExoCache.java +++ b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/AbstractExoCache.java @@ -18,7 +18,6 @@ */ package org.exoplatform.services.cache.impl.infinispan; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.services.cache.CacheInfo; import org.exoplatform.services.cache.CacheListener; import org.exoplatform.services.cache.CacheListenerContext; @@ -27,7 +26,6 @@ import org.exoplatform.services.cache.ExoCache; import org.exoplatform.services.cache.ExoCacheConfig; import org.exoplatform.services.cache.ObjectCacheInfo; -import org.exoplatform.services.cache.impl.infinispan.generic.GenericExoCacheConfig; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.infinispan.AdvancedCache; @@ -45,7 +43,6 @@ import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import java.io.Serializable; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -273,16 +270,7 @@ else if (value == null) } } } - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - - @Override - public Void run() - { - putOnly(key, value, false); - return null; - } - }); + putOnly(key, value, false); onPut(key, value); } @@ -298,16 +286,8 @@ else if (value == null) return; } - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { + putOnly(key, value, true); - @Override - public Void run() - { - putOnly(key, value, true); - return null; - } - }); onPutLocal(key, value); } @@ -350,44 +330,35 @@ public void putMap(final Map objs) throws IllegalArgum throw new IllegalArgumentException("No null cache key accepted"); } } - SecurityHelper.doPrivilegedAction(new PrivilegedAction() + // Start transaction + if(cache.getTransactionManager() != null) { + cache.startBatch(); + } + try { - - @Override - public Void run() + // Make sure that the key and the value are valid + Map map = new LinkedHashMap(); + for (Map.Entry entry : objs.entrySet()) { - // Start transaction - if(cache.getTransactionManager() != null) { - cache.startBatch(); - } - try - { - // Make sure that the key and the value are valid - Map map = new LinkedHashMap(); - for (Map.Entry entry : objs.entrySet()) - { - map.put(entry.getKey(), entry.getValue()); - } - cache.putAll(map); - if(cache.getTransactionManager() != null) { - cache.endBatch(true); - } - // End transaction - for (Map.Entry entry : objs.entrySet()) - { - onPut(entry.getKey(), entry.getValue()); - } - } - catch (Exception e) //NOSONAR - { - if(cache.getTransactionManager() != null) { - cache.endBatch(false); - } - LOG.warn("An error occurs while executing the putMap method", e); - } - return null; + map.put(entry.getKey(), entry.getValue()); + } + cache.putAll(map); + if(cache.getTransactionManager() != null) { + cache.endBatch(true); + } + // End transaction + for (Map.Entry entry : objs.entrySet()) + { + onPut(entry.getKey(), entry.getValue()); + } + } + catch (Exception e) //NOSONAR + { + if(cache.getTransactionManager() != null) { + cache.endBatch(false); } - }); + LOG.warn("An error occurs while executing the putMap method", e); + } } /** @@ -406,34 +377,25 @@ public void putAsyncMap(final Map objs) throws Illegal throw new IllegalArgumentException("No null cache key accepted"); } } - SecurityHelper.doPrivilegedAction(new PrivilegedAction() + try { - - @Override - public Void run() + // Make sure that the key and the value are valid + Map map = new LinkedHashMap(); + for (Map.Entry entry : objs.entrySet()) { - try - { - // Make sure that the key and the value are valid - Map map = new LinkedHashMap(); - for (Map.Entry entry : objs.entrySet()) - { - map.put(entry.getKey(), entry.getValue()); - } - cache.putAllAsync(map); - // End transaction - for (Map.Entry entry : objs.entrySet()) - { - onPut(entry.getKey(), entry.getValue()); - } - } - catch (Exception e) //NOSONAR - { - LOG.warn("An error occurs while executing the putMap method", e); - } - return null; + map.put(entry.getKey(), entry.getValue()); + } + cache.putAllAsync(map); + // End transaction + for (Map.Entry entry : objs.entrySet()) + { + onPut(entry.getKey(), entry.getValue()); } - }); + } + catch (Exception e) //NOSONAR + { + LOG.warn("An error occurs while executing the putMap method", e); + } } /** @@ -446,15 +408,7 @@ public V remove(final Serializable key) throws NullPointerException { throw new IllegalArgumentException("No null cache key accepted"); } - V result = SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - - @Override - public V run() - { - return cache.remove(key); - } - }); + V result = cache.remove(key); onRemove((K)key, result); return result; } @@ -469,16 +423,7 @@ public void removeLocal(final Serializable key) throws NullPointerException { throw new IllegalArgumentException("No null cache key accepted"); } - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - - @Override - public Void run() - { - cache.withFlags(Flag.CACHE_MODE_LOCAL).removeAsync(key); - return null; - } - }); + cache.withFlags(Flag.CACHE_MODE_LOCAL).removeAsync(key); onRemove((K)key, null); } @@ -804,4 +749,4 @@ void onClearCache() throws Exception listener.onClearCache(this); } } -} \ No newline at end of file +} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheFactoryImpl.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheFactoryImpl.java index 6f53336ed..a6c41c80a 100644 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheFactoryImpl.java +++ b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/ExoCacheFactoryImpl.java @@ -18,7 +18,6 @@ */ package org.exoplatform.services.cache.impl.infinispan; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.container.xml.InitParams; @@ -48,8 +47,6 @@ import java.io.InputStream; import java.io.Serializable; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -184,74 +181,53 @@ public ExoCacheFactoryImpl(ExoContainerContext ctx, String cacheConfigTemplate, */ private DefaultCacheManager initCacheManager(final String cacheConfigTemplate) throws ExoCacheInitException { + InputStream is = null; try { - return SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public DefaultCacheManager run() throws Exception - { - InputStream is = null; - try - { - // Read the configuration file of the cache - is = configManager.getInputStream(cacheConfigTemplate); - } - catch (Exception e)//NOSONAR - { - throw new ExoCacheInitException("The configuration of the CacheManager cannot be loaded from '" - + cacheConfigTemplate + "'", e); - } - if (is == null) - { - throw new ExoCacheInitException("The configuration of the CacheManager cannot be found at '" - + cacheConfigTemplate + "'"); - } - GlobalConfigurationBuilder configBuilder; - Configuration config; - try - { - ParserRegistry parser = new ParserRegistry(Thread.currentThread().getContextClassLoader()); - // Loads the configuration from the input stream - ConfigurationBuilderHolder holder = parser.parse(is); - configBuilder = holder.getGlobalConfigurationBuilder(); - config = holder.getDefaultConfigurationBuilder().build(); - } - catch (RuntimeException e) //NOSONAR - { - throw new ExoCacheInitException("Cannot parse the configuration '" + cacheConfigTemplate + "'", e); - } - configureCacheManager(configBuilder); - DefaultCacheManager cacheManager; - try - { - // Create the CacheManager from the new configuration - cacheManager = new DefaultCacheManager(configBuilder.build(), config); - } - catch (RuntimeException e) //NOSONAR - { - throw new ExoCacheInitException( - "Cannot initialize the CacheManager corresponding to the configuration '" + cacheConfigTemplate - + "'", e); - } - // Register the main cache manager - mappingGlobalConfigCacheManager.put(cacheManager.getCacheManagerConfiguration().transport().clusterName(), - cacheManager); - return cacheManager; - } - }); + // Read the configuration file of the cache + is = configManager.getInputStream(cacheConfigTemplate); } - catch (PrivilegedActionException e) + catch (Exception e)//NOSONAR { - Throwable cause = e.getCause(); - if (cause instanceof ExoCacheInitException) - { - throw (ExoCacheInitException)cause;//NOSONAR - } - else - { - throw new ExoCacheInitException(e); - } + throw new ExoCacheInitException("The configuration of the CacheManager cannot be loaded from '" + + cacheConfigTemplate + "'", e); + } + if (is == null) + { + throw new ExoCacheInitException("The configuration of the CacheManager cannot be found at '" + + cacheConfigTemplate + "'"); + } + GlobalConfigurationBuilder configBuilder; + Configuration config; + try + { + ParserRegistry parser = new ParserRegistry(Thread.currentThread().getContextClassLoader()); + // Loads the configuration from the input stream + ConfigurationBuilderHolder holder = parser.parse(is); + configBuilder = holder.getGlobalConfigurationBuilder(); + config = holder.getDefaultConfigurationBuilder().build(); + } + catch (RuntimeException e) //NOSONAR + { + throw new ExoCacheInitException("Cannot parse the configuration '" + cacheConfigTemplate + "'", e); + } + configureCacheManager(configBuilder); + DefaultCacheManager cacheManager; + try + { + // Create the CacheManager from the new configuration + cacheManager = new DefaultCacheManager(configBuilder.build(), config); } + catch (RuntimeException e) //NOSONAR + { + throw new ExoCacheInitException( + "Cannot initialize the CacheManager corresponding to the configuration '" + cacheConfigTemplate + + "'", e); + } + // Register the main cache manager + mappingGlobalConfigCacheManager.put(cacheManager.getCacheManagerConfiguration().transport().clusterName(), + cacheManager); + return cacheManager; } /** @@ -330,60 +306,38 @@ public ExoCache createCache(final ExoCacheConfig config) t final ConfigurationBuilder confBuilder = new ConfigurationBuilder(); if (customConfig != null) { - try - { - cacheManager = - SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public DefaultCacheManager run() throws Exception - { - // A custom configuration has been set - if (LOG.isInfoEnabled()) - LOG.info("A custom configuration has been set for the cache '" + region + "'."); - ParserRegistry parser = new ParserRegistry(Thread.currentThread().getContextClassLoader()); - // Load the configuration - ConfigurationBuilderHolder holder = parser.parse(configManager.getInputStream(customConfig)); - GlobalConfigurationBuilder configBuilder = holder.getGlobalConfigurationBuilder(); - // Configure JGroups and JMX since it could affect the state of the Global Config - configureCacheManager(configBuilder); - GlobalConfiguration gc = configBuilder.build(); - - // Check if a CacheManager with the same GlobalConfiguration exists - DefaultCacheManager currentCacheManager = - mappingGlobalConfigCacheManager.get(gc.transport().clusterName()); - if (currentCacheManager == null) - { - // Use a different cache manager name to prevent naming conflict - configBuilder.globalJmxStatistics().cacheManagerName( - gc.globalJmxStatistics().cacheManagerName() + "_" + region + "_" + ctx.getName()); - // No cache manager has been defined so far for this Cache Configuration - currentCacheManager = - new DefaultCacheManager(configBuilder.build(), holder.getDefaultConfigurationBuilder() - .build(), false); - for (Entry entry : holder.getNamedConfigurationBuilders().entrySet()) - { - currentCacheManager.defineConfiguration(entry.getKey(), entry.getValue().build()); - } - currentCacheManager.start(); - // We register this new cache manager - mappingGlobalConfigCacheManager.put(gc.transport().clusterName(), currentCacheManager); - } - return currentCacheManager; - } - }); - } - catch (PrivilegedActionException e) + // A custom configuration has been set + if (LOG.isInfoEnabled()) + LOG.info("A custom configuration has been set for the cache '" + region + "'."); + ParserRegistry parser = new ParserRegistry(Thread.currentThread().getContextClassLoader()); + // Load the configuration + ConfigurationBuilderHolder holder = parser.parse(configManager.getInputStream(customConfig)); + GlobalConfigurationBuilder configBuilder = holder.getGlobalConfigurationBuilder(); + // Configure JGroups and JMX since it could affect the state of the Global Config + configureCacheManager(configBuilder); + GlobalConfiguration gc = configBuilder.build(); + + // Check if a CacheManager with the same GlobalConfiguration exists + DefaultCacheManager currentCacheManager = + mappingGlobalConfigCacheManager.get(gc.transport().clusterName()); + if (currentCacheManager == null) { - Throwable cause = e.getCause(); - if (cause instanceof Exception) + // Use a different cache manager name to prevent naming conflict + configBuilder.globalJmxStatistics().cacheManagerName( + gc.globalJmxStatistics().cacheManagerName() + "_" + region + "_" + ctx.getName()); + // No cache manager has been defined so far for this Cache Configuration + currentCacheManager = + new DefaultCacheManager(configBuilder.build(), holder.getDefaultConfigurationBuilder() + .build(), false); + for (Entry entry : holder.getNamedConfigurationBuilders().entrySet()) { - throw (Exception)cause;//NOSONAR - } - else - { - throw new Exception(e); + currentCacheManager.defineConfiguration(entry.getKey(), entry.getValue().build()); } + currentCacheManager.start(); + // We register this new cache manager + mappingGlobalConfigCacheManager.put(gc.transport().clusterName(), currentCacheManager); } + cacheManager = currentCacheManager; confBuilder.read(cacheManager.getDefaultCacheConfiguration()); } else if (config.isDistributed()) @@ -419,32 +373,9 @@ else if (config.isDistributed()) { public Cache call() throws Exception { - try - { - return SecurityHelper - .doPrivilegedExceptionAction(new PrivilegedExceptionAction>() - { - public Cache run() throws Exception - { - // Define the configuration - cacheManager.defineConfiguration(region, confBuilder.build()); - // create and start the cache - return cacheManager.getCache(region); - } - }); - } - catch (PrivilegedActionException e) - { - Throwable cause = e.getCause(); - if (cause instanceof Exception) - { - throw (Exception)cause;//NOSONAR - } - else - { - throw new Exception(e); - } - } + cacheManager.defineConfiguration(region, confBuilder.build()); + // create and start the cache + return cacheManager.getCache(region); } }); } diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/distributed/DistributedExoCache.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/distributed/DistributedExoCache.java index a5953d1b6..1e74abb46 100644 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/distributed/DistributedExoCache.java +++ b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/cache/impl/infinispan/distributed/DistributedExoCache.java @@ -18,7 +18,6 @@ */ package org.exoplatform.services.cache.impl.infinispan.distributed; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.management.annotations.Managed; @@ -56,7 +55,6 @@ import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; @@ -199,19 +197,9 @@ private List getListeners(String fullName) */ public void clearCache() { - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - - @Override - public Void run() - { - MapReduceTask, V, Void, Void> task = new MapReduceTask, V, Void, Void>(cache); - task.mappedWith(new ClearCacheMapper(fullName)).reducedWith(new ClearCacheReducer()); - task.execute(); - return null; - } - - }); + MapReduceTask, V, Void, Void> task = new MapReduceTask, V, Void, Void>(cache); + task.mappedWith(new ClearCacheMapper(fullName)).reducedWith(new ClearCacheReducer()); + task.execute(); onClearCache(); } @@ -227,16 +215,7 @@ public V get(Serializable name) } @SuppressWarnings("rawtypes") final CacheKey key = new CacheKey(fullName, name); - final V result = SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - - @Override - public V run() - { - return cache.get(key); - } - - }); + final V result = cache.get(key); if (result == null) { misses.incrementAndGet(); @@ -270,19 +249,9 @@ public int getCacheMiss() */ public int getCacheSize() { - Map map = SecurityHelper.doPrivilegedAction(new PrivilegedAction>() - { - - @Override - public Map run() - { - MapReduceTask, V, String, Integer> task = - new MapReduceTask, V, String, Integer>(cache); - task.mappedWith(new GetSizeMapper(fullName)).reducedWith(new GetSizeReducer()); - return task.execute(); - } - - }); + MapReduceTask, V, String, Integer> task = new MapReduceTask, V, String, Integer>(cache); + task.mappedWith(new GetSizeMapper(fullName)).reducedWith(new GetSizeReducer()); + Map map = task.execute(); int sum = 0; for (Integer i : map.values()) { @@ -296,20 +265,11 @@ public Map run() */ public List getCachedObjects() { - Map> map = SecurityHelper.doPrivilegedAction(new PrivilegedAction>>() - { - - @Override - public Map> run() - { - MapReduceTask, V, String, List> task = - new MapReduceTask, V, String, List>(cache); - task.mappedWith(new GetCachedObjectsMapper(fullName)).reducedWith( - new GetCachedObjectsReducer()); - return task.execute(); - } - - }); + MapReduceTask, V, String, List> task = + new MapReduceTask, V, String, List>(cache); + task.mappedWith(new GetCachedObjectsMapper(fullName)).reducedWith( + new GetCachedObjectsReducer()); + Map> map = task.execute(); List result = new ArrayList(); for (List vals : map.values()) { @@ -372,17 +332,7 @@ else if (value == null) // ignore null values return; } - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - - @Override - public Void run() - { - putOnly(key, value); - return null; - } - - }); + putOnly(key, value); onPut(key, value); } @@ -410,39 +360,30 @@ public void putMap(final Map objs) throws IllegalArgum throw new IllegalArgumentException("No null cache key accepted"); } } - SecurityHelper.doPrivilegedAction(new PrivilegedAction() + // Start transaction + cache.startBatch(); + try { - - @Override - public Void run() + // Wrap the key into a CacheKey and make sure that the key and the value + // are valid + Map, V> map = new LinkedHashMap, V>(); + for (Map.Entry entry : objs.entrySet()) { - // Start transaction - cache.startBatch(); - try - { - // Wrap the key into a CacheKey and make sure that the key and the value - // are valid - Map, V> map = new LinkedHashMap, V>(); - for (Map.Entry entry : objs.entrySet()) - { - map.put(new CacheKey(fullName, entry.getKey()), entry.getValue()); - } - cache.putAll(map); - cache.endBatch(true); - // End transaction - for (Map.Entry entry : objs.entrySet()) - { - onPut(entry.getKey(), entry.getValue()); - } - } - catch (Exception e)//NOSONAR - { - cache.endBatch(false); - LOG.warn("An error occurs while executing the putMap method", e); - } - return null; + map.put(new CacheKey(fullName, entry.getKey()), entry.getValue()); + } + cache.putAll(map); + cache.endBatch(true); + // End transaction + for (Map.Entry entry : objs.entrySet()) + { + onPut(entry.getKey(), entry.getValue()); } - }); + } + catch (Exception e)//NOSONAR + { + cache.endBatch(false); + LOG.warn("An error occurs while executing the putMap method", e); + } } /** @@ -457,14 +398,7 @@ public V remove(Serializable name) throws IllegalArgumentException } @SuppressWarnings("rawtypes") final CacheKey key = new CacheKey(fullName, name); - V result = SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - @Override - public V run() - { - return cache.remove(key); - } - }); + V result = cache.remove(key); onRemove(key, result); return result; } @@ -488,18 +422,9 @@ public void select(CachedObjectSelector selector) throws E { throw new IllegalArgumentException("No null selector"); } - Map map = SecurityHelper.doPrivilegedAction(new PrivilegedAction>() - { - - @Override - public Map run() - { - MapReduceTask, V, K, V> task = new MapReduceTask, V, K, V>(cache); - task.mappedWith(new GetEntriesMapper(fullName)).reducedWith(new GetEntriesReducer()); - return task.execute(); - } - - }); + MapReduceTask, V, K, V> task = new MapReduceTask, V, K, V>(cache); + task.mappedWith(new GetEntriesMapper(fullName)).reducedWith(new GetEntriesReducer()); + Map map = task.execute(); for (K key : map.keySet()) { @@ -1198,4 +1123,4 @@ public V reduce(K reducedKey, Iterator iter) return iter == null || !iter.hasNext() ? null : iter.next(); } } -} \ No newline at end of file +} diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/ispn/DistributedCacheManager.java b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/ispn/DistributedCacheManager.java index 5ae9ec389..570c53652 100644 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/ispn/DistributedCacheManager.java +++ b/exo.kernel.component.ext.cache.impl.infinispan.v8/src/main/java/org/exoplatform/services/ispn/DistributedCacheManager.java @@ -18,7 +18,6 @@ */ package org.exoplatform.services.ispn; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.container.util.TemplateConfigurationHelper; @@ -38,7 +37,6 @@ import org.infinispan.transaction.lookup.TransactionManagerLookup; import org.picocontainer.Startable; -import java.security.PrivilegedExceptionAction; import java.util.Map; import java.util.Map.Entry; @@ -145,41 +143,35 @@ private EmbeddedCacheManager init(final String configurationFile, final Map() + ParserRegistry parser = new ParserRegistry(Thread.currentThread().getContextClassLoader()); + // Load the configuration + ConfigurationBuilderHolder holder = parser.parse(helper.fillTemplate(configurationFile, parameters)); + GlobalConfigurationBuilder configBuilder = holder.getGlobalConfigurationBuilder(); + Utils.loadJGroupsConfig(configManager, configBuilder.build(), configBuilder); + // Create the CacheManager from the new configuration + EmbeddedCacheManager manager = + new DefaultCacheManager(configBuilder.build(), holder.getDefaultConfigurationBuilder().build()); + TransactionManagerLookup tml = new TransactionManagerLookup() { - public EmbeddedCacheManager run() throws Exception + public TransactionManager getTransactionManager() throws Exception { - ParserRegistry parser = new ParserRegistry(Thread.currentThread().getContextClassLoader()); - // Load the configuration - ConfigurationBuilderHolder holder = parser.parse(helper.fillTemplate(configurationFile, parameters)); - GlobalConfigurationBuilder configBuilder = holder.getGlobalConfigurationBuilder(); - Utils.loadJGroupsConfig(configManager, configBuilder.build(), configBuilder); - // Create the CacheManager from the new configuration - EmbeddedCacheManager manager = - new DefaultCacheManager(configBuilder.build(), holder.getDefaultConfigurationBuilder().build()); - TransactionManagerLookup tml = new TransactionManagerLookup() - { - public TransactionManager getTransactionManager() throws Exception - { - return tm; - } - }; - for (Entry entry : holder.getNamedConfigurationBuilders().entrySet()) - { - ConfigurationBuilder b = entry.getValue(); - if (tm != null) - { - b.transaction().transactionManagerLookup(tml); - } - manager.defineConfiguration(entry.getKey(), b.build()); - } - for( String cacheName : manager.getCacheNames()) - { - manager.getCache(cacheName); - } - return manager; + return tm; } - }); + }; + for (Entry entry : holder.getNamedConfigurationBuilders().entrySet()) + { + ConfigurationBuilder b = entry.getValue(); + if (tm != null) + { + b.transaction().transactionManagerLookup(tml); + } + manager.defineConfiguration(entry.getKey(), b.build()); + } + for( String cacheName : manager.getCacheNames()) + { + manager.getCache(cacheName); + } + return manager; } catch (Exception e)//NOSONAR { diff --git a/exo.kernel.container.mt/pom.xml b/exo.kernel.container.mt/pom.xml index a3f26e04b..ff960092f 100644 --- a/exo.kernel.container.mt/pom.xml +++ b/exo.kernel.container.mt/pom.xml @@ -31,10 +31,7 @@ eXo PLF:: Kernel :: Container Multi-Threaded Implementation of Container Multi-Threaded for Exoplatform SAS 'eXo Kernel' project. - - -Djava.security.manager=org.exoplatform.commons.test.TestSecurityManager -Djava.security.policy=${project.build.directory}/test-classes/test.policy ${debug.opts} 0.8 - diff --git a/exo.kernel.container.mt/src/main/java/org/exoplatform/container/ConcurrentContainerMT.java b/exo.kernel.container.mt/src/main/java/org/exoplatform/container/ConcurrentContainerMT.java index 30891f6e3..e66a320e9 100644 --- a/exo.kernel.container.mt/src/main/java/org/exoplatform/container/ConcurrentContainerMT.java +++ b/exo.kernel.container.mt/src/main/java/org/exoplatform/container/ConcurrentContainerMT.java @@ -19,7 +19,6 @@ package org.exoplatform.container; import org.exoplatform.commons.utils.PropertyManager; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.management.ManageableComponentAdapterFactoryMT; import org.exoplatform.container.spi.ComponentAdapter; import org.exoplatform.container.spi.ComponentAdapterFactory; @@ -38,7 +37,6 @@ import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -249,31 +247,24 @@ public List getComponentInstancesOfType(final Class componentType) thr { public void run() { - SecurityHelper.doPrivilegedAction(new PrivilegedAction() + ExoContainer oldContainer = ExoContainerContext.getCurrentContainerIfPresent(); + ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); + try { - public Void run() - { - ExoContainer oldContainer = ExoContainerContext.getCurrentContainerIfPresent(); - ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); - try - { - ExoContainerContext.setCurrentContainer(container); - Thread.currentThread().setContextClassLoader(cl); - Object o = getInstance(adapter, componentType, false); - if (o != null) - adapterToInstanceMap.put(adapter, o); - // This is to ensure all are added. (Indirect dependencies will be added - // from InstantiatingComponentAdapter). - addOrderedComponentAdapter(adapter); - } - finally - { - Thread.currentThread().setContextClassLoader(oldCl); - ExoContainerContext.setCurrentContainer(oldContainer); - } - return null; - } - }); + ExoContainerContext.setCurrentContainer(container); + Thread.currentThread().setContextClassLoader(cl); + Object o = getInstance(adapter, componentType, false); + if (o != null) + adapterToInstanceMap.put(adapter, o); + // This is to ensure all are added. (Indirect dependencies will be added + // from InstantiatingComponentAdapter). + addOrderedComponentAdapter(adapter); + } + finally + { + Thread.currentThread().setContextClassLoader(oldCl); + ExoContainerContext.setCurrentContainer(oldContainer); + } } }; if (submittedTasks == null) @@ -406,71 +397,64 @@ else if (alreadyStarted.containsKey(adapter) || (skippable && startInProgress.co { public void run() { - SecurityHelper.doPrivilegedAction(new PrivilegedAction() + if (error.get() != null) { - public Void run() + return; + } + else if (alreadyStarted.containsKey(adapter) + || (skippable && startInProgress.contains(adapter))) + { + // The component has already been started or is in progress + return; + } + ExoContainer oldContainer = ExoContainerContext.getCurrentContainerIfPresent(); + ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); + try + { + ExoContainerContext.setCurrentContainer(container); + Thread.currentThread().setContextClassLoader(cl); + if (adapter instanceof ComponentAdapterDependenciesAware) { - if (error.get() != null) - { - return null; - } - else if (alreadyStarted.containsKey(adapter) - || (skippable && startInProgress.contains(adapter))) + ComponentAdapterDependenciesAware cada = (ComponentAdapterDependenciesAware)adapter; + startDependencies(alreadyStarted, startInProgress, error, cada); + } + if (!Startable.class.isAssignableFrom(adapter.getComponentImplementation())) + { + alreadyStarted.put(adapter, adapter); + return; + } + else if (alreadyStarted.containsKey(adapter)) + { + // The component has already been started + return; + } + synchronized (adapter) + { + if (alreadyStarted.containsKey(adapter)) { - // The component has already been started or is in progress - return null; + // The component has already been started + return; } - ExoContainer oldContainer = ExoContainerContext.getCurrentContainerIfPresent(); - ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); try { - ExoContainerContext.setCurrentContainer(container); - Thread.currentThread().setContextClassLoader(cl); - if (adapter instanceof ComponentAdapterDependenciesAware) - { - ComponentAdapterDependenciesAware cada = (ComponentAdapterDependenciesAware)adapter; - startDependencies(alreadyStarted, startInProgress, error, cada); - } - if (!Startable.class.isAssignableFrom(adapter.getComponentImplementation())) - { - alreadyStarted.put(adapter, adapter); - return null; - } - else if (alreadyStarted.containsKey(adapter)) - { - // The component has already been started - return null; - } - synchronized (adapter) - { - if (alreadyStarted.containsKey(adapter)) - { - // The component has already been started - return null; - } - try - { - Startable startable = (Startable)adapter.getComponentInstance(); - startable.start(); - } - finally - { - alreadyStarted.put(adapter, adapter); - } - } - } - catch (Exception e) - { - error.compareAndSet(null, e); + Startable startable = (Startable)adapter.getComponentInstance(); + startable.start(); } finally { - Thread.currentThread().setContextClassLoader(oldCl); - ExoContainerContext.setCurrentContainer(oldContainer); + alreadyStarted.put(adapter, adapter); } - return null; } - }); + } + catch (Exception e) + { + error.compareAndSet(null, e); + } + finally + { + Thread.currentThread().setContextClassLoader(oldCl); + ExoContainerContext.setCurrentContainer(oldContainer); + } } }; if (submittedTasks == null) @@ -1009,28 +993,22 @@ public void loadDependencies(Object originalComponentKey, final ComponentTaskCon { public void run() { - SecurityHelper.doPrivilegedAction(new PrivilegedAction() + ExoContainer oldContainer = ExoContainerContext.getCurrentContainerIfPresent(); + ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); + ComponentTaskContext previousCtx = currentCtx.get(); + try { - public Object run() - { - ExoContainer oldContainer = ExoContainerContext.getCurrentContainerIfPresent(); - ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); - ComponentTaskContext previousCtx = currentCtx.get(); - try - { - ExoContainerContext.setCurrentContainer(container); - Thread.currentThread().setContextClassLoader(cl); - currentCtx.set(ctx.addToContext(dependency.getKey(), type)); - return dependency.load(holder); - } - finally - { - Thread.currentThread().setContextClassLoader(oldCl); - ExoContainerContext.setCurrentContainer(oldContainer); - currentCtx.set(previousCtx); - } - } - }); + ExoContainerContext.setCurrentContainer(container); + Thread.currentThread().setContextClassLoader(cl); + currentCtx.set(ctx.addToContext(dependency.getKey(), type)); + dependency.load(holder); + } + finally + { + Thread.currentThread().setContextClassLoader(oldCl); + ExoContainerContext.setCurrentContainer(oldContainer); + currentCtx.set(previousCtx); + } } }; if (submittedTasks == null) @@ -1232,8 +1210,7 @@ private static class KernelThreadFactory implements ThreadFactory KernelThreadFactory() { - SecurityManager s = System.getSecurityManager(); - group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); + group = Thread.currentThread().getThreadGroup(); namePrefix = "kernel-thread-"; } diff --git a/exo.kernel.container.mt/src/main/java/org/exoplatform/container/jmx/MX4JComponentAdapterMT.java b/exo.kernel.container.mt/src/main/java/org/exoplatform/container/jmx/MX4JComponentAdapterMT.java index a5e4f39bd..02b733923 100644 --- a/exo.kernel.container.mt/src/main/java/org/exoplatform/container/jmx/MX4JComponentAdapterMT.java +++ b/exo.kernel.container.mt/src/main/java/org/exoplatform/container/jmx/MX4JComponentAdapterMT.java @@ -20,7 +20,6 @@ import org.exoplatform.commons.utils.ClassLoading; import org.exoplatform.commons.utils.PropertyManager; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.ComponentAdapterDependenciesAware; import org.exoplatform.container.ComponentTask; import org.exoplatform.container.ComponentTaskContext; @@ -46,7 +45,6 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -368,14 +366,7 @@ public Void execute(final CreationalContextComponentAdapter cCtx) throws Exce } final Object[] params = {cplugin}; - SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public Void run() throws Exception - { - m.invoke(cCtx.get(), params); - return null; - } - }); + m.invoke(cCtx.get(), params); if (debug) LOG.debug("==> add component plugin: " + cplugin); diff --git a/exo.kernel.container/pom.xml b/exo.kernel.container/pom.xml index b0f7b22a9..442f91314 100644 --- a/exo.kernel.container/pom.xml +++ b/exo.kernel.container/pom.xml @@ -102,7 +102,6 @@ org.javassist javassist - provided ch.qos.logback @@ -111,12 +110,6 @@ - - maven-surefire-plugin - - @{argLine} -Djava.security.manager=org.exoplatform.commons.test.TestSecurityManager -Djava.security.policy=${project.build.directory}/test-classes/test.policy - - org.jibx maven-jibx-plugin diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/ConcurrentContainer.java b/exo.kernel.container/src/main/java/org/exoplatform/container/ConcurrentContainer.java index b8f15b750..4c54027f4 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/ConcurrentContainer.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/ConcurrentContainer.java @@ -231,10 +231,6 @@ public void registerComponentAdapter(ComponentAdapter componentAdapter) { */ protected ComponentAdapter registerComponent(ComponentAdapter componentAdapter) throws ContainerException { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_COMPONENT_PERMISSION); - Object componentKey = componentAdapter.getComponentKey(); if (componentKeyToAdapterCache.putIfAbsent(componentKey, componentAdapter) != null) { @@ -246,10 +242,6 @@ protected ComponentAdapter registerComponent(ComponentAdapter componentAda public ComponentAdapter unregisterComponent(Object componentKey) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_COMPONENT_PERMISSION); - ComponentAdapter adapter = componentKeyToAdapterCache.remove(componentKey); if (adapter instanceof InstanceComponentAdapter) { diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/ExoContainer.java b/exo.kernel.container/src/main/java/org/exoplatform/container/ExoContainer.java index 52a07614f..567605aa6 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/ExoContainer.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/ExoContainer.java @@ -20,11 +20,9 @@ import org.exoplatform.commons.utils.ClassLoading; import org.exoplatform.commons.utils.PropertyManager; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.component.ComponentLifecyclePlugin; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.container.context.ContextManager; -import org.exoplatform.container.security.ContainerPermissions; import org.exoplatform.container.spi.ComponentAdapter; import org.exoplatform.container.spi.Container; import org.exoplatform.container.spi.ContainerException; @@ -44,7 +42,6 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Modifier; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -198,14 +195,8 @@ public ExoContainer(ExoContainer parent) this.context = new ExoContainerContext(this, this.getClass().getSimpleName()); this.parent = parent; this.delegate = InterceptorChainFactoryProvider.getInterceptorChainFactory().getInterceptorChain(this, parent); - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - registerComponentInstance(context); - return null; - } - }); + registerComponentInstance(context); + } public ExoContainerContext getContext() @@ -257,10 +248,6 @@ protected void initContainerInternal() public synchronized void dispose() { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - if (canBeDisposed()) { destroyContainerInternal(); @@ -284,10 +271,6 @@ public synchronized void start(boolean init) public synchronized void initialize() { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - if (canBeInitialized()) { // Initialize the successors @@ -300,10 +283,6 @@ public synchronized void initialize() public synchronized void start() { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - if (canBeStarted()) { super.start(); @@ -314,10 +293,6 @@ public synchronized void start() public synchronized void stop() { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - if (canBeStopped()) { stopping.set(true); @@ -374,10 +349,6 @@ private void destroyContainerInternal() public void addComponentLifecylePlugin(ComponentLifecyclePlugin plugin) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - List list = plugin.getManageableComponents(); for (String component : list) componentLifecylePlugin_.put(component, plugin); @@ -385,10 +356,6 @@ public void addComponentLifecylePlugin(ComponentLifecyclePlugin plugin) public void addContainerLifecylePlugin(ContainerLifecyclePlugin plugin) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - containerLifecyclePlugin_.add(plugin); } @@ -717,81 +684,75 @@ public ComponentAdapter getComponentAdapterOfType(Class componentType, private boolean autoRegister(final DefinitionType definitionType, final Object componentKey, final Class componentType) { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() + Class type; + Class[] containers; + if (definitionType == DefinitionType.TYPE) + { + DefinitionByType definition = componentType.getAnnotation(DefinitionByType.class); + containers = definition.target(); + type = definition.type(); + } + else if (definitionType == DefinitionType.NAME) { - public Boolean run() + DefinitionByName definition = componentType.getAnnotation(DefinitionByName.class); + if (!definition.named().equals(componentKey)) { - Class type; - Class[] containers; - if (definitionType == DefinitionType.TYPE) - { - DefinitionByType definition = componentType.getAnnotation(DefinitionByType.class); - containers = definition.target(); - type = definition.type(); - } - else if (definitionType == DefinitionType.NAME) - { - DefinitionByName definition = componentType.getAnnotation(DefinitionByName.class); - if (!definition.named().equals(componentKey)) - { - return false; - } - containers = definition.target(); - type = definition.type(); - } - else - { - DefinitionByQualifier definition = componentType.getAnnotation(DefinitionByQualifier.class); - if (!definition.qualifier().equals(componentKey)) - { - return false; - } - containers = definition.target(); - type = definition.type(); - } - if (!accepts(containers)) - { - // The class of the current container is not part of the allowed classes. - return false; - } - if (type.equals(void.class)) - { - // No default implementation has been set - if (componentType.isInterface() || Modifier.isAbstract(componentType.getModifiers())) - { - throw new IllegalArgumentException("The class " + componentType.getName() - + " is an interface or an abstract class so it cannot be automatically registered without a type."); - } - if (definitionType == DefinitionType.TYPE) - { - registerComponentImplementation(componentType); - } - else - { - registerComponentImplementation(componentKey, componentType); - } - } - else if (!componentType.isAssignableFrom(type)) - { - throw new IllegalArgumentException("The class " + type.getName() + " must be a sub class of " - + componentType.getName() + "."); - } - else if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) - { - throw new IllegalArgumentException("The class " + type.getName() - + " is an interface or an abstract class so it cannot be used as default implementation."); - } - else if (definitionType == DefinitionType.TYPE) - { - registerComponentImplementation(componentType, type); - } - else - { - registerComponentImplementation(componentKey, type); - } - return true; + return false; + } + containers = definition.target(); + type = definition.type(); + } + else + { + DefinitionByQualifier definition = componentType.getAnnotation(DefinitionByQualifier.class); + if (!definition.qualifier().equals(componentKey)) + { + return false; + } + containers = definition.target(); + type = definition.type(); + } + if (!accepts(containers)) + { + // The class of the current container is not part of the allowed classes. + return false; + } + if (type.equals(void.class)) + { + // No default implementation has been set + if (componentType.isInterface() || Modifier.isAbstract(componentType.getModifiers())) + { + throw new IllegalArgumentException("The class " + componentType.getName() + + " is an interface or an abstract class so it cannot be automatically registered without a type."); + } + if (definitionType == DefinitionType.TYPE) + { + registerComponentImplementation(componentType); + } + else + { + registerComponentImplementation(componentKey, componentType); } - }); + } + else if (!componentType.isAssignableFrom(type)) + { + throw new IllegalArgumentException("The class " + type.getName() + " must be a sub class of " + + componentType.getName() + "."); + } + else if (type.isInterface() || Modifier.isAbstract(type.getModifiers())) + { + throw new IllegalArgumentException("The class " + type.getName() + + " is an interface or an abstract class so it cannot be used as default implementation."); + } + else if (definitionType == DefinitionType.TYPE) + { + registerComponentImplementation(componentType, type); + } + else + { + registerComponentImplementation(componentKey, type); + } + return true; } /** diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/ExoContainerContext.java b/exo.kernel.container/src/main/java/org/exoplatform/container/ExoContainerContext.java index dcf160989..d948aacb0 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/ExoContainerContext.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/ExoContainerContext.java @@ -131,9 +131,6 @@ public String getName() */ public void setName(String name) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); this.name = name; } /** @@ -152,10 +149,6 @@ public static ExoContainer getTopContainer() */ static void setTopContainer(ExoContainer cont) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - if (topContainer != null && cont != null && cont != topContainer) //NOSONAR { throw new IllegalStateException("Two top level containers created, but must be only one."); @@ -195,9 +188,6 @@ public static ExoContainer getCurrentContainerIfPresent() */ public static void setCurrentContainer(ExoContainer instance) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); currentContainer.set(instance == null ? null : new WeakReference(instance)); } /** @@ -233,10 +223,6 @@ public Object getAttribute(String name) */ public void setAttribute(String name, Object value) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - attributes.put(name, value); } diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/PortalContainer.java b/exo.kernel.container/src/main/java/org/exoplatform/container/PortalContainer.java index 567bac4e7..3ee1de28d 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/PortalContainer.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/PortalContainer.java @@ -19,12 +19,10 @@ package org.exoplatform.container; import org.exoplatform.commons.utils.PropertyManager; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.RootContainer.PortalContainerInitTask; import org.exoplatform.container.RootContainer.PortalContainerPostInitTask; import org.exoplatform.container.RootContainer.PortalContainerPreInitTask; import org.exoplatform.container.definition.PortalContainerConfig; -import org.exoplatform.container.security.ContainerPermissions; import org.exoplatform.container.util.ContainerUtil; import org.exoplatform.container.xml.Configuration; import org.exoplatform.container.xml.PortalContainerInfo; @@ -35,7 +33,6 @@ import org.exoplatform.management.jmx.annotations.Property; import org.exoplatform.management.rest.annotations.RESTEndpoint; -import java.security.PrivilegedAction; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; @@ -140,24 +137,11 @@ public PortalContainer(RootContainer parent, final ServletContext portalContext) { super(parent); this.name = ContainerUtil.getServletContextName(portalContext); - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - context.setName(name); - return null; - } - }); + context.setName(name); + pinfo_ = new PortalContainerInfo(portalContext); - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - registerComponentInstance(ServletContext.class, portalContext); - registerComponentInstance(PortalContainerInfo.class, pinfo_); - return null; - } - }); + registerComponentInstance(ServletContext.class, portalContext); + registerComponentInstance(PortalContainerInfo.class, pinfo_); final PortalContainerConfig config = parent.getPortalContainerConfig(); final List dependencies = config == null ? null : config.getDependencies(name); if (dependencies == null || dependencies.isEmpty()) @@ -172,13 +156,7 @@ public Void run() this.webAppContexts = Collections.singleton(new WebAppInitContext(portalContext)); this.portalContext = portalContext; this.portalMergedContext = new PortalContainerContext(this); - this.portalMergedClassLoader = SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public ClassLoader run() - { - return new PortalContainerClassLoader(PortalContainer.this); - } - }); + this.portalMergedClassLoader = new PortalContainerClassLoader(PortalContainer.this); this.webAppClassLoaders = Collections.unmodifiableMap(Collections.singletonMap(name, portalMergedClassLoader)); } @@ -248,9 +226,6 @@ public ServletContext getPortalContext() */ public synchronized void registerContext(ServletContext context) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); final WebAppInitContext webappCtx = new WebAppInitContext(context); if (!webAppContexts.contains(webappCtx)) { @@ -275,10 +250,6 @@ public synchronized void registerContext(ServletContext context) */ public synchronized void unregisterContext(ServletContext context) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - final WebAppInitContext webappCtx = new WebAppInitContext(context); if (webAppContexts.contains(webappCtx)) { @@ -343,14 +314,7 @@ public static PortalContainer getInstance() { container = RootContainer.getInstance().getPortalContainer(DEFAULT_PORTAL_CONTAINER_NAME); final PortalContainer currentPortalContainer = container; - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - PortalContainer.setInstance(currentPortalContainer); - return null; - } - }); + PortalContainer.setInstance(currentPortalContainer); } return container; } diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/RootContainer.java b/exo.kernel.container/src/main/java/org/exoplatform/container/RootContainer.java index bc91a0483..e6b8aedeb 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/RootContainer.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/RootContainer.java @@ -18,9 +18,7 @@ */ package org.exoplatform.container; -import org.exoplatform.commons.utils.PrivilegedFileHelper; import org.exoplatform.commons.utils.PropertyManager; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.ar.Archive; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.container.configuration.ConfigurationManagerImpl; @@ -28,7 +26,6 @@ import org.exoplatform.container.definition.PortalContainerDefinition; import org.exoplatform.container.monitor.jvm.J2EEServerInfo; import org.exoplatform.container.monitor.jvm.OperatingSystemInfo; -import org.exoplatform.container.security.ContainerPermissions; import org.exoplatform.container.spi.ContainerException; import org.exoplatform.container.util.ContainerUtil; import org.exoplatform.container.xml.Configuration; @@ -51,9 +48,6 @@ import java.io.File; import java.lang.ref.WeakReference; import java.net.URL; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; @@ -173,31 +167,18 @@ public RootContainer() profiles.addAll(ExoContainer.getProfilesFromProperty()); // - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - Runtime.getRuntime().addShutdownHook(hook); - return null; - } - }); + Runtime.getRuntime().addShutdownHook(hook); + // Log the active profiles LOG.info("Active profiles for Root container: " + profiles); - SecurityHelper.doPrivilegedAction(new PrivilegedAction() + registerComponentInstance(J2EEServerInfo.class, serverenv_); + if (PropertyManager.isDevelopping()) { - public Void run() - { - registerComponentInstance(J2EEServerInfo.class, serverenv_); - if (PropertyManager.isDevelopping()) - { - loadingCL = Thread.currentThread().getContextClassLoader(); - loadingSystemProperties = (Properties)System.getProperties().clone(); - } - return null; - } - }); + loadingCL = Thread.currentThread().getContextClassLoader(); + loadingSystemProperties = (Properties)System.getProperties().clone(); + } } public OperatingSystemInfo getOSEnvironment() @@ -263,29 +244,16 @@ public PortalContainer getPortalContainer(final String name) MockServletContext scontext = new MockServletContext(name); pcontainer = new PortalContainer(this, scontext); final PortalContainer currentPortalContainer = pcontainer; - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - PortalContainer.setInstance(currentPortalContainer); - return null; - } - }); + PortalContainer.setInstance(currentPortalContainer); + final ConfigurationManagerImpl cService = new MockConfigurationManagerImpl(scontext); cService.addConfiguration(ContainerUtil.getConfigurationURL("conf/portal/configuration.xml")); cService.addConfiguration(ContainerUtil.getConfigurationURL("conf/portal/test-configuration.xml")); cService.processRemoveConfiguration(); - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - currentPortalContainer.registerComponentInstance(ConfigurationManager.class, cService); - registerComponentInstance(name, currentPortalContainer); - currentPortalContainer.start(true); - onStartupComplete(); - return null; - } - }); + currentPortalContainer.registerComponentInstance(ConfigurationManager.class, cService); + registerComponentInstance(name, currentPortalContainer); + currentPortalContainer.start(true); + onStartupComplete(); } catch (Exception ex) { @@ -304,10 +272,6 @@ public Void run() */ public void registerPortalContainer(ServletContext context) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - PortalContainerConfig config = getPortalContainerConfig(); if (config.hasDefinition()) { @@ -688,10 +652,6 @@ private void cleanupSessions() */ public synchronized void createPortalContainer(ServletContext context) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - // Keep the old ClassLoader final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); boolean hasChanged = false; @@ -849,10 +809,6 @@ private void showDependencies(final String portalContainerName) */ synchronized public void removePortalContainer(ServletContext servletContext) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - this.unregisterComponent(ContainerUtil.getServletContextName(servletContext)); } @@ -871,23 +827,16 @@ private static RootContainer buildRootContainer() { try { - return SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public RootContainer run() throws Exception - { - RootContainer rootContainer = new RootContainer(); - ConfigurationManager service = loadConfigurationManager(rootContainer, true); - rootContainer.registerComponentInstance(ConfigurationManager.class, service); - rootContainer.start(true); - return rootContainer; - } - }); + RootContainer rootContainer = new RootContainer(); + ConfigurationManager service = loadConfigurationManager(rootContainer, true); + rootContainer.registerComponentInstance(ConfigurationManager.class, service); + rootContainer.start(true); + return rootContainer; } - catch (PrivilegedActionException e) + catch (Exception e) { - Exception cause = e.getException(); - LOG.error("Could not build root container", cause); - LOG.error(e.getLocalizedMessage(), cause); + LOG.error("Could not build root container", e); + LOG.error(e.getLocalizedMessage(), e); return null; } } @@ -914,7 +863,7 @@ private static ConfigurationManager loadConfigurationManager(RootContainer rootC String confDir = serverEnv.getExoConfigurationDirectory(); String overrideConf = confDir + "/configuration.xml"; File file = new File(overrideConf); - if (PrivilegedFileHelper.exists(file)) + if (file.exists()) { service.addConfiguration("file:" + overrideConf); } @@ -963,14 +912,8 @@ public static RootContainer getInstance() time += System.currentTimeMillis(); LOG.info("Root container is built (build time " + time + "ms)"); singleton_ = result; - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - ExoContainerContext.setTopContainer(singleton_); - return null; - } - }); + ExoContainerContext.setTopContainer(singleton_); + LOG.info("Root container booted"); } else @@ -994,10 +937,6 @@ public Void run() */ static public void setInstance(RootContainer rcontainer) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - singleton_ = rcontainer; } /** @@ -1046,14 +985,8 @@ else if (stopping.get()) singleton_ = null; LOG.info("All the containers have been stopped successfully"); // We unregister the root container - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - Runtime.getRuntime().removeShutdownHook(hook); - return null; - } - }); + Runtime.getRuntime().removeShutdownHook(hook); + ServletContainerFactory.getServletContainer().removeWebAppListener(this); ServletContainerFactory.getServletContainer().removeAuthenticationlistener(this); LOG.info("Trying to restart the root container"); @@ -1191,10 +1124,6 @@ public void addInitTask(ServletContext context, PortalContainerInitTask task) */ public void addInitTask(ServletContext context, PortalContainerInitTask task, String portalContainer) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - final PortalContainer container = getPortalContainer(portalContainer); if (!task.alreadyExists(container) || lastUpdateTime.get() > 0) { @@ -1391,14 +1320,7 @@ static class ShutdownThread extends Thread @Override public void run() { - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - container_.stop(); - return null; - } - }); + container_.stop(); } } diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/StandaloneContainer.java b/exo.kernel.container/src/main/java/org/exoplatform/container/StandaloneContainer.java index c2e0f0c0f..ee0147a3f 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/StandaloneContainer.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/StandaloneContainer.java @@ -18,8 +18,6 @@ */ package org.exoplatform.container; -import org.exoplatform.commons.utils.PrivilegedSystemHelper; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.configuration.ConfigurationException; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.container.configuration.ConfigurationManagerImpl; @@ -38,8 +36,6 @@ import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @@ -92,18 +88,11 @@ private StandaloneContainer(ClassLoader configClassLoader) { // configurationManager = new ConfigurationManagerImpl(configClassLoader, ExoContainer.getProfilesFromProperty()); - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - registerComponentInstance(ConfigurationManager.class, configurationManager); - // Workaround used to allow to use the PropertyConfigurator with the StandaloneContainer - // If the system property PropertyManager.PROPERTIES_URL has been set properly, it will load the properties - // from the file and load them as system properties - new PropertyConfigurator(configurationManager); - return null; - } - }); + registerComponentInstance(ConfigurationManager.class, configurationManager); + // Workaround used to allow to use the PropertyConfigurator with the StandaloneContainer + // If the system property PropertyManager.PROPERTIES_URL has been set properly, it will load the properties + // from the file and load them as system properties + new PropertyConfigurator(configurationManager); } /** @@ -173,14 +162,8 @@ private static StandaloneContainer createNStartContainer(ClassLoader configClass MalformedURLException, ConfigurationException { final StandaloneContainer container = new StandaloneContainer(configClassLoader); - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - ExoContainerContext.setTopContainer(container); - return null; - } - }); + ExoContainerContext.setTopContainer(container); + if (useDefault) container.initDefaultConf(); // initialize configurationURL @@ -188,15 +171,8 @@ public Void run() container.populate(configurationURL); if (components != null) container.registerArray(components); - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - container.start(true); - return null; - } - }); - PrivilegedSystemHelper.setProperty("exo.standalone-container", StandaloneContainer.class.getName()); + container.start(true); + System.setProperty("exo.standalone-container", StandaloneContainer.class.getName()); LOG.info("StandaloneContainer initialized using: " + configurationURL); container.onStartupComplete(); return container; @@ -278,13 +254,7 @@ public static void addConfigurationPath(final String path) throws MalformedURLEx if ((path == null) || (path.length() == 0)) return; - URL confURL = SecurityHelper.doPrivilegedMalformedURLExceptionAction(new PrivilegedExceptionAction() - { - public URL run() throws Exception - { - return new File(path).toURI().toURL(); - } - }); + URL confURL = new File(path).toURI().toURL(); configurationURL = fileExists(confURL) ? confURL : null; } @@ -341,14 +311,7 @@ private static boolean fileExists(final URL url) { try { - SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction() - { - public Void run() throws IOException - { - url.openStream().close(); - return null; - } - }); + url.openStream().close(); return true; } catch (IOException e) @@ -388,26 +351,12 @@ private static URL getConfigurationURL(ClassLoader configClassLoader) throws Mal final J2EEServerInfo env = new J2EEServerInfo(); // (2) exo-configuration.xml in AS (standalone) home directory - URL configurationURL = - SecurityHelper.doPrivilegedMalformedURLExceptionAction(new PrivilegedExceptionAction() - { - public URL run() throws Exception - { - return (new File(env.getServerHome() + "/exo-configuration.xml")).toURI().toURL(); - } - }); + URL configurationURL = (new File(env.getServerHome() + "/exo-configuration.xml")).toURI().toURL(); // (3) AS_HOME/conf/exo-conf (JBossAS usecase) if (!fileExists(configurationURL)) { - configurationURL = - SecurityHelper.doPrivilegedMalformedURLExceptionAction(new PrivilegedExceptionAction() - { - public URL run() throws Exception - { - return (new File(env.getExoConfigurationDirectory() + "/exo-configuration.xml")).toURI().toURL(); - } - }); + configurationURL = (new File(env.getExoConfigurationDirectory() + "/exo-configuration.xml")).toURI().toURL(); } // (4) conf/exo-configuration.xml in war/ear(?) @@ -439,14 +388,7 @@ private void populate(URL conf) throws Exception { configurationManager.addConfiguration(conf); configurationManager.processRemoveConfiguration(); - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - ContainerUtil.addComponents(StandaloneContainer.this, configurationManager); - return null; - } - }); + ContainerUtil.addComponents(StandaloneContainer.this, configurationManager); } /** diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/UnifiedClassLoader.java b/exo.kernel.container/src/main/java/org/exoplatform/container/UnifiedClassLoader.java index 2b7d15331..48b31a0a7 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/UnifiedClassLoader.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/UnifiedClassLoader.java @@ -18,10 +18,8 @@ */ package org.exoplatform.container; -import org.exoplatform.commons.utils.SecurityHelper; import java.io.IOException; import java.net.URL; -import java.security.PrivilegedAction; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashSet; @@ -133,12 +131,6 @@ public Enumeration getResources(String name) throws IOException static protected UnifiedClassLoader createUnifiedClassLoaderInPrivilegedMode(final ClassLoader... cls) { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public UnifiedClassLoader run() - { - return new UnifiedClassLoader(cls); - } - }); + return new UnifiedClassLoader(cls); } } diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/ar/Archive.java b/exo.kernel.container/src/main/java/org/exoplatform/container/ar/Archive.java index ac63c52b0..7c1ddc551 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/ar/Archive.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/ar/Archive.java @@ -18,7 +18,6 @@ */ package org.exoplatform.container.ar; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.xml.Deserializer; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; @@ -28,7 +27,6 @@ import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; -import java.security.PrivilegedExceptionAction; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -448,13 +446,7 @@ public static URL createArchiveURL(String url) throws MalformedURLException // we ensure that we don't have windows path separator in the url url = url.replace('\\', '/'); final String sUrl = url; - return SecurityHelper.doPrivilegedMalformedURLExceptionAction(new PrivilegedExceptionAction() - { - public URL run() throws Exception - { - return new URL(null, sUrl, HANDLER); - } - }); + return new URL(null, sUrl, HANDLER); } /** diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/component/ThreadContext.java b/exo.kernel.container/src/main/java/org/exoplatform/container/component/ThreadContext.java index 40832dc57..468bd09e3 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/component/ThreadContext.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/component/ThreadContext.java @@ -50,9 +50,6 @@ public class ThreadContext @SuppressWarnings("unchecked") public ThreadContext(ThreadLocal... threadLocals) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ThreadContextHolder.MANAGE_THREAD_LOCAL); this.threadLocals = (ThreadLocal[])threadLocals; } @@ -63,9 +60,6 @@ public ThreadContext(ThreadLocal... threadLocals) @SuppressWarnings("unchecked") private ThreadContext(List contexts) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ThreadContextHolder.MANAGE_THREAD_LOCAL); if (contexts == null) { this.threadLocals = null; diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/component/ThreadContextHandler.java b/exo.kernel.container/src/main/java/org/exoplatform/container/component/ThreadContextHandler.java index fbb173144..c5da1e35a 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/component/ThreadContextHandler.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/component/ThreadContextHandler.java @@ -18,10 +18,8 @@ */ package org.exoplatform.container.component; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.ExoContainer; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.List; @@ -58,25 +56,18 @@ public void store() components.addAll((List)current.getComponentInstancesOfType(ThreadContextHolder.class)); } contexts = new ArrayList(components.size()); - SecurityHelper.doPrivilegedAction(new PrivilegedAction() + for (int i = 0, length = components.size(); i < length; i++) { - public Void run() + ThreadContextHolder holder = components.get(i); + ThreadContext tc = holder.getThreadContext(); + if (tc == null) { - for (int i = 0, length = components.size(); i < length; i++) - { - ThreadContextHolder holder = components.get(i); - ThreadContext tc = holder.getThreadContext(); - if (tc == null) - { - // This ThreadContextHolder has nothing valuable to share so we skip it - continue; - } - contexts.add(tc); - tc.store(); - } - return null; + // This ThreadContextHolder has nothing valuable to share so we skip it + continue; } - }); + contexts.add(tc); + tc.store(); + } } /** diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/ConfigurationManager.java b/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/ConfigurationManager.java index b62218274..9583a44be 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/ConfigurationManager.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/ConfigurationManager.java @@ -18,7 +18,6 @@ */ package org.exoplatform.container.configuration; -import org.exoplatform.commons.utils.PrivilegedSystemHelper; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.xml.Component; import org.exoplatform.container.xml.Configuration; @@ -63,7 +62,7 @@ public interface ConfigurationManager * Constant that indicates whether the logger of the configuration * must be in debug more or not. */ - public static final boolean LOG_DEBUG = PrivilegedSystemHelper.getProperty(LOG_DEBUG_PROPERTY) != null; + public static final boolean LOG_DEBUG = System.getProperty(LOG_DEBUG_PROPERTY) != null; /** * Gives the entire configuration diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/ConfigurationManagerImpl.java b/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/ConfigurationManagerImpl.java index fa0811791..8f44e9113 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/ConfigurationManagerImpl.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/ConfigurationManagerImpl.java @@ -18,7 +18,6 @@ */ package org.exoplatform.container.configuration; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.ar.Archive; import org.exoplatform.container.xml.Component; import org.exoplatform.container.xml.Configuration; @@ -30,8 +29,6 @@ import java.io.IOException; import java.io.InputStream; import java.net.URL; -import java.security.PrivilegedAction; -import java.security.PrivilegedExceptionAction; import java.util.Collection; import java.util.Collections; import java.util.Iterator; @@ -317,13 +314,7 @@ public InputStream getInputStream(String uri) throws Exception + ") could not be found or the invoker doesn't have adequate privileges to get the resource"); } - return SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction() - { - public InputStream run() throws Exception - { - return url.openStream(); - } - }); + return url.openStream(); } public URL getURL(String url) throws Exception @@ -346,13 +337,7 @@ else if (url.startsWith("jar:")) } final ClassLoader cl = Thread.currentThread().getContextClassLoader(); final String finalPath = path; - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public URL run() - { - return cl.getResource(finalPath); - } - }); + return cl.getResource(finalPath); } else if (url.startsWith("classpath:")) { @@ -363,13 +348,7 @@ else if (url.startsWith("classpath:")) } final ClassLoader cl = Thread.currentThread().getContextClassLoader(); final String finalPath = path; - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public URL run() - { - return cl.getResource(finalPath); - } - }); + return cl.getResource(finalPath); } else if (url.startsWith("war:")) { @@ -377,13 +356,7 @@ else if (url.startsWith("war:")) if (context != null) { final String fPath = path; - return SecurityHelper.doPrivilegedMalformedURLExceptionAction(new PrivilegedExceptionAction() - { - public URL run() throws Exception - { - return context.getResource(WAR_CONF_LOCATION + fPath); - } - }); + return context.getResource(WAR_CONF_LOCATION + fPath); } if (scontextClassLoader_ != null) { @@ -393,13 +366,7 @@ public URL run() throws Exception path = path.substring(1); } final String fPath = path; - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public URL run() - { - return scontextClassLoader_.getResource(fPath); - } - }); + return scontextClassLoader_.getResource(fPath); } throw new Exception("unsupport war uri in this configuration service"); } diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/ConfigurationUnmarshaller.java b/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/ConfigurationUnmarshaller.java index 9810f45a9..bc493e96c 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/ConfigurationUnmarshaller.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/ConfigurationUnmarshaller.java @@ -19,7 +19,6 @@ package org.exoplatform.container.configuration; import org.exoplatform.commons.utils.PropertyManager; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.util.Utils; import org.exoplatform.container.xml.Configuration; import org.exoplatform.container.xml.Deserializer; @@ -28,7 +27,6 @@ import org.jibx.runtime.BindingDirectory; import org.jibx.runtime.IBindingFactory; import org.jibx.runtime.IUnmarshallingContext; -import org.jibx.runtime.JiBXException; import org.w3c.dom.Document; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; @@ -41,8 +39,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.Collections; import java.util.Set; @@ -52,9 +48,6 @@ import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXTransformerFactory; @@ -155,33 +148,27 @@ public boolean isValid(final URL url) throws NullPointerException, IOException factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", KERNEL_NAMESPACES); factory.setNamespaceAware(true); factory.setValidating(true); - return SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction() + try { - public Boolean run() throws Exception - { - try - { - DocumentBuilder builder = factory.newDocumentBuilder(); - Reporter reporter = new Reporter(url); - builder.setErrorHandler(reporter); - builder.setEntityResolver(Namespaces.resolver); - String content = Deserializer.resolveVariables(Utils.readStream(url.openStream())); - InputSource is = new InputSource(new StringReader(content)); - builder.parse(is); - return reporter.valid; - } - catch (ParserConfigurationException e) - { - LOG.error("Got a parser configuration exception when doing XSD validation"); - return false; - } - catch (SAXException e) - { - LOG.error("Got a sax exception when doing XSD validation"); - return false; - } - } - }); + DocumentBuilder builder = factory.newDocumentBuilder(); + Reporter reporter = new Reporter(url); + builder.setErrorHandler(reporter); + builder.setEntityResolver(Namespaces.resolver); + String content = Deserializer.resolveVariables(Utils.readStream(url.openStream())); + InputSource is = new InputSource(new StringReader(content)); + builder.parse(is); + return reporter.valid; + } + catch (ParserConfigurationException e) + { + LOG.error("Got a parser configuration exception when doing XSD validation"); + return false; + } + catch (SAXException e) + { + LOG.error("Got a sax exception when doing XSD validation"); + return false; + } } public Configuration unmarshall(final URL url) throws Exception @@ -240,93 +227,40 @@ public Configuration unmarshall(final URL url) throws Exception factory.setNamespaceAware(true); final DocumentBuilderFactory builderFactory = factory; - try - { - return SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public Configuration run() throws Exception - { - DocumentBuilder builder = builderFactory.newDocumentBuilder(); - Document doc = builder.parse(url.openStream()); + DocumentBuilder builder = builderFactory.newDocumentBuilder(); + Document doc = builder.parse(url.openStream()); - // Filter DOM - ProfileDOMFilter filter = new ProfileDOMFilter(profiles); - filter.process(doc.getDocumentElement()); + // Filter DOM + ProfileDOMFilter filter = new ProfileDOMFilter(profiles); + filter.process(doc.getDocumentElement()); - // SAX event stream -> String - StringWriter buffer = new StringWriter(); - SAXTransformerFactory tf = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); - TransformerHandler hd = tf.newTransformerHandler(); - StreamResult result = new StreamResult(buffer); - hd.setResult(result); - Transformer serializer = tf.newTransformer(); - serializer.setOutputProperty(OutputKeys.ENCODING, "UTF8"); - serializer.setOutputProperty(OutputKeys.INDENT, "yes"); + // SAX event stream -> String + StringWriter buffer = new StringWriter(); + SAXTransformerFactory tf = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); + TransformerHandler hd = tf.newTransformerHandler(); + StreamResult result = new StreamResult(buffer); + hd.setResult(result); + Transformer serializer = tf.newTransformer(); + serializer.setOutputProperty(OutputKeys.ENCODING, "UTF8"); + serializer.setOutputProperty(OutputKeys.INDENT, "yes"); - // Transform -> SAX event stream - SAXResult saxResult = new SAXResult(new NoKernelNamespaceSAXFilter(hd)); + // Transform -> SAX event stream + SAXResult saxResult = new SAXResult(new NoKernelNamespaceSAXFilter(hd)); - // DOM -> Transform - serializer.transform(new DOMSource(doc), saxResult); + // DOM -> Transform + serializer.transform(new DOMSource(doc), saxResult); - // Reuse the parsed document - String document = buffer.toString(); + // Reuse the parsed document + String document = buffer.toString(); - // Debug - if (LOG.isTraceEnabled()) - LOG.trace("About to parse configuration file " + document); + // Debug + if (LOG.isTraceEnabled()) + LOG.trace("About to parse configuration file " + document); - // - IBindingFactory bfact = BindingDirectory.getFactory(Configuration.class); - IUnmarshallingContext uctx = bfact.createUnmarshallingContext(); + // + IBindingFactory bfact = BindingDirectory.getFactory(Configuration.class); + IUnmarshallingContext uctx = bfact.createUnmarshallingContext(); - return (Configuration)uctx.unmarshalDocument(new StringReader(document), null); - } - }); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof JiBXException) - { - throw (JiBXException)cause; - } - else if (cause instanceof ParserConfigurationException) - { - throw (ParserConfigurationException)cause; - } - else if (cause instanceof IOException) - { - throw (IOException)cause; - } - else if (cause instanceof SAXException) - { - throw (SAXException)cause; - } - else if (cause instanceof IllegalArgumentException) - { - throw (IllegalArgumentException)cause; - } - else if (cause instanceof TransformerException) - { - throw (TransformerException)cause; - } - else if (cause instanceof TransformerConfigurationException) - { - throw (TransformerConfigurationException)cause; - } - else if (cause instanceof TransformerFactoryConfigurationError) - { - throw (TransformerFactoryConfigurationError)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } + return (Configuration)uctx.unmarshalDocument(new StringReader(document), null); } } diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/EntityResolverImpl.java b/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/EntityResolverImpl.java index 6a821137d..55c4bd5de 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/EntityResolverImpl.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/configuration/EntityResolverImpl.java @@ -19,7 +19,6 @@ package org.exoplatform.container.configuration; import org.exoplatform.commons.utils.IOUtil; -import org.exoplatform.commons.utils.SecurityHelper; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -27,7 +26,6 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.security.PrivilegedAction; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -69,13 +67,7 @@ public InputSource resolveEntity(String publicId, String systemId) throws SAXExc final String path = systemIdToResourcePath.get(systemId); if (path != null) { - InputStream in = SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public InputStream run() - { - return loader.getResourceAsStream(path); - } - }); + InputStream in = loader.getResourceAsStream(path); if (in != null) { diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/definition/PortalContainerConfig.java b/exo.kernel.container/src/main/java/org/exoplatform/container/definition/PortalContainerConfig.java index 9838114c4..38044a265 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/definition/PortalContainerConfig.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/definition/PortalContainerConfig.java @@ -18,14 +18,12 @@ */ package org.exoplatform.container.definition; -import org.exoplatform.commons.utils.PrivilegedFileHelper; import org.exoplatform.commons.utils.PropertyManager; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.PropertyConfigurator; import org.exoplatform.container.RootContainer; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.container.monitor.jvm.J2EEServerInfo; -import org.exoplatform.container.security.ContainerPermissions; import org.exoplatform.container.util.ContainerUtil; import org.exoplatform.container.xml.Deserializer; import org.exoplatform.container.xml.InitParams; @@ -381,10 +379,6 @@ public boolean hasDefinition() */ public synchronized void disablePortalContainer(String name) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - if (!portalContainerNamesDisabled.contains(name)) { if (PropertyManager.isDevelopping()) @@ -447,10 +441,6 @@ public boolean isPortalContainerNameDisabled(String name) */ public synchronized void registerPortalContainerName(String name) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - if (!portalContainerNames.contains(name) && !portalContainerNamesDisabled.contains(name)) { final List lPortalContainerNames = new ArrayList(portalContainerNames.size() + 1); @@ -466,10 +456,6 @@ public synchronized void registerPortalContainerName(String name) */ public synchronized void unregisterPortalContainerName(String name) { - SecurityManager security = System.getSecurityManager(); - if (security != null) - security.checkPermission(ContainerPermissions.MANAGE_CONTAINER_PERMISSION); - if (portalContainerNames.contains(name)) { final List lPortalContainerNames = new ArrayList(portalContainerNames); @@ -1001,7 +987,7 @@ private Map loadExternalSettings(String path, boolean isPath4Def serverInfo.getExoConfigurationDirectory() + "/portal/" + (isPath4DefaultPCD ? "" : def.getName() + "/") + path; File file = new File(fullPath); - if (PrivilegedFileHelper.exists(file)) + if (file.exists()) { // The file exists so we will use it url = file.toURI().toURL(); diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/jmx/MX4JComponentAdapter.java b/exo.kernel.container/src/main/java/org/exoplatform/container/jmx/MX4JComponentAdapter.java index 028d6801d..018c7e4b7 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/jmx/MX4JComponentAdapter.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/jmx/MX4JComponentAdapter.java @@ -21,7 +21,6 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; import org.exoplatform.commons.utils.ClassLoading; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.AbstractComponentAdapter; import org.exoplatform.container.ConcurrentContainer; import org.exoplatform.container.ConcurrentContainer.CreationalContextComponentAdapter; @@ -44,8 +43,6 @@ import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.reflect.Method; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; @@ -264,86 +261,68 @@ private T createInstance(final CreationalContextComponentAdapter ctx, final C final ConfigurationManager manager, final String componentKey, final InitParams params, final boolean debug) throws Exception { - try + T instance; + final Class implementationClass = getComponentImplementation(); + // Please note that we cannot fully initialize the Object "instance_" before releasing other + // threads because it could cause StackOverflowError due to recursive calls + instance = exocontainer.createComponent(implementationClass, params); + if (instance_ != null) { - return SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public T run() throws Exception - { - T instance; - final Class implementationClass = getComponentImplementation(); - // Please note that we cannot fully initialize the Object "instance_" before releasing other - // threads because it could cause StackOverflowError due to recursive calls - instance = exocontainer.createComponent(implementationClass, params); - if (instance_ != null) - { - // Avoid instantiating twice the same component in case of a cyclic reference due - // to component plugins - return instance_; - } - else if (ctx.get() != null) - return ctx.get(); - - ctx.push(instance); - boolean isSingleton = MX4JComponentAdapter.this.isSingleton; - boolean isInitialized = MX4JComponentAdapter.this.isInitialized; - if (debug) - LOG.debug("==> create component : " + instance); - boolean hasInjectableConstructor = - !isSingleton || ContainerUtil.hasInjectableConstructor(implementationClass); - boolean hasOnlyEmptyPublicConstructor = - !isSingleton || ContainerUtil.hasOnlyEmptyPublicConstructor(implementationClass); - if (hasInjectableConstructor || hasOnlyEmptyPublicConstructor) - { - // There is at least one constructor JSR 330 compliant or we already know - // that it is not a singleton such that the new behavior is expected - boolean isInjectPresent = container.initializeComponent(instance); - isSingleton = manageScope(isSingleton, isInitialized, hasInjectableConstructor, isInjectPresent); - } - else if (!isInitialized) - { - // The adapter has not been initialized yet - // The old behavior is expected as there is no constructor JSR 330 compliant - isSingleton = MX4JComponentAdapter.this.isSingleton = true; - scope.set(Singleton.class); - } - if (component != null && component.getComponentPlugins() != null) - { - addComponentPlugin(debug, instance, component.getComponentPlugins(), exocontainer); - } - ExternalComponentPlugins ecplugins = - manager == null ? null : manager.getConfiguration().getExternalComponentPlugins(componentKey); - if (ecplugins != null) - { - addComponentPlugin(debug, instance, ecplugins.getComponentPlugins(), exocontainer); - } - // check if component implement the ComponentLifecycle - if (instance instanceof ComponentLifecycle) - { - ComponentLifecycle lc = (ComponentLifecycle)instance; - lc.initComponent(exocontainer); - } - if (!isInitialized) - { - if (isSingleton) - { - instance_ = instance; - } - MX4JComponentAdapter.this.isInitialized = true; - } - return instance; - } - }); + // Avoid instantiating twice the same component in case of a cyclic reference due + // to component plugins + return instance_; + } + else if (ctx.get() != null) + return ctx.get(); + + ctx.push(instance); + boolean isSingleton = MX4JComponentAdapter.this.isSingleton; + boolean isInitialized = MX4JComponentAdapter.this.isInitialized; + if (debug) + LOG.debug("==> create component : " + instance); + boolean hasInjectableConstructor = + !isSingleton || ContainerUtil.hasInjectableConstructor(implementationClass); + boolean hasOnlyEmptyPublicConstructor = + !isSingleton || ContainerUtil.hasOnlyEmptyPublicConstructor(implementationClass); + if (hasInjectableConstructor || hasOnlyEmptyPublicConstructor) + { + // There is at least one constructor JSR 330 compliant or we already know + // that it is not a singleton such that the new behavior is expected + boolean isInjectPresent = container.initializeComponent(instance); + isSingleton = manageScope(isSingleton, isInitialized, hasInjectableConstructor, isInjectPresent); + } + else if (!isInitialized) + { + // The adapter has not been initialized yet + // The old behavior is expected as there is no constructor JSR 330 compliant + isSingleton = MX4JComponentAdapter.this.isSingleton = true; + scope.set(Singleton.class); + } + if (component != null && component.getComponentPlugins() != null) + { + addComponentPlugin(debug, instance, component.getComponentPlugins(), exocontainer); } - catch (PrivilegedActionException e) + ExternalComponentPlugins ecplugins = + manager == null ? null : manager.getConfiguration().getExternalComponentPlugins(componentKey); + if (ecplugins != null) { - Throwable cause = e.getCause(); - if (cause instanceof Exception) + addComponentPlugin(debug, instance, ecplugins.getComponentPlugins(), exocontainer); + } + // check if component implement the ComponentLifecycle + if (instance instanceof ComponentLifecycle) + { + ComponentLifecycle lc = (ComponentLifecycle)instance; + lc.initComponent(exocontainer); + } + if (!isInitialized) + { + if (isSingleton) { - throw (Exception)cause; + instance_ = instance; } - throw new Exception(cause); + MX4JComponentAdapter.this.isInitialized = true; } + return instance; } /** @@ -379,14 +358,7 @@ private void addComponentPlugin(boolean debug, final Object component, } final Object[] params = {cplugin}; - SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public Void run() throws Exception - { - m.invoke(component, params); - return null; - } - }); + m.invoke(component, params); if (debug) LOG.debug("==> add component plugin: " + cplugin); diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/management/ManagementContextImpl.java b/exo.kernel.container/src/main/java/org/exoplatform/container/management/ManagementContextImpl.java index 917afadfe..d764f0fe0 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/management/ManagementContextImpl.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/management/ManagementContextImpl.java @@ -18,7 +18,6 @@ */ package org.exoplatform.container.management; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.RootContainer; @@ -35,7 +34,6 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -357,19 +355,12 @@ public void beforeInvoke(Object managedResource) final ManageableContainer container = findContainer(); if (container != null && container.getHolder() != null) { - SecurityHelper.doPrivilegedAction(new PrivilegedAction() + ExoContainer oldContainer = ExoContainerContext.getCurrentContainerIfPresent(); + if (!(oldContainer instanceof RootContainer)) { - public Void run() - { - ExoContainer oldContainer = ExoContainerContext.getCurrentContainerIfPresent(); - if (!(oldContainer instanceof RootContainer)) - { - previousContainer.set(oldContainer); - } - ExoContainerContext.setCurrentContainer(container.getHolder()); - return null; - } - }); + previousContainer.set(oldContainer); + } + ExoContainerContext.setCurrentContainer(container.getHolder()); RequestLifeCycle.begin(container.getHolder()); } } @@ -382,19 +373,12 @@ public void afterInvoke(Object managedResource) } finally { - SecurityHelper.doPrivilegedAction(new PrivilegedAction() + ExoContainer oldContainer = previousContainer.get(); + if (oldContainer != null) { - public Void run() - { - ExoContainer oldContainer = previousContainer.get(); - if (oldContainer != null) - { - previousContainer.set(null); - } - ExoContainerContext.setCurrentContainer(oldContainer); - return null; - } - }); + previousContainer.set(null); + } + ExoContainerContext.setCurrentContainer(oldContainer); } } diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/monitor/jvm/J2EEServerInfo.java b/exo.kernel.container/src/main/java/org/exoplatform/container/monitor/jvm/J2EEServerInfo.java index 25a658c7a..f747b015a 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/monitor/jvm/J2EEServerInfo.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/monitor/jvm/J2EEServerInfo.java @@ -19,7 +19,6 @@ package org.exoplatform.container.monitor.jvm; import org.exoplatform.commons.utils.PropertyManager; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.ar.Archive; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; @@ -29,7 +28,6 @@ import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; -import java.security.PrivilegedAction; import java.util.*; import javax.management.MBeanServer; @@ -83,200 +81,192 @@ public J2EEServerInfo() public J2EEServerInfo(final boolean logEnabled) { - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { + String jonasHome = System.getProperty("jonas.base"); + String jbossHome = System.getProperty("jboss.home.dir"); + String jettyHome = System.getProperty("jetty.home"); + String websphereHome = System.getProperty("was.install.root"); + String weblogicHome = System.getProperty("wls.home"); + String glassfishHome = System.getProperty("com.sun.aas.instanceRoot"); + String catalinaHome = System.getProperty("catalina.home"); + String testHome = System.getProperty("maven.exoplatform.dir"); - String jonasHome = System.getProperty("jonas.base"); - String jbossHome = System.getProperty("jboss.home.dir"); - String jettyHome = System.getProperty("jetty.home"); - String websphereHome = System.getProperty("was.install.root"); - String weblogicHome = System.getProperty("wls.home"); - String glassfishHome = System.getProperty("com.sun.aas.instanceRoot"); - String catalinaHome = System.getProperty("catalina.home"); - String testHome = System.getProperty("maven.exoplatform.dir"); + // The name of the configuration directory + final String confDirName = System.getProperty(EXO_CONF_DIR_NAME_PARAM, "exo-conf"); + if (jonasHome != null) + { + serverName_ = "jonas"; + serverHome_ = jonasHome; + } + else if (jbossHome != null) + { + serverName_ = "jboss"; + serverHome_ = jbossHome; - // The name of the configuration directory - final String confDirName = System.getProperty(EXO_CONF_DIR_NAME_PARAM, "exo-conf"); - if (jonasHome != null) + // try find and use jboss.server.config.url + // based on http://www.jboss.org/community/docs/DOC-10730 + String jbossConfigUrl = System.getProperty("jboss.server.config.url"); + if (jbossConfigUrl != null) + { + try { - serverName_ = "jonas"; - serverHome_ = jonasHome; + exoConfDir_ = new File(new File(new URI(jbossConfigUrl)), confDirName).getAbsolutePath(); + appDeployDirectories_ = Collections.singletonList(new File(new File(new URI(jbossConfigUrl)).getParentFile(), "deploy").getAbsolutePath()); } - else if (jbossHome != null) + catch (SecurityException e) { - serverName_ = "jboss"; - serverHome_ = jbossHome; - - // try find and use jboss.server.config.url - // based on http://www.jboss.org/community/docs/DOC-10730 - String jbossConfigUrl = System.getProperty("jboss.server.config.url"); - if (jbossConfigUrl != null) + if (logEnabled && LOG.isTraceEnabled()) { - try - { - exoConfDir_ = new File(new File(new URI(jbossConfigUrl)), confDirName).getAbsolutePath(); - appDeployDirectories_ = Collections.singletonList(new File(new File(new URI(jbossConfigUrl)).getParentFile(), "deploy").getAbsolutePath()); - } - catch (SecurityException e) - { - if (logEnabled && LOG.isTraceEnabled()) - { - LOG.trace("An exception occurred: " + e.getMessage()); - } - } - catch (URISyntaxException e) - { - if (logEnabled && LOG.isTraceEnabled()) - { - LOG.trace("An exception occurred: " + e.getMessage()); - } - } - catch (IllegalArgumentException e) - { - if (logEnabled && LOG.isTraceEnabled()) - { - LOG.trace("An exception occurred: " + e.getMessage()); - } - } + LOG.trace("An exception occurred: " + e.getMessage()); } - else + } + catch (URISyntaxException e) + { + if (logEnabled && LOG.isTraceEnabled()) { - // New variable that exists only since JBoss AS 7 - String jbossConfigDir = System.getProperty("jboss.server.config.dir"); - if (jbossConfigDir != null) - { - try - { - exoConfDir_ = new File(jbossConfigDir, confDirName).getAbsolutePath(); - appDeployDirectories_ = Collections.singletonList(new File(new File(jbossConfigDir).getParentFile(), "deployments").getAbsolutePath()); - } - catch (SecurityException e) - { - if (logEnabled && LOG.isTraceEnabled()) - { - LOG.trace("An exception occurred: " + e.getMessage()); - } - } - } + LOG.trace("An exception occurred: " + e.getMessage()); } - try + } + catch (IllegalArgumentException e) + { + if (logEnabled && LOG.isTraceEnabled()) { - Class clazz = Thread.currentThread().getContextClassLoader() - .loadClass("org.jboss.mx.util.MBeanServerLocator"); - Method m = clazz.getMethod("locateJBoss"); - mbeanServer = (MBeanServer)m.invoke(null); + LOG.trace("An exception occurred: " + e.getMessage()); } - catch (ClassNotFoundException ignore) + } + } + else + { + // New variable that exists only since JBoss AS 7 + String jbossConfigDir = System.getProperty("jboss.server.config.dir"); + if (jbossConfigDir != null) + { + try { - // We assume that JBoss AS 7 or higher is currently used - // since this class has been removed starting from this version - // of JBoss AS - if (logEnabled && LOG.isDebugEnabled()) - LOG.debug(ignore.getLocalizedMessage(), ignore); + exoConfDir_ = new File(jbossConfigDir, confDirName).getAbsolutePath(); + appDeployDirectories_ = Collections.singletonList(new File(new File(jbossConfigDir).getParentFile(), "deployments").getAbsolutePath()); } - catch (Exception ignore) + catch (SecurityException e) { - if (logEnabled && LOG.isErrorEnabled()) - LOG.error(ignore.getLocalizedMessage(), ignore); + if (logEnabled && LOG.isTraceEnabled()) + { + LOG.trace("An exception occurred: " + e.getMessage()); + } } } - else if (jettyHome != null) - { - serverName_ = "jetty"; - serverHome_ = jettyHome; - appDeployDirectories_ = Collections.singletonList(new File(jettyHome, "webapps").getAbsolutePath()); - appDeployArchives_ = Collections.singleton(Archive.WAR); - } - else if (websphereHome != null) - { - serverName_ = "websphere"; - serverHome_ = websphereHome; - } - else if (weblogicHome != null) - { - serverName_ = "weblogic"; - serverHome_ = weblogicHome; - } - else if (glassfishHome != null) - { - serverName_ = "glassfish"; - serverHome_ = glassfishHome; - } - else if (catalinaHome != null) - { - // Catalina has to be processed at the end as other servers may embed it - serverName_ = "tomcat"; - serverHome_ = catalinaHome; - appDeployDirectories_ = Collections.singletonList(new File(catalinaHome, "webapps").getAbsolutePath()); - appDeployArchives_ = Collections.singleton(new Archive("war", PropertyManager.isDevelopping(), false, null)); - } - else if (testHome != null) - { - serverName_ = "test"; - serverHome_ = testHome; - } - else - { - // throw new UnsupportedOperationException("unknown server platform") ; - serverName_ = "standalone"; - serverHome_ = System.getProperty("user.dir"); - } - if (exoConfDir_ == null) - { - exoConfDir_ = serverHome_ + "/" + confDirName; - } - if (mbeanServer == null) - { - mbeanServer = ManagementFactory.getPlatformMBeanServer(); - } + } + try + { + Class clazz = Thread.currentThread().getContextClassLoader() + .loadClass("org.jboss.mx.util.MBeanServerLocator"); + Method m = clazz.getMethod("locateJBoss"); + mbeanServer = (MBeanServer)m.invoke(null); + } + catch (ClassNotFoundException ignore) + { + // We assume that JBoss AS 7 or higher is currently used + // since this class has been removed starting from this version + // of JBoss AS + if (logEnabled && LOG.isDebugEnabled()) + LOG.debug(ignore.getLocalizedMessage(), ignore); + } + catch (Exception ignore) + { + if (logEnabled && LOG.isErrorEnabled()) + LOG.error(ignore.getLocalizedMessage(), ignore); + } + } + else if (jettyHome != null) + { + serverName_ = "jetty"; + serverHome_ = jettyHome; + appDeployDirectories_ = Collections.singletonList(new File(jettyHome, "webapps").getAbsolutePath()); + appDeployArchives_ = Collections.singleton(Archive.WAR); + } + else if (websphereHome != null) + { + serverName_ = "websphere"; + serverHome_ = websphereHome; + } + else if (weblogicHome != null) + { + serverName_ = "weblogic"; + serverHome_ = weblogicHome; + } + else if (glassfishHome != null) + { + serverName_ = "glassfish"; + serverHome_ = glassfishHome; + } + else if (catalinaHome != null) + { + // Catalina has to be processed at the end as other servers may embed it + serverName_ = "tomcat"; + serverHome_ = catalinaHome; + appDeployDirectories_ = Collections.singletonList(new File(catalinaHome, "webapps").getAbsolutePath()); + appDeployArchives_ = Collections.singleton(new Archive("war", PropertyManager.isDevelopping(), false, null)); + } + else if (testHome != null) + { + serverName_ = "test"; + serverHome_ = testHome; + } + else + { + // throw new UnsupportedOperationException("unknown server platform") ; + serverName_ = "standalone"; + serverHome_ = System.getProperty("user.dir"); + } + if (exoConfDir_ == null) + { + exoConfDir_ = serverHome_ + "/" + confDirName; + } + if (mbeanServer == null) + { + mbeanServer = ManagementFactory.getPlatformMBeanServer(); + } - String exoConfHome = System.getProperty(EXO_CONF_PARAM); - if (exoConfHome != null && exoConfHome.length() > 0) - { - if (logEnabled && LOG.isInfoEnabled()) - LOG.info("Override exo-conf directory '" + exoConfDir_ + "' with location '" + exoConfHome + "'"); - exoConfDir_ = exoConfHome; - } + String exoConfHome = System.getProperty(EXO_CONF_PARAM); + if (exoConfHome != null && exoConfHome.length() > 0) + { + if (logEnabled && LOG.isInfoEnabled()) + LOG.info("Override exo-conf directory '" + exoConfDir_ + "' with location '" + exoConfHome + "'"); + exoConfDir_ = exoConfHome; + } - String archiveDirs = System.getProperty(EXO_ARCHIVE_DIRS_PARAM); - if (archiveDirs != null) + String archiveDirs = System.getProperty(EXO_ARCHIVE_DIRS_PARAM); + if (archiveDirs != null) + { + StringTokenizer st = new StringTokenizer(archiveDirs, ","); + if (st.hasMoreTokens()) + { + if (logEnabled && LOG.isInfoEnabled()) + LOG.info("The location of the archives has been set to '" + archiveDirs + "'"); + List dirs = new ArrayList(); + while (st.hasMoreTokens()) { - StringTokenizer st = new StringTokenizer(archiveDirs, ","); - if (st.hasMoreTokens()) + String dir = st.nextToken().trim().replace('\\', '/'); + String path = new File(serverHome_, dir).getAbsolutePath(); + if (logEnabled && LOG.isDebugEnabled()) { - if (logEnabled && LOG.isInfoEnabled()) - LOG.info("The location of the archives has been set to '" + archiveDirs + "'"); - List dirs = new ArrayList(); - while (st.hasMoreTokens()) - { - String dir = st.nextToken().trim().replace('\\', '/'); - String path = new File(serverHome_, dir).getAbsolutePath(); - if (logEnabled && LOG.isDebugEnabled()) - { - LOG.debug("Location of the archives: {}", path); - } - dirs.add(path); - } - appDeployDirectories_ = dirs; + LOG.debug("Location of the archives: {}", path); } - else - { - appDeployDirectories_ = null; - } - } - - if (appDeployDirectories_ == null) - { - if (logEnabled && LOG.isInfoEnabled()) - LOG.info("No location of the archives has been set"); + dirs.add(path); } - serverHome_ = serverHome_.replace('\\', '/'); - exoConfDir_ = exoConfDir_.replace('\\', '/'); - return null; + appDeployDirectories_ = dirs; } - }); + else + { + appDeployDirectories_ = null; + } + } + + if (appDeployDirectories_ == null) + { + if (logEnabled && LOG.isInfoEnabled()) + LOG.info("No location of the archives has been set"); + } + serverHome_ = serverHome_.replace('\\', '/'); + exoConfDir_ = exoConfDir_.replace('\\', '/'); } /** diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/monitor/jvm/JVMRuntimeInfoImpl.java b/exo.kernel.container/src/main/java/org/exoplatform/container/monitor/jvm/JVMRuntimeInfoImpl.java index 91f93831a..34bd025a7 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/monitor/jvm/JVMRuntimeInfoImpl.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/monitor/jvm/JVMRuntimeInfoImpl.java @@ -19,15 +19,12 @@ package org.exoplatform.container.monitor.jvm; import org.exoplatform.commons.utils.ExoProperties; -import org.exoplatform.commons.utils.PrivilegedSystemHelper; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.PropertiesParam; import org.picocontainer.Startable; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; -import java.security.PrivilegedAction; import java.util.Date; import java.util.Iterator; import java.util.List; @@ -55,7 +52,7 @@ public JVMRuntimeInfoImpl(InitParams params) throws Exception while (i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); - PrivilegedSystemHelper.setProperty((String)entry.getKey(), (String)entry.getValue()); + System.setProperty((String)entry.getKey(), (String)entry.getValue()); } } } @@ -63,178 +60,82 @@ public JVMRuntimeInfoImpl(InitParams params) throws Exception public String getName() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public String run() - { - return mxbean_.getName(); - } - }); + return mxbean_.getName(); } public String getSpecName() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public String run() - { - return mxbean_.getSpecName(); - } - }); + return mxbean_.getSpecName(); } public String getSpecVendor() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public String run() - { - return mxbean_.getSpecVendor(); - } - }); + return mxbean_.getSpecVendor(); } public String getSpecVersion() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public String run() - { - return mxbean_.getSpecVersion(); - } - }); + return mxbean_.getSpecVersion(); } public String getManagementSpecVersion() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public String run() - { - return mxbean_.getManagementSpecVersion(); - } - }); + return mxbean_.getManagementSpecVersion(); } public String getVmName() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public String run() - { - return mxbean_.getVmName(); - } - }); + return mxbean_.getVmName(); } public String getVmVendor() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public String run() - { - return mxbean_.getVmVendor(); - } - }); + return mxbean_.getVmVendor(); } public String getVmVersion() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public String run() - { - return mxbean_.getVmVersion(); - } - }); + return mxbean_.getVmVersion(); } public List getInputArguments() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public List run() - { - return mxbean_.getInputArguments(); - } - }); + return mxbean_.getInputArguments(); } public Map getSystemProperties() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Map run() - { - return mxbean_.getSystemProperties(); - } - }); + return mxbean_.getSystemProperties(); } public boolean getBootClassPathSupported() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Boolean run() - { - return mxbean_.isBootClassPathSupported(); - } - }); + return mxbean_.isBootClassPathSupported(); } public String getBootClassPath() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public String run() - { - return mxbean_.getBootClassPath(); - } - }); + return mxbean_.getBootClassPath(); } public String getClassPath() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public String run() - { - return mxbean_.getClassPath(); - } - }); + return mxbean_.getClassPath(); } public String getLibraryPath() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public String run() - { - return mxbean_.getLibraryPath(); - } - }); + return mxbean_.getLibraryPath(); } public long getStartTime() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Long run() - { - return mxbean_.getStartTime(); - } - }); + return mxbean_.getStartTime(); } public long getUptime() { - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Long run() - { - return mxbean_.getUptime(); - } - }); + return mxbean_.getUptime(); } public boolean isManagementSupported() @@ -245,7 +146,7 @@ public boolean isManagementSupported() public String getSystemPropertiesAsText() { StringBuffer b = new StringBuffer(); - Iterator i = PrivilegedSystemHelper.getProperties().entrySet().iterator(); + Iterator i = System.getProperties().entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/util/ContainerUtil.java b/exo.kernel.container/src/main/java/org/exoplatform/container/util/ContainerUtil.java index bb31e26e2..f3589da6d 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/util/ContainerUtil.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/util/ContainerUtil.java @@ -24,7 +24,6 @@ import org.exoplatform.commons.utils.ClassLoading; import org.exoplatform.commons.utils.PropertiesLoader; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.commons.utils.Tools; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.configuration.ConfigurationManager; @@ -44,8 +43,6 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -279,13 +276,7 @@ public static Collection getConfigurationURL(final String configuration) th { final ClassLoader cl = Thread.currentThread().getContextClassLoader(); - Collection c = SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction() - { - public Collection run() throws IOException - { - return Collections.list(cl.getResources(configuration)); - } - }); + Collection c = Collections.list(cl.getResources(configuration)); Map map = new LinkedHashMap<>(); Iterator i = c.iterator(); @@ -511,56 +502,31 @@ else if (LOG.isDebugEnabled()) public static T createProxy(final Class superClass, final Provider provider) throws UnproxyableResolutionException { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() + Method[] methods = superClass.getDeclaredMethods(); + for (int i = 0; i < methods.length; i++) { - - public T run() throws Exception + Method m = methods[i]; + int modifiers = m.getModifiers(); + if (Modifier.isFinal(modifiers) && !Modifier.isPrivate(modifiers) && !Modifier.isStatic(modifiers)) { - // We first make sure that there is no non-static, final methods with public, protected or default visibility - Method[] methods = superClass.getDeclaredMethods(); - for (int i = 0; i < methods.length; i++) - { - Method m = methods[i]; - int modifiers = m.getModifiers(); - if (Modifier.isFinal(modifiers) && !Modifier.isPrivate(modifiers) && !Modifier.isStatic(modifiers)) - { - throw new UnproxyableResolutionException( - "Cannot create a proxy for the class " - + superClass.getName() - + " because it has at least one non-static, final method with public, protected or default visibility"); - } - } - try - { - ProxyFactory factory = new ProxyFactory(); - factory.setSuperclass(superClass); - factory.setFilter(MethodFilterHolder.METHOD_FILTER); - MethodHandler handler = new ProxyMethodHandler(provider); - return superClass.cast(factory.create(new Class[0], new Object[0], handler)); - } - catch (Exception e) - { - throw new UnproxyableResolutionException("Cannot create a proxy for the class " + superClass.getName(), - e); - } + throw new UnproxyableResolutionException( + "Cannot create a proxy for the class " + + superClass.getName() + + " because it has at least one non-static, final method with public, protected or default visibility"); } - }; + } try { - return SecurityHelper.doPrivilegedExceptionAction(action); + ProxyFactory factory = new ProxyFactory(); + factory.setSuperclass(superClass); + factory.setFilter(MethodFilterHolder.METHOD_FILTER); + MethodHandler handler = new ProxyMethodHandler(provider); + return superClass.cast(factory.create(new Class[0], new Object[0], handler)); } - catch (PrivilegedActionException e) + catch (Exception e) { - Throwable cause = e.getCause(); - if (cause instanceof UnproxyableResolutionException) - { - throw (UnproxyableResolutionException)cause; - } - else - { - throw new UnproxyableResolutionException("Cannot create a proxy for the class " + superClass.getName(), - cause); - } + throw new UnproxyableResolutionException("Cannot create a proxy for the class " + superClass.getName(), + e); } } diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/util/TemplateConfigurationHelper.java b/exo.kernel.container/src/main/java/org/exoplatform/container/util/TemplateConfigurationHelper.java index 0c05215ca..223b0aac0 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/util/TemplateConfigurationHelper.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/util/TemplateConfigurationHelper.java @@ -18,12 +18,12 @@ */ package org.exoplatform.container.util; -import org.exoplatform.commons.utils.PrivilegedFileHelper; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import java.io.ByteArrayInputStream; +import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -176,7 +176,7 @@ public static InputStream getInputStream(ConfigurationManager cfm, String filena { try { - inputStream = PrivilegedFileHelper.fileInputStream(filename); + inputStream = new FileInputStream(filename); } catch (IOException e) { diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/web/PortalContainerCreator.java b/exo.kernel.container/src/main/java/org/exoplatform/container/web/PortalContainerCreator.java index 152816d7a..8b416219e 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/web/PortalContainerCreator.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/web/PortalContainerCreator.java @@ -18,11 +18,8 @@ */ package org.exoplatform.container.web; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.RootContainer; -import java.security.PrivilegedAction; - import jakarta.servlet.ServletContextEvent; import jakarta.servlet.ServletContextListener; @@ -43,16 +40,7 @@ public class PortalContainerCreator implements ServletContextListener */ public void contextDestroyed(ServletContextEvent event) { - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - // Ensure that the root container is stopped properly since the shutdown hook - // doesn't work in some cases for example with tomcat when we call the stop command - RootContainer.getInstance().stop(); - return null; - } - }); + RootContainer.getInstance().stop(); } /** @@ -61,13 +49,6 @@ public Void run() public void contextInitialized(ServletContextEvent event) { final RootContainer rootContainer = RootContainer.getInstance(); - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - rootContainer.createPortalContainers(); - return null; - } - }); + rootContainer.createPortalContainers(); } } diff --git a/exo.kernel.container/src/main/java/org/exoplatform/container/xml/Deserializer.java b/exo.kernel.container/src/main/java/org/exoplatform/container/xml/Deserializer.java index d81ca2c41..5d80fc59d 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/container/xml/Deserializer.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/container/xml/Deserializer.java @@ -18,7 +18,6 @@ */ package org.exoplatform.container.xml; -import org.exoplatform.commons.utils.PrivilegedSystemHelper; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.PortalContainer; @@ -278,7 +277,7 @@ else if (key.startsWith(Deserializer.PORTAL_CONTAINER_VARIABLE_PREFIX)) { // No value could be found so far, thus we try to get it from the // system properties - value = PrivilegedSystemHelper.getProperty(key); + value = System.getProperty(key); } } if (value == null && defaultValue != null) diff --git a/exo.kernel.container/src/main/java/org/exoplatform/management/jmx/impl/JMXManagementProvider.java b/exo.kernel.container/src/main/java/org/exoplatform/management/jmx/impl/JMXManagementProvider.java index cf8e59e6c..e59a9cc6e 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/management/jmx/impl/JMXManagementProvider.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/management/jmx/impl/JMXManagementProvider.java @@ -18,15 +18,12 @@ */ package org.exoplatform.management.jmx.impl; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.management.jmx.annotations.NameTemplate; import org.exoplatform.management.spi.ManagedResource; import org.exoplatform.management.spi.ManagementProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -184,32 +181,19 @@ private void attemptToRegister(final ObjectName name, final Object mbean) } try { - SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public Void run() throws Exception - { - server.unregisterMBean(name); - return null; - } - }); + server.unregisterMBean(name); } - catch (PrivilegedActionException e) + catch (Exception e) { throw new RuntimeException("Failed to unregister MBean '" + name + " due to " + e.getMessage(), e); } } try { - SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public Void run() throws Exception - { - server.registerMBean(mbean, name); - return null; - } - }); + server.registerMBean(mbean, name); + } - catch (PrivilegedActionException e) + catch (Exception e) { throw new RuntimeException("Failed to register MBean '" + name + " due to " + e.getMessage(), e); } @@ -221,39 +205,9 @@ public void unmanage(Object key) final ObjectName name = (ObjectName)key; try { - try - { - SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public Void run() throws Exception - { - if (server.isRegistered(name)) - { - server.unregisterMBean(name); - } - return null; - } - }); - } - catch (PrivilegedActionException pae) + if (server.isRegistered(name)) { - Throwable cause = pae.getCause(); - if (cause instanceof InstanceNotFoundException) - { - throw (InstanceNotFoundException)cause; - } - else if (cause instanceof MBeanRegistrationException) - { - throw (MBeanRegistrationException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } + server.unregisterMBean(name); } } catch (InstanceNotFoundException e) diff --git a/exo.kernel.container/src/main/java/org/exoplatform/test/MockConfigurationManagerImpl.java b/exo.kernel.container/src/main/java/org/exoplatform/test/MockConfigurationManagerImpl.java index 0710a49ec..70550685b 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/test/MockConfigurationManagerImpl.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/test/MockConfigurationManagerImpl.java @@ -18,13 +18,10 @@ */ package org.exoplatform.test; -import org.exoplatform.commons.utils.PrivilegedSystemHelper; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.configuration.ConfigurationManagerImpl; import java.net.URL; -import java.security.PrivilegedAction; import jakarta.servlet.ServletContext; @@ -42,7 +39,7 @@ public class MockConfigurationManagerImpl extends ConfigurationManagerImpl public MockConfigurationManagerImpl(ServletContext context) throws Exception { super(context, ExoContainer.getProfilesFromProperty()); - confDir_ = PrivilegedSystemHelper.getProperty("mock.portal.dir") + "/WEB-INF"; + confDir_ = System.getProperty("mock.portal.dir") + "/WEB-INF"; } @Override @@ -57,13 +54,7 @@ public URL getURL(String uri) throws Exception } final ClassLoader cl = Thread.currentThread().getContextClassLoader(); final String finalPath = path; - return SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public URL run() - { - return cl.getResource(finalPath); - } - }); + return cl.getResource(finalPath); } else if (uri.startsWith("classpath:")) { @@ -72,7 +63,7 @@ else if (uri.startsWith("classpath:")) { path = path.substring(1); } - return PrivilegedSystemHelper.getResource(path); + return Thread.currentThread().getContextClassLoader().getResource(path); } else if (uri.startsWith("war:")) { diff --git a/exo.kernel.container/src/main/java/org/exoplatform/xml/object/XMLObject.java b/exo.kernel.container/src/main/java/org/exoplatform/xml/object/XMLObject.java index 597e9aed2..0d6623cf0 100644 --- a/exo.kernel.container/src/main/java/org/exoplatform/xml/object/XMLObject.java +++ b/exo.kernel.container/src/main/java/org/exoplatform/xml/object/XMLObject.java @@ -19,7 +19,6 @@ package org.exoplatform.xml.object; import org.exoplatform.commons.utils.ClassLoading; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.container.xml.Configuration; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; @@ -33,9 +32,6 @@ import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; @@ -266,14 +262,7 @@ static void findFields(Map fields, Class clazz) final Field fld = field[i]; - SecurityHelper.doPrivilegedAction(new PrivilegedAction() - { - public Void run() - { - fld.setAccessible(true); - return null; - } - }); + fld.setAccessible(true); fields.put(field[i].getName(), field[i]); } @@ -281,31 +270,6 @@ public Void run() protected static IBindingFactory getBindingFactoryInPriviledgedMode(final Class clazz) throws JiBXException { - try - { - return SecurityHelper.doPrivilegedExceptionAction(new PrivilegedExceptionAction() - { - public IBindingFactory run() throws Exception - { - return BindingDirectory.getFactory(clazz); - } - }); - } - catch (PrivilegedActionException pae) - { - Throwable cause = pae.getCause(); - if (cause instanceof JiBXException) - { - throw (JiBXException)cause; - } - else if (cause instanceof RuntimeException) - { - throw (RuntimeException)cause; - } - else - { - throw new RuntimeException(cause); - } - } + return BindingDirectory.getFactory(clazz); } } diff --git a/exo.kernel.container/src/test/java/org/exoplatform/container/ContainerBuilder.java b/exo.kernel.container/src/test/java/org/exoplatform/container/ContainerBuilder.java index e39c8d463..d5d5019c3 100644 --- a/exo.kernel.container/src/test/java/org/exoplatform/container/ContainerBuilder.java +++ b/exo.kernel.container/src/test/java/org/exoplatform/container/ContainerBuilder.java @@ -21,14 +21,11 @@ import junit.framework.AssertionFailedError; import org.exoplatform.commons.utils.PropertyManager; -import org.exoplatform.commons.utils.SecurityHelper; import org.exoplatform.commons.utils.Tools; import java.io.IOException; import java.lang.reflect.Field; import java.net.URL; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; @@ -142,20 +139,13 @@ private List urls(String path) public RootContainer build() { - PrivilegedExceptionAction action = new PrivilegedExceptionAction() - { - public RootContainer run() throws Exception - { - return _build(); - } - }; try { - return SecurityHelper.doPrivilegedExceptionAction(action); + return _build(); } - catch (PrivilegedActionException pae) + catch (Exception e) { - Throwable cause = pae.getCause(); + Throwable cause = e.getCause(); AssertionFailedError err = new AssertionFailedError(); err.initCause(cause); throw err; From 24dee53f8892de1ef76bcb0024d5de5f7da13e26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Romain=20D=C3=A9nari=C3=A9?= Date: Fri, 17 May 2024 15:19:07 +0200 Subject: [PATCH 2/2] Factorize surefire argLine --- exo.kernel.component.cache/pom.xml | 2 +- exo.kernel.component.common/pom.xml | 2 +- exo.kernel.component.ext.cache.impl.infinispan.v8/pom.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/exo.kernel.component.cache/pom.xml b/exo.kernel.component.cache/pom.xml index ec12e52c3..067cd58dd 100644 --- a/exo.kernel.component.cache/pom.xml +++ b/exo.kernel.component.cache/pom.xml @@ -64,7 +64,7 @@ org.apache.maven.plugins maven-surefire-plugin - @{argLine} -Djava.net.preferIPv4Stack=true + @{argLine} @{surefire.argLine} -Djava.net.preferIPv4Stack=true diff --git a/exo.kernel.component.common/pom.xml b/exo.kernel.component.common/pom.xml index 99dfc609e..c5d8d5e09 100644 --- a/exo.kernel.component.common/pom.xml +++ b/exo.kernel.component.common/pom.xml @@ -140,7 +140,7 @@ org.apache.maven.plugins maven-surefire-plugin - @{argLine} -Djava.net.preferIPv4Stack=true + @{argLine} @{surefire.argLine} -Djava.net.preferIPv4Stack=true diff --git a/exo.kernel.component.ext.cache.impl.infinispan.v8/pom.xml b/exo.kernel.component.ext.cache.impl.infinispan.v8/pom.xml index da9394c17..d3c1aa69b 100644 --- a/exo.kernel.component.ext.cache.impl.infinispan.v8/pom.xml +++ b/exo.kernel.component.ext.cache.impl.infinispan.v8/pom.xml @@ -95,7 +95,7 @@ org.apache.maven.plugins maven-surefire-plugin - @{argLine} --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.util.concurrent=ALL-UNNAMED -Djava.net.preferIPv4Stack=true + @{argLine} @{surefire.argLine} -Djava.net.preferIPv4Stack=true