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:com.hurence.logisland.documentation.DocGenerator.java

/**
 * Generates documentation into the work/docs dir specified from a specified set of class
 *///from   w  w  w. java2 s  .c  o m
public static void generate(final File docsDirectory, final String writerType) {

    Map<String, Class> extensionClasses = new TreeMap<>();

    PluginLoader.getRegistry().forEach((className, classLoader) -> {
        try {
            extensionClasses.put(className, classLoader.loadClass(className));
        } catch (Exception e) {
            logger.error("Unable to load class " + className, e);

        }
    });

    ClassFinder.findClasses(clazz -> {
        if (!clazz.startsWith("BOOT-INF") && clazz.contains("logisland") && !clazz.contains("Mock")
                && !clazz.contains("shade")) {
            try {
                Class c = Class.forName(clazz);
                if (c.isAssignableFrom(ConfigurableComponent.class) && !Modifier.isAbstract(c.getModifiers())) {
                    extensionClasses.put(c.getSimpleName(), c);
                }
            } catch (Throwable e) {
                logger.error("Unable to load class " + clazz + " : " + e.getMessage());
            }
        }

        return true; // return false if you don't want to see any more classes
    });

    docsDirectory.mkdirs();

    // write headers for single rst file
    if (writerType.equals("rst"))

    {
        final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType);
        if (baseDocumenationFile.exists())
            baseDocumenationFile.delete();

        try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) {
            writer.println("Components");
            writer.println("==========");
            writer.println(
                    "You'll find here the list of all usable Processors, Engines, Services and other components "
                            + "that can be usable out of the box in your analytics streams");
            writer.println();
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage());
        }
    } else if (writerType.equals("json"))

    {
        final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType);
        if (baseDocumenationFile.exists())
            baseDocumenationFile.delete();

        try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) {
            writer.println("[");
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage());
        }
    }

    Class[] sortedExtensionsClasses = new Class[extensionClasses.size()];
    extensionClasses.values().

            toArray(sortedExtensionsClasses);

    Arrays.sort(sortedExtensionsClasses, new Comparator<Class>()

    {
        @Override
        public int compare(Class s1, Class s2) {
            // the +1 is to avoid including the '.' in the extension and to avoid exceptions
            // EDIT:
            // We first need to make sure that either both files or neither file
            // has an extension (otherwise we'll end up comparing the extension of one
            // to the start of the other, or else throwing an exception)
            final int s1Dot = s1.getName().lastIndexOf('.');
            final int s2Dot = s2.getName().lastIndexOf('.');
            if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither
                String s1Name = s1.getName().substring(s1Dot + 1);
                String s2Name = s2.getName().substring(s2Dot + 1);
                return s1Name.compareTo(s2Name);
            } else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first
                return -1;
            } else { // only s1 has an extension, so s1 goes second
                return 1;
            }
        }
    });

    logger.info("Generating " + writerType + " documentation for " + Arrays.stream(sortedExtensionsClasses).

            count() + " components in: " + docsDirectory);

    Arrays.stream(sortedExtensionsClasses).

            forEach(extensionClass ->

    {
                final Class componentClass = extensionClass.asSubclass(ConfigurableComponent.class);
                try {
                    document(docsDirectory, componentClass, writerType);

                } catch (Exception e) {
                    logger.error("Unexpected error for " + extensionClass, e);
                }

            });

    if (writerType.equals("json"))

    {
        final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType);
        try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) {
            writer.println("]");
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage());
        }
    }

}

From source file:com.judoscript.jamaica.parser.JamaicaDumpVisitor.java

public Object visit(ASTMethodDeclaration node, Object data) throws Exception {
    boolean abs = Modifier.isAbstract(node.getAccessFlags());
    out.print("\n  ");
    printAccessFlags(node.getAccessFlags());
    out.print(node.getType());/*  ww w.  j a v a 2  s .c o  m*/
    out.print(' ');
    out.print(node.getName());
    out.print('(');
    ((ASTFormalParameters) node.jjtGetChild(0)).jjtAccept(this, data);
    out.println(')');
    printStringArray("    throws ", node.getExceptions(), !abs);
    if (abs) {
        out.println(";\n");
    } else {
        int bodyLen = node.jjtGetNumChildren();
        out.println("  {");
        int state = 0;
        for (int i = 1; i < bodyLen; ++i) {
            Node n = node.jjtGetChild(i);
            switch (state) {
            case 0:
                if (n instanceof ASTVariableDeclarator)
                    state = 1;
                else if (n instanceof ASTVariableDeclarator)
                    state = 2;
                break;
            case 1:
                if (!(n instanceof ASTVariableDeclarator)) {
                    state = 2;
                    out.println();
                }
            case 2:
                if (n instanceof ASTCatchClause) {
                    state = 3;
                    out.println();
                }
                break;
            }
            n.jjtAccept(this, data);
        }
        out.println("  }");
    }
    return null;
}

From source file:com.github.geequery.codegen.ast.JavaMethod.java

public boolean isAbstract() {
    return Modifier.isAbstract(modifier);
}

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

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

    Constructor<? extends Set<T>> constructor;

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

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

From source file:com.comtop.cap.bm.metadata.common.dwr.CapMapConverter.java

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object convertInbound(Class<?> paramType, InboundVariable data) throws ConversionException {
    if (data.isNull()) {
        return null;
    }// www .j  a  v  a 2s  . c  o  m

    String value = data.getValue();

    // If the text is null then the whole bean is null
    if (value.trim().equals(ProtocolConstants.INBOUND_NULL)) {
        return null;
    }

    if (!value.startsWith(ProtocolConstants.INBOUND_MAP_START)
            || !value.endsWith(ProtocolConstants.INBOUND_MAP_END)) {
        log.warn("Expected object while converting data for " + paramType.getName() + " in "
                + data.getContext().getCurrentProperty() + ". Passed: " + value);
        throw new ConversionException(paramType, "Data conversion error. See logs for more details.");
    }

    value = value.substring(1, value.length() - 1);

    try {
        // Maybe we ought to check that the paramType isn't expecting a more
        // distinct type of Map and attempt to create that?
        Map<Object, Object> map;

        // If paramType is concrete then just use whatever we've got.
        if (!paramType.isInterface() && !Modifier.isAbstract(paramType.getModifiers())) {
            // If there is a problem creating the type then we have no way
            // of completing this - they asked for a specific type and we
            // can't create that type. I don't know of a way of finding
            // subclasses that might be instaniable so we accept failure.
            map = (Map<Object, Object>) paramType.newInstance();
        } else {
            map = new HashMap<Object, Object>();
        }

        // Get the extra type info
        Property parent = data.getContext().getCurrentProperty();

        Property keyProp = parent.createChild(0);
        keyProp = converterManager.checkOverride(keyProp);

        Property valProp = parent.createChild(1);
        valProp = converterManager.checkOverride(valProp);

        // We should put the new object into the working map in case it
        // is referenced later nested down in the conversion process.
        data.getContext().addConverted(data, paramType, map);
        InboundContext incx = data.getContext();

        // Loop through the property declarations
        StringTokenizer st = new StringTokenizer(value, ",");
        int size = st.countTokens();
        for (int i = 0; i < size; i++) {
            String token = st.nextToken();
            if (token.trim().length() == 0) {
                continue;
            }

            int colonpos = token.indexOf(ProtocolConstants.INBOUND_MAP_ENTRY);
            if (colonpos == -1) {
                throw new ConversionException(paramType, "Missing " + ProtocolConstants.INBOUND_MAP_ENTRY
                        + " in object description: {1}" + token);
            }

            String valStr = token.substring(colonpos + 1).trim();
            String[] splitIv = ConvertUtil.splitInbound(valStr);
            String splitIvValue = splitIv[ConvertUtil.INBOUND_INDEX_VALUE];
            String splitIvType = splitIv[ConvertUtil.INBOUND_INDEX_TYPE];
            InboundVariable valIv = new InboundVariable(incx, null, splitIvType, splitIvValue);
            valIv.dereference();

            Class valTyClass = String.class;

            if ("boolean".equals(valIv.getType())) {
                valTyClass = Boolean.class;
            } else if ("array".equals(valIv.getType())) {
                valTyClass = ArrayList.class;
            } else if ("number".equals(valIv.getType())) {
                String strValue = valIv.getValue();
                if (strValue.indexOf(".") != -1) {
                    valTyClass = Double.class;
                } else {
                    valTyClass = Integer.class;
                }
            } else if ("date".equals(valIv.getType())) {
                valTyClass = Date.class;
            }

            Object val = converterManager.convertInbound(valTyClass, valIv, valProp);
            String keyStr = token.substring(0, colonpos).trim();
            map.put(keyStr, val);
        }

        return map;
    } catch (ConversionException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ConversionException(paramType, ex);
    }
}

From source file:com.basistech.rosette.apimodel.ModelTest.java

@Test
public void packageTest() throws ClassNotFoundException, IllegalAccessException, InvocationTargetException,
        InstantiationException, IOException {
    Reflections reflections = new Reflections(this.getClass().getPackage().getName(),
            new SubTypesScanner(false));

    Set<Class<?>> allClasses = reflections.getSubTypesOf(Object.class);
    for (Object clazz : allClasses) {
        String className = ((Class) clazz).getName();
        if (className.contains("com.basistech.rosette.dm")) {
            continue;
        }//from  w ww  .ja v a  2s  . co  m
        if (className.contains("Adm")) {
            continue; // these are too hard.
        }
        if (className.endsWith(".ModelTest")) {
            continue;
        }
        if (className.endsWith(".NonNullTest")) {
            continue;
        }
        if (className.endsWith("Mixin")) {
            continue;
        }

        if (className.endsWith("Builder")) {
            continue;
        }
        if (className.contains(".batch.")) {
            // there are polymorphism issues in here for this test strategy.
            continue;
        }

        Class c = Class.forName(className);
        if (Modifier.isAbstract(c.getModifiers())) {
            continue;
        }
        Constructor[] ctors = c.getDeclaredConstructors();
        if (ctors.length == 0) {
            continue;
        }
        Constructor ctor = ctors[0];
        if (ctor.getParameterTypes().length == 0) {
            continue; // don't want empty constructor
        }
        Object o1;
        if (Modifier.isPublic(ctor.getModifiers())) {

            boolean oldInputStreams = inputStreams;
            try {
                if (className.endsWith("ConstantsResponse")) {
                    inputStreams = false; // special case due to Object in there.
                }
                o1 = createObject(ctor);
            } finally {
                inputStreams = oldInputStreams;
            }

            // serialize
            // for a request, we might need a view
            ObjectWriter writer = mapper.writerWithView(Object.class);
            if (o1 instanceof DocumentRequest) {
                DocumentRequest r = (DocumentRequest) o1;
                if (r.getRawContent() instanceof String) {
                    writer = mapper.writerWithView(DocumentRequestMixin.Views.Content.class);
                }
            }
            String json = writer.writeValueAsString(o1);
            // deserialize
            Object o2 = mapper.readValue(json, (Class<? extends Object>) clazz);
            // verify
            assertEquals(o1, o2);
        }
    }
}

From source file:com.alta189.bukkit.script.event.EventScanner.java

public static void scanPlugin(Plugin plugin) {
    if (pluginEvents.containsKey(plugin)) {
        return;/*from w ww  .  j  a v a 2s  .com*/
    }
    BScript.getInstance().debug("Scanning plugin " + plugin.getName());
    if (plugin instanceof JavaPlugin) {
        ClassLoader loader = ReflectionUtil.getFieldValue(JavaPlugin.class, plugin, "classLoader");
        Reflections reflections = new Reflections(new ConfigurationBuilder()
                .filterInputsBy(new FilterBuilder().exclude(FilterBuilder.prefix("org.bukkit")))
                .setUrls(ClasspathHelper.forClassLoader(loader)));

        Set<Class<? extends Event>> classes = reflections.getSubTypesOf(Event.class);

        BScript.getInstance().info("Found " + classes.size() + " classes extending "
                + Event.class.getCanonicalName() + " in " + plugin.getName());
        for (Class<? extends Event> clazz : classes) {
            if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
                continue;
            }
            BScript.getInstance().debug(clazz.getCanonicalName());

            String className = clazz.getCanonicalName();
            if (className == null) {
                className = clazz.getName();
            }
            BScript.getInstance().debug(className);
            events.put(className, clazz);
            String simpleName = clazz.getSimpleName();
            if (simpleNameEvents.get(simpleName) != null) {
                simpleNameEvents.remove(simpleName);
            } else {
                simpleNameEvents.put(simpleName, clazz);
            }
        }
        if (classes.size() > 0) {
            pluginEvents.put(plugin, classes);
        }
    } else {
        BScript.getInstance().debug("Plugin is not JavaPlugin " + plugin.getName());
    }
}

From source file:org.topazproject.otm.mapping.java.ClassBinder.java

/**
 * Creates a new ClassBinder object./*from   w w  w.j a v  a 2 s.  c  o m*/
 *
 * @param clazz the java class to bind this entity to
 * @param suppressAlias to dis-allow registration of the class name as an alias. 
 *                      This allows binding the same class to multiple entities.
 */
public ClassBinder(Class<T> clazz, boolean suppressAlias) {
    this.clazz = clazz;
    this.suppressAlias = suppressAlias;

    int mod = clazz.getModifiers();
    instantiable = !Modifier.isAbstract(mod) && !Modifier.isInterface(mod) && Modifier.isPublic(mod);
}

From source file:com.evolveum.midpoint.prism.PrismContainer.java

public PrismContainer(QName name, Class<C> compileTimeClass) {
    super(name);//from  ww w  . j a  va 2  s. c  o  m
    if (Modifier.isAbstract(compileTimeClass.getModifiers())) {
        throw new IllegalArgumentException("Can't use class '" + compileTimeClass.getSimpleName()
                + "' as compile-time class for " + name + "; the class is abstract.");
    }
    this.compileTimeClass = compileTimeClass;
}

From source file:com.intelligentsia.dowsers.entity.serializer.EntityMapper.java

/**
 * Method that can be used to parse JSON to specified Java value, using
 * reader provided./*ww  w  .j  av a  2 s . c o  m*/
 * 
 * @param reader
 * @param valueType
 * @return
 * @throws DowsersException
 */
@SuppressWarnings("unchecked")
public <T> T readValue(final Reader reader, final Class<T> valueType) throws DowsersException {
    if (valueType.isInterface() || Modifier.isAbstract(valueType.getModifiers())) {
        try {
            final EntityProxy entityProxy = mapper.readValue(reader, EntityProxy.class);
            return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                    new Class[] { valueType, EntityProxyHandler.class }, entityProxy);
        } catch (final Throwable e) {
            throw new DowsersException(e);
        }
    }
    try {
        return mapper.readValue(reader, valueType);
    } catch (final Throwable e) {
        throw new DowsersException(e);
    }
}