Example usage for java.lang.reflect Modifier isAbstract

List of usage examples for java.lang.reflect Modifier isAbstract

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isAbstract.

Prototype

public static boolean isAbstract(int mod) 

Source Link

Document

Return true if the integer argument includes the abstract modifier, false otherwise.

Usage

From source file:in.hatimi.nosh.support.CommandExecutor.java

private Method findMainMethod() {
    Method[] methods = cmdCls.getMethods();
    for (Method method : methods) {
        if (!method.getName().equals("execute")) {
            continue; //method name must be 'execute'
        }// ww  w.j a v a2 s  .  co m
        int mod = method.getModifiers();
        if (Modifier.isAbstract(mod)) {
            continue; //method cannot be abstract.
        }
        if (Modifier.isStatic(mod)) {
            continue; //method cannot be static.
        }
        if (Modifier.isSynchronized(mod)) {
            continue; //method cannot be synthetic.
        }
        if (!Modifier.isPublic(mod)) {
            continue; //method must be public.
        }
        if (method.getReturnType() != Void.TYPE) {
            continue; //method must not return a value.
        }
        Class<?>[] paramTypes = method.getParameterTypes();
        if (paramTypes.length > 1) {
            continue; //method can take at most one parameter.
        }
        if (paramTypes.length == 1 && !paramTypes[0].equals(String[].class)) {
            continue; //if single parameter, must be String[]
        }
        return method;
    }
    return null;
}

From source file:fr.exanpe.tapestry.tldgen.taglib.builder.StructureBuilder.java

/**
 * Builds the output taglib structure//from  w  w w  .  j a  v a 2 s.  c  o m
 * 
 * @param rootPackage the root package to look the components for
 * @param supportedPackages all sub packages to scan
 * @param urls the urls used to scan the packages
 * @return the structure containing the information on the taglib to generate
 * @throws MojoExecutionException if any unexpected error occurs
 */
public Taglib build(String rootPackage, String[] supportedPackages, URL[] urls) throws MojoExecutionException {
    Taglib taglib = new Taglib();

    log.debug("Creating taglib object model...");

    for (String subPackage : supportedPackages) {
        String pkgname = rootPackage + "." + subPackage;

        log.debug("Processing taglib for full package named : " + pkgname);

        Reflections reflections = new Reflections(new ConfigurationBuilder()
                .filterInputsBy(new FilterBuilder.Include(FilterBuilder.prefix(pkgname))).setUrls(urls)
                .setScanners(new TypesScanner()));

        Store store = reflections.getStore();

        // Return classes anaylised by TypeScanner
        Multimap<String, String> classes = store.getStoreMap().values().iterator().next();

        log.debug(String.format("%s classes to analyse for %s package...", classes.keySet().size(), pkgname));

        // Loop on found classes
        for (final String s : classes.keySet()) {
            Class<?> c;
            try {
                log.debug(String.format("Load class %s into classloader", s));
                c = Thread.currentThread().getContextClassLoader().loadClass(s);
            } catch (ClassNotFoundException e) {
                // should not happen as it has just been parsed by Reflection...
                log.error(e);
                throw new MojoExecutionException("Class loader internal error for class :" + s, e);
            }

            if (!c.isAnnotation() && !c.isAnonymousClass() && !c.isEnum() && !c.isInterface()
                    && !c.isLocalClass() && !c.isMemberClass() && !c.isSynthetic()
                    && !Modifier.isAbstract(c.getModifiers())) {
                log.debug("Processing Tag : " + c.getName());

                Tag tag = buildTagFromClass(rootPackage, c);
                taglib.getTags().add(tag);
            }
        }
    }

    log.debug("Taglib object model completed");
    return taglib;
}

From source file:lineage2.gameserver.scripts.Scripts.java

/**
 * Method load.//from   ww w  .j  a  v a 2s  . c o  m
 */
private void load() {
    _log.info("Scripts: Loading...");

    List<Class<?>> classes = new ArrayList<>();

    boolean result = false;

    File f = new File("../libs/lineage2-scripts.jar");
    if (f.exists()) {
        JarInputStream stream = null;
        try {
            stream = new JarInputStream(new FileInputStream(f));
            JarEntry entry = null;
            while ((entry = stream.getNextJarEntry()) != null) {
                if (entry.getName().contains(ClassUtils.INNER_CLASS_SEPARATOR)
                        || !entry.getName().endsWith(".class")) {
                    continue;
                }

                String name = entry.getName().replace(".class", "").replace("/", ".");

                Class<?> clazz = Class.forName(name);
                if (Modifier.isAbstract(clazz.getModifiers())) {
                    continue;
                }
                classes.add(clazz);
            }
            result = true;
        } catch (Exception e) {
            _log.error("Fail to load scripts.jar!", e);
            classes.clear();
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    if (!result) {
        result = load(classes, "");
    }

    if (!result) {
        _log.error("Scripts: Failed loading scripts!");
        Runtime.getRuntime().exit(0);
        return;
    }

    _log.info("Scripts: Loaded " + classes.size() + " classes.");

    Class<?> clazz;
    for (int i = 0; i < classes.size(); i++) {
        clazz = classes.get(i);
        _classes.put(clazz.getName(), clazz);
    }
}

From source file:org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactory.java

@Override
public void validate(Class<?> aspectClass) throws AopConfigException {
    // If the parent has the annotation and isn't abstract it's an error
    if (aspectClass.getSuperclass().getAnnotation(Aspect.class) != null
            && !Modifier.isAbstract(aspectClass.getSuperclass().getModifiers())) {
        throw new AopConfigException("[" + aspectClass.getName() + "] cannot extend concrete aspect ["
                + aspectClass.getSuperclass().getName() + "]");
    }// w ww  . j  a va 2  s . c  om

    AjType<?> ajType = AjTypeSystem.getAjType(aspectClass);
    if (!ajType.isAspect()) {
        throw new NotAnAtAspectException(aspectClass);
    }
    if (ajType.getPerClause().getKind() == PerClauseKind.PERCFLOW) {
        throw new AopConfigException(aspectClass.getName() + " uses percflow instantiation model: "
                + "This is not supported in Spring AOP.");
    }
    if (ajType.getPerClause().getKind() == PerClauseKind.PERCFLOWBELOW) {
        throw new AopConfigException(aspectClass.getName() + " uses percflowbelow instantiation model: "
                + "This is not supported in Spring AOP.");
    }
}

From source file:edu.northwestern.bioinformatics.studycalendar.xml.writers.ChangeableXmlSerializerFactoryTest.java

@SuppressWarnings({ "RawUseOfParameterizedType" })
public void testASerializerCanBeBuiltForEveryElementCorrespondingToAChangeable() throws Exception {
    List<String> errors = new ArrayList<String>();
    for (Class<? extends Changeable> aClass : domainReflections.getSubTypesOf(Changeable.class)) {
        if (!Modifier.isAbstract(aClass.getModifiers()) && !aClass.isAnonymousClass()) {
            XsdElement x = XsdElement.forCorrespondingClass(aClass);
            try {
                factory.createXmlSerializer(x.create());
            } catch (StudyCalendarError sce) {
                errors.add(String.format("Failure with %s: %s", x, sce.getMessage()));
            }/*from w  ww.java 2 s.  c  om*/
        }
    }
    if (!errors.isEmpty()) {
        fail(StringUtils.join(errors.iterator(), '\n'));
    }
}

From source file:au.com.addstar.cellblock.configuration.AutoConfig.java

private <T> List<T> newList(Class<? extends List<T>> listClass, Collection<T> data)
        throws InvalidConfigurationException {
    Validate.isTrue(!Modifier.isAbstract(listClass.getModifiers()),
            "You cannot use an abstract type for AutoConfiguration");

    Constructor<? extends List<T>> constructor;

    try {/*from www. j  a  v  a2 s  .  c  o m*/
        constructor = listClass.getConstructor(Collection.class);

        return constructor.newInstance(data);
    } catch (Exception e) {
        throw new InvalidConfigurationException(e);
    }
}

From source file:com.industrieit.ohr.OHRJavassister.java

public static Class ohr(Class cll) {
    try {// w w w. j ava 2s.  c  om
        //System.out.println("++++++++++ "+cll.getName());
        /*if (cll.getName().startsWith("ohr."))
        {
        throw new RuntimeException(cll.getName());
        }*/
        if (processed2.containsKey(cll)) {
            return processed2.get(cll);
        }

        HashSet<Long> handleOffsets = new HashSet<Long>();

        String cnam = cll.getName();
        if (!cnam.startsWith("ohr.")) {
            cnam = "ohr." + cll.getName();
            //cnam=cnam.substring(4);
        }

        Class cl = Class.forName(cnam.substring(4));

        int clnumber = incrementClsCounter();

        List<Integer> owned = new ArrayList<Integer>();

        //remove the old implementation if its around from another process
        String fname = "target/classes/" + cnam.replace(".", "/") + ".class";
        System.out.println("deleted" + fname + " " + (new File(fname).delete()));

        if (!Modifier.isAbstract(cl.getModifiers())) {
            throw new RuntimeException("not an abstract class " + cl.getName());
        }

        System.out.println("processing ohr " + cnam);

        CtClass bc = getDefault().getCtClass(cl.getName());
        CtClass cc = getDefault().makeClass(cnam, bc);

        StringBuilder initBuilder = new StringBuilder();
        initBuilder.append("public void internalInit() {\n");

        StringBuilder constructBuilder = new StringBuilder();
        constructBuilder.append("{");

        String intname = OHRBase.class.getName();
        System.out.println("intername is " + intname);

        CtClass ci = getDefault().getCtClass(intname);
        CtClass extern = getDefault().getCtClass(Externalizable.class.getName());

        //cc.addInterface(ci);
        cc.setInterfaces(new CtClass[] { ci, extern });
        cc.setSuperclass(bc);

        //add base implmenetation methods and properties
        setBaseMixinsPre(cc, false);

        //first long for id and other stuff
        long offset = 8;

        BeanInfo bi = Introspector.getBeanInfo(cl);
        PropertyDescriptor[] pds = bi.getPropertyDescriptors();

        for (int co = 0; co < propertyOrdering.length; co++) {
            Class cprop = propertyOrdering[co];

            for (int i = 0; i < pds.length; i++) {
                // Get property name
                String propName = pds[i].getName();

                if (propName.equals("class")) {
                    continue;
                }

                String typ = pds[i].getPropertyType().getName();
                Class type = pds[i].getPropertyType();
                //if (propName.startsWith("fath"))
                //PL.pl("[[[[["+type+" "+propName+" "+cprop);
                if (cprop == Object.class) {
                    //handle refs only
                    if (type.isPrimitive()) {
                        continue;
                    }
                    if (type == String.class) {
                        continue;
                    }
                    if (type == CharSequence.class) {
                        continue;
                    }
                    if (type == OHRLongArray.class) {
                        continue;
                    }
                    if (type == OHRIntArray.class) {
                        continue;
                    }
                    if (type == OHRShortArray.class) {
                        continue;
                    }
                    if (type == OHRByteArray.class) {
                        continue;
                    }
                    if (type == OHRBooleanArray.class) {
                        continue;
                    }
                    if (type == OHRDoubleArray.class) {
                        continue;
                    }
                    if (type == OHRFloatArray.class) {
                        continue;
                    }
                } else if (cprop != type) {
                    //PL.pl("skipping "+type+" "+cprop);
                    continue;
                }
                //PL.pl("[[[[[    " + type + " - " + propName + " - " + cprop);
                //System.out.println("--prop--" + propName);

                String rname = pds[i].getReadMethod().getName();
                String wname = null;
                if (pds[i].getWriteMethod() != null) {
                    wname = pds[i].getWriteMethod().getName();
                }

                boolean reifread = isMethodReifAnnotated(pds[i].getReadMethod());
                boolean reifwrite = isMethodReifAnnotated(pds[i].getWriteMethod());

                String wcons = getConsistencyAsString(pds[i].getWriteMethod());
                String rcons = getConsistencyAsString(pds[i].getReadMethod());

                System.out.println("TYPE " + pds[i].getPropertyType().getName() + " "
                        + pds[i].getPropertyType().getInterfaces());

                if (pds[i].getPropertyType() == String.class && isInlineString(pds[i])) {
                    //NOTE - only for inline strings - normal strings are handled as extrefs like any other object
                    System.out.println("ITS An inline string!!!!");

                    int length = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class).length();
                    boolean trim = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class)
                            .trimOverflow();
                    boolean ascii = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class).asciiOnly();

                    String wmeth = "public void " + wname + "(" + typ + " o) { ohwritestr" + wcons + "("
                            + offset + "l,o," + length + "," + trim + "," + ascii + "); }";
                    //add setter
                    CtMethod wmethod = CtNewMethod.make(wmeth, cc);

                    cc.addMethod(wmethod);

                    System.out.println(wmeth);
                    String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadstr" + rcons
                            + "(" + offset + "l," + ascii + "); }";
                    //add setter
                    CtMethod rmethod = CtNewMethod.make(rmeth, cc);
                    //rmethod.getMethodInfo().addAttribute(attr);
                    cc.addMethod(rmethod);
                    System.out.println(rmeth);

                    int bytesperchar = ascii ? 1 : 2;

                    //pad to 16 bits
                    int ll = 4 + length * bytesperchar;
                    if (ll % 2 != 0) {
                        ll++;
                    }
                    offset += ll; //lebgth marker as well as unicode 16 encoded characters
                } else if (pds[i].getPropertyType() == CharSequence.class && isInlineString(pds[i])) {
                    //NOTE - only for inline strings - normal strings are handled as extrefs like any other object
                    System.out.println("ITS An inline charsequence!!!!");

                    int length = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class).length();
                    boolean trim = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class)
                            .trimOverflow();
                    boolean ascii = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class).asciiOnly();
                    String wmeth = "public void " + wname + "(" + typ + " o) { ohwritestr" + wcons + "("
                            + offset + "l,o," + length + "," + trim + "," + ascii + "); }";
                    //add setter
                    CtMethod wmethod = CtNewMethod.make(wmeth, cc);

                    cc.addMethod(wmethod);

                    System.out.println(wmeth);
                    String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadcs" + rcons
                            + "(" + offset + "l," + ascii + "); }";
                    //add setter
                    CtMethod rmethod = CtNewMethod.make(rmeth, cc);
                    //rmethod.getMethodInfo().addAttribute(attr);
                    cc.addMethod(rmethod);
                    System.out.println(rmeth);

                    int bytesperchar = ascii ? 1 : 2;
                    //pad to 8 byte boundary!
                    int ll = (int) Math.ceil((4.0 + length * bytesperchar) / 8) * 8;
                    offset += ll; //lebgth marker as well as unicode 16 encoded characters
                } else if ((pds[i].getPropertyType() == OHRLongArray.class
                        || pds[i].getPropertyType() == OHRIntArray.class
                        || pds[i].getPropertyType() == OHRShortArray.class
                        || pds[i].getPropertyType() == OHRByteArray.class
                        || pds[i].getPropertyType() == OHRFloatArray.class
                        || pds[i].getPropertyType() == OHRDoubleArray.class
                        || pds[i].getPropertyType() == OHRBooleanArray.class)
                        && pds[i].getReadMethod().isAnnotationPresent(InlineArrayReify.class)) {

                    int bitsperitem = 0;
                    String cldef = null;
                    Class at = pds[i].getPropertyType();
                    boolean unchecked = pds[i].getReadMethod().isAnnotationPresent(UncheckedBoundsXXX.class);
                    if (at == OHRLongArray.class) {
                        bitsperitem = 8 * 8;
                        cldef = LongInlineOHRArray.class.getName();
                    } else if (at == OHRIntArray.class) {
                        bitsperitem = 4 * 8;
                        //cldef=IntInlineOHRArrayCop.class.getName();
                        if (unchecked) {
                            cldef = IntInlineOHRArrayUnchecked.class.getName();
                        } else {
                            cldef = IntInlineOHRArray.class.getName();
                        }
                    }
                    if (at == OHRDoubleArray.class) {
                        bitsperitem = 8 * 8;
                        cldef = DoubleInlineOHRArray.class.getName();
                    }
                    if (at == OHRFloatArray.class) {
                        bitsperitem = 4 * 8;
                        cldef = FloatInlineOHRArray.class.getName();
                    }
                    if (at == OHRShortArray.class) {
                        bitsperitem = 2 * 8;
                        cldef = ShortInlineOHRArray.class.getName();
                    }
                    if (at == OHRByteArray.class) {
                        bitsperitem = 1 * 8;
                        cldef = ByteInlineOHRArray.class.getName();
                    }
                    if (at == OHRBooleanArray.class) {
                        bitsperitem = 1;
                        cldef = BooleanInlineOHRArray.class.getName();
                    }
                    //NOTE - only for inline strings - normal strings are handled as extrefs like any other object
                    System.out.println("ITS An inline array!!!!");

                    int length = pds[i].getReadMethod().getAnnotation(InlineArrayReify.class).length();

                    long bytealloc = OHRInlineArrayHandler.getGenericArrayAllocationSize(bitsperitem, length);

                    //PL.pl("byte allocation for logn array length "+length+" "+bytealloc);

                    CtClass ctc = getDefault().getCtClass(cldef);

                    String varname = "var" + i;
                    CtField cf = new CtField(ctc, varname, cc);
                    cf.setModifiers(Modifier.PRIVATE);
                    cc.addField(cf);

                    //add data to constructor
                    initBuilder.append(
                            "com.industrieit.ohr.OHRInlineArrayHandler.initialiseInlineGenericArray(this.basePtr+"
                                    + offset + "l," + length + "l," + bitsperitem + ");\n");
                    constructBuilder.append(varname + "=new " + cldef + "(this," + offset + "l);\n");

                    //+ "//this.basePtr"+offset+"l);");

                    //String wmeth = "public void " + wname + "(" + typ + " o) { throw new java.lang.RuntimeException(\"not supported\"); }";
                    //add setter
                    //CtMethod wmethod = CtNewMethod.make(wmeth, cc);

                    //cc.addMethod(wmethod);

                    //System.out.println(wmeth);
                    String rmeth = "public " + typ + " " + rname + "() { return " + varname + "; }";
                    //add setter
                    CtMethod rmethod = CtNewMethod.make(rmeth, cc);
                    //rmethod.getMethodInfo().addAttribute(attr);
                    cc.addMethod(rmethod);
                    System.out.println("||||||||" + rmeth + "|||||||||");

                    offset += bytealloc;
                } else if (pds[i].getPropertyType().isPrimitive()) {
                    //PL.pl("ITS A PRIMITIVE!");
                    int vv = 0;
                    if (cprop == long.class) {
                        vv = 8;
                    }
                    if (cprop == double.class) {
                        vv = 8;
                    }
                    if (cprop == int.class) {
                        vv = 4;
                    }
                    if (cprop == float.class) {
                        vv = 4;
                    }
                    if (cprop == short.class) {
                        vv = 2;
                    }
                    if (cprop == byte.class) {
                        vv = 1;
                    }

                    System.out.println(
                            "for " + pds[i].getName() + " typ is " + pds[i].getPropertyType().getName());

                    String wmeth = "public void " + wname + "(" + typ + " o) { ohwrite" + wcons + "(" + offset
                            + "l,o); }";
                    //add setter

                    //ConstPool constpool = cc.getClassFile().getConstPool();

                    if (reifwrite) {
                        CtMethod wmethod = CtNewMethod.make(wmeth, cc);
                        cc.addMethod(wmethod);
                        System.out.println("&&&&&&&" + wmeth);
                    }

                    String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohread" + typ
                            + rcons + "(" + offset + "l); }";
                    //add setter

                    //rmethod.getMethodInfo().addAttribute(attr);
                    if (reifread) {
                        CtMethod rmethod = CtNewMethod.make(rmeth, cc);
                        cc.addMethod(rmethod);
                        System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&" + rmeth + vv);
                    }

                    offset += vv;
                } else {
                    System.out.println("ITS AN ASSUMED REIFY!!!");

                    if (pds[i].getWriteMethod().isAnnotationPresent(Owned.class)) {
                        owned.add(i);
                    }
                    //CtClass tc = getDefault().getCtClass(pds[i].getPropertyType().getName());
                    CtClass tc = getDefault().getCtClass(OHRBase.class.getName());
                    //String fnam="ohrt"+i;
                    //CtField f = new CtField(tc, fnam, cc);
                    //f.setModifiers(Modifier.PROTECTED);
                    //cc.addField(f);
                    //store by reify
                    //handleOffsets.add(offset);
                    String wmeth = "public void " + wname + "(" + typ + " o) { ohwritere" + wcons + "(" + offset
                            + "l,o); }";
                    //add setter
                    CtMethod wmethod = CtNewMethod.make(wmeth, cc);

                    if (reifwrite) {
                        cc.addMethod(wmethod);
                    }

                    System.out.println(wmeth);
                    //String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadre(" + offset + "l," + typ + ".class); }";
                    String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadre" + rcons
                            + "(" + offset + "l);  };";
                    //add setter
                    CtMethod rmethod = CtNewMethod.make(rmeth, cc);
                    //rmethod.getMethodInfo().addAttribute(attr);
                    if (reifread) {
                        cc.addMethod(rmethod);
                    }
                    System.out.println(rmeth);
                    handleOffsets.add(offset);
                    offset += 8;
                }

                /* if (!isReif(type)) {
                        
                PL.pl(""+pds[i].getName()+" is a non reified handle!!!!");
                //store by handle
                handleOffsets.add(offset);
                String wmeth = "public void " + wname + "(" + typ + " o) { ohwritehand(" + offset + "l,o); }";
                //add setter
                CtMethod wmethod = CtNewMethod.make(wmeth, cc);
                        
                if (reifwrite) {
                    cc.addMethod(wmethod);
                }
                        
                System.out.println(wmeth);
                String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadhand(" + offset + "l); }";
                //add setter
                        
                CtMethod rmethod = CtNewMethod.make(rmeth, cc);
                //rmethod.getMethodInfo().addAttribute(attr);
                if (reifread) {
                    cc.addMethod(rmethod);
                }
                System.out.println(rmeth);
                }*/
            }

            //PL.pl("offset is "+offset);

        }
        //offset+=8;
        //ok create the get handleoffsets method

        //print out total byts allocated
        //PL.pl("%%%%%%%%%% TOTAL BYTES = " + offset);

        StringBuilder sb = new StringBuilder();
        sb.append("public long[] handleOffsets() { ");
        sb.append("long a[] = new long[").append(handleOffsets.size()).append("];");
        int c = 0;
        for (long l : handleOffsets) {
            sb.append("a[").append(c).append("]=").append(l).append("l;");
            c++;
        }
        sb.append("return a; }");

        System.out.println(sb.toString());
        CtMethod om = CtNewMethod.make(sb.toString(), cc);
        cc.addMethod(om);

        String sizem = "public long gsize() { return " + (offset) + "l; }";
        //PL.pl(sizem);

        CtMethod sm = CtNewMethod.make(sizem, cc);
        cc.addMethod(sm);

        //add clsid
        CtMethod cmid = CtNewMethod.make("public int ohclassId() { return " + clnumber + "; }", cc);
        cc.addMethod(cmid);

        setBaseMixinsPost(cc, false, owned, pds, constructBuilder, initBuilder);

        cc.writeFile("target/classes");

        /*for (Method me : cc.toClass().getDeclaredMethods()) { //test print, ok
         //System.out.println(me.getName());
         }*/

        Class ppp = Class.forName(cnam);
        Field f = ppp.getDeclaredField("u");
        f.setAccessible(true);
        f.set(ppp.newInstance(), USafe.getUnsafe());
        //synchronized (mutex)
        //{
        processed2.put(cl, ppp);
        processed2.put(ppp, ppp);
        cls[clnumber] = ppp;
        return ppp;
        //}

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:objenome.util.bytecode.SgUtils.java

private static void checkModifiers(int type, int modifiers) {
    for (int modifier = ABSTRACT; modifier <= STRICTFP; modifier++) {
        if (Modifier.isPrivate(modifiers) && !MODIFIERS_MATRIX[PRIVATE][type]) {
            throwIllegalArgument(type, PRIVATE);
        }//from  w  w  w  . j ava 2s .  co  m
        if (Modifier.isProtected(modifiers) && !MODIFIERS_MATRIX[PROTECTED][type]) {
            throwIllegalArgument(type, PROTECTED);
        }
        if (Modifier.isPublic(modifiers) && !MODIFIERS_MATRIX[PUBLIC][type]) {
            throwIllegalArgument(type, PUBLIC);
        }
        if (Modifier.isStatic(modifiers) && !MODIFIERS_MATRIX[STATIC][type]) {
            throwIllegalArgument(type, STATIC);
        }
        if (Modifier.isAbstract(modifiers) && !MODIFIERS_MATRIX[ABSTRACT][type]) {
            throwIllegalArgument(type, ABSTRACT);
        }
        if (Modifier.isFinal(modifiers) && !MODIFIERS_MATRIX[FINAL][type]) {
            throwIllegalArgument(type, FINAL);
        }
        if (Modifier.isNative(modifiers) && !MODIFIERS_MATRIX[NATIVE][type]) {
            throwIllegalArgument(type, NATIVE);
        }
        if (Modifier.isSynchronized(modifiers) && !MODIFIERS_MATRIX[SYNCHRONIZED][type]) {
            throwIllegalArgument(type, SYNCHRONIZED);
        }
        if (Modifier.isTransient(modifiers) && !MODIFIERS_MATRIX[TRANSIENT][type]) {
            throwIllegalArgument(type, TRANSIENT);
        }
        if (Modifier.isVolatile(modifiers) && !MODIFIERS_MATRIX[VOLATILE][type]) {
            throwIllegalArgument(type, VOLATILE);
        }
        if (Modifier.isStrict(modifiers) && !MODIFIERS_MATRIX[STRICTFP][type]) {
            throwIllegalArgument(type, STRICTFP);
        }
    }
}

From source file:pl.otros.logview.api.BaseLoader.java

public <T> List<Class<T>> getInterfaceImplementations(Class<T> interfaceClass, File f)
        throws IOException, ClassNotFoundException {
    ArrayList<Class<T>> list = new ArrayList<>();
    List<String> classes = null;
    if (f.isDirectory()) {
        classes = getClassesFromDir(f);/*w  ww  .j a v a 2 s. co  m*/
    } else {
        classes = getClassesFromJar(f);
    }
    URL url = f.toURI().toURL();
    ClassLoader cl = new URLClassLoader(new URL[] { url }, this.getClass().getClassLoader());
    for (String klazz : classes) {
        try {
            Class<?> c = cl.loadClass(klazz);
            if (interfaceClass.isAssignableFrom(c) && !Modifier.isAbstract(c.getModifiers())) {
                list.add((Class<T>) c);
            }
        } catch (Throwable t) {
            LOGGER.warn(String.format("Error checking if class %s from file %s is implementing %s: %s", klazz,
                    f, interfaceClass.getName(), t.getMessage()));
        }
    }
    return list;

}

From source file:at.ac.tuwien.infosys.jcloudscale.classLoader.caching.fileCollectors.FileCollectorAbstract.java

/**
 * Collects the list of required files without content.
 * @param clazz the class that related files should be collected for. (joda style)
 * @return List of files that are required for specified class or 
 * null if none are required. //ww w.j a va2  s.co m
 */
protected List<ClassLoaderFile> collectRequiredFiles(Class<?> clazz) {
    FileDependency fileDependency = clazz.getAnnotation(FileDependency.class);

    if (fileDependency == null)
        return null;

    List<ClassLoaderFile> files = new ArrayList<ClassLoaderFile>();

    if (fileDependency.dependencyProvider().equals(IFileDependencyProvider.class)) {// we have static files
        //         ContentType contentType = fileDependency.accessType() == FileAccess.ReadOnly ? 
        //                                    ContentType.ROFILE : ContentType.RWFILE;
        ContentType contentType = ContentType.ROFILE;

        String[] fileNames = fileDependency.files();

        if (fileNames == null || fileNames.length == 0)
            return null;

        for (String filename : fileNames) {
            File file = RemoteClassLoaderUtils.getRelativePathFile(filename);
            if (!file.exists()) {
                log.severe("Class " + clazz.getName() + " set file " + filename
                        + " as required, but the file is missing at " + file.getAbsolutePath());
                continue;
            }

            files.add(new ClassLoaderFile(filename, file.lastModified(), file.length(), contentType));
        }
    } else {// we have dynamic file list, let's process it.
        Class<? extends IFileDependencyProvider> dependentFilesProviderClass = fileDependency
                .dependencyProvider();
        if (dependentFilesProviderClass == null)
            return null;

        //checking if we can create this class
        if (dependentFilesProviderClass.isInterface()
                || Modifier.isAbstract(dependentFilesProviderClass.getModifiers()))
            throw new JCloudScaleException("Class " + clazz.getName()
                    + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName()
                    + " as dependency provider. However, dependency provider class is either abstract or interface.");

        if (dependentFilesProviderClass.getEnclosingClass() != null
                && !Modifier.isStatic(dependentFilesProviderClass.getModifiers()))
            throw new JCloudScaleException("Class " + clazz.getName()
                    + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName()
                    + " as dependency provider. However, dependency provider class is internal and not static. The class has to be static in this case.");

        Constructor<? extends IFileDependencyProvider> constructor = null;
        try {
            constructor = dependentFilesProviderClass.getDeclaredConstructor();
        } catch (NoSuchMethodException ex) {
            throw new JCloudScaleException(ex, "Class " + clazz.getName()
                    + "is anotated with @FileDependency and has class " + dependentFilesProviderClass.getName()
                    + " as dependency provider. However, dependency provider class cannot be created as it has no parameterless constructor.");
        }

        try {
            if (!constructor.isAccessible())
                constructor.setAccessible(true);

            IFileDependencyProvider provider = constructor.newInstance();

            for (DependentFile dependentFile : provider.getDependentFiles()) {
                File file = RemoteClassLoaderUtils.getRelativePathFile(dependentFile.filePath);
                if (!file.exists()) {
                    log.severe("Class " + clazz.getName() + " set file " + dependentFile.filePath
                            + " as required, but the file is missing.");
                    continue;
                }

                //               ContentType contentType = dependentFile.accessType == FileAccess.ReadOnly ? 
                //                     ContentType.ROFILE : ContentType.RWFILE;
                ContentType contentType = ContentType.ROFILE;

                files.add(new ClassLoaderFile(file.getPath(), file.lastModified(), file.length(), contentType));
            }
        } catch (Exception ex) {
            log.severe("Dependent files provider " + dependentFilesProviderClass.getName() + " for class "
                    + clazz.getName() + " threw exception during execution:" + ex.toString());
            throw new JCloudScaleException(ex,
                    "Dependent files provider " + dependentFilesProviderClass.getName() + " for class "
                            + clazz.getName() + " threw exception during execution.");
        }
    }

    return files;
}