Example usage for java.lang.reflect Method isSynthetic

List of usage examples for java.lang.reflect Method isSynthetic

Introduction

In this page you can find the example usage for java.lang.reflect Method isSynthetic.

Prototype

@Override
public boolean isSynthetic() 

Source Link

Usage

From source file:org.grails.datastore.mapping.proxy.JavassistProxyFactory.java

protected Class getProxyClass(Class type) {

    Class proxyClass = PROXY_FACTORIES.get(type);
    if (proxyClass == null) {
        javassist.util.proxy.ProxyFactory pf = new ProxyFactory();
        pf.setSuperclass(type);/* w w w .  j  av  a  2s .  c o m*/
        pf.setInterfaces(new Class[] { EntityProxy.class });
        pf.setFilter(new MethodFilter() {
            public boolean isHandled(Method method) {
                final String methodName = method.getName();
                if (methodName.indexOf("super$") > -1) {
                    return false;
                }
                if (method.getParameterTypes().length == 0 && (methodName.equals("finalize"))) {
                    return false;
                }
                if (EXCLUDES.contains(methodName) || method.isSynthetic() || method.isBridge()) {
                    return false;
                }
                return true;
            }
        });
        proxyClass = pf.createClass();
        PROXY_FACTORIES.put(type, proxyClass);
    }
    return proxyClass;
}

From source file:com.github.venkateshamurthy.designpatterns.builders.FluentBuilders.java

/**
 * Gets a list of writable methods / mutator methods. <br>
 * //from  www. j  a  v  a  2  s . c  o m
 * @param thisPojoClass
 *            for which mutator methods must be found
 * @return List of {@link CtMethod}
 * @throws NotFoundException
 *             when thisPojoClass is not found
 */
private Set<CtMethod> getWritableMethods(final Class<?> thisPojoClass) throws NotFoundException {
    final CtClass ctClass = ctPool.get(thisPojoClass.getName());
    final Set<CtMethod> ctMethodSet = new LinkedHashSet<>(); // Gets
                                                             // collected
    final Set<Class<?>> propTypes = getPropertyClassTypes(thisPojoClass, ctClass, ctMethodSet);

    for (Method method : thisPojoClass.getDeclaredMethods()) {
        if (method.isSynthetic()) {
            LOGGER.warning(method.getName() + " is synthetically added, so ignoring");
            continue;
        }
        final CtMethod ctMethod = ctClass.getDeclaredMethod(method.getName());
        if (Modifier.isPublic(method.getModifiers()) && setMethodNamePattern.matcher(method.getName()).matches()
                && !ctMethodSet.contains(ctMethod)) {
            // Make sure the types u get from method is really is of a field
            // type
            boolean isAdded = /*
                               * propTypes.containsAll(Arrays.asList(method.
                               * getParameterTypes())) &&
                               */ctMethodSet.add(ctMethod);
            if (!isAdded) {
                LOGGER.warning(method.getName() + " is not added");
            }
        }
    }
    return ctMethodSet;
}

From source file:com.github.venkateshamurthy.designpatterns.builders.FluentBuilders.java

private Set<Method> getWritableNormalMethods(final Class<?> thisPojoClass) throws NotFoundException {
    final CtClass ctClass = ctPool.get(thisPojoClass.getName());
    final Set<CtMethod> ctMethodSet = new LinkedHashSet<>(); // Gets
                                                             // collected
    final Set<Method> methodSet = new LinkedHashSet<>(); // Gets collected

    final Set<Class<?>> propTypes = getPropertyClassTypes(thisPojoClass, ctClass, ctMethodSet);

    for (Method method : thisPojoClass.getDeclaredMethods()) {
        if (method.isSynthetic()) {
            LOGGER.warning(method.getName() + " is synthetically added, so ignoring");
            continue;
        }/*w ww  .  j a va 2  s. c  o m*/
        if (Modifier.isPublic(method.getModifiers())
                && setMethodNamePattern.matcher(method.getName()).matches()) {
            methodSet.add(method);
        }
        final CtMethod ctMethod = ctClass.getDeclaredMethod(method.getName());
        if (Modifier.isPublic(method.getModifiers()) && setMethodNamePattern.matcher(method.getName()).matches()
                && !ctMethodSet.contains(ctMethod)) {

            // Make sure the types u get from method is really is of a field
            // type
            boolean isAdded = propTypes.containsAll(Arrays.asList(method.getParameterTypes()))
                    && ctMethodSet.add(ctMethod);
            if (!isAdded) {
                LOGGER.warning(method.getName() + " is not added");
            }
        }
    }
    return methodSet;
}

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

/**
 * Checks if the Method is describeable.
 * //  w  w  w  . ja va2  s  . c o m
 * @param type
 *            the Class of the Method
 * @param method
 *            the Method to check
 * @return true if the method is describeable
 */
private boolean isDescribeable(final Class<?> type, final Method method) {
    boolean isDescribeable = true;
    Class<?> declaringClass = method.getDeclaringClass();
    if ((declaringClass != null) && !type.equals(declaringClass) && (!declaringClass.isInterface())) {
        isDescribeable = false;
    }
    if (method.isSynthetic()) {
        isDescribeable &= false;
    }
    if (Modifier.isStatic(method.getModifiers())) {
        isDescribeable &= false;
    }
    if (Modifier.isTransient(method.getModifiers())) {
        isDescribeable &= false;
    }
    if (!(javaNaming.isAddMethod(method) || javaNaming.isCreateMethod(method) || javaNaming.isGetMethod(method)
            || javaNaming.isIsMethod(method) || javaNaming.isSetMethod(method))) {
        isDescribeable = false;
    }
    return isDescribeable;
}

From source file:jp.go.nict.langrid.servicecontainer.handler.jsonrpc.servlet.JsonRpcServlet.java

/**
 * //  w w  w .jav  a 2s. co m
 * 
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServiceContext sc = new ServletConfigServiceContext(getServletConfig());
    HttpServletRequestParameterContext param = new HttpServletRequestParameterContext(req);
    if (param.getValue("sample") == null && param.getValue("method") != null && getMethodEnabled) {
        doProcess(req, resp);
        return;
    }
    ServiceLoader loader = new ServiceLoader(sc, defaultLoaders);
    String sample = param.getValue("sample");
    if (sample != null) {
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter os = resp.getWriter();
        String serviceName = getServiceName(req);
        String method = req.getParameter("method");
        os.println("request:");
        printSampleRequest(loader, serviceName, method, os);
        os.println("");
        os.println("");
        os.println("response:");
        printSampleResponse(loader, serviceName, method, os);
        os.flush();
        return;
    }
    String uri = req.getRequestURI();
    String cp = getServletContext().getContextPath();
    int idx = uri.indexOf(cp);
    if (idx == -1) {
        super.doGet(req, resp);
        return;
    }
    int sidx = uri.indexOf('/', idx + cp.length() + 1);
    if (sidx != -1) {
        resp.sendRedirect(uri.substring(idx, sidx));
        return;
    }

    resp.setContentType("text/html");
    resp.setCharacterEncoding("UTF-8");
    PrintWriter w = resp.getWriter();
    w.println("<html><head>");
    w.println(css);
    w.println(js);
    w.println("</head><body>");
    w.println("<h2>And now... Some JsonRpc Services</h2>");
    w.println("<ul>");
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Set<String> names = new TreeSet<String>();
    try {
        for (String s : loader.listServiceNames()) {
            names.add(s);
        }
        int id = 0;
        for (String s : names) {
            w.print("<li><b>" + s);
            ServiceFactory f = loader.loadServiceFactory(cl, s);
            if (f == null) {
                w.println("<font color=\"red\">(Failed to load service factory(null))</font></b></li>");
                continue;
            }
            Object service = f.getService();
            if (service instanceof StreamingNotifier) {
                w.print("(Streaming ready!)");
            }
            String sdesc = RpcAnnotationUtil.getServiceDescriptions(Service.class, "en");
            if (sdesc != null && sdesc.length() > 0) {
                w.print(" - " + StringEscapeUtils.escapeHtml(sdesc));
            }
            w.print("</b><ul>");
            w.print("<li>interfaces<ul>");
            try {
                Set<Class<?>> visited = new HashSet<Class<?>>();
                for (Class<?> intf : f.getInterfaces()) {
                    if (visited.contains(intf))
                        continue;
                    visited.add(intf);
                    if (StreamingNotifier.class.isAssignableFrom(intf))
                        continue;
                    w.print("<li>" + prettyName(intf));
                    String desc = RpcAnnotationUtil.getServiceDescriptions(intf, "en");
                    if (desc != null && desc.length() > 0) {
                        w.print(" - " + StringEscapeUtils.escapeHtml(desc));
                    }
                    w.print("<ul>");
                    try {
                        Set<Method> methods = new TreeSet<Method>(new Comparator<Method>() {
                            public int compare(Method o1, Method o2) {
                                int r = o1.getName().compareTo(o2.getName());
                                if (r != 0)
                                    return r;
                                return o1.getParameterTypes().length - o2.getParameterTypes().length;
                            }
                        });
                        methods.addAll(Arrays.asList(intf.getMethods()));
                        for (Method m : methods) {
                            if (m.isSynthetic())
                                continue;
                            if ((m.getModifiers() & Modifier.PUBLIC) == 0)
                                continue;
                            printMethod(s, m, getImplementedMethod(service, m), id++, w);
                        }
                    } finally {
                        w.println("</ul></li>");
                    }
                }
            } catch (SecurityException e) {
            } finally {
                w.println("</ul></li>");
            }
            w.print("<li>implementation<ul>");
            if (service != null) {
                w.println("<li>" + prettyName(service.getClass()) + "</li>");
                if (service instanceof AbstractCompositeService) {
                    boolean first = true;
                    for (Pair<Invocation, Class<?>> v : ((AbstractCompositeService) service).invocations()) {
                        if (first) {
                            w.println("<li>invocations<ul>");
                            first = false;
                        }
                        w.println(
                                "<li><b>" + v.getFirst().name() + (v.getFirst().required() ? "(required)" : "")
                                        + "</b>: " + prettyName(v.getSecond()) + "</li>");
                    }
                    if (!first) {
                        w.println("</ul></li>");
                    }
                }
            } else {
                w.println("<li><font color=\"red\"><b>failed to load implementation class.</b></font></li>");
            }
            w.println("</ul></li>");
            w.println("</ul></li>");
            w.println("<br/>");
        }
    } catch (IOException e) {
        w.println("<pre><font color=\"red\">");
        e.printStackTrace(w);
        w.println("</font></pre>");
    }
    w.println("</ul>");
    w.println("</body></html>");
}

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;//from ww  w .  j  av a2 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:hu.bme.mit.sette.common.tasks.TestSuiteRunner.java

private void analyzeOne(Snippet snippet, File[] binaryDirectories) throws Exception {
    String snippetClassName = snippet.getContainer().getJavaClass().getName();
    String snippetMethodName = snippet.getMethod().getName();
    String testClassName = snippet.getContainer().getJavaClass().getName() + "_" + snippet.getMethod().getName()
            + "_Tests";

    logger.debug("Snippet: {}#{}()", snippetClassName, snippetMethodName);
    logger.debug("Tests: {}", testClassName);

    // create JaCoCo runtime and instrumenter
    IRuntime runtime = new LoggerRuntime();
    Instrumenter instrumenter = new Instrumenter(runtime);

    // start runtime
    RuntimeData data = new RuntimeData();
    runtime.startup(data);//  w w  w . java  2 s. c o  m

    // create class loader

    JaCoCoClassLoader classLoader = new JaCoCoClassLoader(binaryDirectories, instrumenter,
            getSnippetProject().getClassLoader());

    // load test class
    // snippet class and other dependencies will be loaded and instrumented
    // on the fly
    Class<?> testClass = classLoader.loadClass(testClassName);

    TestCase testClassInstance = (TestCase) testClass.newInstance();

    // invoke test methods
    // TODO separate collect and invoke
    for (Method m : testClass.getDeclaredMethods()) {
        if (m.isSynthetic()) {
            // skip synthetic method
            continue;
        }

        if (m.getName().startsWith("test")) {
            logger.trace("Invoking: " + m.getName());
            try {
                m.invoke(testClassInstance);
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();

                if (cause instanceof NullPointerException || cause instanceof ArrayIndexOutOfBoundsException
                        || cause instanceof AssertionFailedError) {
                    logger.warn(cause.getClass().getName() + ": " + m.getDeclaringClass().getName() + "."
                            + m.getName());
                } else {
                    logger.error("Exception: " + m.getDeclaringClass().getName() + "." + m.getName());
                }
                logger.debug(e.getMessage(), e);
            }
        } else {
            logger.warn("Not test method: {}", m.getName());
        }
    }

    // collect data
    ExecutionDataStore executionData = new ExecutionDataStore();
    SessionInfoStore sessionInfos = new SessionInfoStore();
    data.collect(executionData, sessionInfos, false);
    runtime.shutdown();

    // get classes to analyse
    // store string to avoid the mess up between the different class loaders
    Set<String> javaClasses = new HashSet<>();
    javaClasses.add(snippetClassName);

    for (Constructor<?> inclConstructor : snippet.getIncludedConstructors()) {
        javaClasses.add(inclConstructor.getDeclaringClass().getName());
    }

    for (Method inclMethod : snippet.getIncludedMethods()) {
        javaClasses.add(inclMethod.getDeclaringClass().getName());
    }

    // TODO inner classes are not handled well enough

    // TODO anonymous classes can also have anonymous classes -> recursion

    Set<String> toAdd = new HashSet<>();
    for (String javaClass : javaClasses) {
        int i = 1;
        while (true) {
            // guess anonymous classes, like ClassName$1, ClassName$2 etc.
            try {
                classLoader.loadClass(javaClass + "$" + i);
                toAdd.add(javaClass + "$" + i);
                i++;
            } catch (ClassNotFoundException e) {
                // bad guess, no more anonymous classes on this level
                break;
            }
        }
    }
    javaClasses.addAll(toAdd);

    // analyse classes
    CoverageBuilder coverageBuilder = new CoverageBuilder();
    Analyzer analyzer = new Analyzer(executionData, coverageBuilder);

    for (String javaClassName : javaClasses) {
        logger.trace("Analysing: {}", javaClassName);
        analyzer.analyzeClass(classLoader.readBytes(javaClassName), javaClassName);
    }

    // TODO remove debug
    // new File("D:/SETTE/!DUMP/" + getTool().getName()).mkdirs();
    // PrintStream out = new PrintStream("D:/SETTE/!DUMP/"
    // + getTool().getName() + "/" + testClassName + ".out");

    Map<String, Triple<TreeSet<Integer>, TreeSet<Integer>, TreeSet<Integer>>> coverageInfo = new HashMap<>();

    for (final IClassCoverage cc : coverageBuilder.getClasses()) {
        String file = cc.getPackageName() + '/' + cc.getSourceFileName();
        file = file.replace('\\', '/');

        if (!coverageInfo.containsKey(file)) {
            coverageInfo.put(file,
                    Triple.of(new TreeSet<Integer>(), new TreeSet<Integer>(), new TreeSet<Integer>()));
        }

        // out.printf("Coverage of class %s%n", cc.getName());
        //
        // printCounter(out, "instructions",
        // cc.getInstructionCounter());
        // printCounter(out, "branches", cc.getBranchCounter());
        // printCounter(out, "lines", cc.getLineCounter());
        // printCounter(out, "methods", cc.getMethodCounter());
        // printCounter(out, "complexity", cc.getComplexityCounter());

        for (int l = cc.getFirstLine(); l <= cc.getLastLine(); l++) {
            switch (cc.getLine(l).getStatus()) {
            case ICounter.FULLY_COVERED:
                coverageInfo.get(file).getLeft().add(l);
                break;

            case ICounter.PARTLY_COVERED:
                coverageInfo.get(file).getMiddle().add(l);
                break;

            case ICounter.NOT_COVERED:
                coverageInfo.get(file).getRight().add(l);
                break;
            }
        }
    }

    // create coverage XML
    SnippetCoverageXml coverageXml = new SnippetCoverageXml();
    coverageXml.setToolName(getTool().getName());
    coverageXml.setSnippetProjectElement(
            new SnippetProjectElement(getSnippetProjectSettings().getBaseDirectory().getCanonicalPath()));

    coverageXml.setSnippetElement(
            new SnippetElement(snippet.getContainer().getJavaClass().getName(), snippet.getMethod().getName()));

    coverageXml.setResultType(ResultType.S);

    for (Entry<String, Triple<TreeSet<Integer>, TreeSet<Integer>, TreeSet<Integer>>> entry : coverageInfo
            .entrySet()) {
        TreeSet<Integer> full = entry.getValue().getLeft();
        TreeSet<Integer> partial = entry.getValue().getMiddle();
        TreeSet<Integer> not = entry.getValue().getRight();

        FileCoverageElement fce = new FileCoverageElement();
        fce.setName(entry.getKey());
        fce.setFullyCoveredLines(StringUtils.join(full, ' '));
        fce.setPartiallyCoveredLines(StringUtils.join(partial, ' '));
        fce.setNotCoveredLines(StringUtils.join(not, ' '));

        coverageXml.getCoverage().add(fce);
    }

    coverageXml.validate();

    // TODO needs more documentation
    File coverageFile = RunnerProjectUtils.getSnippetCoverageFile(getRunnerProjectSettings(), snippet);

    Serializer serializer = new Persister(new AnnotationStrategy(),
            new Format("<?xml version=\"1.0\" encoding= \"UTF-8\" ?>"));

    serializer.write(coverageXml, coverageFile);

    // TODO move HTML generation to another file/phase
    File htmlFile = RunnerProjectUtils.getSnippetHtmlFile(getRunnerProjectSettings(), snippet);

    String htmlTitle = getTool().getName() + " - " + snippetClassName + '.' + snippetMethodName + "()";
    StringBuilder htmlData = new StringBuilder();
    htmlData.append("<!DOCTYPE html>\n");
    htmlData.append("<html lang=\"hu\">\n");
    htmlData.append("<head>\n");
    htmlData.append("       <meta charset=\"utf-8\" />\n");
    htmlData.append("       <title>" + htmlTitle + "</title>\n");
    htmlData.append("       <style type=\"text/css\">\n");
    htmlData.append("               .code { font-family: 'Consolas', monospace; }\n");
    htmlData.append("               .code .line { border-bottom: 1px dotted #aaa; white-space: pre; }\n");
    htmlData.append("               .code .green { background-color: #CCFFCC; }\n");
    htmlData.append("               .code .yellow { background-color: #FFFF99; }\n");
    htmlData.append("               .code .red { background-color: #FFCCCC; }\n");
    htmlData.append("               .code .line .number {\n");
    htmlData.append("                       display: inline-block;\n");
    htmlData.append("                       width:50px;\n");
    htmlData.append("                       text-align:right;\n");
    htmlData.append("                       margin-right:5px;\n");
    htmlData.append("               }\n");
    htmlData.append("       </style>\n");
    htmlData.append("</head>\n");
    htmlData.append("\n");
    htmlData.append("<body>\n");
    htmlData.append("       <h1>" + htmlTitle + "</h1>\n");

    for (FileCoverageElement fce : coverageXml.getCoverage()) {
        htmlData.append("       <h2>" + fce.getName() + "</h2>\n");
        htmlData.append("       \n");

        File src = new File(getSnippetProject().getSettings().getSnippetSourceDirectory(), fce.getName());
        List<String> srcLines = FileUtils.readLines(src);

        SortedSet<Integer> full = linesToSortedSet(fce.getFullyCoveredLines());
        SortedSet<Integer> partial = linesToSortedSet(fce.getPartiallyCoveredLines());
        SortedSet<Integer> not = linesToSortedSet(fce.getNotCoveredLines());

        htmlData.append("       <div class=\"code\">\n");
        int i = 1;
        for (String srcLine : srcLines) {
            String divClass = getLineDivClass(i, full, partial, not);
            htmlData.append("               <div class=\"" + divClass + "\"><div class=\"number\">" + i
                    + "</div> " + srcLine + "</div>\n");
            i++;
        }
        htmlData.append("       </div>\n\n");

    }

    // htmlData.append("               <div class=\"line\"><div class=\"number\">1</div> package samplesnippets;</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">2</div> </div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">3</div> import hu.bme.mit.sette.annotations.SetteIncludeCoverage;</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">4</div> import hu.bme.mit.sette.annotations.SetteNotSnippet;</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">5</div> import hu.bme.mit.sette.annotations.SetteRequiredStatementCoverage;</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">6</div> import hu.bme.mit.sette.annotations.SetteSnippetContainer;</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">7</div> import samplesnippets.inputs.SampleContainer_Inputs;</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">8</div> </div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">9</div> @SetteSnippetContainer(category = "X1",</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">10</div>         goal = "Sample
    // snippet container",</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">11</div>         inputFactoryContainer = SampleContainer_Inputs.class)</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">12</div> public final class SampleContainer {</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">13</div>     private SampleContainer() {</div>\n");
    // htmlData.append("               <div class=\"line red\"><div class=\"number\">14</div>         throw new UnsupportedOperationException("Static
    // class");</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">15</div>     }</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">16</div> </div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">17</div>     @SetteRequiredStatementCoverage(value = 100)</div>\n");
    // htmlData.append("               <div class=\"line green\"><div class=\"number\">18</div>     public static boolean snippet(int x) {</div>\n");
    // htmlData.append("               <div class=\"line yellow\"><div class=\"number\">19</div>         if (20 * x + 2 == 42) {</div>\n");
    // htmlData.append("               <div class=\"line green\"><div class=\"number\">20</div>             return true;</div>\n");
    // htmlData.append("               <div class=\"line green\"><div class=\"number\">21</div>         } else {</div>\n");
    // htmlData.append("               <div class=\"line green\"><div class=\"number\">22</div>             return false;</div>\n");
    // htmlData.append("               <div class=\"line green\"><div class=\"number\">23</div>         }</div>\n");
    // htmlData.append("               <div class=\"line green\"><div class=\"number\">24</div>     }</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">25</div> }</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">26</div> </div>\n");

    htmlData.append("</body>\n");
    htmlData.append("</html>\n");

    FileUtils.write(htmlFile, htmlData);
}

From source file:com.haulmont.cuba.core.sys.MetaModelLoader.java

protected void initProperties(Class<?> clazz, MetaClassImpl metaClass, Collection<RangeInitTask> tasks) {
    if (!metaClass.getOwnProperties().isEmpty())
        return;//from   www  .  j  av a 2  s.  c  o  m

    // 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:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Find get methods with no params. All getters that aren't Native, Static,
 * Abstract, Synthetic, or Bridge are returned.
 * /*ww w  . j  av a 2 s .  c o  m*/
 * @param clazz
 *          the clazz
 * @return the list
 */
public synchronized static List<Method> findGetMethodsWithNoParams(Class<?> clazz) {

    /* if a cache already exists simply return it */
    List<Method> returnMethods = cachedMethods.get(clazz);

    if (returnMethods == null) {
        /* create a new cache and return it */
        returnMethods = new ArrayList<Method>();

        for (Method method : findAllMethods(clazz)) {

            // check for compiler introduced methods, as well as native methods.
            // simply ignore these methods, as they are probably not what we are
            // looking for.

            int modifiers = method.getModifiers();

            if (Modifier.isNative(modifiers) //
                    || Modifier.isStatic(modifiers) //
                    || Modifier.isAbstract(modifiers) //
                    || method.isSynthetic() //
                    || method.isBridge()) {
                continue;
            }

            // if its a getter then add it to the list
            if (isIs(method) || isGetter(method)) {
                if (!doesMethodHaveParams(method)) {
                    returnMethods.add(method);
                }
            }
        }

        cachedMethods.put(clazz, returnMethods);
    }

    return returnMethods;
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static boolean checkMethod(Method m, List<Class> classes) {
    if (m.getDeclaringClass().getName().equals(m.getName())) {
        if (verbose) {
            System.out.println("checkMethod skipping " + m + " method same as classname.");
        }/*from  w w w .j  a  v  a 2 s.c o  m*/
        return false;
    }
    if (m.getDeclaringClass().getName().endsWith("." + m.getName())) {
        if (verbose) {
            System.out.println("checkMethod skipping " + m + " method same as classname.");
        }
        return false;
    }
    if (m.isSynthetic()) {
        if (verbose) {
            System.out.println("checkMethod skipping " + m + " isSynthetic.");
        }
        return false;
    }
    if (!Modifier.isPublic(m.getModifiers())) {
        if (verbose) {
            System.out.println("checkMethod skipping " + m + " not public");
        }
        return false;
    }
    if (!checkClass(m.getReturnType(), classes)) {
        if (verbose) {
            System.out.println("checkMethod skipping " + m + " return type not in classes list.");
        }
        return false;
    }
    boolean ret = checkParameters(m.getParameterTypes(), classes);
    if (!ret) {
        if (verbose) {
            System.out.println("checkMethod skipping " + m + " a parameter type is not in classes list");
        }
    }
    return ret;
}