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:net.minecraftforge.fml.client.FMLClientHandler.java

/**
 * Called a bit later on during initialization to finish loading mods
 * Also initializes key bindings//from  w  w  w  .  j a  va 2s .c o  m
 *
 */
public void finishMinecraftLoading() {
    if (modsMissing != null || wrongMC != null || customError != null || dupesFound != null
            || modSorting != null || j8onlymods != null) {
        SplashProgress.finish();
        return;
    }
    try {
        Loader.instance().initializeMods();
    } catch (CustomModLoadingErrorDisplayException custom) {
        FMLLog.log(Level.ERROR, custom, "A custom exception was thrown by a mod, the game will now halt");
        customError = custom;
        SplashProgress.finish();
        return;
    } catch (LoaderException le) {
        haltGame("There was a severe problem during mod loading that has caused the game to fail", le);
        return;
    }

    // Reload resources
    client.refreshResources();
    RenderingRegistry.loadEntityRenderers(Minecraft.getMinecraft().getRenderManager().entityRenderMap);
    guiFactories = HashBiMap.create();
    for (ModContainer mc : Loader.instance().getActiveModList()) {
        String className = mc.getGuiClassName();
        if (Strings.isNullOrEmpty(className)) {
            continue;
        }
        try {
            Class<?> clazz = Class.forName(className, true, Loader.instance().getModClassLoader());
            Class<? extends IModGuiFactory> guiClassFactory = clazz.asSubclass(IModGuiFactory.class);
            IModGuiFactory guiFactory = guiClassFactory.newInstance();
            guiFactory.initialize(client);
            guiFactories.put(mc, guiFactory);
        } catch (Exception e) {
            FMLLog.log(Level.ERROR, e, "A critical error occurred instantiating the gui factory for mod %s",
                    mc.getModId());
        }
    }
    loading = false;
    client.gameSettings.loadOptions(); //Reload options to load any mod added keybindings.
    Loader.instance().loadingComplete();
    SplashProgress.finish();
}

From source file:edu.uw.sig.frames2owl.Converter.java

private boolean init(String framesPath, String owlUriString, String configPath,
        Map<FrameID, String> frame2ProjectMap) {
    try {/*from   w  w  w  .j  av a  2s.c  o  m*/
        cReader = new ConfigReader(configPath);
    } catch (ConfigurationException e1) {
        e1.printStackTrace();
        return false;
    }

    // load frames ontology
    framesKB = KnowledgeBaseLoader.loadKB(framesPath);
    if (framesKB == null) {
        System.err.println("Error: frames ontology not found");
        return false;
    }

    // create new owl ontology
    man = OWLManager.createOWLOntologyManager();
    df = man.getOWLDataFactory();
    try {
        owlOnt = man.createOntology(IRI.create(owlUriString));
    } catch (OWLOntologyCreationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }

    this.iriUtils = new IRIUtils(framesKB, owlOnt, cReader, frame2ProjectMap);
    this.convUtils = new ConvUtils(iriUtils, df, framesKB);

    // handle import statements (for includes in frames)
    String owlExt = ".owl";
    for (URI includedFileURI : (Collection<URI>) framesKB.getProject().getDirectIncludedProjectURIs()) {
        // this block parses the name of the included ontology out of the include file path
        // (that is the only place it is really represented)
        String path = includedFileURI.getPath();

        int lastSlashInd = path.lastIndexOf('/');
        int lastPeriodInd = path.lastIndexOf('.');
        String fileName = path.substring(lastSlashInd + 1, lastPeriodInd);

        // create import statement
        // construct IRI
        String iriString = /*iriUtils.getProjectIRIBaseString(fileName);iriUtils.getIRIBaseString()//*/fileName
                + owlExt;
        IRI importIRI = IRI.create(iriString);
        System.err.println("will gen import statement for " + importIRI);

        // insert import statement
        OWLImportsDeclaration importDec = df.getOWLImportsDeclaration(importIRI);
        man.applyChange(new AddImport(owlOnt, importDec));
    }

    // determine if we should assert that sibling classes are disjoint
    Map<String, Boolean> configFlags = cReader.getConfigFlags();
    makeSiblingClsesDisj = configFlags.get("disjoint-siblings");

    // determine if domain and range classes will be created, set-up if necessary
    createAnnotDomainRangeClses = configFlags.get("create-annot-domain-range");
    if (createAnnotDomainRangeClses == null)
        createAnnotDomainRangeClses = false;
    if (createAnnotDomainRangeClses == true) {
        String domainClsName = cReader.getDomainClsName();
        if (domainClsName != null) {
            try {
                IRI domainClassIRI = iriUtils.getClassIRIForString(domainClsName);
                domainClass = df.getOWLClass(domainClassIRI);
                addLabel(domainClass, domainClsName);

                // Now create the subclass axiom
                OWLAxiom axiom = df.getOWLSubClassOfAxiom(domainClass, df.getOWLThing());

                // add the subclass axiom to the ontology.
                AddAxiom addAxiom = new AddAxiom(owlOnt, axiom);

                // We now use the manager to apply the change
                man.applyChange(addAxiom);
            } catch (IRIGenerationException e) {
                e.printStackTrace();
            }

        }
        String rangeClsName = cReader.getRangeClsName();
        if (rangeClsName != null) {
            try {
                IRI rangeClassIRI = iriUtils.getClassIRIForString(rangeClsName);
                rangeClass = df.getOWLClass(rangeClassIRI);
                addLabel(rangeClass, rangeClsName);

                // Now create the subclass axiom
                OWLAxiom axiom = df.getOWLSubClassOfAxiom(rangeClass, df.getOWLThing());

                // add the subclass axiom to the ontology.
                AddAxiom addAxiom = new AddAxiom(owlOnt, axiom);

                // We now use the manager to apply the change
                man.applyChange(addAxiom);
            } catch (IRIGenerationException e) {
                e.printStackTrace();
            }
        }
    }

    Map<String, Class> slotConvClassMap = cReader.getSlotConvClassMap();
    Map<String, Map<String, String>> slotInitArgsMap = cReader.getConvInitArgsMap();

    // build reified slot exclusion set
    List<String> excReifSubSlots = cReader.getReifExclusions();
    for (String subSlotName : excReifSubSlots) {
        Slot currSlot = framesKB.getSlot(subSlotName);
        if (currSlot == null) {
            System.err.println("unknown slot marked for exclusion: " + subSlotName);
            continue;
        }
        reifExclusions.add(currSlot);
    }

    // build slot annotation exclusion set
    List<String> excSlotAnnotSlots = cReader.getSlotAnnotExclusions();
    for (String slotName : excSlotAnnotSlots) {
        Slot currSlot = framesKB.getSlot(slotName);
        if (currSlot == null) {
            System.err.println("unknown slot marked for exclusion: " + slotName);
            continue;
        }
        slotAnnotExclusions.add(currSlot);
    }
    //TODO, the above exclusions are not yet passed to any converters !!!

    for (Slot currSlot : (Collection<Slot>) framesKB.getSlots()) {
        if (currSlot.isSystem() || currSlot.isIncluded())
            continue;

        String slotName = currSlot.getName();
        try {
            //SlotValueConverter currConverter = null;
            Class convClass = slotConvClassMap.get(slotName);
            Map<String, String> initArgs = slotInitArgsMap.get(slotName);
            if (convClass == null)
                convClass = guessSlotConverter(currSlot);
            if (initArgs == null) // use empty map
                initArgs = new HashMap<String, String>();
            SlotValueConverter converter = (SlotValueConverter) convClass
                    .asSubclass(SlotValueConverter.class).getConstructor(KnowledgeBase.class, Slot.class,
                            OWLOntology.class, IRIUtils.class, ConvUtils.class)
                    .newInstance(framesKB, currSlot, owlOnt, iriUtils, convUtils);

            // add additional reified exclusions if necessary
            if (converter instanceof BaseReifiedPropertyConverter) {
                BaseReifiedPropertyConverter reifConv = (BaseReifiedPropertyConverter) converter;
                reifConv.addExcludedSlots(reifExclusions);
            }

            // add domain and range classes for annotation property if needed
            if (converter instanceof AnnotationPropertyConverter && createAnnotDomainRangeClses == true) {
                AnnotationPropertyConverter annotConv = (AnnotationPropertyConverter) converter;
                annotConv.setDomainClass(domainClass);
                annotConv.setRangeClass(rangeClass);
            }

            // init with any args from the config file
            boolean initSuccess = converter.init(initArgs);
            if (!initSuccess) {
                System.err.println("Failed to initialize converter for slot " + slotName);
                System.exit(-1);
            }
            slot2ConvMap.put(currSlot, converter);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            continue;
        } catch (SecurityException e) {
            e.printStackTrace();
            continue;
        } catch (InstantiationException e) {
            e.printStackTrace();
            continue;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            continue;
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            continue;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            continue;
        }
    }

    return true;
}

From source file:org.apache.nifi.registry.security.authorization.AuthorizerFactory.java

private Authorizer createAuthorizer(final String identifier, final String authorizerClassName,
        final String classpathResources) throws Exception {
    final Authorizer instance;

    final ClassLoader classLoader = extensionManager.getExtensionClassLoader(authorizerClassName);
    if (classLoader == null) {
        throw new IllegalStateException(
                "Extension not found in any of the configured class loaders: " + authorizerClassName);
    }//from  w ww  . j a va 2s.c o m

    // attempt to load the class
    Class<?> rawAuthorizerClass = Class.forName(authorizerClassName, true, classLoader);
    Class<? extends Authorizer> authorizerClass = rawAuthorizerClass.asSubclass(Authorizer.class);

    // otherwise create a new instance
    Constructor constructor = authorizerClass.getConstructor();
    instance = (Authorizer) constructor.newInstance();

    // method injection
    performMethodInjection(instance, authorizerClass);

    // field injection
    performFieldInjection(instance, authorizerClass);

    // call post construction lifecycle event
    instance.initialize(new StandardAuthorizerInitializationContext(identifier, this, this, this));

    return installIntegrityChecks(instance);
}

From source file:org.apache.nifi.registry.security.authorization.AuthorizerFactory.java

private UserGroupProvider createUserGroupProvider(final String identifier,
        final String userGroupProviderClassName) throws Exception {

    final UserGroupProvider instance;

    final ClassLoader classLoader = extensionManager.getExtensionClassLoader(userGroupProviderClassName);
    if (classLoader == null) {
        throw new IllegalStateException(
                "Extension not found in any of the configured class loaders: " + userGroupProviderClassName);
    }//  w  w w  .  j ava 2s . c om

    // attempt to load the class
    Class<?> rawUserGroupProviderClass = Class.forName(userGroupProviderClassName, true, classLoader);
    Class<? extends UserGroupProvider> userGroupProviderClass = rawUserGroupProviderClass
            .asSubclass(UserGroupProvider.class);

    // otherwise create a new instance
    Constructor constructor = userGroupProviderClass.getConstructor();
    instance = (UserGroupProvider) constructor.newInstance();

    // method injection
    performMethodInjection(instance, userGroupProviderClass);

    // field injection
    performFieldInjection(instance, userGroupProviderClass);

    // call post construction lifecycle event
    instance.initialize(new StandardAuthorizerInitializationContext(identifier, this, this, this));

    return instance;
}

From source file:org.apache.nifi.registry.security.authorization.AuthorizerFactory.java

private AccessPolicyProvider createAccessPolicyProvider(final String identifier,
        final String accessPolicyProviderClassName) throws Exception {
    final AccessPolicyProvider instance;

    final ClassLoader classLoader = extensionManager.getExtensionClassLoader(accessPolicyProviderClassName);
    if (classLoader == null) {
        throw new IllegalStateException(
                "Extension not found in any of the configured class loaders: " + accessPolicyProviderClassName);
    }/*from  ww w  .j a va2s  . co m*/

    // attempt to load the class
    Class<?> rawAccessPolicyProviderClass = Class.forName(accessPolicyProviderClassName, true, classLoader);
    Class<? extends AccessPolicyProvider> accessPolicyClass = rawAccessPolicyProviderClass
            .asSubclass(AccessPolicyProvider.class);

    // otherwise create a new instance
    Constructor constructor = accessPolicyClass.getConstructor();
    instance = (AccessPolicyProvider) constructor.newInstance();

    // method injection
    performMethodInjection(instance, accessPolicyClass);

    // field injection
    performFieldInjection(instance, accessPolicyClass);

    // call post construction lifecycle event
    instance.initialize(new StandardAuthorizerInitializationContext(identifier, this, this, this));

    return instance;
}

From source file:net.es.sense.rm.api.SenseRmController.java

/**
 * Initialize API by loading technology specific driver using reflection.
 *
 * @throws Exception/*ww w . ja  v  a  2 s .co m*/
 */
@PostConstruct
public void init() throws Exception {
    utilities = new UrlTransform(config.getProxy());
    Class<?> forName = Class.forName(config.getDriver());
    driver = context.getBean(forName.asSubclass(Driver.class));
}

From source file:com.ellychou.todo.rest.service.SpringContextJerseyTest.java

/**
* Returns an instance of {@link TestContainerFactory} class. This instance can be set by a constructor ({@link
* #JerseyTest(org.glassfish.jersey.test.spi.TestContainerFactory)}, as an application {@link Providers Provider} or the
* {@link TestContainerFactory} class can be set as a {@value org.glassfish.jersey.test.TestProperties#CONTAINER_FACTORY}
* property./*from   w w  w  . ja  va 2s .c  o m*/
*
* @return an instance of {@link TestContainerFactory} class.
* @throws TestContainerException if the initialization of {@link TestContainerFactory} instance is not successful.
*/
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
    if (testContainerFactory == null) {
        if (testContainerFactoryClass == null) {

            final String tcfClassName = getProperty(TestProperties.CONTAINER_FACTORY);
            if ((tcfClassName == null)) {
                Set<TestContainerFactory> testContainerFactories = Providers
                        .getProviders(application.getServiceLocator(), TestContainerFactory.class);

                if (testContainerFactories.size() >= 1) {
                    // if default factory is present, use it.
                    for (TestContainerFactory tcFactory : testContainerFactories) {

                        if (tcFactory.getClass().getName().equals(TestProperties.DEFAULT_CONTAINER_FACTORY)) {
                            LOGGER.log(Level.CONFIG,
                                    "Found multiple TestContainerFactory implementations, using default {0}",
                                    tcFactory.getClass().getName());

                            testContainerFactoryClass = tcFactory.getClass(); // is this necessary?
                            return tcFactory;
                        }
                    }

                    if (testContainerFactories.size() != 1) {
                        LOGGER.log(Level.WARNING,
                                "Found multiple TestContainerFactory implementations, using {0}",
                                testContainerFactories.iterator().next().getClass().getName());
                    }

                    testContainerFactoryClass = testContainerFactories.iterator().next().getClass();
                    return testContainerFactories.iterator().next();

                }
            } else {
                final Class<Object> tfClass = AccessController
                        .doPrivileged(ReflectionHelper.classForNamePA(tcfClassName, null));
                if (tfClass == null) {
                    throw new TestContainerException("The default test container factory class name, "
                            + tcfClassName + ", cannot be loaded");
                }
                try {
                    testContainerFactoryClass = tfClass.asSubclass(TestContainerFactory.class);
                } catch (ClassCastException ex) {
                    throw new TestContainerException("The default test container factory class, " + tcfClassName
                            + ", is not an instance of TestContainerFactory", ex);
                }
            }
        }

        try {
            return testContainerFactoryClass.newInstance();
        } catch (Exception ex) {
            throw new TestContainerException("The default test container factory, " + testContainerFactoryClass
                    + ", could not be instantiated", ex);
        }
    }

    return testContainerFactory;
}

From source file:fr.efl.chaine.xslt.GauloisPipe.java

@SuppressWarnings("LocalVariableHidesMemberVariable")
public Config parseCommandLine(String[] args) throws InvalidSyntaxException {
    List<String> inputFiles = new ArrayList<>();
    List<String> inputParams = new ArrayList<>();
    List<String> inputXsls = new ArrayList<>();
    String nbThreads = null;// w  ww  . java2s .  c o  m
    String inputOutput = null;
    String _messageListener = null;
    String configFileName = null;
    String __instanceName = INSTANCE_DEFAULT_NAME;
    boolean logFileSize = false;
    boolean skipSchemaValidation = false;
    int inputMode = -1;
    for (String argument : args) {
        if (null != argument) {
            switch (argument) {
            case "PARAMS":
                inputMode = INPUT_PARAMS;
                continue;
            case "FILES":
                inputMode = INPUT_FILES;
                continue;
            case "XSL":
                inputMode = INPUT_XSL;
                continue;
            case "--output":
            case "-o":
                inputMode = INPUT_OUTPUT;
                continue;
            case "--nbthreads":
            case "-n":
                inputMode = INPUT_THREADS;
                continue;
            case "--msg-listener":
                inputMode = MESSAGE_LISTENER;
                continue;
            case "--instance-name":
            case "-iName":
                inputMode = INSTANCE_NAME;
                continue;
            case "--config":
                inputMode = CONFIG;
                continue;
            case "--logFileSize":
                logFileSize = true;
                continue;
            case "--skipSchemaValidation":
                skipSchemaValidation = true;
                continue;
            case "--working-dir":
            case "-wd":
                inputMode = CURRENT_DIR;
                continue;
            }
        }

        switch (inputMode) {
        case INPUT_FILES:
            inputFiles.add(argument);
            break;
        case INPUT_PARAMS:
            inputParams.add(argument);
            break;
        case INPUT_XSL:
            inputXsls.add(argument);
            break;
        case INPUT_THREADS:
            nbThreads = argument;
            break;
        case INPUT_OUTPUT:
            inputOutput = argument;
            break;
        case MESSAGE_LISTENER:
            _messageListener = argument;
            break;
        case INSTANCE_NAME:
            __instanceName = argument;
            break;
        case CONFIG:
            configFileName = argument;
            break;
        case CURRENT_DIR:
            currentDir = argument;
            break;
        }
    }
    HashMap<QName, ParameterValue> inputParameters = new HashMap<>(inputParams.size());
    for (String paramPattern : inputParams) {
        LOGGER.debug("parsing parameter " + paramPattern);
        ParameterValue pv = ConfigUtil.parseParameterPattern(paramPattern);
        inputParameters.put(pv.getKey(), pv);
    }
    LOGGER.debug("parameters from command line are : " + inputParameters);
    Config config;
    if (configFileName != null) {
        LOGGER.debug("loading config file " + configFileName);
        config = parseConfig(configFileName, inputParameters, configurationFactory.getConfiguration(),
                skipSchemaValidation);
        LOGGER.debug("computed parameters in config are :" + config.getParams());
    } else {
        config = new Config(currentDir);
    }
    for (String inputFile : inputFiles)
        ConfigUtil.addInputFile(config, inputFile);
    for (String inputXsl : inputXsls)
        ConfigUtil.addTemplate(config, inputXsl);
    if (nbThreads != null)
        ConfigUtil.setNbThreads(config, nbThreads);
    if (inputOutput != null)
        ConfigUtil.setOutput(config, inputOutput);
    config.setLogFileSize(logFileSize);
    config.skipSchemaValidation(skipSchemaValidation);
    config.verify();
    LOGGER.debug("merged parameters into config are : " + config.getParams());
    config.__instanceName = __instanceName;
    if (_messageListener != null) {
        try {
            Class clazz = Class.forName(_messageListener);
            messageListenerclass = clazz.asSubclass(MessageListener.class);
        } catch (ClassNotFoundException ex) {
            LOGGER.warn(_messageListener + " is not a " + MessageListener.class.getName());
        }
    }
    return config;
}

From source file:eu.stratosphere.api.java.typeutils.TypeExtractor.java

@SuppressWarnings("unchecked")
public static <X> TypeInformation<X> getForClass(Class<X> clazz) {
    Validate.notNull(clazz);//  www. ja  v  a2 s.  c  o  m

    // check for abstract classes or interfaces
    if (Modifier.isInterface(clazz.getModifiers())
            || (Modifier.isAbstract(clazz.getModifiers()) && !clazz.isArray())) {
        throw new InvalidTypesException("Interfaces and abstract classes are not valid types.");
    }

    // check for arrays
    if (clazz.isArray()) {

        // primitive arrays: int[], byte[], ...
        PrimitiveArrayTypeInfo<X> primitiveArrayInfo = PrimitiveArrayTypeInfo.getInfoFor(clazz);
        if (primitiveArrayInfo != null) {
            return primitiveArrayInfo;
        }

        // basic type arrays: String[], Integer[], Double[]
        BasicArrayTypeInfo<X, ?> basicArrayInfo = BasicArrayTypeInfo.getInfoFor(clazz);
        if (basicArrayInfo != null) {
            return basicArrayInfo;
        }

        // object arrays
        else {
            return ObjectArrayTypeInfo.getInfoFor(clazz);
        }
    }

    // check for writable types
    if (Writable.class.isAssignableFrom(clazz)) {
        return (TypeInformation<X>) WritableTypeInfo.getWritableTypeInfo((Class<? extends Writable>) clazz);
    }

    // check for basic types
    TypeInformation<X> basicTypeInfo = BasicTypeInfo.getInfoFor(clazz);
    if (basicTypeInfo != null) {
        return basicTypeInfo;
    }

    // check for subclasses of Value
    if (Value.class.isAssignableFrom(clazz)) {
        Class<? extends Value> valueClass = clazz.asSubclass(Value.class);
        return (TypeInformation<X>) ValueTypeInfo.getValueTypeInfo(valueClass);
    }

    // check for subclasses of Tuple
    if (Tuple.class.isAssignableFrom(clazz)) {
        throw new InvalidTypesException(
                "Type information extraction for tuples cannot be done based on the class.");
    }

    // return a generic type
    return new GenericTypeInfo<X>(clazz);
}

From source file:com.meltmedia.cadmium.servlets.guice.CadmiumListener.java

private ServletModule createServletModule() {
    return new ServletModule() {
        @Override//from ww w .  j a  va  2s.  c  o m
        protected void configureServlets() {
            Map<String, String> maintParams = new HashMap<String, String>();
            maintParams.put("ignorePrefix", "/system");
            Map<String, String> aclParams = new HashMap<String, String>();
            maintParams.put("jersey-prefix", "/api/");

            Map<String, String> fileParams = new HashMap<String, String>();
            fileParams.put("basePath",
                    com.meltmedia.cadmium.core.FileSystemManager.exists(contentDir) ? contentDir : failOver);

            // hook Jackson into Jersey as the POJO <-> JSON mapper
            bind(JacksonJsonProvider.class).in(Scopes.SINGLETON);

            bind(SecureRedirectStrategy.class).to(XForwardedSecureRedirectStrategy.class).in(Scopes.SINGLETON);

            serve("/system/*").with(SystemGuiceContainer.class);
            serve("/api/*").with(ApiGuiceContainer.class);
            serve("/*").with(FileServlet.class, fileParams);

            filter("/*").through(ErrorPageFilter.class, maintParams);
            filter("/*").through(RedirectFilter.class);
            filter("/*").through(SecureRedirectFilter.class);
            filter("/api/*").through(ApiEndpointAccessFilter.class, aclParams);

            try {
                Set<Class<?>> discoveredFilters = reflections
                        .getTypesAnnotatedWith(com.meltmedia.cadmium.core.CadmiumFilter.class);
                if (discoveredFilters != null) {
                    for (Class<?> filterClass : discoveredFilters) {
                        if (Filter.class.isAssignableFrom(filterClass)) {
                            com.meltmedia.cadmium.core.CadmiumFilter annot = filterClass
                                    .getAnnotation(com.meltmedia.cadmium.core.CadmiumFilter.class);
                            if (!StringUtils.isEmptyOrNull(annot.value())) {
                                log.debug("Adding Filter {} mapped with {}", filterClass.getName(),
                                        annot.value());
                                filter(annot.value()).through(filterClass.asSubclass(Filter.class));
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("Failed to find servlet Filter implementations.", e);
            }
        }
    };
}