List of usage examples for java.lang Class isInterface
@HotSpotIntrinsicCandidate public native boolean isInterface();
From source file:edu.cmu.tetradapp.util.TetradSerializableUtils.java
/** * Returns all of the classes x in the given directory (recursively) such * that clazz.isAssignableFrom(x).//from www. ja v a2s . c o m */ public List<Class> getAssignableClasses(File path, Class<TetradSerializable> clazz) { if (!path.isDirectory()) { throw new IllegalArgumentException("Not a directory: " + path); } List<Class> classes = new LinkedList<Class>(); File[] files = path.listFiles(); for (File file : files) { if (file.isDirectory()) { classes.addAll(getAssignableClasses(file, clazz)); } else { String packagePath = file.getPath(); packagePath = packagePath.replace('\\', '.'); packagePath = packagePath.replace('/', '.'); packagePath = packagePath.substring(packagePath.indexOf("edu.cmu"), packagePath.length()); int index = packagePath.indexOf(".class"); if (index == -1) { continue; } packagePath = packagePath.substring(0, index); try { Class _clazz = getClass().getClassLoader().loadClass(packagePath); if (clazz.isAssignableFrom(_clazz) && !_clazz.isInterface()) { classes.add(_clazz); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } } return classes; }
From source file:org.apache.openjpa.kernel.AbstractBrokerFactory.java
private boolean needsSub(Class<?> cls) { return !cls.isInterface() && !PersistenceCapable.class.isAssignableFrom(cls); }
From source file:org.eclipse.emf.mwe.utils.StandaloneSetup.java
/** * Adds an extension/*from ww w . ja v a 2 s . com*/ * * @param m * <tt>from</tt>: extension name, <tt>to</tt> factory classname * @throws ConfigurationException * <ul> * <li>The factory class for the extension cannot be found * <li>The inner factory class for the extension cannot be found * </ul> */ public void addExtensionMap(final Mapping m) throws ConfigurationException { log.info("Adding Extension mapping from '" + m.getFrom() + "' to '" + m.getTo() + "'"); try { // locate the factory class of the extension Class<?> factoryClass = ResourceLoaderFactory.createResourceLoader().loadClass(m.getTo()); if (factoryClass == null) throw new ConfigurationException( "cannot find class " + m.getTo() + " for extension " + m.getFrom()); Object factoryInstance = null; if (factoryClass.isInterface()) { final Class<?>[] innerClasses = factoryClass.getDeclaredClasses(); factoryClass = null; for (int j = 0; j < innerClasses.length; j++) { if (Resource.Factory.class.isAssignableFrom(innerClasses[j])) { factoryClass = innerClasses[j]; } } if (factoryClass == null) throw new ConfigurationException( "cannot find inner factory class " + m.getTo() + " for extension " + m.getFrom()); final Field instanceField = factoryClass.getField("INSTANCE"); factoryInstance = instanceField.get(null); } else { factoryInstance = factoryClass.newInstance(); } Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(m.getFrom(), factoryInstance); } catch (final Exception e) { throw new ConfigurationException(e); } }
From source file:com.hihsoft.baseclass.web.controller.BaseController.java
/** * ???(xiaojf?)/*from ww w. j av a 2s . c o m*/ */ @Override protected void bind(final HttpServletRequest request, final Object command) { final PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(command.getClass()); for (final PropertyDescriptor pd : pds) { final Class<?> clas = pd.getPropertyType();// ?class final boolean isSimpleProperty = BeanUtils.isSimpleProperty(clas); final boolean isInterface = clas.isInterface(); final boolean hasConstruct = clas.getConstructors().length == 0 ? false : true; if (!isSimpleProperty && !isInterface && hasConstruct) { // try { pd.getWriteMethod().invoke(command, clas.newInstance()); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } try { super.bind(request, command); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.atricore.idbus.kernel.main.databinding.JAXBUtils.java
private static ArrayList<Class> getClassesFromDirectory(String pkg, ClassLoader cl) throws ClassNotFoundException { // This will hold a list of directories matching the pckgname. There may be more than one if a package is split over multiple jars/paths String pckgname = pkg;//from w ww . j a v a 2s .c om ArrayList<File> directories = new ArrayList<File>(); try { String path = pckgname.replace('.', '/'); // Ask for all resources for the path Enumeration<URL> resources = cl.getResources(path); while (resources.hasMoreElements()) { directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8"))); } } catch (UnsupportedEncodingException e) { if (log.isDebugEnabled()) { log.debug(pckgname + " does not appear to be a valid package (Unsupported encoding)"); } throw new ClassNotFoundException( pckgname + " might not be a valid package because the encoding is unsupported."); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("IOException was thrown when trying to get all resources for " + pckgname); } throw new ClassNotFoundException( "An IOException error was thrown when trying to get all of the resources for " + pckgname); } ArrayList<Class> classes = new ArrayList<Class>(); // For every directory identified capture all the .class files for (File directory : directories) { if (log.isDebugEnabled()) { log.debug(" Adding JAXB classes from directory: " + directory.getName()); } if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (String file : files) { // we are only interested in .class files if (file.endsWith(".class")) { // removes the .class extension // TODO Java2 Sec String className = pckgname + '.' + file.substring(0, file.length() - 6); try { Class clazz = forName(className, false, getContextClassLoader()); // Don't add any interfaces or JAXWS specific classes. // Only classes that represent data and can be marshalled // by JAXB should be added. if (!clazz.isInterface() && (clazz.isEnum() || getAnnotation(clazz, XmlType.class) != null || ClassUtils.getDefaultPublicConstructor(clazz) != null) && !ClassUtils.isJAXWSClass(clazz) && !isSkipClass(clazz) && !Exception.class.isAssignableFrom(clazz)) { // Ensure that all the referenced classes are loadable too clazz.getDeclaredMethods(); clazz.getDeclaredFields(); if (log.isDebugEnabled()) { log.debug("Adding class: " + file); } classes.add(clazz); // REVIEW: // Support of RPC list (and possibly other scenarios) requires that the array classes should also be present. // This is a hack until we can determine how to get this information. // The arrayName and loadable name are different. Get the loadable // name, load the array class, and add it to our list //className += "[]"; //String loadableName = ClassUtils.getLoadableClassName(className); //Class aClazz = Class.forName(loadableName, false, Thread.currentThread().getContextClassLoader()); } //Catch Throwable as ClassLoader can throw an NoClassDefFoundError that //does not extend Exception } catch (Throwable e) { if (log.isDebugEnabled()) { log.debug("Tried to load class " + className + " while constructing a JAXBContext. This class will be skipped. Processing Continues."); log.debug(" The reason that class could not be loaded:" + e.toString()); log.trace(JavaUtils.stackToString(e)); } } } } } } return classes; }
From source file:eu.qualityontime.commons.MethodUtils.java
/** * Gets the number of steps required needed to turn the source class into * the destination class. This represents the number of steps in the object * hierarchy graph./*from www . j a v a2 s .c o m*/ * * @param srcClass * The source class * @param destClass * The destination class * @return The cost of transforming an object */ private static float getObjectTransformationCost(Class<?> srcClass, final Class<?> destClass) { float cost = 0.0f; while (srcClass != null && !destClass.equals(srcClass)) { if (destClass.isPrimitive()) { final Class<?> destClassWrapperClazz = getPrimitiveWrapper(destClass); if (destClassWrapperClazz != null && destClassWrapperClazz.equals(srcClass)) { cost += 0.25f; break; } } if (destClass.isInterface() && isAssignmentCompatible(destClass, srcClass)) { // slight penalty for interface match. // we still want an exact match to override an interface match, // but // an interface match should override anything where we have to // get a // superclass. cost += 0.25f; break; } cost++; srcClass = srcClass.getSuperclass(); } /* * If the destination class is null, we've travelled all the way up to * an Object match. We'll penalize this by adding 1.5 to the cost. */ if (srcClass == null) { cost += 1.5f; } return cost; }
From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java
private static ArrayList<Class> getClassesFromDirectory(String pkg, ClassLoader cl) throws ClassNotFoundException { // This will hold a list of directories matching the pckgname. There may be more than one if a package is split over multiple jars/paths String pckgname = pkg;//ww w .ja v a 2 s .c om ArrayList<File> directories = new ArrayList<File>(); try { String path = pckgname.replace('.', '/'); // Ask for all resources for the path Enumeration<URL> resources = cl.getResources(path); while (resources.hasMoreElements()) { directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8"))); } } catch (UnsupportedEncodingException e) { if (log.isDebugEnabled()) { log.debug(pckgname + " does not appear to be a valid package (Unsupported encoding)"); } throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr2", pckgname)); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("IOException was thrown when trying to get all resources for " + pckgname); } throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr3", pckgname)); } ArrayList<Class> classes = new ArrayList<Class>(); // For every directory identified capture all the .class files for (File directory : directories) { if (log.isDebugEnabled()) { log.debug(" Adding JAXB classes from directory: " + directory.getName()); } if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (String file : files) { // we are only interested in .class files if (file.endsWith(".class")) { // removes the .class extension // TODO Java2 Sec String className = pckgname + '.' + file.substring(0, file.length() - 6); try { Class clazz = forName(className, false, getContextClassLoader()); // Don't add any interfaces or JAXWS specific classes. // Only classes that represent data and can be marshalled // by JAXB should be added. if (!clazz.isInterface() && (clazz.isEnum() || getAnnotation(clazz, XmlType.class) != null || ClassUtils.getDefaultPublicConstructor(clazz) != null) && !ClassUtils.isJAXWSClass(clazz) && !isSkipClass(clazz) && !java.lang.Exception.class.isAssignableFrom(clazz)) { // Ensure that all the referenced classes are loadable too clazz.getDeclaredMethods(); clazz.getDeclaredFields(); if (log.isDebugEnabled()) { log.debug("Adding class: " + file); } classes.add(clazz); // REVIEW: // Support of RPC list (and possibly other scenarios) requires that the array classes should also be present. // This is a hack until we can determine how to get this information. // The arrayName and loadable name are different. Get the loadable // name, load the array class, and add it to our list //className += "[]"; //String loadableName = ClassUtils.getLoadableClassName(className); //Class aClazz = Class.forName(loadableName, false, Thread.currentThread().getContextClassLoader()); } //Catch Throwable as ClassLoader can throw an NoClassDefFoundError that //does not extend Exception } catch (Throwable e) { if (log.isDebugEnabled()) { log.debug("Tried to load class " + className + " while constructing a JAXBContext. This class will be skipped. Processing Continues."); log.debug(" The reason that class could not be loaded:" + e.toString()); log.trace(JavaUtils.stackToString(e)); } } } } } } return classes; }
From source file:com.app.server.JarDeployer.java
/** * This method implements the jar deployer which configures the executor services. * Frequently monitors the deploy directory and configures the executor services map * once the jar is deployed in deploy directory and reconfigures if the jar is modified and * placed in the deploy directory./* w w w . j a v a2 s.c o m*/ */ public void run() { StandardFileSystemManager fsManager = new StandardFileSystemManager(); try { fsManager.init(); DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } File file = new File(scanDirectory.split(";")[0]); File[] files = file.listFiles(); CopyOnWriteArrayList<String> classList = new CopyOnWriteArrayList<String>(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) continue; //Long lastModified=(Long) fileMap.get(files[i].getName()); if (files[i].getName().endsWith(".jar")) { String filePath = files[i].getAbsolutePath(); FileObject jarFile = null; try { jarFile = fsManager.resolveFile("jar:" + filePath); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //logger.info("filePath"+filePath); filePath = filePath.substring(0, filePath.toLowerCase().lastIndexOf(".jar")); WebClassLoader customClassLoader = null; try { URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); try { customClassLoader = new WebClassLoader(urls); log.info(customClassLoader.geturlS()); customClassLoader.addURL(new URL("file:/" + files[i].getAbsolutePath())); CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList(); getUsersJars(new File(libDir), jarList); for (String jarFilePath : jarList) customClassLoader.addURL(new URL("file:/" + jarFilePath.replace("\\", "/"))); log.info("deploy=" + customClassLoader.geturlS()); this.urlClassLoaderMap.put(scanDirectory + "/" + files[i].getName(), customClassLoader); jarsDeployed.add(files[i].getName()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } log.info(urlClassLoaderMap); getChildren(jarFile, classList); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for (int classCount = 0; classCount < classList.size(); classCount++) { String classwithpackage = classList.get(classCount).substring(0, classList.get(classCount).indexOf(".class")); classwithpackage = classwithpackage.replace("/", "."); log.info("classList:" + classwithpackage.replace("/", ".")); try { if (!classwithpackage.contains("$")) { Class executorServiceClass = customClassLoader.loadClass(classwithpackage); //log.info("executor class in ExecutorServicesConstruct"+executorServiceClass); //log.info(); if (!executorServiceClass.isInterface()) { Annotation[] classServicesAnnot = executorServiceClass.getDeclaredAnnotations(); if (classServicesAnnot != null) { for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) { if (classServicesAnnot[annotcount] instanceof RemoteCall) { RemoteCall remoteCall = (RemoteCall) classServicesAnnot[annotcount]; //registry.unbind(remoteCall.servicename()); log.info(remoteCall.servicename().trim()); try { //for(int count=0;count<500;count++){ RemoteInterface reminterface = (RemoteInterface) UnicastRemoteObject .exportObject((Remote) executorServiceClass.newInstance(), 2004); registry.rebind(remoteCall.servicename().trim(), reminterface); //} } catch (Exception ex) { ex.printStackTrace(); } } } } } Method[] methods = executorServiceClass.getDeclaredMethods(); for (Method method : methods) { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof ExecutorServiceAnnot) { ExecutorServiceAnnot executorServiceAnnot = (ExecutorServiceAnnot) annotation; ExecutorServiceInfo executorServiceInfo = new ExecutorServiceInfo(); executorServiceInfo.setExecutorServicesClass(executorServiceClass); executorServiceInfo.setMethod(method); executorServiceInfo.setMethodParams(method.getParameterTypes()); //log.info("method="+executorServiceAnnot.servicename()); //log.info("method info="+executorServiceInfo); //if(servicesMap.get(executorServiceAnnot.servicename())==null)throw new Exception(); executorServiceMap.put(executorServiceAnnot.servicename(), executorServiceInfo); } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } ClassLoaderUtil.closeClassLoader(customClassLoader); try { jarFile.close(); } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fsManager.closeFileSystem(jarFile.getFileSystem()); } } fsManager.close(); fsManager = new StandardFileSystemManager(); try { DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir)); //fsManager.setReplicator(new PrivilegedFileReplicator(replicator)); fsManager.setTemporaryFileStore(replicator); } catch (FileSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JarFileListener jarFileListener = new JarFileListener(executorServiceMap, libDir, urlClassLoaderMap, jarsDeployed); DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener); jarFileListener.setFm(fm); FileObject listendir = null; String[] dirsToScan = scanDirectory.split(";"); try { FileSystemOptions opts = new FileSystemOptions(); FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true); fsManager.init(); for (String dir : dirsToScan) { if (dir.startsWith("ftp://")) { listendir = fsManager.resolveFile(dir, opts); } else { listendir = fsManager.resolveFile(dir); } fm.addFile(listendir); } } catch (FileSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } fm.setRecursive(true); fm.setDelay(3000); fm.start(); //fsManager.close(); }
From source file:be.objectify.deadbolt.java.actions.AbstractDeadboltAction.java
/** * Gets the current {@link DeadboltHandler}. This can come from one of three places: * - a handler key is provided in the annotation. A cached instance of that class will be used. This has the highest priority. * - a class name is provided in the annotation. A new instance of that class will be created. * - the global handler defined in the application.conf by deadbolt.handler. This has the lowest priority. * * @param handlerKey the DeadboltHandler key, if any, coming from the annotation. May be null. * @param deadboltHandlerClass the DeadboltHandler class, if any, coming from the annotation. May be null. * @param <C> the actual class of the DeadboltHandler * @return an instance of DeadboltHandler. *//*from w w w . ja v a 2 s.co m*/ protected <C extends DeadboltHandler> DeadboltHandler getDeadboltHandler(String handlerKey, Class<C> deadboltHandlerClass) throws Throwable { DeadboltHandler deadboltHandler; if (StringUtils.isNotEmpty(handlerKey)) { LOGGER.info("Getting Deadbolt handler with key [{}]", handlerKey); deadboltHandler = PluginUtils.getDeadboltHandler(handlerKey); LOGGER.info("Deadbolt handler with key [{}] - found [{}]", handlerKey, deadboltHandler); if (deadboltHandler == null) { LOGGER.error("Falling back to global handler because requested handler [{}] is null", handlerKey); deadboltHandler = PluginUtils.getDeadboltHandler(); } } else if (deadboltHandlerClass != null && !deadboltHandlerClass.isInterface()) { try { deadboltHandler = deadboltHandlerClass.newInstance(); } catch (Exception e) { throw new RuntimeException("Error creating Deadbolt handler", e); } } else { deadboltHandler = PluginUtils.getDeadboltHandler(); } return deadboltHandler; }
From source file:org.eclipse.wb.internal.core.parser.AbstractParseFactory.java
/** * Processing instance factory//from w w w . j a v a2 s . c o m * * @param methodBinding */ protected JavaInfo createInstanceFactory(AstEditor editor, MethodInvocation invocation, IMethodBinding methodBinding, JavaInfo[] argumentInfos, InstanceFactoryInfo factoryInfo, FactoryMethodDescription description) throws Exception { Class<?> returnClass = description.getReturnClass(); // ignore interfaces if (returnClass.isInterface()) { return null; } // create JavaInfo JavaInfo javaInfo = JavaInfoUtils.createJavaInfo(editor, returnClass, new InstanceFactoryCreationSupport(factoryInfo, description, invocation)); // try to associate with parent for (ParameterDescription parameter : description.getParameters()) { if (parameter.isParent()) { JavaInfo parameterJavaInfo = argumentInfos[parameter.getIndex()]; if (parameterJavaInfo != null) { javaInfo.setAssociation(new FactoryParentAssociation(invocation)); parameterJavaInfo.addChild(javaInfo); } } } // check for non-visual bean NonVisualBeanInfo nonVisualInfo = NonVisualBeanContainerInfo.getNonVisualInfo(invocation); if (nonVisualInfo != null) { nonVisualInfo.setJavaInfo(javaInfo); } // component created using instance factory return javaInfo; }