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:org.apache.bookkeeper.meta.LedgerManagerFactory.java

/**
 * Create new Ledger Manager Factory./*ww w .j  a v  a2  s . co  m*/
 *
 * @param conf
 *          Configuration Object.
 * @param zk
 *          ZooKeeper Client Handle, talk to zk to know which ledger manager is used.
 * @return new ledger manager factory
 * @throws IOException
 */
public static LedgerManagerFactory newLedgerManagerFactory(final AbstractConfiguration conf, final ZooKeeper zk)
        throws IOException, KeeperException, InterruptedException {
    Class<? extends LedgerManagerFactory> factoryClass;
    try {
        factoryClass = conf.getLedgerManagerFactoryClass();
    } catch (Exception e) {
        throw new IOException("Failed to get ledger manager factory class from configuration : ", e);
    }
    String ledgerRootPath = conf.getZkLedgersRootPath();

    if (null == ledgerRootPath || ledgerRootPath.length() == 0) {
        throw new IOException("Empty Ledger Root Path.");
    }

    // if zk is null, return the default ledger manager
    if (zk == null) {
        return new FlatLedgerManagerFactory().initialize(conf, null, FlatLedgerManagerFactory.CUR_VERSION);
    }

    LedgerManagerFactory lmFactory;

    // check that the configured ledger manager is
    // compatible with the existing layout
    LedgerLayout layout = LedgerLayout.readLayout(zk, ledgerRootPath);
    if (layout == null) { // no existing layout
        lmFactory = createNewLMFactory(conf, zk, factoryClass);
        return lmFactory.initialize(conf, zk, lmFactory.getCurrentVersion());
    }
    LOG.debug("read ledger layout {}", layout);

    // there is existing layout, we need to look into the layout.
    // handle pre V2 layout
    if (layout.getLayoutFormatVersion() <= V1) {
        // pre V2 layout we use type of ledger manager
        @SuppressWarnings("deprecation")
        String lmType = conf.getLedgerManagerType();
        if (lmType != null && !layout.getManagerFactoryClass().equals(lmType)) {
            throw new IOException("Configured layout " + lmType + " does not match existing layout "
                    + layout.getManagerFactoryClass());
        }

        // create the ledger manager
        if (FlatLedgerManagerFactory.NAME.equals(layout.getManagerFactoryClass())) {
            lmFactory = new FlatLedgerManagerFactory();
        } else if (HierarchicalLedgerManagerFactory.NAME.equals(layout.getManagerFactoryClass())) {
            lmFactory = new HierarchicalLedgerManagerFactory();
        } else {
            throw new IOException("Unknown ledger manager type: " + lmType);
        }
        return lmFactory.initialize(conf, zk, layout.getManagerVersion());
    }

    // handle V2 layout case
    if (factoryClass != null && !layout.getManagerFactoryClass().equals(factoryClass.getName())) {

        throw new IOException("Configured layout " + factoryClass.getName() + " does not match existing layout "
                + layout.getManagerFactoryClass());
    }
    if (factoryClass == null) {
        // no factory specified in configuration
        try {
            Class<?> theCls = Class.forName(layout.getManagerFactoryClass());
            if (!LedgerManagerFactory.class.isAssignableFrom(theCls)) {
                throw new IOException("Wrong ledger manager factory " + layout.getManagerFactoryClass());
            }
            factoryClass = theCls.asSubclass(LedgerManagerFactory.class);
        } catch (ClassNotFoundException cnfe) {
            throw new IOException(
                    "Failed to instantiate ledger manager factory " + layout.getManagerFactoryClass());
        }
    }
    // instantiate a factory
    lmFactory = ReflectionUtils.newInstance(factoryClass);
    return lmFactory.initialize(conf, zk, layout.getManagerVersion());
}

From source file:org.apache.bookkeeper.meta.AbstractZkLedgerManagerFactory.java

/**
 * Create new Ledger Manager Factory.//from w ww  .j  ava2  s.  c om
 *
 * @param conf
 *          Configuration Object.
 * @param layoutManager
 *          layout manager
 * @return new ledger manager factory
 * @throws IOException
 */
@SuppressWarnings("deprecation")
public static LedgerManagerFactory newLedgerManagerFactory(final AbstractConfiguration<?> conf,
        LayoutManager layoutManager) throws IOException, InterruptedException {
    String metadataServiceUriStr;
    try {
        metadataServiceUriStr = conf.getMetadataServiceUri();
    } catch (ConfigurationException e) {
        log.error("Failed to retrieve metadata service uri from configuration", e);
        throw new IOException("Failed to retrieve metadata service uri from configuration", e);
    }

    Class<? extends LedgerManagerFactory> factoryClass;
    String ledgerRootPath;
    // `metadataServiceUri` can be null when constructing bookkeeper client using an external zookeeper client.
    if (null == metadataServiceUriStr) { //
        try {
            factoryClass = conf.getLedgerManagerFactoryClass();
        } catch (ConfigurationException e) {
            log.error("Failed to get ledger manager factory class when using an external zookeeper client", e);
            throw new IOException(
                    "Failed to get ledger manager factory class when using an external zookeeper client", e);
        }
        ledgerRootPath = conf.getZkLedgersRootPath();
    } else {
        URI metadataServiceUri = URI.create(metadataServiceUriStr);
        factoryClass = ZKMetadataDriverBase.resolveLedgerManagerFactory(metadataServiceUri);
        ledgerRootPath = metadataServiceUri.getPath();
    }

    if (null == ledgerRootPath || ledgerRootPath.length() == 0) {
        throw new IOException("Empty Ledger Root Path.");
    }

    // if layoutManager is null, return the default ledger manager
    if (layoutManager == null) {
        return new FlatLedgerManagerFactory().initialize(conf, null, FlatLedgerManagerFactory.CUR_VERSION);
    }

    LedgerManagerFactory lmFactory;

    // check that the configured ledger manager is
    // compatible with the existing layout
    LedgerLayout layout = layoutManager.readLedgerLayout();

    if (layout == null) { // no existing layout
        lmFactory = createNewLMFactory(conf, layoutManager, factoryClass);
        return lmFactory.initialize(conf, layoutManager, lmFactory.getCurrentVersion());
    }
    if (log.isDebugEnabled()) {
        log.debug("read ledger layout {}", layout);
    }

    // there is existing layout, we need to look into the layout.
    // handle pre V2 layout
    if (layout.getLayoutFormatVersion() <= V1) {
        // pre V2 layout we use type of ledger manager
        String lmType = conf.getLedgerManagerType();
        if (lmType != null && !layout.getManagerFactoryClass().equals(lmType)) {
            throw new IOException("Configured layout " + lmType + " does not match existing layout "
                    + layout.getManagerFactoryClass());
        }

        // create the ledger manager
        if (FlatLedgerManagerFactory.NAME.equals(layout.getManagerFactoryClass())) {
            lmFactory = new FlatLedgerManagerFactory();
        } else if (HierarchicalLedgerManagerFactory.NAME.equals(layout.getManagerFactoryClass())) {
            lmFactory = new HierarchicalLedgerManagerFactory();
        } else {
            throw new IOException("Unknown ledger manager type: " + lmType);
        }
        return lmFactory.initialize(conf, layoutManager, layout.getManagerVersion());
    }

    // handle V2 layout case
    if (factoryClass != null
            && !isSameLedgerManagerFactory(conf, layout.getManagerFactoryClass(), factoryClass.getName())
            && conf.getProperty(AbstractConfiguration.LEDGER_MANAGER_FACTORY_DISABLE_CLASS_CHECK) == null) {
        // Disable should ONLY happen during compatibility testing.

        throw new IOException("Configured layout " + factoryClass.getName() + " does not match existing layout "
                + layout.getManagerFactoryClass());
    }
    if (factoryClass == null) {
        // no factory specified in configuration
        try {
            Class<?> theCls = Class.forName(layout.getManagerFactoryClass());
            if (!LedgerManagerFactory.class.isAssignableFrom(theCls)) {
                throw new IOException("Wrong ledger manager factory " + layout.getManagerFactoryClass());
            }
            factoryClass = theCls.asSubclass(LedgerManagerFactory.class);
        } catch (ClassNotFoundException | IOException e) {
            factoryClass = attemptToResolveShadedLedgerManagerFactory(conf, layout.getManagerFactoryClass(), e);
        }
    }
    // instantiate a factory
    lmFactory = ReflectionUtils.newInstance(factoryClass);
    return lmFactory.initialize(conf, layoutManager, layout.getManagerVersion());
}

From source file:net.yck.wkrdb.common.shared.PropertyConverter.java

/**
 * Helper method for converting a value to a constant of an enumeration
 * class.// www.  j a v a2s  . c o  m
 *
 * @param enumClass
 *            the enumeration class
 * @param value
 *            the value to be converted
 * @return the converted value
 */
// conversion is safe because we know that the class is an Enum class
private static Object convertToEnum(Class<?> enumClass, Object value) {
    return toEnum(value, enumClass.asSubclass(Enum.class));
}

From source file:org.lenskit.data.entities.EntityDefaults.java

/**
 * Create an entity defaults object from a bean.
 * @param type The entity type./*from w  w w . j  a  v a 2s . c  o  m*/
 * @param bean The bean.
 * @return The entity defaults.
 */
private static EntityDefaults fromBean(EntityType type, DefaultsBean bean) {
    Map<String, TypedName<?>> attrs = new HashMap<>();
    for (Map.Entry<String, String> ab : bean.getAttributes().entrySet()) {
        attrs.put(ab.getKey(), TypedName.create(ab.getKey(), ab.getValue()));
    }

    List<TypedName<?>> cols = new ArrayList<>();
    for (String col : bean.getColumns()) {
        cols.add(attrs.get(col));
    }

    List<EntityDerivation> derivs = new ArrayList<>();
    for (Map.Entry<String, String> d : bean.getDerivations().entrySet()) {
        EntityType et = EntityType.forName(d.getKey());
        TypedName<?> attr = attrs.get(d.getValue());
        if (!attr.getType().equals(Long.class)) {
            throw new RuntimeException("derived entity derives from non-Long column");
        }
        derivs.add(EntityDerivation.create(et, type, (TypedName<Long>) attr));
    }

    Class<?> builder;
    String builderName = bean.getBuilder();
    if (builderName != null) {
        try {
            builder = ClassUtils.getClass(bean.getBuilder());
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException("could not find builder class", ex);
        }
    } else {
        builder = BasicEntityBuilder.class;
    }

    return new EntityDefaults(type, attrs.values(), cols, builder.asSubclass(EntityBuilder.class), derivs);
}

From source file:com.asakusafw.yaess.tools.log.cli.Main.java

private static <T> T create(CommandLine cmd, Option opt, Class<T> type, ClassLoader loader) {
    assert cmd != null;
    assert opt != null;
    assert type != null;
    assert loader != null;
    String value = cmd.getOptionValue(opt.getOpt());
    Class<?> aClass;
    try {//from   w  ww . j  a  v a2 s.c  om
        aClass = Class.forName(value, false, loader);
    } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException(
                MessageFormat.format("Failed to initialize the class \"{1}\" (-{0})", opt.getOpt(), value), e);
    }
    if (type.isAssignableFrom(aClass) == false) {
        throw new IllegalArgumentException(MessageFormat.format("\"{1}\" must be a subtype of \"{2}\" (-{0})",
                opt.getOpt(), value, type.getName()));
    }
    try {
        return aClass.asSubclass(type).getConstructor().newInstance();
    } catch (Exception e) {
        throw new IllegalArgumentException(
                MessageFormat.format("Failed to initialize the class \"{1}\" (-{0})", opt.getOpt(), value), e);
    }
}

From source file:com.asakusafw.compiler.bootstrap.AllBatchCompilerDriver.java

private static Class<? extends BatchDescription> loadIfBatchClass(String className) {
    try {//from  w  w  w  .ja  va 2s  .c  o m
        Class<?> aClass = Class.forName(className, false, AllBatchCompilerDriver.class.getClassLoader());
        if (BatchDescription.class.isAssignableFrom(aClass) == false) {
            return null;
        }
        if (aClass.isAnnotationPresent(Batch.class) == false) {
            LOG.warn(MessageFormat.format(Messages.getString("AllBatchCompilerDriver.warnMissingAnnotation"), //$NON-NLS-1$
                    aClass.getName()));
            return null;
        }
        return aClass.asSubclass(BatchDescription.class);
    } catch (ClassNotFoundException e) {
        LOG.debug("failed to load batch class", e); //$NON-NLS-1$
        return null;
    }
}

From source file:com.javadeobfuscator.deobfuscator.DeobfuscatorMain.java

public static int run(String[] args) {
    Options options = new Options();
    options.addOption("transformer", true, "A transformer to use");
    options.addOption("path", true, "A JAR to be placed in the classpath");
    options.addOption("input", true, "The input file");
    options.addOption("output", true, "The output file");
    //TODO:/*from ww w .  j  a  v  a  2 s .c o  m*/
    // * keepClass
    // * custom normalizer name

    CommandLineParser parser = new DefaultParser();
    try {
        Deobfuscator deobfuscator = new Deobfuscator();
        CommandLine cmd = parser.parse(options, args);

        if (!cmd.hasOption("input")) {
            System.out.println("No input jar specified");
            return 3;
        }

        if (!cmd.hasOption("output")) {
            System.out.println("No output jar specified");
            return 4;
        }

        File input = new File(cmd.getOptionValue("input"));
        if (!input.exists()) {
            System.out.println("Input file does not exist");
            return 5;
        }

        File output = new File(cmd.getOptionValue("output"));
        if (output.exists()) {
            System.out.println("Warning! Output file already exists");
        }

        deobfuscator.withInput(input).withOutput(output);

        String[] transformers = cmd.getOptionValues("transformer");
        if (transformers == null || transformers.length == 0) {
            System.out.println("No transformers specified");
            return 2;
        }
        for (String transformer : transformers) {
            Class<?> clazz = null;
            try {
                clazz = Class.forName("com.javadeobfuscator.deobfuscator.transformers." + transformer);
            } catch (ClassNotFoundException exception) {
                try {
                    clazz = Class.forName(transformer);
                } catch (ClassNotFoundException exception1) {
                    System.out.println("Could not locate transformer " + transformer);
                }
            }
            if (clazz != null) {
                if (Transformer.class.isAssignableFrom(clazz)) {
                    deobfuscator.withTransformer(clazz.asSubclass(Transformer.class));
                } else {
                    System.out.println(clazz.getCanonicalName()
                            + " does not extend com.javadeobfuscator.deobfuscator.transformers.Transformer");
                }
            }
        }

        String[] paths = cmd.getOptionValues("path");
        if (paths != null) {
            for (String path : paths) {
                File file = new File(path);
                if (file.exists()) {
                    deobfuscator.withClasspath(file);
                } else {
                    System.out.println("Could not find classpath file " + path);
                }
            }
        }

        try {
            deobfuscator.start();
            return 0;
        } catch (Deobfuscator.NoClassInPathException ex) {
            System.out.println("Could not locate a class file.");
            System.out.println("Have you added the necessary files to the -path argument?");
            System.out.println("The error was:");
            ex.printStackTrace(System.out);
            return -2;
        } catch (Throwable t) {
            System.out.println("Deobfuscation failed. Please open a ticket on GitHub");
            t.printStackTrace(System.out);
            return -1;
        }
    } catch (ParseException e) {
        return 1;
    }
}

From source file:org.apache.nifi.controller.state.manager.StandardStateManagerProvider.java

private static StateProvider instantiateStateProvider(final String type)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    final ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
    try {/*from  w ww  .  j  a v a2  s . c om*/
        final ClassLoader detectedClassLoaderForType = ExtensionManager.getClassLoader(type);
        final Class<?> rawClass;
        if (detectedClassLoaderForType == null) {
            // try to find from the current class loader
            rawClass = Class.forName(type);
        } else {
            // try to find from the registered classloader for that type
            rawClass = Class.forName(type, true, ExtensionManager.getClassLoader(type));
        }

        Thread.currentThread().setContextClassLoader(detectedClassLoaderForType);
        final Class<? extends StateProvider> mgrClass = rawClass.asSubclass(StateProvider.class);
        return mgrClass.newInstance();
    } finally {
        if (ctxClassLoader != null) {
            Thread.currentThread().setContextClassLoader(ctxClassLoader);
        }
    }
}

From source file:lodsve.core.config.properties.PropertyConverter.java

/**
 * Helper method for converting a value to a constant of an enumeration
 * class./*from   w  ww. ja v a 2 s.com*/
 * 
 * @param enumClass
 *            the enumeration class
 * @param value
 *            the value to be converted
 * @return the converted value
 */
@SuppressWarnings("unchecked")
// conversion is safe because we know that the class is an Enum class
private static Object convertToEnum(Class<?> enumClass, Object value) {
    return toEnum(value, enumClass.asSubclass(Enum.class));
}

From source file:demo.config.PropertyConverter.java

/**
 * Helper method for converting a value to a constant of an enumeration
 * class./*from  w w w. java2  s .c o m*/
 * 
 * @param enumClass
 *            the enumeration class
 * @param value
 *            the value to be converted
 * @return the converted value
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
// conversion is safe because we know that the class is an Enum class
private static Object convertToEnum(Class<?> enumClass, Object value) {
    return toEnum(value, (Class<? extends Enum>) enumClass.asSubclass(Enum.class));
}