Example usage for java.lang Class asSubclass

List of usage examples for java.lang Class asSubclass

Introduction

In this page you can find the example usage for java.lang Class asSubclass.

Prototype

@SuppressWarnings("unchecked")
public <U> Class<? extends U> asSubclass(Class<U> clazz) 

Source Link

Document

Casts this Class object to represent a subclass of the class represented by the specified class object.

Usage

From source file:ome.services.graphs.GraphPathBean.java

/**
 * Process the Hibernate domain object model to initialize this class' instance fields.
 * No other method should write to them.
 * @param sessionFactory the Hibernate session factory
 *//*from w  w  w . j a  v a  2  s  .  co  m*/
private void initialize(SessionFactoryImplementor sessionFactory) {
    /* note all the direct superclasses */
    final Map<String, String> superclasses = new HashMap<String, String>();
    final Map<String, ClassMetadata> classesMetadata = sessionFactory.getAllClassMetadata();
    for (final String className : classesMetadata.keySet()) {
        try {
            final Class<?> actualClass = Class.forName(className);
            if (IObject.class.isAssignableFrom(actualClass)) {
                classesBySimpleName.put(actualClass.getSimpleName(), actualClass.asSubclass(IObject.class));
                final Set<String> subclassNames = sessionFactory.getEntityPersister(className)
                        .getEntityMetamodel().getSubclassEntityNames();
                for (final String subclassName : subclassNames) {
                    if (!subclassName.equals(className)) {
                        final Class<?> actualSubclass = Class.forName(subclassName);
                        if (actualSubclass.getSuperclass() == actualClass) {
                            superclasses.put(subclassName, className);
                        }
                    }
                }
            } else {
                log.warn("mapped class " + className + " is not a " + IObject.class.getName());
            }
        } catch (ClassNotFoundException e) {
            log.error("could not instantiate class", e);
        }
    }
    /* note the indirect superclasses and subclasses */
    for (final Entry<String, String> superclassRelationship : superclasses.entrySet()) {
        final String startClass = superclassRelationship.getKey();
        String superclass = superclassRelationship.getValue();
        while (superclass != null) {
            allSuperclasses.put(startClass, superclass);
            allSubclasses.put(superclass, startClass);
            superclass = superclasses.get(superclass);
        }
    }
    /* queue for processing all the properties of all the mapped entities: name, type, nullability */
    final Queue<PropertyDetails> propertyQueue = new LinkedList<PropertyDetails>();
    final Map<String, Set<String>> allPropertyNames = new HashMap<String, Set<String>>();
    for (final Entry<String, ClassMetadata> classMetadata : classesMetadata.entrySet()) {
        final String className = classMetadata.getKey();
        final ClassMetadata metadata = classMetadata.getValue();
        /* note name of identifier property */
        classIdProperties.put(metadata.getEntityName(), metadata.getIdentifierPropertyName());
        /* queue other properties */
        final String[] propertyNames = metadata.getPropertyNames();
        final Type[] propertyTypes = metadata.getPropertyTypes();
        final boolean[] propertyNullabilities = metadata.getPropertyNullability();
        for (int i = 0; i < propertyNames.length; i++) {
            final List<String> propertyPath = Collections.singletonList(propertyNames[i]);
            propertyQueue.add(
                    new PropertyDetails(className, propertyPath, propertyTypes[i], propertyNullabilities[i]));
        }
        final Set<String> propertyNamesSet = new HashSet<String>(propertyNames.length);
        propertyNamesSet.addAll(Arrays.asList(propertyNames));
        allPropertyNames.put(className, propertyNamesSet);
    }
    /* process each property to note entity linkages */
    while (!propertyQueue.isEmpty()) {
        final PropertyDetails property = propertyQueue.remove();
        if (ignoreProperty(property.path.get(property.path.size() - 1))) {
            continue;
        }
        /* if the property has a component type, queue the parts for processing */
        if (property.type instanceof ComponentType) {
            final ComponentType componentType = (ComponentType) property.type;
            final String[] componentPropertyNames = componentType.getPropertyNames();
            final Type[] componentPropertyTypes = componentType.getSubtypes();
            final boolean[] componentPropertyNullabilities = componentType.getPropertyNullability();
            for (int i = 0; i < componentPropertyNames.length; i++) {
                final List<String> componentPropertyPath = new ArrayList<String>(property.path.size() + 1);
                componentPropertyPath.addAll(property.path);
                componentPropertyPath.add(componentPropertyNames[i]);
                propertyQueue.add(new PropertyDetails(property.holder, componentPropertyPath,
                        componentPropertyTypes[i], componentPropertyNullabilities[i]));
            }
        } else {
            /* determine if another mapped entity class is linked by this property */
            final boolean isAssociatedEntity;
            if (property.type instanceof CollectionType) {
                final CollectionType ct = (CollectionType) property.type;
                isAssociatedEntity = sessionFactory.getCollectionPersister(ct.getRole()).getElementType()
                        .isEntityType();
            } else {
                isAssociatedEntity = property.type instanceof AssociationType;
            }
            /* the property can link to entities, so process it further */
            String propertyPath = Joiner.on('.').join(property.path);
            /* find if the property is accessible (e.g., not protected) */
            boolean propertyIsAccessible = false;
            String classToInstantiateName = property.holder;
            Class<?> classToInstantiate = null;
            try {
                classToInstantiate = Class.forName(classToInstantiateName);
                while (Modifier.isAbstract(classToInstantiate.getModifiers())) {
                    classToInstantiateName = allSubclasses.get(classToInstantiateName).iterator().next();
                    classToInstantiate = Class.forName(classToInstantiateName);
                }
                try {
                    PropertyUtils.getNestedProperty(classToInstantiate.newInstance(), propertyPath);
                    propertyIsAccessible = true;
                } catch (NoSuchMethodException e) {
                    /* expected for collection properties */
                } catch (NestedNullException e) {
                    log.warn("guessing " + propertyPath + " of " + property.holder + " to be accessible");
                    propertyIsAccessible = true;
                }
            } catch (ReflectiveOperationException e) {
                log.error("could not probe property " + propertyPath + " of " + property.holder, e);
                continue;
            }
            /* build property report line for log */
            final char arrowShaft = property.isNullable ? '-' : '=';
            final StringBuffer sb = new StringBuffer();
            sb.append(property.holder);
            sb.append(' ');
            for (final String propertyName : property.path) {
                sb.append(arrowShaft);
                sb.append(arrowShaft);
                sb.append(propertyName);
            }
            sb.append(arrowShaft);
            sb.append(arrowShaft);
            sb.append("> ");
            final String valueClassName;
            if (isAssociatedEntity) {
                valueClassName = ((AssociationType) property.type).getAssociatedEntityName(sessionFactory);
                sb.append(valueClassName);
            } else {
                valueClassName = null;
                sb.append("value");
            }
            if (property.type.isCollectionType()) {
                sb.append("[]");
            }
            if (!propertyIsAccessible) {
                sb.append(" (inaccessible)");
            }
            /* determine from which class the property is inherited, if at all */
            String superclassWithProperty = null;
            String currentClass = property.holder;
            while (true) {
                currentClass = superclasses.get(currentClass);
                if (currentClass == null) {
                    break;
                } else if (allPropertyNames.get(currentClass).contains(property.path.get(0))) {
                    superclassWithProperty = currentClass;
                }
            }
            /* check if the property actually comes from an interface */
            final String declaringClassName = superclassWithProperty == null ? property.holder
                    : superclassWithProperty;
            final Class<? extends IObject> interfaceForProperty = getInterfaceForProperty(declaringClassName,
                    property.path.get(0));
            /* report where the property is declared */
            if (superclassWithProperty != null) {
                sb.append(" from ");
                sb.append(superclassWithProperty);
            } else {
                if (interfaceForProperty != null) {
                    sb.append(" see ");
                    sb.append(interfaceForProperty.getName());
                    /* It would be nice to set PropertyDetails to have the interface as the holder,
                     * but then properties would not be unique by declarer class and instance ID. */
                }
                /* entity linkages by non-inherited properties are recorded */
                if (valueClassName == null && property.path.size() > 1) {
                    /* assume that the top-level property suffices for describing simple properties */
                    log.debug("recording " + propertyPath + " as " + property.path.get(0));
                    propertyPath = property.path.get(0);
                }
                final Entry<String, String> classPropertyName = Maps.immutableEntry(property.holder,
                        propertyPath);
                if (valueClassName == null) {
                    simpleProperties.put(property.holder, propertyPath);
                } else {
                    linkedTo.put(property.holder, Maps.immutableEntry(valueClassName, propertyPath));
                    linkedBy.put(valueClassName, classPropertyName);
                }
                final PropertyKind propertyKind;
                if (property.type.isCollectionType()) {
                    propertyKind = PropertyKind.COLLECTION;
                } else if (property.isNullable) {
                    propertyKind = PropertyKind.OPTIONAL;
                } else {
                    propertyKind = PropertyKind.REQUIRED;
                }
                propertyKinds.put(classPropertyName, propertyKind);
                if (propertyIsAccessible) {
                    accessibleProperties.add(classPropertyName);
                }
            }
            if (log.isDebugEnabled()) {
                log.debug(sb.toString());
            }
        }
    }
    log.info("initialized graph path bean with " + propertyKinds.size() + " properties");
}

From source file:org.seedstack.seed.core.internal.application.ApplicationPlugin.java

@Override
public InitState init(InitContext initContext) {
    ApplicationDiagnosticCollector applicationDiagnosticCollector = new ApplicationDiagnosticCollector();
    ((CorePlugin) initContext.pluginsRequired().iterator().next())
            .registerDiagnosticCollector("org.seedstack.seed.core.application", applicationDiagnosticCollector);

    Set<String> allConfigurationResources = Sets.newHashSet();

    for (String propertiesResource : initContext.mapResourcesByRegex().get(PROPERTIES_REGEX)) {
        if (propertiesResource.startsWith(CONFIGURATION_LOCATION)) {
            allConfigurationResources.add(propertiesResource);
        }//w ww .  j  a v  a2s .  co  m
    }

    for (String propsResource : initContext.mapResourcesByRegex().get(PROPS_REGEX)) {
        if (propsResource.startsWith(CONFIGURATION_LOCATION)) {
            allConfigurationResources.add(propsResource);
        }
    }

    Map<String, Class<? extends StrLookup>> configurationLookups = new HashMap<String, Class<? extends StrLookup>>();

    for (Class<?> candidate : initContext.scannedClassesByAnnotationClass().get(ConfigurationLookup.class)) {
        ConfigurationLookup configurationLookup = candidate.getAnnotation(ConfigurationLookup.class);
        if (StrLookup.class.isAssignableFrom(candidate) && configurationLookup != null
                && !configurationLookup.value().isEmpty()) {
            configurationLookups.put(configurationLookup.value(), candidate.asSubclass(StrLookup.class));
            LOGGER.trace("Detected configuration lookup {}", configurationLookup.value());
        }
    }

    for (String configurationResource : allConfigurationResources) {
        boolean isOverrideResource = configurationResource.endsWith(".override.properties")
                || configurationResource.endsWith(".override.props");

        try {
            Enumeration<URL> urlEnumeration = classLoader.getResources(configurationResource);
            while (urlEnumeration.hasMoreElements()) {
                URL url = urlEnumeration.nextElement();
                InputStream resourceAsStream = null;

                try {
                    resourceAsStream = url.openStream();

                    if (isOverrideResource) {
                        LOGGER.debug("Adding {} to configuration override", url.toExternalForm());
                        propsOverride.load(resourceAsStream);
                    } else {
                        LOGGER.debug("Adding {} to configuration", url.toExternalForm());
                        props.load(resourceAsStream);
                    }
                } finally {
                    if (resourceAsStream != null) {
                        try { // NOSONAR
                            resourceAsStream.close();
                        } catch (IOException e) {
                            LOGGER.warn("Unable to close configuration resource " + configurationResource, e);
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw SeedException.wrap(e, ApplicationErrorCode.UNABLE_TO_LOAD_CONFIGURATION_RESOURCE)
                    .put("resource", configurationResource);
        }
    }

    // Determine configuration profile
    String[] profiles = getStringArray(System.getProperty("org.seedstack.seed.profiles"));
    if (profiles == null || profiles.length == 0) {
        LOGGER.info("No configuration profile selected");
        applicationDiagnosticCollector.setActiveProfiles("");
    } else {
        String activeProfiles = Arrays.toString(profiles);
        LOGGER.info("Active configuration profile(s): {}", activeProfiles);
        applicationDiagnosticCollector.setActiveProfiles(activeProfiles);
    }

    // Build configuration
    Configuration configuration = buildConfiguration(props, propsOverride, configurationLookups, profiles);
    applicationDiagnosticCollector.setConfiguration(configuration);
    Configuration coreConfiguration = configuration.subset(CorePlugin.CORE_PLUGIN_PREFIX);

    String appId = coreConfiguration.getString("application-id");
    if (appId == null || appId.isEmpty()) {
        throw SeedException.createNew(ApplicationErrorCode.MISSING_APPLICATION_IDENTIFIER).put("property",
                CorePlugin.CORE_PLUGIN_PREFIX + ".application-id");
    }

    String appName = coreConfiguration.getString("application-name");
    if (appName == null) {
        appName = appId;
    }

    String appVersion = coreConfiguration.getString("application-version");
    if (appVersion == null) {
        appVersion = "0.0.0";
    }

    LOGGER.info("Application info: '{}' / '{}' / '{}'", appId, appName, appVersion);
    applicationDiagnosticCollector.setApplicationId(appId);
    applicationDiagnosticCollector.setApplicationName(appName);
    applicationDiagnosticCollector.setApplicationVersion(appVersion);

    String seedStorage = coreConfiguration.getString("storage");
    File seedDirectory;
    if (seedStorage == null) {
        seedDirectory = new File(new File(getUserHome(), ".seed"), appId);
    } else {
        seedDirectory = new File(seedStorage);
    }

    if (!seedDirectory.exists() && !seedDirectory.mkdirs()) {
        throw SeedException.createNew(ApplicationErrorCode.UNABLE_TO_CREATE_STORAGE_DIRECTORY).put("path",
                seedDirectory.getAbsolutePath());
    }

    if (!seedDirectory.isDirectory()) {
        throw SeedException.createNew(ApplicationErrorCode.STORAGE_PATH_IS_NOT_A_DIRECTORY).put("path",
                seedDirectory.getAbsolutePath());
    }

    if (!seedDirectory.canWrite()) {
        throw SeedException.createNew(ApplicationErrorCode.STORAGE_DIRECTORY_IS_NOT_WRITABLE).put("path",
                seedDirectory.getAbsolutePath());
    }

    LOGGER.debug("Application storage location is {}", seedDirectory.getAbsolutePath());
    applicationDiagnosticCollector.setStorageLocation(seedDirectory.getAbsolutePath());

    if (coreConfiguration.getBoolean("redirect-jul", true)) {
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();

        LOGGER.debug(
                "Java logging to SLF4J redirection enabled, if you're using logback be sure to have a LevelChangePropagator in your configuration");
    }

    this.application = new ApplicationImpl(appName, appId, appVersion, seedDirectory, configuration);

    return InitState.INITIALIZED;
}

From source file:com.mg.framework.service.ApplicationDictionaryImpl.java

public FieldMetadata getFieldMetadata(ReflectionMetadata propertyMetadata) {
    if (propertyMetadata == null)
        throw new NullPointerException("Metadata is null");
    String dataItemName = propertyMetadata.getDataItemName();
    Class<?> propertyClass = propertyMetadata.getPropertyType();
    if (!StringUtils.stringNullOrEmpty(dataItemName)) {
        if (log.isDebugEnabled())
            log.debug("create field metadata, dataitem: " + dataItemName);

        FieldMetadata result = new FieldMetadata(getDataItem(dataItemName), propertyMetadata.getPropertyType());

        if (Enum.class.isAssignableFrom(propertyClass))
            result.setEnumConstantsText(UIUtils.enumToEnumConstantsText(propertyClass.asSubclass(Enum.class)));
        else if (PersistentObject.class.isAssignableFrom(propertyClass)) {
            if (result.getEntityPropertyText() == null) {
                //   ?   ?  ? ? 
                EntityPropertyText entityPropertyText = propertyClass.getAnnotation(EntityPropertyText.class);
                if (entityPropertyText != null) {
                    result.setEntityPropertyText(entityPropertyText.value());
                    result.setEntityPropertyFormatText(UIUtils.loadL10nText(entityPropertyText.format()));
                }//from w ww  . j  a va 2  s  .  co m
            }
        }

        //? SearchHelp ?     ??
        String searchHelpName = propertyMetadata.getSearchHelpName();
        if (!StringUtils.stringNullOrEmpty(searchHelpName))
            result.setSearchHelp(SearchHelpProcessor.createSearch(searchHelpName));

        return result;
    } else {
        if (log.isDebugEnabled())
            log.debug("create field metadata, class: " + propertyClass.getName());
        //?  ?? ? ? ,  ?? ? 
        // ? ? ?
        FieldMetadata result = new FieldMetadata(propertyClass.getName(),
                MiscUtils.javaTypeToBuiltInType(propertyClass), propertyClass, 0, "");
        if (Enum.class.isAssignableFrom(propertyClass))
            result.setEnumConstantsText(UIUtils.enumToEnumConstantsText(propertyClass.asSubclass(Enum.class)));
        return result;
    }
}

From source file:org.vivoweb.harvester.score.Score.java

/**
 * Constructor/* w  w  w.j a  v a 2s .  co  m*/
 * @param inputJena model containing statements to be scored
 * @param vivoJena model containing vivoJena statements
 * @param scoreJena model containing scoring data statements
 * @param tempJenaDir model in which to store temp copy of input and vivo data statements
 * @param algorithms the classes of the algorithms to execute
 * @param inputPredicates the predicates to look for in inputJena model
 * @param vivoPredicates the predicates to look for in vivoJena model
 * @param namespace limit match Algorithm to only match rdf nodes in inputJena whose URI begin with this namespace
 * @param weights the weightings (0.0 , 1.0) for this score
 * @param matchThreshold score things with a total current score greater than or equal to this threshold
 * @param batchSize number of records to use in batch
 * @param reloadInput reload the temp copy of input, only needed if input has changed since last score
 * @param reloadVivo reload the temp copy of Vivo, only needed if Vivo has changed since last score
 */
public Score(JenaConnect inputJena, JenaConnect vivoJena, JenaConnect scoreJena, String tempJenaDir,
        Map<String, Class<? extends Algorithm>> algorithms, Map<String, String> inputPredicates,
        Map<String, String> vivoPredicates, String namespace, Map<String, Float> weights, Float matchThreshold,
        int batchSize, boolean reloadInput, boolean reloadVivo) {
    if (inputJena == null) {
        throw new IllegalArgumentException("Input model cannot be null");
    }
    this.inputJena = inputJena;

    if (vivoJena == null) {
        throw new IllegalArgumentException("Vivo model cannot be null");
    }
    this.vivoJena = vivoJena;

    if (scoreJena == null) {
        throw new IllegalArgumentException("Score Data model cannot be null");
    }
    this.scoreJena = scoreJena;

    String tempDir = tempJenaDir;
    if (tempDir == null) {
        log.trace("temp model directory is not specified, using system temp directory");
        //         tempDir = File.createTempFile("tempVivoInputCopyJena", "db").getAbsolutePath();
        //         log.debug("temp model is not specifiedhi , using memory jena model");
        this.tempJena = new MemJenaConnect("urn:x-arq:UnionGraph");
    } else {
        this.tempJena = new TDBJenaConnect(tempDir, "urn:x-arq:UnionGraph");
    }

    if (algorithms == null) {
        throw new IllegalArgumentException("Algorithm cannot be null");
    }
    this.algorithms = algorithms;

    if (inputPredicates == null) {
        throw new IllegalArgumentException("Input Predicate cannot be null");
    }
    this.inputPredicates = inputPredicates;

    if (vivoPredicates == null) {
        throw new IllegalArgumentException("Vivo Predicate cannot be null");
    }
    this.vivoPredicates = vivoPredicates;

    if (this.algorithms.size() < 1) {
        throw new IllegalArgumentException("No runs specified!");
    }

    this.namespace = namespace;

    for (Float weight : weights.values()) {
        float d = weight.floatValue();
        if (d > 1f) {
            throw new IllegalArgumentException("Weights cannot be greater than 1.0");
        }
        if (d < 0f) {
            throw new IllegalArgumentException("Weights cannot be less than 0.0");
        }
    }
    this.weights = weights;

    Map<String, Map<String, ? extends Object>> maps = new HashMap<String, Map<String, ? extends Object>>();
    maps.put("vivoJena predicates", this.vivoPredicates);
    maps.put("inputJena predicates", this.inputPredicates);
    maps.put("algorithms", this.algorithms);
    maps.put("weights", this.weights);
    verifyRunNames(maps);
    boolean test = true;
    for (Class<?> algClass : this.algorithms.values()) {
        try {
            algClass.asSubclass(EqualityTest.class);
        } catch (ClassCastException e) {
            test = false;
            break;
        }
    }
    this.equalityOnlyMode = test;
    this.matchThreshold = matchThreshold;
    setBatchSize(batchSize);
    log.trace("equalityOnlyMode: " + this.equalityOnlyMode);
    this.reloadInput = reloadInput;
    this.reloadVivo = reloadVivo;

}

From source file:org.carrot2.core.Controller.java

/**
 * Returns an internal {@link ProcessingComponentConfiguration} based on the component
 * id, class or class name./*from  ww w  .  j  a  va  2  s  .c  o  m*/
 */
private ProcessingComponentConfiguration resolveComponent(Object classOrId) {
    if (classOrId instanceof String) {
        // Check if there's a matching configuration
        final ProcessingComponentConfiguration configuration = componentIdToConfiguration.get(classOrId);

        if (configuration != null) {
            return configuration;
        }

        // If not, check if the string denotes an existing class name
        try {
            classOrId = ReflectionUtils.classForName((String) classOrId);

            // Fall through to the condition below
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Unknown component id: " + classOrId);
        }
    }

    if (classOrId instanceof Class<?>) {
        final Class<?> clazz = (Class<?>) classOrId;
        if (!IProcessingComponent.class.isAssignableFrom(clazz)) {
            throw new IllegalArgumentException("Expected a Class<? extends "
                    + IProcessingComponent.class.getSimpleName() + "> but got: " + clazz.getName());
        }

        return new ProcessingComponentConfiguration(clazz.asSubclass(IProcessingComponent.class), null);
    }

    throw new IllegalArgumentException(
            "Expected a String or a Class<? extends " + IProcessingComponent.class.getSimpleName() + ">");
}

From source file:com.ocs.dynamo.domain.model.impl.ModelBasedFieldFactory.java

/**
 * Resolves an entity model by falling back first to the nested attribute model and then to the
 * default model/*from ww w.ja va 2s.c  o m*/
 * 
 * @param entityModel
 *            the entity model
 * @param attributeModel
 *            the attribute model
 * @return
 */
private EntityModel<?> resolveEntityModel(EntityModel<?> entityModel, AttributeModel attributeModel) {
    if (entityModel == null) {
        if (attributeModel.getNestedEntityModel() != null) {
            entityModel = attributeModel.getNestedEntityModel();
        } else {
            Class<?> type = attributeModel.getMemberType() != null ? attributeModel.getMemberType()
                    : attributeModel.getType();
            entityModel = ServiceLocator.getEntityModelFactory()
                    .getModel(type.asSubclass(AbstractEntity.class));
        }
    }
    return entityModel;
}

From source file:org.teavm.maven.BuildJavascriptTestMojo.java

private TestAdapter createAdapter(ClassLoader classLoader) throws MojoExecutionException {
    Class<?> adapterClsRaw;
    try {//  ww w  .j a  v a2 s .  co  m
        adapterClsRaw = Class.forName(adapterClass, true, classLoader);
    } catch (ClassNotFoundException e) {
        throw new MojoExecutionException("Adapter not found: " + adapterClass, e);
    }
    if (!TestAdapter.class.isAssignableFrom(adapterClsRaw)) {
        throw new MojoExecutionException(
                "Adapter " + adapterClass + " does not implement " + TestAdapter.class.getName());
    }
    Class<? extends TestAdapter> adapterCls = adapterClsRaw.asSubclass(TestAdapter.class);
    Constructor<? extends TestAdapter> cons;
    try {
        cons = adapterCls.getConstructor();
    } catch (NoSuchMethodException e) {
        throw new MojoExecutionException("No default constructor found for test adapter " + adapterClass, e);
    }
    try {
        return cons.newInstance();
    } catch (IllegalAccessException | InstantiationException e) {
        throw new MojoExecutionException("Error creating test adapter", e);
    } catch (InvocationTargetException e) {
        throw new MojoExecutionException("Error creating test adapter", e.getTargetException());
    }
}

From source file:com.chiorichan.event.EventBus.java

public Map<Class<? extends Event>, Set<RegisteredListener>> createRegisteredListeners(Listener listener,
        final EventCreator plugin) {
    Validate.notNull(plugin, "Creator can not be null");
    Validate.notNull(listener, "Listener can not be null");

    Map<Class<? extends Event>, Set<RegisteredListener>> ret = new HashMap<Class<? extends Event>, Set<RegisteredListener>>();
    Set<Method> methods;
    try {//from  w  w w .  ja  v a2s.  c o  m
        Method[] publicMethods = listener.getClass().getMethods();
        methods = new HashSet<Method>(publicMethods.length, Float.MAX_VALUE);
        for (Method method : publicMethods) {
            methods.add(method);
        }
        for (Method method : listener.getClass().getDeclaredMethods()) {
            methods.add(method);
        }
    } catch (NoClassDefFoundError e) {
        Loader.getLogger()
                .severe("Plugin " + plugin.getDescription().getFullName()
                        + " has failed to register events for " + listener.getClass() + " because "
                        + e.getMessage() + " does not exist.");
        return ret;
    }

    for (final Method method : methods) {
        final EventHandler eh = method.getAnnotation(EventHandler.class);
        if (eh == null)
            continue;
        final Class<?> checkClass;
        if (method.getParameterTypes().length != 1
                || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) {
            Loader.getLogger()
                    .severe(plugin.getDescription().getFullName()
                            + " attempted to register an invalid EventHandler method signature \""
                            + method.toGenericString() + "\" in " + listener.getClass());
            continue;
        }
        final Class<? extends Event> eventClass = checkClass.asSubclass(Event.class);
        method.setAccessible(true);
        Set<RegisteredListener> eventSet = ret.get(eventClass);
        if (eventSet == null) {
            eventSet = new HashSet<RegisteredListener>();
            ret.put(eventClass, eventSet);
        }

        for (Class<?> clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) {
            // This loop checks for extending deprecated events
            if (clazz.getAnnotation(Deprecated.class) != null) {
                Warning warning = clazz.getAnnotation(Warning.class);
                WarningState warningState = Loader.getInstance().getWarningState();
                if (!warningState.printFor(warning)) {
                    break;
                }
                Loader.getLogger().log(Level.WARNING, String.format(
                        "\"%s\" has registered a listener for %s on method \"%s\", but the event is Deprecated."
                                + " \"%s\"; please notify the authors %s.",
                        plugin.getDescription().getFullName(), clazz.getName(), method.toGenericString(),
                        (warning != null && warning.reason().length() != 0) ? warning.reason()
                                : "Server performance will be affected",
                        Arrays.toString(plugin.getDescription().getAuthors().toArray())),
                        warningState == WarningState.ON ? new AuthorNagException(null) : null);
                break;
            }
        }

        EventExecutor executor = new EventExecutor() {
            public void execute(Listener listener, Event event) throws EventException {
                try {
                    if (!eventClass.isAssignableFrom(event.getClass())) {
                        return;
                    }
                    method.invoke(listener, event);
                } catch (InvocationTargetException ex) {
                    throw new EventException(ex.getCause());
                } catch (Throwable t) {
                    throw new EventException(t);
                }
            }
        };
        if (useTimings) {
            eventSet.add(new TimedRegisteredListener(listener, executor, eh.priority(), plugin,
                    eh.ignoreCancelled()));
        } else {
            eventSet.add(
                    new RegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled()));
        }
    }
    return ret;
}

From source file:org.jdbcluster.privilege.PrivilegeCheckerImpl.java

/**
 * intersects required static privileges for cluster new against given
 * privileges/*from  w  w w .ja  v  a  2s  .  co m*/
 * 
 * @param clusterType defines the Cluster to check
 * @return true if the privileges are sufficient
 */
public boolean checkClusterNew(IUser user, String clusterType) {

    Assert.hasLength(clusterType, "clusterType may not be null or \"\"");

    Class<? extends Cluster> clazz = ClusterTypeFactory.newInstance(clusterType).getClusterClass();

    // if Cluster is no PrivilegedCluster creation is always possible
    if (!PrivilegedCluster.class.isAssignableFrom(clazz))
        return true;

    Class<? extends PrivilegedCluster> clusterClass = clazz.asSubclass(PrivilegedCluster.class);
    Set<String> requiredPrivileges = calcStaticClusterPrivileges(clusterClass);
    return userPrivilegeIntersect(user, requiredPrivileges);
}

From source file:org.apache.hadoop.hbase.util.RegionSplitter.java

/**
 * @throws IOException if the specified SplitAlgorithm class couldn't be
 * instantiated//from w w  w  .j a v a 2  s  .  c o m
 */
public static SplitAlgorithm newSplitAlgoInstance(Configuration conf, String splitClassName)
        throws IOException {
    Class<?> splitClass;

    // For split algorithms builtin to RegionSplitter, the user can specify
    // their simple class name instead of a fully qualified class name.
    if (splitClassName.equals(HexStringSplit.class.getSimpleName())) {
        splitClass = HexStringSplit.class;
    } else if (splitClassName.equals(UniformSplit.class.getSimpleName())) {
        splitClass = UniformSplit.class;
    } else {
        try {
            splitClass = conf.getClassByName(splitClassName);
        } catch (ClassNotFoundException e) {
            throw new IOException("Couldn't load split class " + splitClassName, e);
        }
        if (splitClass == null) {
            throw new IOException("Failed loading split class " + splitClassName);
        }
        if (!SplitAlgorithm.class.isAssignableFrom(splitClass)) {
            throw new IOException("Specified split class doesn't implement SplitAlgorithm");
        }
    }
    try {
        return splitClass.asSubclass(SplitAlgorithm.class).newInstance();
    } catch (Exception e) {
        throw new IOException("Problem loading split algorithm: ", e);
    }
}