Return-Path: X-Original-To: apmail-incubator-deltaspike-commits-archive@minotaur.apache.org Delivered-To: apmail-incubator-deltaspike-commits-archive@minotaur.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id CD55497C0 for ; Tue, 24 Jan 2012 23:26:41 +0000 (UTC) Received: (qmail 33360 invoked by uid 500); 24 Jan 2012 23:26:41 -0000 Delivered-To: apmail-incubator-deltaspike-commits-archive@incubator.apache.org Received: (qmail 33320 invoked by uid 500); 24 Jan 2012 23:26:41 -0000 Mailing-List: contact deltaspike-commits-help@incubator.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: deltaspike-dev@incubator.apache.org Delivered-To: mailing list deltaspike-commits@incubator.apache.org Received: (qmail 33312 invoked by uid 99); 24 Jan 2012 23:26:41 -0000 Received: from nike.apache.org (HELO nike.apache.org) (192.87.106.230) by apache.org (qpsmtpd/0.29) with ESMTP; Tue, 24 Jan 2012 23:26:41 +0000 X-ASF-Spam-Status: No, hits=-2000.0 required=5.0 tests=ALL_TRUSTED X-Spam-Check-By: apache.org Received: from [140.211.11.114] (HELO tyr.zones.apache.org) (140.211.11.114) by apache.org (qpsmtpd/0.29) with ESMTP; Tue, 24 Jan 2012 23:26:31 +0000 Received: by tyr.zones.apache.org (Postfix, from userid 65534) id 4FA0231968D; Tue, 24 Jan 2012 23:26:08 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: gpetracek@apache.org To: deltaspike-commits@incubator.apache.org X-Mailer: ASF-Git Admin Mailer Subject: [1/3] git commit: DELTASPIKE-58 utils and helper moved to a separated package Message-Id: <20120124232608.4FA0231968D@tyr.zones.apache.org> Date: Tue, 24 Jan 2012 23:26:08 +0000 (UTC) X-Virus-Checked: Checked by ClamAV on apache.org Updated Branches: refs/heads/master d60f53e19 -> f3cc56734 DELTASPIKE-58 utils and helper moved to a separated package Project: http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/repo Commit: http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/commit/f3cc5673 Tree: http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/tree/f3cc5673 Diff: http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/diff/f3cc5673 Branch: refs/heads/master Commit: f3cc567349f44d8b7b179213c28e8389223fffdb Parents: d60f53e Author: gpetracek Authored: Wed Jan 25 00:25:01 2012 +0100 Committer: gpetracek Committed: Wed Jan 25 00:25:01 2012 +0100 ---------------------------------------------------------------------- .../deltaspike/core/api/config/ConfigResolver.java | 2 +- .../core/api/metadata/builder/AnnotatedImpl.java | 2 +- .../api/metadata/builder/AnnotatedTypeBuilder.java | 2 +- .../api/metadata/builder/AnnotationBuilder.java | 2 +- .../api/projectstage/ProjectStageProducer.java | 218 --- .../core/api/provider/BeanManagerProvider.java | 2 +- .../deltaspike/core/api/util/ClassUtils.java | 276 --- .../core/api/util/HierarchyDiscovery.java | 230 --- .../core/api/util/ParameterizedTypeImpl.java | 107 -- .../deltaspike/core/api/util/Reflections.java | 1424 --------------- .../api/util/SetAccessiblePrivilegedAction.java | 46 - .../org/apache/deltaspike/core/api/util/Types.java | 101 - .../core/spi/activation/Deactivatable.java | 2 +- .../spi/activation/util/ClassDeactivation.java | 177 -- .../deltaspike/core/util/ClassDeactivation.java | 176 ++ .../apache/deltaspike/core/util/ClassUtils.java | 276 +++ .../deltaspike/core/util/HierarchyDiscovery.java | 230 +++ .../core/util/ParameterizedTypeImpl.java | 107 ++ .../deltaspike/core/util/ProjectStageProducer.java | 218 +++ .../apache/deltaspike/core/util/Reflections.java | 1424 +++++++++++++++ .../core/util/SetAccessiblePrivilegedAction.java | 46 + .../org/apache/deltaspike/core/util/Types.java | 101 + .../impl/config/DefaultConfigSourceProvider.java | 2 +- .../core/impl/exclude/ExcludeExtension.java | 6 +- .../deltaspike/core/impl/util/JndiUtils.java | 2 +- .../test/core/api/exclude/ExcludeTest.java | 2 +- .../ExcludeTestProjectStageDevelopment.java | 2 +- .../api/projectstage/ProjectStageProducerTest.java | 2 +- .../impl/activation/TestClassDeactivation.java | 2 +- .../core/impl/activation/TestClassDeactivator.java | 2 +- .../core/api/exclude/ExcludeIntegrationTest.java | 2 +- .../IntegrationTestProjectStageProducer.java | 4 +- .../META-INF/apache-deltaspike.properties | 2 +- 33 files changed, 2598 insertions(+), 2599 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/blob/f3cc5673/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java ---------------------------------------------------------------------- diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java index 6c71add..2590986 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java @@ -28,7 +28,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; -import org.apache.deltaspike.core.api.util.ClassUtils; +import org.apache.deltaspike.core.util.ClassUtils; import org.apache.deltaspike.core.spi.config.ConfigSource; import org.apache.deltaspike.core.spi.config.ConfigSourceProvider; http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/blob/f3cc5673/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotatedImpl.java ---------------------------------------------------------------------- diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotatedImpl.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotatedImpl.java index d161835..17ca2d5 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotatedImpl.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotatedImpl.java @@ -19,7 +19,7 @@ package org.apache.deltaspike.core.api.metadata.builder; -import org.apache.deltaspike.core.api.util.HierarchyDiscovery; +import org.apache.deltaspike.core.util.HierarchyDiscovery; import javax.enterprise.inject.spi.Annotated; import java.lang.annotation.Annotation; http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/blob/f3cc5673/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotatedTypeBuilder.java ---------------------------------------------------------------------- diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotatedTypeBuilder.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotatedTypeBuilder.java index 57e9f73..b1a236a 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotatedTypeBuilder.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotatedTypeBuilder.java @@ -19,7 +19,7 @@ package org.apache.deltaspike.core.api.metadata.builder; -import org.apache.deltaspike.core.api.util.Reflections; +import org.apache.deltaspike.core.util.Reflections; import javax.enterprise.inject.spi.Annotated; import javax.enterprise.inject.spi.AnnotatedConstructor; http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/blob/f3cc5673/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotationBuilder.java ---------------------------------------------------------------------- diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotationBuilder.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotationBuilder.java index c85e03e..5f4317a 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotationBuilder.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/metadata/builder/AnnotationBuilder.java @@ -19,7 +19,7 @@ package org.apache.deltaspike.core.api.metadata.builder; -import org.apache.deltaspike.core.api.util.Reflections; +import org.apache.deltaspike.core.util.Reflections; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/blob/f3cc5673/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/projectstage/ProjectStageProducer.java ---------------------------------------------------------------------- diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/projectstage/ProjectStageProducer.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/projectstage/ProjectStageProducer.java deleted file mode 100644 index ab83232..0000000 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/projectstage/ProjectStageProducer.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.deltaspike.core.api.projectstage; - -import org.apache.deltaspike.core.api.config.ConfigResolver; -import org.apache.deltaspike.core.api.util.ClassUtils; - -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.context.Dependent; -import javax.enterprise.inject.Default; -import javax.enterprise.inject.Produces; -import java.io.Serializable; -import java.util.logging.Logger; - -/** - *

Produces {@link ProjectStage} configurations.

- * - *

The producer will try to detect the currently active ProjectStage on startup - * and use that for all generated fields.

- *

Usage:

- * Simply inject the current ProjectStage into any bean: - *
- * public class MyBean {
- *   private @Inject ProjectStage projectStage;
- *
- *   public void fn() {
- *     if(projectStage == ProjectStage.Production) {
- *        // do some prodution stuff...
- *     }
- *   }
- * }
- * 
- * - */ -@ApplicationScoped -public class ProjectStageProducer implements Serializable -{ - protected static final Logger LOG = Logger.getLogger(ProjectStageProducer.class.getName()); - - private static final long serialVersionUID = -2987762608635612074L; - - /** - * The detected ProjectStage - */ - private static ProjectStage projectStage; - - /** - * for the singleton factory - */ - private static volatile ProjectStageProducer projectStageProducer; - - /** - * ProjectStageProducers must only be created by subclassing producers - */ - protected ProjectStageProducer() - { - } - - /** - * We can only produce @Dependent scopes since an enum is final. - * @return current ProjectStage - */ - @Produces - @Dependent - @Default - public ProjectStage getProjectStage() - { - if (projectStage == null) - { - //triggers initialization - getInstance(); - } - return projectStage; - } - - /** - *

This factory method should only get used if there is absolutly no way - * to get the current {@link ProjectStage} via @Inject.

- * - *

- * - * @return the ProjectStageProducer instance. - */ - public static ProjectStageProducer getInstance() - { - if (projectStageProducer == null) - { - lazyInit(); - } - - if (projectStage == null) - { - projectStageProducer.initProjectStage(); - } - - return projectStageProducer; - } - - private static synchronized void lazyInit() - { - // switch into paranoia mode - if (projectStageProducer != null) - { - return; - } - - String customProjectStageProducerName = ConfigResolver.getPropertyValue(ProjectStageProducer.class.getName()); - - if (customProjectStageProducerName != null) - { - //e.g. the JSF module can provide a config-source implementation which - //returns a custom implementation which is aware of the JSF project-stage - //if a custom ProjectStageProducer is needed a custom config-source with a higher ordinal can be used - ProjectStageProducer customConfiguredProducer = - ClassUtils.tryToInstantiateClassForName(customProjectStageProducerName, ProjectStageProducer.class); - - if (customConfiguredProducer != null) - { - projectStageProducer = customConfiguredProducer; - - LOG.fine("Using custom project-stage-producer: " + customConfiguredProducer.getClass().getName()); - } - else - { - LOG.warning("Custom project-stage-producer couldn't be instantiated - class-name: " + - customProjectStageProducerName); - } - } - - if (projectStageProducer == null) - { - projectStageProducer = new ProjectStageProducer(); - } - - projectStageProducer.initProjectStage(); - } - - /** - * Resolves the project-stage configured for DeltaSpike - * @return the resolved {@link ProjectStage} or null if none defined. - */ - protected ProjectStage resolveProjectStage() - { - String stageName = ConfigResolver.getPropertyValue("org.apache.deltaspike.ProjectStage"); - - if (stageName != null) - { - return ProjectStage.valueOf(stageName); - } - - return null; - } - - protected void initProjectStage() - { - // switch into paranoia mode - synchronized (ProjectStageProducer.class) - { - if (projectStage == null) - { - projectStage = resolveProjectStage(); - - if (projectStage == null) - { - projectStage = ProjectStage.Production; - } - - LOG.info("Computed the following DeltaSpike ProjectStage: " + projectStage); - } - } - } - - /* - * Methods which might be needed for unti tests - */ - - /** - * Can be used esp. for internal tests. - * Usage: - *
-     * new ProjectStageProducer() {
-     *     @Override
-     *     protected void reset() { super.reset(); }
-     * }.reset();
-     * 
- */ - protected void reset() - { - projectStage = null; - projectStageProducer = null; - } - - /** - * This function can be used to manually set the ProjectStage for the application. - * This is e.g. useful in unit tests. - * @param ps the ProjectStage to set - */ - public static void setProjectStage(ProjectStage ps) - { - projectStage = ps; - } -} http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/blob/f3cc5673/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanManagerProvider.java ---------------------------------------------------------------------- diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanManagerProvider.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanManagerProvider.java index f6d714a..f53213a 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanManagerProvider.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/BeanManagerProvider.java @@ -28,7 +28,7 @@ import javax.naming.NamingException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import org.apache.deltaspike.core.api.util.ClassUtils; +import org.apache.deltaspike.core.util.ClassUtils; /** http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/blob/f3cc5673/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/ClassUtils.java ---------------------------------------------------------------------- diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/ClassUtils.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/ClassUtils.java deleted file mode 100644 index c4360bb..0000000 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/ClassUtils.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.deltaspike.core.api.util; - -import javax.enterprise.inject.Typed; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.jar.Manifest; -import java.util.jar.Attributes; -import java.net.URL; - -/** - * Util methods for classes, {@link ClassLoader} and {@link Manifest} handling - */ -//X TODO quite a few of this methods needs merging with Seam Solder and a few can get dropped at all. -@Typed() -public abstract class ClassUtils -{ - /** - * Constructor which prevents the instantiation of this class - */ - private ClassUtils() - { - // prevent instantiation - } - - /** - * Detect the right ClassLoader. - * The lookup order is determined by: - *
    - *
  1. ContextClassLoader of the current Thread
  2. - *
  3. ClassLoader of the given Object 'o'
  4. - *
  5. ClassLoader of this very ClassUtils class
  6. - *
- * - * @param o if not null it may get used to detect the classloader. - * @return The {@link ClassLoader} which should get used to create new instances - */ - public static ClassLoader getClassLoader(Object o) - { - ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction() - { - /** - * {@inheritDoc} - */ - @Override - public ClassLoader run() - { - try - { - return Thread.currentThread().getContextClassLoader(); - } - catch (Exception e) - { - return null; - } - } - } - ); - - if (loader == null && o != null) - { - loader = o.getClass().getClassLoader(); - } - - if (loader == null) - { - loader = ClassUtils.class.getClassLoader(); - } - - return loader; - } - - /** - * Tries to load a class based on the given name and interface or abstract class. - * @param name name of the concrete class - * @param targetType target type (interface or abstract class) - * @param current type - * @return loaded class or null if it isn't in the classpath - */ - public static Class tryToLoadClassForName(String name, Class targetType) - { - return (Class) tryToLoadClassForName(name); - } - - /** - * Tries to load a class based on the given name - * @param name name of the class - * @return loaded class or null if it isn't in the classpath - */ - public static Class tryToLoadClassForName(String name) - { - try - { - return loadClassForName(name); - } - catch (ClassNotFoundException e) - { - //do nothing - it's just a try - return null; - } - } - - /** - * Loads class for the given name - * @param name name of the class - * @return loaded class - * @throws ClassNotFoundException if the class can't be loaded - */ - public static Class loadClassForName(String name) throws ClassNotFoundException - { - try - { - // Try WebApp ClassLoader first - return Class.forName(name, false, // do not initialize for faster startup - getClassLoader(null)); - } - catch (ClassNotFoundException ignore) - { - // fallback: Try ClassLoader for ClassUtils (i.e. the myfaces.jar lib) - return Class.forName(name, false, // do not initialize for faster startup - ClassUtils.class.getClassLoader()); - } - } - - /** - * Instantiates a given class via the default constructor - * @param targetClass class which should be instantiated - * @param current type - * @return created instance or null if the instantiation failed - */ - public static T tryToInstantiateClass(Class targetClass) - { - try - { - return targetClass.newInstance(); - } - catch (InstantiationException e) - { - //do nothing - it was just a try - } - catch (IllegalAccessException e) - { - //do nothing - it was just a try - } - return null; - } - - /** - * Tries to instantiate a class for the given name and type via the default constructor - * @param className name of the class - * @param targetType target type - * @param current type - * @return created instance or null if the instantiation failed - */ - public static T tryToInstantiateClassForName(String className, Class targetType) - { - Object result = tryToInstantiateClassForName(className); - - //noinspection unchecked - return result != null ? (T) result : null; - } - - /** - * Tries to instantiate a class for the given name via the default constructor - * @param className name of the class - * @return created instance or null if the instantiation failed - */ - public static Object tryToInstantiateClassForName(String className) - { - try - { - return instantiateClassForName(className); - } - catch (Exception e) - { - //do nothing - it was just a try - } - return null; - } - - /** - * Creates an instance for the given class-name - * @param className name of the class which should be instantiated - * @return created instance - * @throws ClassNotFoundException if the instantiation failed - * @throws IllegalAccessException if the instantiation failed - * @throws InstantiationException if the instantiation failed - */ - public static Object instantiateClassForName(String className) - throws ClassNotFoundException, IllegalAccessException, InstantiationException - { - return loadClassForName(className).newInstance(); - } - - /** - * Reads the version of the jar which contains the given class - * @param targetClass class within the jar - * @return version-string which has been found in the manifest or null if there is no version information available - */ - public static String getJarVersion(Class targetClass) - { - String manifestFileLocation = getManifestFileLocationOfClass(targetClass); - - try - { - return new Manifest(new URL(manifestFileLocation).openStream()) - .getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION); - } - catch (Exception e) - { - return null; - } - } - - /** - * Reads the VCS revision which was used for creating the jar - * @param targetClass class within the jar - * @return revision-string which has been found in the manifest or null if there is no information available - */ - public static String getRevision(Class targetClass) - { - String manifestFileLocation = getManifestFileLocationOfClass(targetClass); - - try - { - return new Manifest(new URL(manifestFileLocation).openStream()) - .getMainAttributes().getValue("Revision"); - } - catch (Exception e) - { - return null; - } - } - - private static String getManifestFileLocationOfClass(Class targetClass) - { - String manifestFileLocation; - - try - { - manifestFileLocation = getManifestLocation(targetClass); - } - catch (Exception e) - { - //in this case we have a proxy - manifestFileLocation = getManifestLocation(targetClass.getSuperclass()); - } - return manifestFileLocation; - } - - private static String getManifestLocation(Class targetClass) - { - String classFilePath = targetClass.getCanonicalName().replace('.', '/') + ".class"; - String manifestFilePath = "/META-INF/MANIFEST.MF"; - - String classLocation = targetClass.getResource(targetClass.getSimpleName() + ".class").toString(); - return classLocation.substring(0, classLocation.indexOf(classFilePath) - 1) + manifestFilePath; - } -} http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/blob/f3cc5673/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/HierarchyDiscovery.java ---------------------------------------------------------------------- diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/HierarchyDiscovery.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/HierarchyDiscovery.java deleted file mode 100644 index 4a7fe51..0000000 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/HierarchyDiscovery.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.deltaspike.core.api.util; - -import javax.enterprise.inject.Typed; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * Utility class for resolving all bean types from a given type. - */ -//X TODO: Look at merging this with ClassUtils perhaps -//X TODO: JavaDoc -@Typed() -public class HierarchyDiscovery -{ - private final Type type; - - private Map> types; - - public HierarchyDiscovery(Type type) - { - this.type = type; - } - - protected void add(Class clazz, Type type) - { - types.put(type, clazz); - } - - public Set getTypeClosure() - { - if (types == null) - { - init(); - } - // Return an independent set with no ties to the BiMap used - return new HashSet(types.keySet()); - } - - private void init() - { - this.types = new HashMap>(); - try - { - discoverTypes(type); - } - catch (StackOverflowError e) - { - System.out.println("type" + type); - Thread.dumpStack(); - throw e; - } - } - - public Type getResolvedType() - { - if (type instanceof Class) - { - Class clazz = (Class) type; - return resolveType(clazz); - } - return type; - } - - private void discoverTypes(Type type) - { - if (type != null) - { - if (type instanceof Class) - { - Class clazz = (Class) type; - add(clazz, resolveType(clazz)); - discoverFromClass(clazz); - } - else - { - Class clazz = null; - if (type instanceof ParameterizedType) - { - Type rawType = ((ParameterizedType) type).getRawType(); - if (rawType instanceof Class) - { - discoverFromClass((Class) rawType); - clazz = (Class) rawType; - } - } - add(clazz, type); - } - } - } - - private Type resolveType(Class clazz) - { - if (clazz.getTypeParameters().length > 0) - { - TypeVariable[] actualTypeParameters = clazz.getTypeParameters(); - - @SuppressWarnings("UnnecessaryLocalVariable") - ParameterizedType parameterizedType = - new ParameterizedTypeImpl(clazz, actualTypeParameters, clazz.getDeclaringClass()); - return parameterizedType; - } - else - { - return clazz; - } - } - - private void discoverFromClass(Class clazz) - { - discoverTypes(resolveType(type, type, clazz.getGenericSuperclass())); - for (Type c : clazz.getGenericInterfaces()) - { - discoverTypes(resolveType(type, type, c)); - } - } - - /** - * Gets the actual types by resolving TypeParameters. - * - * @param beanType - * @param type - * @return actual type - */ - private Type resolveType(Type beanType, Type beanType2, Type type) - { - if (type instanceof ParameterizedType) - { - if (beanType instanceof ParameterizedType) - { - return resolveParameterizedType((ParameterizedType) beanType, (ParameterizedType) type); - } - if (beanType instanceof Class) - { - return resolveType(((Class) beanType).getGenericSuperclass(), beanType2, type); - } - } - - if (type instanceof TypeVariable) - { - if (beanType instanceof ParameterizedType) - { - return resolveTypeParameter((ParameterizedType) beanType, beanType2, (TypeVariable) type); - } - if (beanType instanceof Class) - { - return resolveType(((Class) beanType).getGenericSuperclass(), beanType2, type); - } - } - return type; - } - - private Type resolveParameterizedType(ParameterizedType beanType, ParameterizedType parameterizedType) - { - Type rawType = parameterizedType.getRawType(); - Type[] actualTypes = parameterizedType.getActualTypeArguments(); - - Type resolvedRawType = resolveType(beanType, beanType, rawType); - Type[] resolvedActualTypes = new Type[actualTypes.length]; - - for (int i = 0; i < actualTypes.length; i++) - { - resolvedActualTypes[i] = resolveType(beanType, beanType, actualTypes[i]); - } - // reconstruct ParameterizedType by types resolved TypeVariable. - return new ParameterizedTypeImpl(resolvedRawType, resolvedActualTypes, parameterizedType.getOwnerType()); - } - - private Type resolveTypeParameter(ParameterizedType type, Type beanType, TypeVariable typeVariable) - { - // step1. raw type - Class actualType = (Class) type.getRawType(); - TypeVariable[] typeVariables = actualType.getTypeParameters(); - Type[] actualTypes = type.getActualTypeArguments(); - for (int i = 0; i < typeVariables.length; i++) - { - if (typeVariables[i].equals(typeVariable) && !actualTypes[i].equals(typeVariable)) - { - return resolveType(this.type, beanType, actualTypes[i]); - } - } - - // step2. generic super class - Type genericSuperType = actualType.getGenericSuperclass(); - Type resolvedGenericSuperType = resolveType(genericSuperType, beanType, typeVariable); - if (!(resolvedGenericSuperType instanceof TypeVariable)) - { - return resolvedGenericSuperType; - } - - // step3. generic interfaces - if (beanType instanceof ParameterizedType) - { - for (Type interfaceType : ((Class) ((ParameterizedType) beanType).getRawType()).getGenericInterfaces()) - { - Type resolvedType = resolveType(interfaceType, interfaceType, typeVariable); - if (!(resolvedType instanceof TypeVariable)) - { - return resolvedType; - } - } - } - - // don't resolve type variable - return typeVariable; - } -} http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/blob/f3cc5673/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/ParameterizedTypeImpl.java ---------------------------------------------------------------------- diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/ParameterizedTypeImpl.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/ParameterizedTypeImpl.java deleted file mode 100644 index 1c37e52..0000000 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/ParameterizedTypeImpl.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.deltaspike.core.api.util; - -import javax.enterprise.inject.Typed; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.Arrays; - -/** - * A basic implementation of {@link ParameterizedType}. - */ -@Typed() -class ParameterizedTypeImpl implements ParameterizedType -{ - private final Type[] actualTypeArguments; - private final Type rawType; - private final Type ownerType; - - ParameterizedTypeImpl(Type rawType, Type[] actualTypeArguments, Type ownerType) - { - this.actualTypeArguments = actualTypeArguments; - this.rawType = rawType; - this.ownerType = ownerType; - } - - public Type[] getActualTypeArguments() - { - return Arrays.copyOf(actualTypeArguments, actualTypeArguments.length); - } - - public Type getOwnerType() - { - return ownerType; - } - - public Type getRawType() - { - return rawType; - } - - @Override - public int hashCode() - { - return Arrays.hashCode(actualTypeArguments) ^ (ownerType == null ? 0 : - ownerType.hashCode()) ^ (rawType == null ? 0 : rawType.hashCode()); - } - - @Override - public boolean equals(Object obj) - { - if (this == obj) - { - return true; - } - else if (obj instanceof ParameterizedType) - { - ParameterizedType that = (ParameterizedType) obj; - Type thatOwnerType = that.getOwnerType(); - Type thatRawType = that.getRawType(); - return (ownerType == null ? thatOwnerType == null : ownerType.equals(thatOwnerType)) - && (rawType == null ? thatRawType == null : rawType.equals(thatRawType)) - && Arrays.equals(actualTypeArguments, that.getActualTypeArguments()); - } - else - { - return false; - } - - } - - @Override - public String toString() - { - StringBuilder sb = new StringBuilder(); - sb.append(rawType); - if (actualTypeArguments.length > 0) - { - sb.append("<"); - for (Type actualType : actualTypeArguments) - { - sb.append(actualType); - sb.append(","); - } - sb.delete(sb.length() - 1, sb.length()); - sb.append(">"); - } - return sb.toString(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/blob/f3cc5673/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/Reflections.java ---------------------------------------------------------------------- diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/Reflections.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/Reflections.java deleted file mode 100644 index 0be23ae..0000000 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/Reflections.java +++ /dev/null @@ -1,1424 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.deltaspike.core.api.util; - -import javax.enterprise.inject.Typed; -import javax.enterprise.inject.spi.AnnotatedField; -import javax.enterprise.inject.spi.AnnotatedType; -import javax.enterprise.inject.spi.BeanManager; -import javax.inject.Qualifier; -import java.beans.Introspector; -import java.io.Serializable; -import java.lang.annotation.Annotation; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Member; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.security.AccessController; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -//import java.util.Arrays; - -/** - * Utilities for common reflection based actions. Some are basic Java Reflection based, others are CDI based. - */ -//X TODO: Look at merging this with some of the other classes from CODI, or if they're really needed -//X TODO: Also some methods need JavaDoc -@Typed() -public class Reflections -{ - /** - * An empty array of type {@link Annotation}, useful converting lists to - * arrays. - */ - public static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0]; - - /** - * An empty array of type {@link Object}, useful for converting lists to - * arrays. - */ - public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; - - public static final Type[] EMPTY_TYPES = {}; - - public static final Class[] EMPTY_CLASSES = new Class[0]; - - private Reflections() - { - } - - /** - *

- * Perform a runtime cast. Similar to {@link Class#cast(Object)}, but useful - * when you do not have a {@link Class} object for type you wish to cast to. - *

- *

- *

- * {@link Class#cast(Object)} should be used if possible - *

- * - * @param the type to cast to - * @param obj the object to perform the cast on - * @return the casted object - * @throws ClassCastException if the type T is not a subtype of the object - * @see Class#cast(Object) - */ - @SuppressWarnings("unchecked") - public static T cast(Object obj) - { - return (T) obj; - } - - /** - * Get all the declared fields on the class hierarchy. This will - * return overridden fields. - * - * @param clazz The class to search - * @return the set of all declared fields or an empty set if there are none - */ - public static Set getAllDeclaredFields(Class clazz) - { - HashSet fields = new HashSet(); - for (Class c = clazz; c != null && c != Object.class; c = c.getSuperclass()) - { - for (Field a : c.getDeclaredFields()) - { - fields.add(a); - } - } - return fields; - } - - /** - * Search the class hierarchy for a field with the given name. Will return - * the nearest match, starting with the class specified and searching up the - * hierarchy. - * - * @param clazz The class to search - * @param name The name of the field to search for - * @return The field found, or null if no field is found - */ - public static Field findDeclaredField(Class clazz, String name) - { - for (Class c = clazz; c != null && c != Object.class; c = c.getSuperclass()) - { - try - { - return c.getDeclaredField(name); - } - catch (NoSuchFieldException e) - { - // No-op, we continue looking up the class hierarchy - } - } - return null; - } - - /** - * Search the annotatedType for the field, returning the - * {@link AnnotatedField} - * - * @param annotatedType The annotatedType to search - * @param field the field to search for - * @return The {@link AnnotatedField} found, or null if no field is found - */ - public static AnnotatedField getField(AnnotatedType annotatedType, Field field) - { - for (AnnotatedField annotatedField : annotatedType.getFields()) - { - if (annotatedField.getDeclaringType().getJavaClass().equals(field.getDeclaringClass()) && - annotatedField.getJavaMember().getName().equals(field.getName())) - { - return annotatedField; - } - } - return null; - } - - /** - * Search for annotations with the specified meta annotation type - * - * @param annotations The annotation set to search - * @param metaAnnotationType The type of the meta annotation to search for - * @return The set of annotations with the specified meta annotation, or an - * empty set if none are found - */ - public static Set getAnnotationsWithMetaAnnotation(Set annotations, - Class metaAnnotationType) - { - Set set = new HashSet(); - for (Annotation annotation : annotations) - { - if (annotation.annotationType().isAnnotationPresent(metaAnnotationType)) - { - set.add(annotation); - } - } - return set; - } - - /** - * Extract any qualifiers from the set of annotations - * - * @param annotations The set of annotations to search - * @param beanManager The beanManager to use to establish if an annotation is - * a qualifier - * @return The qualifiers present in the set, or an empty set if there are - * none - */ - public static Set getQualifiers(Set annotations, BeanManager beanManager) - { - Set set = new HashSet(); - for (Annotation annotation : annotations) - { - if (beanManager.isQualifier(annotation.annotationType())) - { - set.add(annotation); - } - } - return set; - } - - /** - * Determine if a method exists in a specified class hierarchy - * - * @param clazz The class to search - * @param name The name of the method - * @return true if a method is found, otherwise false - */ - public static boolean methodExists(Class clazz, String name) - { - for (Class c = clazz; c != null && c != Object.class; c = c.getSuperclass()) - { - for (Method m : c.getDeclaredMethods()) - { - if (m.getName().equals(name)) - { - return true; - } - } - } - return false; - } - - /** - * Get all the declared methods on the class hierarchy. This will - * return overridden methods. - * - * @param clazz The class to search - * @return the set of all declared methods or an empty set if there are none - */ - public static Set getAllDeclaredMethods(Class clazz) - { - HashSet methods = new HashSet(); - for (Class c = clazz; c != null && c != Object.class; c = c.getSuperclass()) - { - for (Method a : c.getDeclaredMethods()) - { - methods.add(a); - } - } - return methods; - } - - /** - * Search the class hierarchy for a method with the given name and arguments. - * Will return the nearest match, starting with the class specified and - * searching up the hierarchy. - * - * @param clazz The class to search - * @param name The name of the method to search for - * @param args The arguments of the method to search for - * @return The method found, or null if no method is found - */ - public static Method findDeclaredMethod(Class clazz, String name, Class... args) - { - for (Class c = clazz; c != null && c != Object.class; c = c.getSuperclass()) - { - try - { - return c.getDeclaredMethod(name, args); - } - catch (NoSuchMethodException e) - { - // No-op, continue the search - } - } - return null; - } - - /** - * Search the class hierarchy for a constructor with the given arguments. - * Will return the nearest match, starting with the class specified and - * searching up the hierarchy. - * - * @param clazz The class to search - * @param args The arguments of the constructor to search for - * @return The constructor found, or null if no constructor is found - */ - public static Constructor findDeclaredConstructor(Class clazz, Class... args) - { - for (Class c = clazz; c != null && c != Object.class; c = c.getSuperclass()) - { - try - { - return c.getDeclaredConstructor(args); - } - catch (NoSuchMethodException e) - { - // No-op, continue the search - } - } - return null; - } - - /** - * Get all the declared constructors on the class hierarchy. This will - * return overridden constructors. - * - * @param clazz The class to search - * @return the set of all declared constructors or an empty set if there are - * none - */ - public static Set> getAllDeclaredConstructors(Class clazz) - { - HashSet> constructors = new HashSet>(); - for (Class c = clazz; c != null && c != Object.class; c = c.getSuperclass()) - { - for (Constructor constructor : c.getDeclaredConstructors()) - { - constructors.add(constructor); - } - } - return constructors; - } - - /** - * Get the type of the member - * - * @param member The member - * @return The type of the member - * @throws UnsupportedOperationException if the member is not a field, - * method, or constructor - */ - public static Class getMemberType(Member member) - { - if (member instanceof Field) - { - return ((Field) member).getType(); - } - else if (member instanceof Method) - { - return ((Method) member).getReturnType(); - } - else if (member instanceof Constructor) - { - return ((Constructor) member).getDeclaringClass(); - } - else - { - throw new UnsupportedOperationException("Cannot operate on a member of type " + member.getClass()); - } - } - - /** - *

- * Loads and initializes a class for the given name. - *

- *

- *

- * If the Thread Context Class Loader is available, it will be used, - * otherwise the classloader used to load {@link Reflections} will be used - *

- *

- *

- * It is also possible to specify additional classloaders to attempt to load - * the class with. If the first attempt fails, then these additional loaders - * are tried in order. - *

- * - * @param name the name of the class to load - * @param loaders additional classloaders to use to attempt to load the class - * @return the class object - * @throws ClassNotFoundException if the class cannot be found - * @deprecated move/merge with ClassUtils - */ - public static Class classForName(String name, ClassLoader... loaders) throws ClassNotFoundException - { - try - { - if (Thread.currentThread().getContextClassLoader() != null) - { - return Class.forName(name, true, Thread.currentThread().getContextClassLoader()); - } - else - { - return Class.forName(name); - } - } - catch (ClassNotFoundException e) - { - for (ClassLoader l : loaders) - { - try - { - return Class.forName(name, true, l); - } - catch (ClassNotFoundException ex) - { - - } - } - } - if (Thread.currentThread().getContextClassLoader() != null) - { - throw new ClassNotFoundException(String.format( - "Could not load class %s with the context class loader %s or any of the additional ClassLoaders: %s", - name, Thread.currentThread().getContextClassLoader(), loaders)); - } - else - { - throw new ClassNotFoundException("Could not load class " + name + - " using Class.forName or using any of the additional ClassLoaders: " + Arrays.toString(loaders)); - } - } - - private static String buildInvokeMethodErrorMessage(Method method, Object obj, Object... args) - { - StringBuilder message = new StringBuilder(String.format( - "Exception invoking method [%s] on object [%s], using arguments [", method.getName(), obj)); - if (args != null) - { - for (int i = 0; i < args.length; i++) - { - message.append(i > 0 ? "," : "") - .append(args[i]); - } - } - message.append("]"); - return message.toString(); - } - - /** - * Set the accessibility flag on the {@link AccessibleObject} as described in - * {@link AccessibleObject#setAccessible(boolean)} within the context of - * a {@link java.security.PrivilegedAction}. - * - * @param member the accessible object type - * @param member the accessible object - * @return the accessible object after the accessible flag has been altered - */ - public static A setAccessible(A member) - { - AccessController.doPrivileged(new SetAccessiblePrivilegedAction(member)); - return member; - } - - /** - *

- * Invoke the specified method on the provided instance, passing any additional - * arguments included in this method as arguments to the specified method. - *

- *

- *

This method provides the same functionality and throws the same exceptions as - * {@link Reflections#invokeMethod(boolean, Method, Class, Object, Object...)}, with the - * expected return type set to {@link Object} and no change to the method's accessibility.

- * - * @see Reflections#invokeMethod(boolean, Method, Class, Object, Object...) - * @see Method#invoke(Object, Object...) - */ - public static Object invokeMethod(Method method, Object instance, Object... args) - { - return invokeMethod(false, method, Object.class, instance, args); - } - - /** - *

- * Invoke the specified method on the provided instance, passing any additional - * arguments included in this method as arguments to the specified method. - *

- *

- *

- * This method attempts to set the accessible flag of the method in a - * {@link PrivilegedAction} before invoking the method if the first argument - * is true. - *

- *

- *

This method provides the same functionality and throws the same exceptions as - * {@link Reflections#invokeMethod(boolean, Method, Class, Object, Object...)}, with the - * expected return type set to {@link Object}.

- * - * @see Reflections#invokeMethod(boolean, Method, Class, Object, Object...) - * @see Method#invoke(Object, Object...) - */ - public static Object invokeMethod(boolean setAccessible, Method method, Object instance, Object... args) - { - return invokeMethod(setAccessible, method, Object.class, instance, args); - } - - /** - *

- * Invoke the specified method on the provided instance, passing any additional - * arguments included in this method as arguments to the specified method. - *

- *

- *

This method provides the same functionality and throws the same exceptions as - * {@link Reflections#invokeMethod(boolean, Method, Class, Object, Object...)}, with the - * expected return type set to {@link Object} and honoring the accessibility of - * the method.

- * - * @see Reflections#invokeMethod(boolean, Method, Class, Object, Object...) - * @see Method#invoke(Object, Object...) - */ - public static T invokeMethod(Method method, Class expectedReturnType, Object instance, Object... args) - { - return invokeMethod(false, method, expectedReturnType, instance, args); - } - - /** - *

- * Invoke the method on the instance, with any arguments specified, casting - * the result of invoking the method to the expected return type. - *

- *

- *

- * This method wraps {@link Method#invoke(Object, Object...)}, converting the - * checked exceptions that {@link Method#invoke(Object, Object...)} specifies - * to runtime exceptions. - *

- *

- *

- * If instructed, this method attempts to set the accessible flag of the method in a - * {@link PrivilegedAction} before invoking the method. - *

- * - * @param setAccessible flag indicating whether method should first be set as - * accessible - * @param method the method to invoke - * @param instance the instance to invoke the method - * @param args the arguments to the method - * @return the result of invoking the method, or null if the method's return - * type is void - * @throws RuntimeException if this Method object enforces Java - * language access control and the underlying method is - * inaccessible or if the underlying method throws an exception or - * if the initialization provoked by this method fails. - * @throws IllegalArgumentException if the method is an instance method and - * the specified instance argument is not an instance - * of the class or interface declaring the underlying method (or - * of a subclass or implementor thereof); if the number of actual - * and formal parameters differ; if an unwrapping conversion for - * primitive arguments fails; or if, after possible unwrapping, a - * parameter value cannot be converted to the corresponding formal - * parameter type by a method invocation conversion. - * @throws NullPointerException if the specified instance is - * null and the method is an instance method. - * @throws ClassCastException if the result of invoking the method cannot be - * cast to the expectedReturnType - * @throws ExceptionInInitializerError if the initialization provoked by this - * method fails. - * @see Method#invoke(Object, Object...) - */ - public static T invokeMethod(boolean setAccessible, - Method method, Class expectedReturnType, - Object instance, Object... args) - { - if (setAccessible && !method.isAccessible()) - { - setAccessible(method); - } - - try - { - return expectedReturnType.cast(method.invoke(instance, args)); - } - catch (IllegalAccessException ex) - { - throw new RuntimeException(buildInvokeMethodErrorMessage(method, instance, args), ex); - } - catch (IllegalArgumentException ex) - { - throw new IllegalArgumentException(buildInvokeMethodErrorMessage(method, instance, args), ex); - } - catch (InvocationTargetException ex) - { - throw new RuntimeException(buildInvokeMethodErrorMessage(method, instance, args), ex.getCause()); - } - catch (NullPointerException ex) - { - NullPointerException ex2 = new NullPointerException(buildInvokeMethodErrorMessage(method, instance, args)); - ex2.initCause(ex.getCause()); - throw ex2; - } - catch (ExceptionInInitializerError e) - { - ExceptionInInitializerError e2 = - new ExceptionInInitializerError(buildInvokeMethodErrorMessage(method, instance, args)); - e2.initCause(e.getCause()); - throw e2; - } - } - - /** - *

- * Set the value of a field on the instance to the specified value. - *

- *

- *

This method provides the same functionality and throws the same exceptions as - * {@link Reflections#setFieldValue(boolean, Method, Class, Object, Object...)}, honoring - * the accessibility of the field.

- */ - public static void setFieldValue(Field field, Object instance, Object value) - { - setFieldValue(false, field, instance, value); - } - - /** - *

- * Sets the value of a field on the instance to the specified value. - *

- *

- *

- * This method wraps {@link Field#set(Object, Object)}, converting the - * checked exceptions that {@link Field#set(Object, Object)} specifies to - * runtime exceptions. - *

- *

- *

- * If instructed, this method attempts to set the accessible flag of the method in a - * {@link PrivilegedAction} before invoking the method. - *

- * - * @param field the field on which to operate, or null if the field is static - * @param instance the instance on which the field value should be set upon - * @param value the value to set the field to - * @throws RuntimeException if the underlying field is inaccessible. - * @throws IllegalArgumentException if the specified instance is not an - * instance of the class or interface declaring the underlying - * field (or a subclass or implementor thereof), or if an - * unwrapping conversion fails. - * @throws NullPointerException if the specified instance is null and the field - * is an instance field. - * @throws ExceptionInInitializerError if the initialization provoked by this - * method fails. - * @see Field#set(Object, Object) - */ - public static void setFieldValue(boolean setAccessible, Field field, Object instance, Object value) - { - if (setAccessible && !field.isAccessible()) - { - setAccessible(field); - } - - try - { - field.set(instance, value); - } - catch (IllegalAccessException e) - { - throw new RuntimeException(buildSetFieldValueErrorMessage(field, instance, value), e); - } - catch (NullPointerException ex) - { - NullPointerException ex2 = new NullPointerException(buildSetFieldValueErrorMessage(field, instance, value)); - ex2.initCause(ex.getCause()); - throw ex2; - } - catch (ExceptionInInitializerError e) - { - ExceptionInInitializerError e2 = - new ExceptionInInitializerError(buildSetFieldValueErrorMessage(field, instance, value)); - e2.initCause(e.getCause()); - throw e2; - } - } - - private static String buildSetFieldValueErrorMessage(Field field, Object obj, Object value) - { - return String.format("Exception setting [%s] field on object [%s] to value [%s]", field.getName(), obj, value); - } - - private static String buildGetFieldValueErrorMessage(Field field, Object obj) - { - return String.format("Exception reading [%s] field from object [%s].", field.getName(), obj); - } - - public static Object getFieldValue(Field field, Object instance) - { - return getFieldValue(field, instance, Object.class); - } - - /** - *

- * Get the value of the field, on the specified instance, casting the value - * of the field to the expected type. - *

- *

- *

- * This method wraps {@link Field#get(Object)}, converting the checked - * exceptions that {@link Field#get(Object)} specifies to runtime exceptions. - *

- * - * @param the type of the field's value - * @param field the field to operate on - * @param instance the instance from which to retrieve the value - * @param expectedType the expected type of the field's value - * @return the value of the field - * @throws RuntimeException if the underlying field is inaccessible. - * @throws IllegalArgumentException if the specified instance is not an - * instance of the class or interface declaring the underlying - * field (or a subclass or implementor thereof). - * @throws NullPointerException if the specified instance is null and the field - * is an instance field. - * @throws ExceptionInInitializerError if the initialization provoked by this - * method fails. - */ - public static T getFieldValue(Field field, Object instance, Class expectedType) - { - try - { - return Reflections.cast(field.get(instance)); - } - catch (IllegalAccessException e) - { - throw new RuntimeException(buildGetFieldValueErrorMessage(field, instance), e); - } - catch (NullPointerException ex) - { - NullPointerException ex2 = new NullPointerException(buildGetFieldValueErrorMessage(field, instance)); - ex2.initCause(ex.getCause()); - throw ex2; - } - catch (ExceptionInInitializerError e) - { - ExceptionInInitializerError e2 = - new ExceptionInInitializerError(buildGetFieldValueErrorMessage(field, instance)); - e2.initCause(e.getCause()); - throw e2; - } - } - - /** - * Extract the raw type, given a type. - * - * @param the type - * @param type the type to extract the raw type from - * @return the raw type, or null if the raw type cannot be determined. - */ - @SuppressWarnings("unchecked") - public static Class getRawType(Type type) - { - if (type instanceof Class) - { - return (Class) type; - } - else if (type instanceof ParameterizedType) - { - if (((ParameterizedType) type).getRawType() instanceof Class) - { - return (Class) ((ParameterizedType) type).getRawType(); - } - } - return null; - } - - /** - * Check if a class is serializable. - * - * @param clazz The class to check - * @return true if the class implements serializable or is a primitive - */ - public static boolean isSerializable(Class clazz) - { - return clazz.isPrimitive() || Serializable.class.isAssignableFrom(clazz); - } - - - public static Map, Type> buildTypeMap(Set types) - { - Map, Type> map = new HashMap, Type>(); - for (Type type : types) - { - if (type instanceof Class) - { - map.put((Class) type, type); - } - else if (type instanceof ParameterizedType) - { - if (((ParameterizedType) type).getRawType() instanceof Class) - { - map.put((Class) ((ParameterizedType) type).getRawType(), type); - } - } - else if (type instanceof TypeVariable) - { - - } - } - return map; - } - - public static boolean isCacheable(Set annotations) - { - for (Annotation qualifier : annotations) - { - Class clazz = qualifier.getClass(); - if (clazz.isAnonymousClass() || (clazz.isMemberClass() && isStatic(clazz))) - { - return false; - } - } - return true; - } - - public static boolean isCacheable(Annotation[] annotations) - { - for (Annotation qualifier : annotations) - { - Class clazz = qualifier.getClass(); - if (clazz.isAnonymousClass() || (clazz.isMemberClass() && isStatic(clazz))) - { - return false; - } - } - return true; - } - - /** - * Gets the property name from a getter method. - *

- * We extend JavaBean conventions, allowing the getter method to have parameters - * - * @param method The getter method - * @return The name of the property. Returns null if method wasn't JavaBean - * getter-styled - */ - public static String getPropertyName(Method method) - { - String methodName = method.getName(); - if (methodName.matches("^(get).*")) - { - return Introspector.decapitalize(methodName.substring(3)); - } - else if (methodName.matches("^(is).*")) - { - return Introspector.decapitalize(methodName.substring(2)); - } - else - { - return null; - } - - } - - /** - * Checks if class is final - * - * @param clazz The class to check - * @return True if final, false otherwise - */ - public static boolean isFinal(Class clazz) - { - return Modifier.isFinal(clazz.getModifiers()); - } - - public static int getNesting(Class clazz) - { - if (clazz.isMemberClass() && !isStatic(clazz)) - { - return 1 + getNesting(clazz.getDeclaringClass()); - } - else - { - return 0; - } - } - - /** - * Checks if member is final - * - * @param member The member to check - * @return True if final, false otherwise - */ - public static boolean isFinal(Member member) - { - return Modifier.isFinal(member.getModifiers()); - } - - /** - * Checks if member is private - * - * @param member The member to check - * @return True if final, false otherwise - */ - public static boolean isPrivate(Member member) - { - return Modifier.isPrivate(member.getModifiers()); - } - - /** - * Checks if type or member is final - * - * @param type Type or member - * @return True if final, false otherwise - */ - public static boolean isTypeOrAnyMethodFinal(Class type) - { - return getNonPrivateFinalMethodOrType(type) != null; - } - - public static Object getNonPrivateFinalMethodOrType(Class type) - { - if (isFinal(type)) - { - return type; - } - for (Method method : type.getDeclaredMethods()) - { - if (isFinal(method) && !isPrivate(method)) - { - return method; - } - } - return null; - } - - public static boolean isPackagePrivate(int mod) - { - return !(Modifier.isPrivate(mod) || Modifier.isProtected(mod) || Modifier.isPublic(mod)); - } - - /** - * Checks if type is static - * - * @param type Type to check - * @return True if static, false otherwise - */ - public static boolean isStatic(Class type) - { - return Modifier.isStatic(type.getModifiers()); - } - - /** - * Checks if member is static - * - * @param member Member to check - * @return True if static, false otherwise - */ - public static boolean isStatic(Member member) - { - return Modifier.isStatic(member.getModifiers()); - } - - public static boolean isTransient(Member member) - { - return Modifier.isTransient(member.getModifiers()); - } - - /** - * Checks if a method is abstract - * - * @param method - * @return - */ - public static boolean isAbstract(Method method) - { - return Modifier.isAbstract(method.getModifiers()); - } - - /** - * Gets the actual type arguments of a class - * - * @param clazz The class to examine - * @return The type arguments - */ - public static Type[] getActualTypeArguments(Class clazz) - { - Type type = new HierarchyDiscovery(clazz).getResolvedType(); - if (type instanceof ParameterizedType) - { - return ((ParameterizedType) type).getActualTypeArguments(); - } - else - { - return EMPTY_TYPES; - } - } - - /** - * Gets the actual type arguments of a Type - * - * @param type The type to examine - * @return The type arguments - */ - public static Type[] getActualTypeArguments(Type type) - { - Type resolvedType = new HierarchyDiscovery(type).getResolvedType(); - if (resolvedType instanceof ParameterizedType) - { - return ((ParameterizedType) resolvedType).getActualTypeArguments(); - } - else - { - return EMPTY_TYPES; - } - } - - /** - * Checks if raw type is array type - * - * @param rawType The raw type to check - * @return True if array, false otherwise - */ - public static boolean isArrayType(Class rawType) - { - return rawType.isArray(); - } - - /** - * Checks if type is parameterized type - * - * @param type The type to check - * @return True if parameterized, false otherwise - */ - public static boolean isParameterizedType(Class type) - { - return type.getTypeParameters().length > 0; - } - - public static boolean isParamerterizedTypeWithWildcard(Class type) - { - if (isParameterizedType(type)) - { - return containsWildcards(type.getTypeParameters()); - } - else - { - return false; - } - } - - public static boolean containsWildcards(Type[] types) - { - for (Type type : types) - { - if (type instanceof WildcardType) - { - return true; - } - } - return false; - } - - /** - * Checks the bindingType to make sure the annotation was declared properly - * as a binding type (annotated with @BindingType) and that it has a runtime - * retention policy. - * - * @param binding The binding type to check - * @return true only if the annotation is really a binding type - */ - @Deprecated - // TODO Replace usage of this with metadatacache - public static boolean isBindings(Annotation binding) - { - boolean isBindingAnnotation = false; - if (binding.annotationType().isAnnotationPresent(Qualifier.class) - && binding.annotationType().isAnnotationPresent(Retention.class) - && binding.annotationType().getAnnotation(Retention.class).value().equals(RetentionPolicy.RUNTIME)) - { - isBindingAnnotation = true; - } - return isBindingAnnotation; - } - - /** - * Check the assignability of one type to another, taking into account the - * actual type arguements - * - * @param rawType1 the raw type of the class to check - * @param actualTypeArguments1 the actual type arguements to check, or an - * empty array if not a parameterized type - * @param rawType2 the raw type of the class to check - * @param actualTypeArguments2 the actual type arguements to check, or an - * empty array if not a parameterized type - * @return - */ - public static boolean isAssignableFrom(Class rawType1, - Type[] actualTypeArguments1, - Class rawType2, - Type[] actualTypeArguments2) - { - return Types.boxedClass(rawType1).isAssignableFrom(Types.boxedClass(rawType2)) && - isAssignableFrom(actualTypeArguments1, actualTypeArguments2); - } - - public static boolean matches(Class rawType1, - Type[] actualTypeArguments1, - Class rawType2, - Type[] actualTypeArguments2) - { - return Types.boxedClass(rawType1).equals(Types.boxedClass(rawType2)) && - isAssignableFrom(actualTypeArguments1, actualTypeArguments2); - } - - public static boolean isAssignableFrom(Type[] actualTypeArguments1, Type[] actualTypeArguments2) - { - for (int i = 0; i < actualTypeArguments1.length; i++) - { - Type type1 = actualTypeArguments1[i]; - Type type2 = Object.class; - if (actualTypeArguments2.length > i) - { - type2 = actualTypeArguments2[i]; - } - if (!isAssignableFrom(type1, type2)) - { - return false; - } - } - return true; - } - - public static boolean isAssignableFrom(Type type1, Set types2) - { - for (Type type2 : types2) - { - if (isAssignableFrom(type1, type2)) - { - return true; - } - } - return false; - } - - public static boolean matches(Type type1, Set types2) - { - for (Type type2 : types2) - { - if (matches(type1, type2)) - { - return true; - } - } - return false; - } - - public static boolean isAssignableFrom(Type type1, Type[] types2) - { - for (Type type2 : types2) - { - if (isAssignableFrom(type1, type2)) - { - return true; - } - } - return false; - } - - public static boolean isAssignableFrom(Type type1, Type type2) - { - if (type1 instanceof Class) - { - Class clazz = (Class) type1; - if (isAssignableFrom(clazz, EMPTY_TYPES, type2)) - { - return true; - } - } - if (type1 instanceof ParameterizedType) - { - ParameterizedType parameterizedType1 = (ParameterizedType) type1; - if (parameterizedType1.getRawType() instanceof Class) - { - if (isAssignableFrom((Class) parameterizedType1.getRawType(), - parameterizedType1.getActualTypeArguments(), - type2)) - { - return true; - } - } - } - if (type1 instanceof WildcardType) - { - WildcardType wildcardType = (WildcardType) type1; - if (isTypeBounded(type2, wildcardType.getLowerBounds(), wildcardType.getUpperBounds())) - { - return true; - } - } - if (type2 instanceof WildcardType) - { - WildcardType wildcardType = (WildcardType) type2; - if (isTypeBounded(type1, wildcardType.getUpperBounds(), wildcardType.getLowerBounds())) - { - return true; - } - } - if (type1 instanceof TypeVariable) - { - TypeVariable typeVariable = (TypeVariable) type1; - if (isTypeBounded(type2, EMPTY_TYPES, typeVariable.getBounds())) - { - return true; - } - } - if (type2 instanceof TypeVariable) - { - TypeVariable typeVariable = (TypeVariable) type2; - if (isTypeBounded(type1, typeVariable.getBounds(), EMPTY_TYPES)) - { - return true; - } - } - return false; - } - - public static boolean matches(Type type1, Type type2) - { - if (type1 instanceof Class) - { - Class clazz = (Class) type1; - if (matches(clazz, EMPTY_TYPES, type2)) - { - return true; - } - } - if (type1 instanceof ParameterizedType) - { - ParameterizedType parameterizedType1 = (ParameterizedType) type1; - if (parameterizedType1.getRawType() instanceof Class) - { - if (matches((Class) parameterizedType1.getRawType(), - parameterizedType1.getActualTypeArguments(), - type2)) - { - return true; - } - } - } - if (type1 instanceof WildcardType) - { - WildcardType wildcardType = (WildcardType) type1; - if (isTypeBounded(type2, wildcardType.getLowerBounds(), wildcardType.getUpperBounds())) - { - return true; - } - } - if (type2 instanceof WildcardType) - { - WildcardType wildcardType = (WildcardType) type2; - if (isTypeBounded(type1, wildcardType.getUpperBounds(), wildcardType.getLowerBounds())) - { - return true; - } - } - if (type1 instanceof TypeVariable) - { - TypeVariable typeVariable = (TypeVariable) type1; - if (isTypeBounded(type2, EMPTY_TYPES, typeVariable.getBounds())) - { - return true; - } - } - if (type2 instanceof TypeVariable) - { - TypeVariable typeVariable = (TypeVariable) type2; - if (isTypeBounded(type1, typeVariable.getBounds(), EMPTY_TYPES)) - { - return true; - } - } - return false; - } - - public static boolean isTypeBounded(Type type, Type[] lowerBounds, Type[] upperBounds) - { - if (lowerBounds.length > 0) - { - if (!isAssignableFrom(type, lowerBounds)) - { - return false; - } - } - if (upperBounds.length > 0) - { - if (!isAssignableFrom(upperBounds, type)) - { - return false; - } - } - return true; - } - - public static boolean isAssignableFrom(Class rawType1, Type[] actualTypeArguments1, Type type2) - { - if (type2 instanceof ParameterizedType) - { - ParameterizedType parameterizedType = (ParameterizedType) type2; - if (parameterizedType.getRawType() instanceof Class) - { - if (isAssignableFrom( - rawType1, - actualTypeArguments1, - (Class) parameterizedType.getRawType(), - parameterizedType.getActualTypeArguments())) - { - return true; - } - } - } - else if (type2 instanceof Class) - { - Class clazz = (Class) type2; - if (isAssignableFrom(rawType1, actualTypeArguments1, clazz, EMPTY_TYPES)) - { - return true; - } - } - else if (type2 instanceof TypeVariable) - { - TypeVariable typeVariable = (TypeVariable) type2; - if (isTypeBounded(rawType1, actualTypeArguments1, typeVariable.getBounds())) - { - return true; - } - } - return false; - } - - public static boolean matches(Class rawType1, Type[] actualTypeArguments1, Type type2) - { - if (type2 instanceof ParameterizedType) - { - ParameterizedType parameterizedType = (ParameterizedType) type2; - if (parameterizedType.getRawType() instanceof Class) - { - if (matches( - rawType1, - actualTypeArguments1, - (Class) parameterizedType.getRawType(), - parameterizedType.getActualTypeArguments())) - { - return true; - } - } - } - else if (type2 instanceof Class) - { - Class clazz = (Class) type2; - if (matches(rawType1, actualTypeArguments1, clazz, EMPTY_TYPES)) - { - return true; - } - } - return false; - } - - /** - * Check the assiginability of a set of flattened types. This - * algorithm will check whether any of the types1 matches a type in types2 - * - * @param types1 - * @param types2 - * @return - */ - public static boolean isAssignableFrom(Set types1, Set types2) - { - for (Type type : types1) - { - if (isAssignableFrom(type, types2)) - { - return true; - } - } - return false; - } - - /** - * Check whether whether any of the types1 matches a type in types2 - * - * @param types1 - * @param types2 - * @return - */ - public static boolean matches(Set types1, Set types2) - { - for (Type type : types1) - { - if (matches(type, types2)) - { - return true; - } - } - return false; - } - - /** - * Check the assiginability of a set of flattened types. This - * algorithm will check whether any of the types1 matches a type in types2 - * - * @param types1 - * @param type2 - * @return - */ - public static boolean isAssignableFrom(Set types1, Type type2) - { - for (Type type : types1) - { - if (isAssignableFrom(type, type2)) - { - return true; - } - } - return false; - } - - public static boolean isAssignableFrom(Type[] types1, Type type2) - { - for (Type type : types1) - { - if (isAssignableFrom(type, type2)) - { - return true; - } - } - return false; - } - - public static boolean isPrimitive(Type type) - { - Class rawType = getRawType(type); - return rawType != null && rawType.isPrimitive(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-deltaspike/blob/f3cc5673/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/SetAccessiblePrivilegedAction.java ---------------------------------------------------------------------- diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/SetAccessiblePrivilegedAction.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/SetAccessiblePrivilegedAction.java deleted file mode 100644 index 53c0115..0000000 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/util/SetAccessiblePrivilegedAction.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.deltaspike.core.api.util; - -import javax.enterprise.inject.Typed; -import java.lang.reflect.AccessibleObject; -import java.security.PrivilegedAction; - -/** - * PrivilegedAction instance to enabling access to the specified {@link AccessibleObject}. - */ -@Typed() -public class SetAccessiblePrivilegedAction implements PrivilegedAction -{ - - private final AccessibleObject member; - - public SetAccessiblePrivilegedAction(AccessibleObject member) - { - this.member = member; - } - - public Void run() - { - member.setAccessible(true); - return null; - } - -}