List of usage examples for java.lang Class asSubclass
@SuppressWarnings("unchecked") public <U> Class<? extends U> asSubclass(Class<U> clazz)
From source file:com.linkedin.restli.internal.server.model.ResourceModelEncoder.java
private static String buildDataSchemaType(final Class<?> type, final DataSchema dataSchema) { final DataSchema schemaToEncode; if (dataSchema instanceof TyperefDataSchema) { return ((TyperefDataSchema) dataSchema).getFullName(); } else if (dataSchema instanceof PrimitiveDataSchema || dataSchema instanceof NamedDataSchema) { return dataSchema.getUnionMemberKey(); } else if (dataSchema instanceof UnionDataSchema && HasTyperefInfo.class.isAssignableFrom(type)) { final TyperefInfo unionRef = DataTemplateUtil.getTyperefInfo(type.asSubclass(DataTemplate.class)); schemaToEncode = unionRef.getSchema(); } else {/*from w ww. java 2 s.com*/ schemaToEncode = dataSchema; } JsonBuilder builder = null; try { builder = new JsonBuilder(JsonBuilder.Pretty.SPACES); final SchemaToJsonEncoder encoder = new NamedSchemaReferencingJsonEncoder(builder); encoder.encode(schemaToEncode); return builder.result(); } catch (IOException e) { throw new RestLiInternalException("could not encode schema for '" + type.getName() + "'", e); } finally { if (builder != null) { builder.closeQuietly(); } } }
From source file:org.apache.accumulo.core.util.shell.commands.SetScanIterCommand.java
@Override protected void setTableProperties(final CommandLine cl, final Shell shellState, final int priority, final Map<String, String> options, final String classname, final String name) throws AccumuloException, AccumuloSecurityException, ShellCommandException, TableNotFoundException { final String tableName = OptUtil.getTableOpt(cl, shellState); // instead of setting table properties, just put the options in a list to use at scan time Class<?> loadClass; try {/* ww w. j a v a 2 s .com*/ loadClass = getClass().getClassLoader().loadClass(classname); } catch (ClassNotFoundException e) { throw new ShellCommandException(ErrorCode.INITIALIZATION_FAILURE, "Unable to load " + classname); } try { loadClass.asSubclass(SortedKeyValueIterator.class); } catch (ClassCastException ex) { throw new ShellCommandException(ErrorCode.INITIALIZATION_FAILURE, "Unable to load " + classname + " as type " + SortedKeyValueIterator.class.getName()); } for (Iterator<Entry<String, String>> i = options.entrySet().iterator(); i.hasNext();) { final Entry<String, String> entry = i.next(); if (entry.getValue() == null || entry.getValue().isEmpty()) { i.remove(); } } List<IteratorSetting> tableScanIterators = shellState.scanIteratorOptions.get(tableName); if (tableScanIterators == null) { tableScanIterators = new ArrayList<IteratorSetting>(); shellState.scanIteratorOptions.put(tableName, tableScanIterators); } final IteratorSetting setting = new IteratorSetting(priority, name, classname); setting.addOptions(options); // initialize a scanner to ensure the new setting does not conflict with existing settings final String user = shellState.getConnector().whoami(); final Authorizations auths = shellState.getConnector().securityOperations().getUserAuthorizations(user); final Scanner scanner = shellState.getConnector().createScanner(tableName, auths); for (IteratorSetting s : tableScanIterators) { scanner.addScanIterator(s); } scanner.addScanIterator(setting); // if no exception has been thrown, it's safe to add it to the list tableScanIterators.add(setting); Shell.log.debug("Scan iterators :" + shellState.scanIteratorOptions.get(tableName)); }
From source file:org.apache.accumulo.core.util.shell.commands.SetShellIterCommand.java
@Override protected void setTableProperties(final CommandLine cl, final Shell shellState, final int priority, final Map<String, String> options, final String classname, final String name) throws AccumuloException, AccumuloSecurityException, ShellCommandException, TableNotFoundException { // instead of setting table properties, just put the options in a list to use at scan time String profile = cl.getOptionValue(profileOpt.getOpt()); // instead of setting table properties, just put the options in a list to use at scan time Class<?> loadClass; try {//from ww w.jav a 2s. c o m loadClass = getClass().getClassLoader().loadClass(classname); } catch (ClassNotFoundException e) { throw new ShellCommandException(ErrorCode.INITIALIZATION_FAILURE, "Unable to load " + classname); } try { loadClass.asSubclass(SortedKeyValueIterator.class); } catch (ClassCastException ex) { throw new ShellCommandException(ErrorCode.INITIALIZATION_FAILURE, "xUnable to load " + classname + " as type " + SortedKeyValueIterator.class.getName()); } for (Iterator<Entry<String, String>> i = options.entrySet().iterator(); i.hasNext();) { final Entry<String, String> entry = i.next(); if (entry.getValue() == null || entry.getValue().isEmpty()) { i.remove(); } } List<IteratorSetting> tableScanIterators = shellState.iteratorProfiles.get(profile); if (tableScanIterators == null) { tableScanIterators = new ArrayList<IteratorSetting>(); shellState.iteratorProfiles.put(profile, tableScanIterators); } final IteratorSetting setting = new IteratorSetting(priority, name, classname); setting.addOptions(options); Iterator<IteratorSetting> iter = tableScanIterators.iterator(); while (iter.hasNext()) { if (iter.next().getName().equals(name)) { iter.remove(); } } tableScanIterators.add(setting); }
From source file:com.ocpsoft.pretty.faces.util.ServiceLoader.java
private Class<? extends S> loadClass(String serviceClassName) { Class<?> clazz = null; Class<? extends S> serviceClass = null; try {/*from ww w . j av a 2 s . c om*/ clazz = loader.loadClass(serviceClassName); serviceClass = clazz.asSubclass(expectedType); } catch (ClassNotFoundException e) { log.warn("Could not load service class " + serviceClassName); } catch (ClassCastException e) { throw new RuntimeException( "Service class " + serviceClassName + " didn't implement the Extension interface"); } return serviceClass; }
From source file:org.seedstack.w20.internal.W20Plugin.java
@Override public InitState init(InitContext initContext) { if (servletContext == null) { logger.info("No servlet context detected, W20 integration disabled"); return InitState.INITIALIZED; }//from w w w . j av a 2 s.c o m ApplicationPlugin applicationPlugin = initContext.dependency(ApplicationPlugin.class); RestPlugin restPlugin = initContext.dependency(RestPlugin.class); Configuration w20Configuration = applicationPlugin.getApplication().getConfiguration() .subset(W20Plugin.W20_PLUGIN_CONFIGURATION_PREFIX); masterPageEnabled = !w20Configuration.getBoolean("disable-masterpage", false); if (masterPageEnabled) { if (restPlugin.getConfiguration().getRestPath().isEmpty()) { restPlugin.addRootResourceVariant(new Variant(MediaType.TEXT_HTML_TYPE, null, null), MasterpageRootResource.class); } else { masterPageAsServlet = true; } } Map<String, Collection<String>> scannedManifestPaths = initContext.mapResourcesByRegex(); ObjectMapper objectMapper = new ObjectMapper(); for (String manifestPath : scannedManifestPaths.get(FRAGMENTS_REGEX)) { try { AvailableFragment availableFragment = new AvailableFragment(manifestPath, objectMapper.readValue(classLoader.getResource(manifestPath), Fragment.class)); w20Fragments.put(availableFragment.getFragmentDefinition().getId(), availableFragment); logger.trace("Detected W20 fragment {} at {}", availableFragment.getFragmentDefinition().getId(), manifestPath); } catch (Exception e) { logger.warn("Unable to parse W20 fragment manifest at " + manifestPath, e); } } logger.debug("Detected {} W20 fragment(s)", w20Fragments.size()); Collection<String> appConfiguration = scannedManifestPaths.get(APP_CONF_REGEX); if (appConfiguration.size() == 1) { try { String confPath = appConfiguration.iterator().next(); configuredApplication = objectMapper.readValue(classLoader.getResource(confPath), ConfiguredApplication.class); logger.debug("Detected W20 configuration at " + confPath); } catch (IOException e) { throw new PluginException("Error reading W20 configuration", e); } } else if (appConfiguration.size() > 1) { throw new PluginException("Found more than one W20 configuration: " + appConfiguration); } Map<Class<?>, Collection<Class<?>>> scannedClassesByParentClass = initContext .scannedSubTypesByParentClass(); Collection<Class<?>> fragmentConfigurationHandlerClasses = scannedClassesByParentClass .get(FragmentConfigurationHandler.class); if (fragmentConfigurationHandlerClasses != null) { for (Class<?> candidate : fragmentConfigurationHandlerClasses) { if (FragmentConfigurationHandler.class.isAssignableFrom(candidate)) { this.fragmentConfigurationHandlerClasses .add(candidate.asSubclass(FragmentConfigurationHandler.class)); } } } return InitState.INITIALIZED; }
From source file:com.asakusafw.testdriver.TestDriverTestToolsBase.java
private String findTimestampColumn(String tableName) { Class<?> tableClass = testUtils.getClassByTablename(tableName); if (tableClass == null) { return null; }//from ww w .ja v a2 s. c o m if (ThunderGateCacheSupport.class.isAssignableFrom(tableClass)) { try { ThunderGateCacheSupport instance = tableClass.asSubclass(ThunderGateCacheSupport.class) .newInstance(); return instance.__tgc__TimestampColumn(); } catch (Exception e) { e.printStackTrace(); } } return null; }
From source file:org.spout.api.plugin.PluginLoader.java
/** * Loads the file as a plugin/*from w w w . j a v a 2 s . co m*/ * * @param file to load * @param ignoreSoftDepends ignores soft dependencies when it attempts to load the plugin * @return instance of the plugin */ public synchronized Plugin loadPlugin(File file, boolean ignoreSoftDepends) throws InvalidPluginException, UnknownDependencyException, InvalidDescriptionFileException { Plugin result = null; PluginDescriptionFile desc; PluginClassLoader loader; desc = getDescription(file); if (desc.isValidPlatform(engine.getPlatform())) { File dataFolder = new File(file.getParentFile(), desc.getName()); processDependencies(desc); if (!ignoreSoftDepends) { processSoftDependencies(desc); } try { loader = new PluginClassLoader(this, this.getClass().getClassLoader(), desc); loader.addURL(file.toURI().toURL()); Class<?> main = Class.forName(desc.getMain(), true, loader); Class<? extends Plugin> plugin = main.asSubclass(Plugin.class); boolean locked = manager.lock(key); Constructor<? extends Plugin> constructor = plugin.getConstructor(); result = constructor.newInstance(); result.initialize(this, engine, desc, dataFolder, file, loader); for (String protocolString : desc.getProtocols()) { Class<? extends Protocol> protocol = Class.forName(protocolString, true, loader) .asSubclass(Protocol.class); Constructor<? extends Protocol> pConstructor = protocol.getConstructor(); Protocol.registerProtocol(pConstructor.newInstance()); } if (!locked) { manager.unlock(key); } } catch (Exception e) { throw new InvalidPluginException(e); } catch (UnsupportedClassVersionError e) { String version = e.getMessage().replaceFirst("Unsupported major.minor version ", "").split(" ")[0]; engine.getLogger().severe("Plugin " + desc.getName() + " is built for a newer Java version than your current installation, and cannot be loaded!"); engine.getLogger() .severe("To run " + desc.getName() + ", you need Java version " + version + " or higher!"); throw new InvalidPluginException(e); } loader.setPlugin(result); loaders.put(desc.getName(), loader); } return result; }
From source file:org.spout.api.plugin.CommonPluginLoader.java
@Override public synchronized Plugin loadPlugin(File paramFile, boolean ignoresoftdepends) throws InvalidPluginException, UnknownDependencyException, InvalidDescriptionFileException { CommonPlugin result;/* w ww . ja v a 2s .c om*/ PluginDescriptionFile desc; CommonClassLoader loader; desc = getDescription(paramFile); File dataFolder = new File(paramFile.getParentFile(), desc.getName()); processDependencies(desc); if (!ignoresoftdepends) { processSoftDependencies(desc); } try { if (engine.getPlatform() == Platform.CLIENT) { loader = new ClientClassLoader(this, this.getClass().getClassLoader()); } else { loader = new CommonClassLoader(this, this.getClass().getClassLoader()); } loader.addURL(paramFile.toURI().toURL()); Class<?> main = Class.forName(desc.getMain(), true, loader); Class<? extends CommonPlugin> plugin = main.asSubclass(CommonPlugin.class); boolean locked = manager.lock(key); Constructor<? extends CommonPlugin> constructor = plugin.getConstructor(); result = constructor.newInstance(); result.initialize(this, engine, desc, dataFolder, paramFile, loader); if (!locked) { manager.unlock(key); } } catch (Exception e) { throw new InvalidPluginException(e); } catch (UnsupportedClassVersionError e) { String version = e.getMessage().replaceFirst("Unsupported major.minor version ", "").split(" ")[0]; Spout.getLogger().severe("Plugin " + desc.getName() + " is built for a newer Java version than your current installation, and cannot be loaded!"); Spout.getLogger() .severe("To run " + desc.getName() + ", you need Java version " + version + " or higher!"); throw new InvalidPluginException(e); } loader.setPlugin(result); loaders.put(desc.getName(), loader); return result; }
From source file:de.xaniox.heavyspleef.addon.java.AddOnClassLoader.java
public AddOnClassLoader(File file, ClassLoader parent, AddOnProperties properties, AddOnManager manager, SharedClassContext ctx, File dataFolder) throws InvalidAddOnException, MalformedURLException { super(new URL[] { file.toURI().toURL() }, parent); this.file = file; this.dataFolder = dataFolder; this.properties = properties; this.classContext = ctx; this.manager = manager; String mainClassName = properties.getMainClass(); Class<?> mainClass; try {/*from www .j a v a 2 s. com*/ mainClass = Class.forName(mainClassName, true, this); } catch (ClassNotFoundException e) { throw new InvalidAddOnException("Cannot find main class \"" + mainClassName + "\"", e); } Class<? extends BasicAddOn> addOnClass; try { addOnClass = mainClass.asSubclass(BasicAddOn.class); } catch (ClassCastException e) { throw new InvalidAddOnException("Main class \"" + mainClassName + "\" does not extend AddOn", e); } try { addOn = addOnClass.newInstance(); } catch (IllegalAccessException e) { throw new InvalidAddOnException( "Main class \"" + mainClassName + "\" does not declare an public empty constructor", e); } catch (InstantiationException e) { throw new InvalidAddOnException("Main class \"" + mainClassName + "\" could not be instantiated", e); } }
From source file:org.apache.nifi.registry.security.authentication.IdentityProviderFactory.java
private IdentityProvider createLoginIdentityProvider(final String identifier, final String loginIdentityProviderClassName) throws Exception { final IdentityProvider instance; final ClassLoader classLoader = extensionManager.getExtensionClassLoader(loginIdentityProviderClassName); if (classLoader == null) { throw new IllegalStateException("Extension not found in any of the configured class loaders: " + loginIdentityProviderClassName); }//www . j a v a2 s . c o m // attempt to load the class Class<?> rawLoginIdentityProviderClass = Class.forName(loginIdentityProviderClassName, true, classLoader); Class<? extends IdentityProvider> loginIdentityProviderClass = rawLoginIdentityProviderClass .asSubclass(IdentityProvider.class); // otherwise create a new instance Constructor constructor = loginIdentityProviderClass.getConstructor(); instance = (IdentityProvider) constructor.newInstance(); // method injection performMethodInjection(instance, loginIdentityProviderClass); // field injection performFieldInjection(instance, loginIdentityProviderClass); return instance; }