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.godhuli.rhipe.RHMRHelper.java

void setup(Configuration cfg, String argv, boolean doPipe) {
    try {//w  ww.  j  a va2 s .  c om
        //        InetAddress addr = InetAddress.getLocalHost();
        //        hostname = addr.getHostName();
        doPartitionRelatedSetup(cfg);
        String squote = cfg.get("rhipe_string_quote");
        if (squote == null)
            squote = "";

        REXPHelper.setFieldSep(cfg.get("mapred.field.separator", " "));
        REXPHelper.setStringQuote(squote);

        BUFFER_SIZE = cfg.getInt("rhipe_stream_buffer", 10 * 1024);
        joinDelay_ = cfg.getLong("rhipe_joindelay_milli", 0);
        nonZeroExitIsFailure_ = cfg.getBoolean("rhipe_non_zero_exit_is_failure", true);
        doPipe_ = doPipe;
        thisfs = FileSystem.get(cfg);

        Class<?> _kc = null;

        if (callID.equals("Mapper")) {
            if (cfg.getInt("mapred.reduce.tasks", 0) == 0)
                _kc = Class.forName(cfg.get("rhipe_outputformat_keyclass"));
            else
                _kc = Class.forName(cfg.get("rhipe_map_output_keyclass"));
        } else {
            _kc = Class.forName(cfg.get("rhipe_outputformat_keyclass"));
        }
        keyclass = _kc.asSubclass(RHBytesWritable.class);

        if (cfg.get("rhipe_output_folder") != null)
            outputFolder = new Path(cfg.get("rhipe_output_folder"));
        if (!doPipe_)
            return;
        copyFile = cfg.get("rhipe_copy_file").equals("TRUE") ? true : false;
        String[] argvSplit = argv.split(" ");
        String prog = argvSplit[0];
        Environment childEnv = (Environment) env().clone();
        cfg.set("io_sort_mb", cfg.get("io.sort.mb"));
        addJobConfToEnvironment(cfg, childEnv);
        childEnv.put("TMPDIR", System.getProperty("java.io.tmpdir"));
        // Start the process
        ProcessBuilder builder = new ProcessBuilder(argvSplit);
        builder.environment().putAll(childEnv.toMap());
        sim = builder.start();
        clientOut_ = new DataOutputStream(new BufferedOutputStream(sim.getOutputStream(), BUFFER_SIZE));
        clientIn_ = new DataInputStream(new BufferedInputStream(sim.getInputStream(), BUFFER_SIZE));
        clientErr_ = new DataInputStream(new BufferedInputStream(sim.getErrorStream()));
        startTime_ = System.currentTimeMillis();
        LOG.info(callID + ":" + "Started external program:" + argv);
        errThread_ = new MRErrorThread();
        LOG.info(callID + ":" + "Started Error Thread");
        errThread_.start();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("configuration exception", e);
    }
}

From source file:org.apache.metamodel.spring.DataContextFactoryBean.java

private DataContextFactoryBeanDelegate createDelegateFromType() {
    final Class<?> cls;
    try {/*from  w  w w . j av a  2s.  c  om*/
        logger.debug("Attempting to interpret type '{}' as a delegate class name", _type);
        cls = Class.forName(_type.trim());
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to load type '" + _type + "' as a class", e);
        }
        return null;
    }

    if (cls == null) {
        return null;
    }

    if (!DataContextFactoryBeanDelegate.class.isAssignableFrom(cls)) {
        return null;
    }

    try {
        final DataContextFactoryBeanDelegate delegate = cls.asSubclass(DataContextFactoryBeanDelegate.class)
                .newInstance();
        return delegate;
    } catch (Exception e) {
        logger.warn("Failed to instantiate delegate " + cls, e);
        return null;
    }
}

From source file:org.deegree.services.wms.controller.WMSController.java

@Override
public void init(DeegreeServicesMetadataType serviceMetadata, DeegreeServiceControllerType mainConfig,
        Object controllerConf) {/*www .jav  a 2  s.  co  m*/

    identification = convertFromJAXB(serviceMetadata.getServiceIdentification());
    provider = convertFromJAXB(serviceMetadata.getServiceProvider());

    NamespaceBindings nsContext = new NamespaceBindings();
    nsContext.addNamespace("wms", "http://www.deegree.org/services/wms");

    conf = (DeegreeWMS) controllerConf;

    if (conf.getExtendedCapabilities() != null) {
        this.extendedCaps = new HashMap<String, List<OMElement>>();
        List<OMElement> caps = new ArrayList<OMElement>(conf.getExtendedCapabilities().size());
        extendedCaps.put("default", caps);
        for (ExtendedCapabilities extendedCapsConf : conf.getExtendedCapabilities()) {
            DOMSource domSource = new DOMSource(extendedCapsConf.getAny());
            XMLStreamReader xmlStream;
            try {
                xmlStream = XMLInputFactory.newInstance().createXMLStreamReader(domSource);
            } catch (Exception t) {
                throw new ResourceInitException("Error extracting extended capabilities: " + t.getMessage(), t);
            }
            caps.add(new XMLAdapter(xmlStream).getRootElement());
        }
    }

    try {
        addSupportedImageFormats(conf);

        if (conf.getFeatureInfoFormats() != null) {
            for (GetFeatureInfoFormat t : conf.getFeatureInfoFormats().getGetFeatureInfoFormat()) {
                if (t.getFile() != null) {
                    featureInfoManager.addOrReplaceFormat(t.getFormat(),
                            metadata.getLocation().resolveToFile(t.getFile()).toString());
                } else if (t.getXSLTFile() != null) {
                    XSLTFile xsltFile = t.getXSLTFile();
                    GMLVersion version = GMLVersion.valueOf(xsltFile.getGmlVersion().toString());
                    featureInfoManager.addOrReplaceXsltFormat(t.getFormat(),
                            metadata.getLocation().resolveToUrl(xsltFile.getValue()), version, workspace);
                } else if (t.getSerializer() != null) {
                    Serializer serializer = t.getSerializer();

                    FeatureInfoSerializer featureInfoSerializer;
                    try {
                        Class<?> clazz = workspace.getModuleClassLoader().loadClass(serializer.getJavaClass());
                        featureInfoSerializer = clazz.asSubclass(FeatureInfoSerializer.class).newInstance();
                    } catch (ClassNotFoundException e) {
                        throw new IllegalArgumentException("Couldn't find serializer class", e);
                    } catch (ClassCastException e) {
                        throw new IllegalArgumentException(
                                "Configured serializer class doesn't implement FeatureInfoSerializer", e);
                    }

                    featureInfoManager.addOrReplaceCustomFormat(t.getFormat(), featureInfoSerializer);
                } else {
                    throw new IllegalArgumentException("Unknown GetFeatureInfoFormat");
                }
            }
        }

        // if ( pi.getImageFormat() != null ) {
        // for ( ImageFormat f : pi.getImageFormat() ) {
        // instantiateSerializer( imageSerializers, f.getFormat(), f.getClazz(), ImageSerializer.class );
        // }
        // }

        final org.deegree.services.jaxb.wms.DeegreeWMS.SupportedVersions versions = conf.getSupportedVersions();
        if (versions == null) {
            ArrayList<String> vs = new ArrayList<String>();
            vs.add("1.1.1");
            vs.add("1.3.0");
            validateAndSetOfferedVersions(vs);
        } else {
            validateAndSetOfferedVersions(versions.getVersion());
        }

        for (Version v : offeredVersions) {
            if (v.equals(VERSION_111)) {
                controllers.put(VERSION_111, new WMSController111());
            }
            if (v.equals(VERSION_130)) {
                controllers.put(VERSION_130, new WMSController130());
            }
        }

        Iterator<Version> iter = controllers.keySet().iterator();
        while (iter.hasNext()) {
            highestVersion = iter.next();
        }

        ServiceConfigurationType sc = conf.getServiceConfiguration();
        service = new MapService(sc, workspace);

        // after the service knows what layers are available:
        handleMetadata(conf.getMetadataURLTemplate(), conf.getMetadataStoreId());

        String configId = getMetadata().getIdentifier().getId();
        metadataProvider = workspace.getResource(OWSMetadataProviderProvider.class, configId + "_metadata");
    } catch (Exception e) {
        throw new ResourceInitException(e.getMessage(), e);
    }

}

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

private boolean convertInsts(Cls rootCls, OWLClass owlClass) {
    // create individual converter if appropriate
    String clsName = rootCls.getName();
    Class instConvClass = cReader.getInstConvMap().get(clsName);
    Map<String, String> instConvInitArgs = cReader.getInstConvInitArgsMap().get(clsName);

    if (instConvClass == null)
        return true; // this is not wrong, but there are no instances to convert
    if (instConvInitArgs == null) // use empty map
        instConvInitArgs = new HashMap<String, String>();

    try {/* ww  w .  j a  v a 2 s.  co m*/
        InstanceConverter converter = (InstanceConverter) instConvClass
                .asSubclass(InstanceConverter.class).getConstructor(KnowledgeBase.class, Cls.class,
                        OWLOntology.class, IRIUtils.class, ConvUtils.class)
                .newInstance(framesKB, rootCls, owlOnt, iriUtils, convUtils);

        // init with any args from the config file
        boolean initSuccess = converter.init(instConvInitArgs);
        if (!initSuccess) {
            System.err.println("Failed to initialize converter for instances of " + rootCls.getBrowserText());
            System.exit(-1);
        }
        converter.convertInsts();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        return false;
    } catch (SecurityException e) {
        e.printStackTrace();
        return false;
    } catch (InstantiationException e) {
        e.printStackTrace();
        return false;
    } catch (IllegalAccessException e) {
        e.printStackTrace();
        return false;
    } catch (InvocationTargetException e) {
        e.printStackTrace();
        return false;
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.kuali.rice.krad.service.impl.RemoteModuleServiceBase.java

/**
 * @see org.kuali.rice.krad.service.ModuleService#getExternalizableDataObjectLookupUrl(java.lang.Class,
 * java.util.Properties)/*from w ww. ja v a2 s.  c o m*/
 */
@Override
public String getExternalizableDataObjectLookupUrl(Class<?> lookupDataObjectClass, Properties parameters) {
    String baseUrl = getBaseLookupUrl();

    // if external business object, replace data object in request with the actual impl object class
    if (ExternalizableBusinessObject.class.isAssignableFrom(lookupDataObjectClass)) {
        Class implementationClass = getExternalizableBusinessObjectImplementation(
                lookupDataObjectClass.asSubclass(ExternalizableBusinessObject.class));
        if (implementationClass == null) {
            throw new RuntimeException("Can't find ExternalizableBusinessObject implementation class for "
                    + lookupDataObjectClass.getName());
        }

        parameters.put(UifParameters.DATA_OBJECT_CLASS_NAME, implementationClass.getName());
    }

    return UrlFactory.parameterizeUrl(baseUrl, parameters);
}

From source file:com.chiorichan.plugin.loader.JavaPluginLoader.java

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

    boolean useTimings = Loader.getEventBus().useTimings();
    Map<Class<? extends Event>, Set<RegisteredListener>> ret = new HashMap<Class<? extends Event>, Set<RegisteredListener>>();
    Set<Method> methods;
    try {/*from  w w  w  .j  av  a  2s .c  om*/
        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) {
        PluginManager.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])) {
            PluginManager.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;
                }
                PluginManager.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.stanwood.media.Controller.java

@SuppressWarnings("unchecked")
private void registerPlugins() throws ConfigException {
    for (Plugin plugin : configReader.getPlugins()) {
        try {//from  w  w w.j  a va2s . c o m
            Class<?> clazz;
            if (plugin.getJar() != null) {
                URL url = new URL("jar:file:" + plugin.getJar() + "!/"); //$NON-NLS-1$//$NON-NLS-2$
                URLClassLoader clazzLoader = new URLClassLoader(new URL[] { url });
                clazz = clazzLoader.loadClass(plugin.getPluginClass());
            } else {
                clazz = Class.forName(plugin.getPluginClass());
            }
            Class<? extends ExtensionInfo<?>> targetClass = (Class<? extends ExtensionInfo<?>>) clazz
                    .asSubclass(ExtensionInfo.class);
            ExtensionInfo<?> info = targetClass.newInstance();
            registerExtension(info);
        } catch (MalformedURLException e) {
            throw new ConfigException(MessageFormat
                    .format(Messages.getString("Controller.UNABLE_TO_REGISTER_PLUGIN"), plugin.toString()), e); //$NON-NLS-1$
        } catch (ClassNotFoundException e) {
            throw new ConfigException(MessageFormat
                    .format(Messages.getString("Controller.UNABLE_TO_REGISTER_PLUGIN"), plugin.toString()), e); //$NON-NLS-1$
        } catch (InstantiationException e) {
            throw new ConfigException(MessageFormat
                    .format(Messages.getString("Controller.UNABLE_TO_REGISTER_PLUGIN"), plugin.toString()), e); //$NON-NLS-1$
        } catch (IllegalAccessException e) {
            throw new ConfigException(MessageFormat
                    .format(Messages.getString("Controller.UNABLE_TO_REGISTER_PLUGIN"), plugin.toString()), e); //$NON-NLS-1$
        }
    }
}

From source file:org.kuali.rice.krad.service.impl.RemoteModuleServiceBase.java

/**
 * @see org.kuali.rice.krad.service.ModuleService#getExternalizableDataObjectInquiryUrl(java.lang.Class,
 * java.util.Properties)/*from ww w . j  a  va  2s .co m*/
 */
@Override
public String getExternalizableDataObjectInquiryUrl(Class<?> inquiryDataObjectClass, Properties parameters) {
    String baseUrl = getBaseInquiryUrl();

    // if external business object, replace data object in request with the actual impl object class
    if (ExternalizableBusinessObject.class.isAssignableFrom(inquiryDataObjectClass)) {
        Class implementationClass = getExternalizableBusinessObjectImplementation(
                inquiryDataObjectClass.asSubclass(ExternalizableBusinessObject.class));
        if (implementationClass == null) {
            throw new RuntimeException("Can't find ExternalizableBusinessObject implementation class for "
                    + inquiryDataObjectClass.getName());
        }

        parameters.put(UifParameters.DATA_OBJECT_CLASS_NAME, implementationClass.getName());
    }

    return UrlFactory.parameterizeUrl(baseUrl, parameters);
}

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

private List<ClassHolderTransformer> instantiateTransformers(ClassLoader classLoader)
        throws MojoExecutionException {
    List<ClassHolderTransformer> transformerInstances = new ArrayList<>();
    if (transformers == null) {
        return transformerInstances;
    }//  w  ww  . jav  a2  s .co  m
    for (String transformerName : transformers) {
        Class<?> transformerRawType;
        try {
            transformerRawType = Class.forName(transformerName, true, classLoader);
        } catch (ClassNotFoundException e) {
            throw new MojoExecutionException("Transformer not found: " + transformerName, e);
        }
        if (!ClassHolderTransformer.class.isAssignableFrom(transformerRawType)) {
            throw new MojoExecutionException("Transformer " + transformerName + " is not subtype of "
                    + ClassHolderTransformer.class.getName());
        }
        Class<? extends ClassHolderTransformer> transformerType = transformerRawType
                .asSubclass(ClassHolderTransformer.class);
        Constructor<? extends ClassHolderTransformer> ctor;
        try {
            ctor = transformerType.getConstructor();
        } catch (NoSuchMethodException e) {
            throw new MojoExecutionException("Transformer " + transformerName + " has no default constructor");
        }
        try {
            ClassHolderTransformer transformer = ctor.newInstance();
            transformerInstances.add(transformer);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new MojoExecutionException("Error instantiating transformer " + transformerName, e);
        }
    }
    return transformerInstances;
}

From source file:edu.ku.brc.specify.extras.ViewToSchemaReview.java

/**
 * @param fcf/* w w w.  ja  va 2 s .com*/
 */
protected void checkPluginForNames(final FormCellFieldIFace cellField, final String pluginName,
        final HashSet<String> fieldsHash) {
    Class<?> pluginClass = TaskMgr.getUIPluginClassForName(pluginName);
    if (pluginClass != null && UIPluginable.class.isAssignableFrom(pluginClass)) {
        try {
            // instantiate the plugin object
            UIPluginable uiPlugin = pluginClass.asSubclass(UIPluginable.class).newInstance();
            if (uiPlugin != null) {
                for (String fieldName : uiPlugin.getFieldNames()) {
                    fieldsHash.add(fieldName);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            FormDevHelper.appendFormDevError(ex);
        }
    }
}