Example usage for java.lang Class getDeclaredMethods

List of usage examples for java.lang Class getDeclaredMethods

Introduction

In this page you can find the example usage for java.lang Class getDeclaredMethods.

Prototype

@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Usage

From source file:org.apache.axis.description.JavaServiceDesc.java

private Method[] getMethods(Class implClass) {
    if (implClass.isInterface()) {
        // only return methods that are not part of start classes
        List methodsList = new ArrayList();
        Method[] methods = implClass.getMethods();
        if (methods != null) {
            for (int i = 0; i < methods.length; i++) {
                String declaringClass = methods[i].getDeclaringClass().getName();
                if (!declaringClass.startsWith("java.") && !declaringClass.startsWith("javax.")) {
                    methodsList.add(methods[i]);
                }/*from   ww w  .j  ava2 s .c o  m*/
            }
        }
        return (Method[]) methodsList.toArray(new Method[] {});
    } else {
        return implClass.getDeclaredMethods();
    }
}

From source file:name.yumaa.ChromeLogger4J.java

/**
 * Converts an object to a better format for logging
 * @param object    variable to conver/*www  .j a v  a2s  .  com*/
 * @param depth     recursion depth
 * @return converted object, ready to put to JSON
 */
private Object convert(Object object, int depth) {
    // *** return simple types as is ***
    if (object == null || object instanceof String || object instanceof Number || object instanceof Boolean)
        return object;

    // *** other simple types ***

    if (object instanceof Character || object instanceof StringBuffer || object instanceof StringBuilder
            || object instanceof Currency || object instanceof Date || object instanceof Locale)
        return object.toString();

    if (object instanceof Calendar)
        return ((Calendar) object).getTime().toString();

    if (object instanceof SimpleDateFormat)
        return ((SimpleDateFormat) object).toPattern();

    // check recursion depth
    if (depth > this.depth)
        return "d>" + this.depth;

    // mark this object as processed so we don't convert it twice and it
    // also avoid recursion when objects refer to each other
    processed.add(object);

    // *** not so simple types, but we can foreach it ***

    if (object instanceof Map) {
        JSONObject jobject = new JSONObject();
        for (Object key : ((Map<Object, Object>) object).keySet()) {
            Object value = ((Map<Object, Object>) object).get(key);
            addValue(jobject, key.toString(), value, depth);
        }
        return jobject;
    }

    if (object instanceof Collection) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Collection<Object>) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    if (object instanceof Iterable) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Iterable<Object>) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    if (object instanceof Object[]) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Object[]) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    // *** object of unknown type ***

    JSONObject jobject = new JSONObject();

    Class<?> cls = object.getClass();
    jobject.put("___class_name", cls.getName()); // add the class name
    jobject.put("___toString()", object.toString()); // and to string representation

    if (!this.reflect)
        return jobject;

    // get all properties using reflection
    if (this.reflectfields) {
        try {
            for (Field field : cls.getDeclaredFields()) {
                Boolean access = field.isAccessible();
                field.setAccessible(true);

                int mod = field.getModifiers();
                String key = getKey(mod, field.getName());
                Object value;
                try {
                    value = field.get(object);
                } catch (Exception e) {
                    value = e.toString();
                }

                field.setAccessible(access);

                if (!this.reflectprivate && (Modifier.isPrivate(mod) || Modifier.isProtected(mod)))
                    continue;
                if (!this.reflectstatic && Modifier.isStatic(mod))
                    continue;

                addValue(jobject, key, value, depth);
            }
        } catch (SecurityException e) {
        }
    }

    // get all methods using reflection
    if (this.reflectmethods) {
        try {
            JSONObject methods = new JSONObject();
            for (Method method : cls.getDeclaredMethods()) {
                Boolean access = method.isAccessible();
                method.setAccessible(true);

                Class<?>[] params = method.getParameterTypes();
                StringBuilder parameters = new StringBuilder("");
                for (int i = 0, j = params.length; i < j; i++) {
                    parameters.append(params[i].getName());
                    if (i + 1 < j)
                        parameters.append(", ");
                }
                int mod = method.getModifiers();
                String key = getKey(mod, method.getName() + "(" + parameters.toString() + ")");
                String value = method.getReturnType().getName();

                method.setAccessible(access);

                if (!this.reflectprivate && (Modifier.isPrivate(mod) || Modifier.isProtected(mod)))
                    continue;
                if (!this.reflectstatic && Modifier.isStatic(mod))
                    continue;

                methods.put(key, value);
            }
            jobject.put("___methods", methods);
        } catch (SecurityException e) {
        }
    }

    return jobject;
}

From source file:org.castor.jaxb.reflection.ClassInfoBuilder.java

/**
 * Build the ClassInfo representation for a Class.
 * /*from   w  w  w  . j  a v a 2 s.  c  o  m*/
 * @param type
 *            the Class to introspect
 * @return ClassInfo build from the Class
 */
public ClassInfo buildClassInfo(final Class<?> type) {
    if (type == null) {
        String message = "Argument type must not be null.";
        LOG.warn(message);
        throw new IllegalArgumentException(message);
    }
    if (!isDescribeable(type)) {
        if (LOG.isDebugEnabled()) {
            String message = "Class: " + type + " cannot be described using this builder.";
            LOG.debug(message);
        }
        return null;
    }
    if (LOG.isInfoEnabled()) {
        LOG.info("Now starting to build ClassInfo for: " + type);
    }

    ClassInfo classInfo = createClassInfo(javaNaming.getClassName(type));
    JaxbClassNature jaxbClassNature = new JaxbClassNature(classInfo);

    jaxbClassNature.setType(type);
    jaxbClassNature.setSupertype(type.getSuperclass());
    jaxbClassNature.setInterfaces(type.getInterfaces());
    jaxbClassNature.setHasPublicEmptyConstructor(hasPublicEmptyConstructor(type));

    Annotation[] unprocessedClassAnnotations = this.classAnnotationProcessingService
            .processAnnotations(jaxbClassNature, type.getAnnotations());
    for (Field field : type.getDeclaredFields()) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Now evaluating field: " + field);
        }
        if (isDescribeable(type, field)) {
            buildFieldInfo(classInfo, field);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Ignoring field: " + field + " of type: " + type.getName()
                        + " it is not useable for mapping.");
            }
        }
    }
    for (Method method : type.getDeclaredMethods()) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Now evaluating method: " + method);
        }
        if (isDescribeable(type, method)) {
            buildFieldInfo(classInfo, method);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Ignoring method: " + method + " of type: " + type.getName()
                        + " it is not useable for mapping.");
            }
        }
    }
    PackageInfo pi = buildPackageInfo(type.getPackage());
    classInfo.setPackageInfo(pi);
    if (LOG.isInfoEnabled()) {
        LOG.info("ClassInfo for: " + type + " build is: " + classInfo);
    }
    return classInfo;
}

From source file:com.evolveum.midpoint.prism.parser.PrismBeanInspector.java

private List<String> getPropOrderUncached(Class<? extends Object> beanClass) {
    List<String> propOrder;

    // Superclass first!
    Class superclass = beanClass.getSuperclass();
    if (superclass.equals(Object.class) || superclass.getAnnotation(XmlType.class) == null) {
        propOrder = new ArrayList<>();
    } else {//from w w w  . ja  va 2 s.co m
        propOrder = new ArrayList<>(getPropOrder(superclass));
    }

    XmlType xmlType = beanClass.getAnnotation(XmlType.class);
    if (xmlType == null) {
        throw new IllegalArgumentException(
                "Cannot marshall " + beanClass + " it does not have @XmlType annotation");
    }

    String[] myPropOrder = xmlType.propOrder();
    if (myPropOrder != null) {
        for (String myProp : myPropOrder) {
            if (StringUtils.isNotBlank(myProp)) {
                // some properties starts with underscore..we don't want to serialize them with underscore, so remove it..
                if (myProp.startsWith("_")) {
                    myProp = myProp.replace("_", "");
                }
                propOrder.add(myProp);
            }
        }
    }

    Field[] fields = beanClass.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (field.isAnnotationPresent(XmlAttribute.class)) {
            propOrder.add(field.getName());
        }
    }

    Method[] methods = beanClass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (method.isAnnotationPresent(XmlAttribute.class)) {
            //            System.out.println("methodName: " + method.getName());
            String propname = getPropertyNameFromGetter(method.getName());
            //StringUtils.uncapitalize(StringUtils.removeStart("get", method.getName()))
            propOrder.add(propname);
        }
    }

    return propOrder;
}

From source file:adalid.core.Project.java

/**
 *
 * @param clazz//from  w  w  w  .j  av  a 2 s  .co  m
 */
public void attachAddAttributesMethods(Class<?> clazz) {
    logger.debug(signature("attachAddAttributesMethods", clazz));
    String name;
    boolean addAttributesMethod;
    int modifiers;
    Class<?> returnType;
    Class<?>[] parameterTypes;
    Method[] methods = clazz.getDeclaredMethods();
    List<Method> list = Arrays.asList(methods);
    Comparator<Method> comparator = new ByMethodSequence();
    ColUtils.sort(list, comparator);
    for (Method method : list) {
        name = method.getName();
        addAttributesMethod = method.isAnnotationPresent(AddAttributesMethod.class);
        modifiers = method.getModifiers();
        returnType = method.getReturnType();
        parameterTypes = method.getParameterTypes();
        if (addAttributesMethod && Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)
                && void.class.equals(returnType) && parameterTypes.length == 1
                && Artifact.class.isAssignableFrom(parameterTypes[0])) {
            logger.debug(signature(clazz.getSimpleName() + "." + name, parameterTypes[0]));
            _addAttributesMethods.add(method);
        }
    }
}

From source file:com.haulmont.chile.core.loader.ChileAnnotationsLoader.java

protected void initProperties(Class<?> clazz, MetaClassImpl metaClass,
        Collection<MetadataObjectInitTask> tasks) {
    if (!metaClass.getOwnProperties().isEmpty())
        return;/*w  ww .j ava 2 s  . c  om*/

    // load collection properties after non-collection in order to have all inverse properties loaded up
    ArrayList<Field> collectionProps = new ArrayList<>();
    for (Field field : clazz.getDeclaredFields()) {
        if (field.isSynthetic())
            continue;

        final String fieldName = field.getName();

        if (isMetaPropertyField(field)) {
            MetaPropertyImpl property = (MetaPropertyImpl) metaClass.getProperty(fieldName);
            if (property == null) {
                MetadataObjectInfo<MetaProperty> info;
                if (isCollection(field) || isMap(field)) {
                    collectionProps.add(field);
                } else {
                    info = loadProperty(metaClass, field);
                    tasks.addAll(info.getTasks());
                    MetaProperty metaProperty = info.getObject();
                    onPropertyLoaded(metaProperty, field);
                }
            } else {
                log.warn("Field " + clazz.getSimpleName() + "." + field.getName()
                        + " is not included in metadata because property " + property + " already exists");
            }
        }
    }

    for (Field f : collectionProps) {
        MetadataObjectInfo<MetaProperty> info = loadCollectionProperty(metaClass, f);
        tasks.addAll(info.getTasks());
        MetaProperty metaProperty = info.getObject();
        onPropertyLoaded(metaProperty, f);
    }

    for (Method method : clazz.getDeclaredMethods()) {
        if (method.isSynthetic())
            continue;

        String methodName = method.getName();
        if (!methodName.startsWith("get") || method.getReturnType() == void.class)
            continue;

        if (isMetaPropertyMethod(method)) {
            String name = StringUtils.uncapitalize(methodName.substring(3));

            MetaPropertyImpl property = (MetaPropertyImpl) metaClass.getProperty(name);
            if (property == null) {
                MetadataObjectInfo<MetaProperty> info;
                if (isCollection(method) || isMap(method)) {
                    throw new UnsupportedOperationException(
                            String.format("Method-based property %s.%s doesn't support collections and maps",
                                    clazz.getSimpleName(), method.getName()));
                } else if (method.getParameterCount() != 0) {
                    throw new UnsupportedOperationException(
                            String.format("Method-based property %s.%s doesn't support arguments",
                                    clazz.getSimpleName(), method.getName()));
                } else {
                    info = loadProperty(metaClass, method, name);
                    tasks.addAll(info.getTasks());
                }
                MetaProperty metaProperty = info.getObject();
                onPropertyLoaded(metaProperty, method);
            } else {
                log.warn("Method " + clazz.getSimpleName() + "." + method.getName()
                        + " is not included in metadata because property " + property + " already exists");
            }
        }
    }
}

From source file:jsondb.JsonDBTemplate.java

public void join(String sourceID, String sourceCollection, String destID, String destiCollection) {
    Object sourceObj = this.findById(sourceID, sourceCollection);
    Object destObj = this.findById(destID, destiCollection);

    Class sc = sourceObj.getClass();
    Class dc = destObj.getClass();

    String scgettermethod = null;
    String scsettermethod = null;
    String destCollection = null;
    String destField = null;//from   ww w . java 2  s.c  o  m
    String dcgettermethod = null;
    String dcsettermethod = null;

    Field[] fields = sc.getDeclaredFields();
    for (Field field : fields) {
        DBRef d = field.getDeclaredAnnotation(DBRef.class);
        if (d != null) {
            // destCollection = d.destcollection();
            destField = d.destfieldname();
            // sourcefield = field.getName();
            scgettermethod = "get" + field.getName();
            scsettermethod = "set" + field.getName();
            Method[] methods = sc.getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().equalsIgnoreCase(scsettermethod)) {
                    scsettermethod = method.getName();
                }
                if (method.getName().equalsIgnoreCase(scgettermethod)) {
                    scgettermethod = method.getName();
                }
            }
        }
    }
    try {
        Method s = sc.getDeclaredMethod(scgettermethod, (Class[]) null);
        String p = (String) s.invoke(sourceObj);

        Field df = dc.getDeclaredField(destField);
        dcgettermethod = "get" + df.getName();
        dcsettermethod = "set" + df.getName();
        Method[] methods = dc.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equalsIgnoreCase(dcsettermethod)) {
                dcsettermethod = method.getName();
            }
            if (method.getName().equalsIgnoreCase(dcgettermethod)) {
                dcgettermethod = method.getName();
            }
        }
        if (p == null) {
            String rs = UUID.randomUUID().toString();
            Method sm = sc.getDeclaredMethod(scsettermethod, rs.getClass());
            sm.invoke(sourceObj, rs);

            Method dm = dc.getDeclaredMethod(dcsettermethod, rs.getClass());
            dm.invoke(destObj, rs);
        } else {
            Method d = dc.getDeclaredMethod(dcsettermethod, p.getClass());
            d.invoke(destObj, p);
        }
        this.upsert(sourceObj);
        this.upsert(destObj);

    } catch (NoSuchMethodException ex) {
        Logger.error("NoSuchMethodExeption");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.error("SecurityException");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.error("IllegalAccessException");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
        Logger.error("IllegalArgumentException");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
        Logger.error("InvokationTargetException");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchFieldException ex) {
        Logger.error("Feld not found");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    }
    this.reloadCollection(destCollection);
    this.reloadCollection(sourceCollection);
}

From source file:RevEngAPI.java

/** Generate a .java file for the outline of the given class. */
public void doClass(Class c) throws IOException {
    className = c.getName();/*from w  w w. j  a v a 2  s . c om*/
    // pre-compute offset for stripping package name
    classNameOffset = className.lastIndexOf('.') + 1;

    // Inner class
    if (className.indexOf('$') != -1)
        return;

    // get name, as String, with . changed to /
    String slashName = className.replace('.', '/');
    String fileName = slashName + ".java";

    System.out.println(className + " --> " + fileName);

    String dirName = slashName.substring(0, slashName.lastIndexOf("/"));
    new File(dirName).mkdirs();

    // create the file.
    PrintWriter out = new PrintWriter(new FileWriter(fileName));

    out.println("// Generated by RevEngAPI for class " + className);

    // If in a package, say so.
    Package pkg;
    if ((pkg = c.getPackage()) != null) {
        out.println("package " + pkg.getName() + ';');
        out.println();
    }
    // print class header
    int cMods = c.getModifiers();
    printMods(cMods, out);
    out.print("class ");
    out.print(trim(c.getName()));
    out.print(' ');
    // XXX get superclass 
    out.println('{');

    // print constructors
    Constructor[] ctors = c.getDeclaredConstructors();
    for (int i = 0; i < ctors.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Constructors");
        }
        Constructor cons = ctors[i];
        int mods = cons.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(cons.getName()) + "(");
        Class[] classes = cons.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.print("\t}");
    }

    // print method names
    Method[] mems = c.getDeclaredMethods();
    for (int i = 0; i < mems.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Methods");
        }
        Method m = mems[i];
        if (m.getName().startsWith("access$"))
            continue;
        int mods = m.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(m.getReturnType());
        out.print(' ');
        out.print(trim(m.getName()) + "(");
        Class[] classes = m.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.println("\treturn " + defaultValue(m.getReturnType()) + ';');
        out.println("\t}");
    }

    // print fields
    Field[] flds = c.getDeclaredFields();
    for (int i = 0; i < flds.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Fields");
        }
        Field f = flds[i];
        int mods = f.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(f.getType().getName()));
        out.print(' ');
        out.print(f.getName());
        if (Modifier.isFinal(mods)) {
            try {
                out.print(" = " + f.get(null));
            } catch (IllegalAccessException ex) {
                out.print("; // " + ex.toString());
            }
        }
        out.println(';');
    }
    out.println("}");
    //out.flush();
    out.close();
}

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.//from w  ww . j av  a2  s .  com
 */
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:com.web.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./*from  w w  w .j a v a  2 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);
                    System.out.println(customClassLoader.geturlS());
                    new WebServer().addURL(new URL("file:/" + files[i].getAbsolutePath()), customClassLoader);
                    CopyOnWriteArrayList<String> jarList = new CopyOnWriteArrayList();
                    getUsersJars(new File(libDir), jarList);
                    for (String jarFilePath : jarList)
                        new WebServer().addURL(new URL("file:/" + jarFilePath.replace("\\", "/")),
                                customClassLoader);
                    System.out.println("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();
                }
                System.out.println(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("/", ".");
                System.out.println("classList:" + classwithpackage.replace("/", "."));
                try {
                    if (!classwithpackage.contains("$")) {
                        Class executorServiceClass = customClassLoader.loadClass(classwithpackage);
                        //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                        //System.out.println();
                        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());
                                        System.out.println(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());
                                    //System.out.println("method="+executorServiceAnnot.servicename());
                                    //System.out.println("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();
}