Example usage for java.lang.reflect Method getModifiers

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

Introduction

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

Prototype

@Override
public int getModifiers() 

Source Link

Usage

From source file:lucee.transformer.bytecode.reflection.ASMProxyFactory.java

private static byte[] _createMethod(Type type, Class clazz, Method method, Resource classRoot, String className)
        throws IOException {
    Class<?> rtn = method.getReturnType();
    Type rtnType = Type.getType(rtn);

    className = className.replace('.', File.separatorChar);
    ClassWriter cw = ASMUtil.getClassWriter();
    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, className, null, ASM_METHOD.getInternalName(), null);

    // CONSTRUCTOR

    GeneratorAdapter adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC, CONSTRUCTOR, null, null, cw);

    Label begin = new Label();
    adapter.visitLabel(begin);//from ww  w. j  a va 2  s  . co m
    adapter.loadThis();

    adapter.visitVarInsn(Opcodes.ALOAD, 1);
    adapter.visitVarInsn(Opcodes.ALOAD, 2);

    adapter.invokeConstructor(ASM_METHOD, CONSTRUCTOR);
    adapter.visitInsn(Opcodes.RETURN);

    Label end = new Label();
    adapter.visitLabel(end);

    adapter.endMethod();

    /*
             
        GeneratorAdapter adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC,CONSTRUCTOR,null,null,cw);
                
        Label begin = new Label();
         adapter.visitLabel(begin);
       adapter.loadThis();
                 
        // clazz
         adapter.visitVarInsn(Opcodes.ALOAD, 2);
                 
         // parameterTypes 
         Class<?>[] params = method.getParameterTypes();
         Type[] paramTypes = new Type[params.length];
        ArrayVisitor av=new ArrayVisitor();
        av.visitBegin(adapter, Types.CLASS, params.length);
        for(int i=0;i<params.length;i++){
           paramTypes[i]=Type.getType(params[i]);
           av.visitBeginItem(adapter, i);
     loadClass(adapter,params[i]);
           av.visitEndItem(adapter);
        }
        av.visitEnd();
                
       adapter.invokeConstructor(ASM_METHOD, ASM_METHOD_CONSTRUCTOR);
       adapter.visitInsn(Opcodes.RETURN);
               
       Label end = new Label();
       adapter.visitLabel(end);
               
       adapter.endMethod();
     */

    // METHOD getName();
    adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC, GET_NAME, null, null, cw);
    adapter.push(method.getName());
    adapter.visitInsn(Opcodes.ARETURN);
    adapter.endMethod();

    // METHOD getModifiers();
    adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC, GET_MODIFIERS, null, null, cw);
    adapter.push(method.getModifiers());
    adapter.visitInsn(Opcodes.IRETURN);
    adapter.endMethod();

    // METHOD getReturnType();
    adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC, GET_RETURN_TYPE_AS_STRING, null, null, cw);

    adapter.push(method.getReturnType().getName());
    adapter.visitInsn(Opcodes.ARETURN);

    adapter.endMethod();

    // METHOD INVOKE
    boolean isStatic = Modifier.isStatic(method.getModifiers());
    adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC, INVOKE, null, null, cw);
    Label start = adapter.newLabel();
    adapter.visitLabel(start);

    // load Object
    if (!isStatic) {
        adapter.visitVarInsn(Opcodes.ALOAD, 1);
        adapter.checkCast(type);
    }

    // load params
    Class<?>[] params = method.getParameterTypes();

    Type[] paramTypes = new Type[params.length];
    for (int i = 0; i < params.length; i++) {
        paramTypes[i] = Type.getType(params[i]);
    }

    for (int i = 0; i < params.length; i++) {
        adapter.visitVarInsn(Opcodes.ALOAD, 2);
        adapter.push(i);
        //adapter.visitInsn(Opcodes.ICONST_0);
        adapter.visitInsn(Opcodes.AALOAD);

        adapter.checkCast(toReferenceType(params[i], paramTypes[i]));

        // cast
        if (params[i] == boolean.class)
            adapter.invokeVirtual(Types.BOOLEAN, BOOL_VALUE);
        else if (params[i] == short.class)
            adapter.invokeVirtual(Types.SHORT, SHORT_VALUE);
        else if (params[i] == int.class)
            adapter.invokeVirtual(Types.INTEGER, INT_VALUE);
        else if (params[i] == float.class)
            adapter.invokeVirtual(Types.FLOAT, FLT_VALUE);
        else if (params[i] == long.class)
            adapter.invokeVirtual(Types.LONG, LONG_VALUE);
        else if (params[i] == double.class)
            adapter.invokeVirtual(Types.DOUBLE, DBL_VALUE);
        else if (params[i] == char.class)
            adapter.invokeVirtual(Types.CHARACTER, CHR_VALUE);
        else if (params[i] == byte.class)
            adapter.invokeVirtual(Types.BYTE, BYT_VALUE);
        //else adapter.checkCast(paramTypes[i]);

    }

    // call method
    final org.objectweb.asm.commons.Method m = new org.objectweb.asm.commons.Method(method.getName(), rtnType,
            paramTypes);
    if (isStatic)
        adapter.invokeStatic(type, m);
    else
        adapter.invokeVirtual(type, m);

    // return
    if (rtn == void.class)
        ASMConstants.NULL(adapter);

    // cast result to object
    if (rtn == boolean.class)
        adapter.invokeStatic(Types.BOOLEAN, BOOL_VALUE_OF);
    else if (rtn == short.class)
        adapter.invokeStatic(Types.SHORT, SHORT_VALUE_OF);
    else if (rtn == int.class)
        adapter.invokeStatic(Types.INTEGER, INT_VALUE_OF);
    else if (rtn == long.class)
        adapter.invokeStatic(Types.LONG, LONG_VALUE_OF);
    else if (rtn == float.class)
        adapter.invokeStatic(Types.FLOAT, FLT_VALUE_OF);
    else if (rtn == double.class)
        adapter.invokeStatic(Types.DOUBLE, DBL_VALUE_OF);
    else if (rtn == char.class)
        adapter.invokeStatic(Types.CHARACTER, CHR_VALUE_OF);
    else if (rtn == byte.class)
        adapter.invokeStatic(Types.BYTE, BYT_VALUE_OF);

    adapter.visitInsn(Opcodes.ARETURN);

    adapter.endMethod();

    if (classRoot != null) {
        Resource classFile = classRoot.getRealResource(className + ".class");
        return store(cw.toByteArray(), classFile);
    }
    return cw.toByteArray();
}

From source file:ca.uhn.fhir.rest.server.RestfulServer.java

private int findResourceMethods(Object theProvider, Class<?> clazz) throws ConfigurationException {
    int count = 0;

    for (Method m : ReflectionUtil.getDeclaredMethods(clazz)) {
        BaseMethodBinding<?> foundMethodBinding = BaseMethodBinding.bindMethod(m, getFhirContext(),
                theProvider);/*from w w w . j av  a 2 s.c  o  m*/
        if (foundMethodBinding == null) {
            continue;
        }

        count++;

        if (foundMethodBinding instanceof ConformanceMethodBinding) {
            myServerConformanceMethod = foundMethodBinding;
            continue;
        }

        if (!Modifier.isPublic(m.getModifiers())) {
            throw new ConfigurationException(
                    "Method '" + m.getName() + "' is not public, FHIR RESTful methods must be public");
        } else {
            if (Modifier.isStatic(m.getModifiers())) {
                throw new ConfigurationException(
                        "Method '" + m.getName() + "' is static, FHIR RESTful methods must not be static");
            } else {
                ourLog.debug("Scanning public method: {}#{}", theProvider.getClass(), m.getName());

                String resourceName = foundMethodBinding.getResourceName();
                ResourceBinding resourceBinding;
                if (resourceName == null) {
                    resourceBinding = myServerBinding;
                } else {
                    RuntimeResourceDefinition definition = getFhirContext().getResourceDefinition(resourceName);
                    if (myResourceNameToBinding.containsKey(definition.getName())) {
                        resourceBinding = myResourceNameToBinding.get(definition.getName());
                    } else {
                        resourceBinding = new ResourceBinding();
                        resourceBinding.setResourceName(resourceName);
                        myResourceNameToBinding.put(resourceName, resourceBinding);
                    }
                }

                List<Class<?>> allowableParams = foundMethodBinding.getAllowableParamAnnotations();
                if (allowableParams != null) {
                    for (Annotation[] nextParamAnnotations : m.getParameterAnnotations()) {
                        for (Annotation annotation : nextParamAnnotations) {
                            Package pack = annotation.annotationType().getPackage();
                            if (pack.equals(IdParam.class.getPackage())) {
                                if (!allowableParams.contains(annotation.annotationType())) {
                                    throw new ConfigurationException("Method[" + m.toString()
                                            + "] is not allowed to have a parameter annotated with "
                                            + annotation);
                                }
                            }
                        }
                    }
                }

                resourceBinding.addMethod(foundMethodBinding);
                ourLog.debug(" * Method: {}#{} is a handler", theProvider.getClass(), m.getName());
            }
        }
    }

    return count;
}

From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java

private void exportData(String dataSource, HttpServletResponse response) throws Exception {
    ServiceDescription serviceDesc = findService(dataSource);
    List<? extends Object> serviceResult = null;
    if (serviceDesc.getFindAll() != null) {
        Class<?>[] parameterTypes = serviceDesc.getFindAll().getParameterTypes();
        Object[] realParameters = new Object[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            if (parameterTypes[i].equals(ServiceContext.class)) {
                realParameters[i] = ServiceContextStore.get();
            } else if (parameterTypes[i].equals(PagingParameter.class)) {
                realParameters[i] = PagingParameter.rowAccess(0, 1000);
            } else {
                throw new IllegalArgumentException("findAll parameter #" + i + " for '" + dataSource
                        + "' has unknown type '" + parameterTypes[i].getName() + "'");
            }//  ww w.  j a  va  2s . c  om
        }
        if (serviceDesc.getFindAll().getReturnType().equals(PagedResult.class)) {
            PagedResult pagedServiceResult = (PagedResult) serviceDesc.getFindAll()
                    .invoke(serviceDesc.getInstance(), realParameters);
            serviceResult = pagedServiceResult.getValues();
        } else {
            serviceResult = (List<? extends Object>) serviceDesc.getFindAll().invoke(serviceDesc.getInstance(),
                    realParameters);
        }
    } else {
        throw new IllegalArgumentException("No fetch (findAll) operation available");
    }

    // application/vnd.oasis.opendocument.spreadsheet
    // application/vnd.ms-excel
    response.setContentType("application/vnd.oasis.opendocument.spreadsheet;charset=UTF-8");
    response.setHeader("Content-Disposition", "filename=" + dataSource + ".csv");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Expires", "-1");

    boolean first = true;
    List<Method> methods = new ArrayList<Method>();
    for (Object dataRow : serviceResult) {
        // prepare header
        if (first) {
            first = false;
            StringBuilder header = new StringBuilder();

            // Resolve getId method
            Method idMethod;
            try {
                idMethod = dataRow.getClass().getMethod("getId", (Class<?>[]) null);
            } catch (Throwable th) {
                idMethod = null;
            }
            if (idMethod != null) {
                methods.add(idMethod);
                header.append("Id " + READ_ONLY + ",");
            }

            // Iterate through methods
            for (Class curClass = dataRow.getClass(); curClass != Object.class; curClass = curClass
                    .getSuperclass()) {
                Method[] declaredMethods = curClass.getDeclaredMethods();
                for (Method m : declaredMethods) {
                    if (m.getName().startsWith(GET_PREFIX) && Modifier.isPublic(m.getModifiers())
                            && !Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0
                            && !"getKey".equals(m.getName()) && !"getCreatedDate".equals(m.getName())
                            && !"getCreatedBy".equals(m.getName()) && !"getLastUpdated".equals(m.getName())
                            && !"getLastUpdatedBy".equals(m.getName()) && !"getVersion".equals(m.getName())
                            && !"getUuid".equals(m.getName()) && !"getId".equals(m.getName())) {
                        Method setMethod;
                        try {
                            setMethod = curClass.getMethod(
                                    SET_PREFIX + m.getName().substring(GET_PREFIX.length()),
                                    new Class[] { m.getReturnType() });
                        } catch (Throwable ex) {
                            setMethod = null;
                        }
                        String readOnly = "";
                        if (setMethod == null) {
                            readOnly = READ_ONLY;
                        }
                        header.append(m.getName().substring(GET_PREFIX.length())).append(readOnly).append(",");
                        methods.add(m);
                    }
                }
            }
            response.getWriter().println(header.length() > 0 ? header.substring(0, header.length() - 1) : "");
        }

        // Export data
        StringBuilder csvRow = new StringBuilder();
        for (Method m : methods) {
            Object value = m.invoke(dataRow, (Object[]) null);
            if (value == null) {
                csvRow.append("null,");
            } else if (value instanceof Map) {
                csvRow.append("HUH-MAPA");
                csvRow.append(",");
            } else if (value instanceof Collection) {
                csvRow.append("HUH-COLLECTION");
                csvRow.append(",");
            } else if (value instanceof List) {
                csvRow.append("HUH-LIST");
                csvRow.append(",");
            } else if (value instanceof Object[]) {
                csvRow.append("HUH-ARRAY");
                csvRow.append(",");
            } else if (value instanceof Date) {
                csvRow.append(dateFormat.format((Date) value));
                csvRow.append(",");
            } else if (value instanceof Boolean) {
                csvRow.append(((Boolean) value) ? "TRUE" : "FALSE");
                csvRow.append(",");
            } else if (value instanceof Number) {
                csvRow.append(value);
                csvRow.append(",");
            } else if (value instanceof CharSequence) {
                csvRow.append(Q).append(((CharSequence) value).toString().replaceAll(Q, Q + Q)).append(Q);
                csvRow.append(",");
            } else if (value instanceof Enum) {
                String enumName = ((Enum) value).name();
                csvRow.append(Q + enumName + Q);
                csvRow.append(",");
            } else {
                csvRow.append("SOMETHING ELSE " + value.getClass());
                csvRow.append(",");
            }
        }
        response.getWriter().println(csvRow.length() > 0 ? csvRow.substring(0, csvRow.length() - 1) : "");
    }
    return;
}

From source file:adalid.core.Project.java

/**
 *
 * @param clazz/*from w  w w. ja  va 2 s . c  om*/
 */
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.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.");
        }/*  w w  w.jav a2s.co  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;
}

From source file:com.dpbymqn.fsm.manager.FsmManager.java

private void onDecision(final Method m, final OnDecision a, Class<? extends StatefulObject> stObjectClz,
        Class<? extends StateListener> clzLst, StateListener sl, StatefulObject st) {
    if (!testDeclaredAndActualClassConformity(m, a.smClass(), st, sl, stObjectClz, clzLst)) {
        return;// www .  j  a  va2 s  . c  o m
    }
    final Class<? extends StatefulObject> stcls = StatefulObject.class.equals(a.smClass()) ? stObjectClz
            : a.smClass();
    final String prev = StringUtils.isEmpty(a.prev()) ? null : a.prev();
    final String next = StringUtils.isEmpty(a.next()) ? null : a.next();
    final WeakReference<StateListener> slRef = new WeakReference<StateListener>(sl);
    if (String.class.equals(m.getReturnType())) {
        if (m.getParameterTypes() != null) {
            switch (m.getParameterTypes().length) {
            case 1:
                if (String.class.equals(m.getParameterTypes()[0])) {
                    regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                        @Override
                        public Boolean query(StatefulObject sm, String fromState, String toState) {
                            return null;
                        }

                        @Override
                        public String query(StatefulObject sm, String fromState) {
                            return (String) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(),
                                    fromState);
                        }
                    });
                } else if (StatefulObject.class.isAssignableFrom(m.getParameterTypes()[0])) {
                    regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                        @Override
                        public Boolean query(StatefulObject sm, String fromState, String toState) {
                            return null;
                        }

                        @Override
                        public String query(StatefulObject sm, String fromState) {
                            return (String) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(),
                                    sm);
                        }
                    });

                }
                break;
            case 2:
                regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                    @Override
                    public Boolean query(StatefulObject sm, String fromState, String toState) {
                        return null;
                    }

                    @Override
                    public String query(StatefulObject sm, String fromState) {

                        return (String) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(), sm,
                                fromState);
                    }
                });
                break;
            }
        } else {
            regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                @Override
                public Boolean query(StatefulObject sm, String fromState, String toState) {
                    return null;
                }

                @Override
                public String query(StatefulObject sm, String fromState) {
                    return (String) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get());
                }
            });
        }
    } else if (Boolean.class.equals(m.getReturnType()) || boolean.class.equals(m.getReturnType())) {

        if (m.getParameterTypes() != null) {
            switch (m.getParameterTypes().length) {
            case 1:
                if (String.class.equals(m.getParameterTypes()[0])) {
                    regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                        @Override
                        public Boolean query(StatefulObject sm, String fromState, String toState) {
                            return (Boolean) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(),
                                    toState);
                        }

                        @Override
                        public String query(StatefulObject sm, String fromState) {
                            return null;
                        }
                    });
                } else if (StatefulObject.class.isAssignableFrom(m.getParameterTypes()[0])) {
                    regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                        @Override
                        public Boolean query(StatefulObject sm, String fromState, String toState) {
                            return (Boolean) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(),
                                    sm);
                        }

                        @Override
                        public String query(StatefulObject sm, String fromState) {
                            return null;
                        }
                    });
                }
                break;
            case 2:
                if (String.class.equals(m.getParameterTypes()[0])) {
                    regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                        @Override
                        public Boolean query(StatefulObject sm, String fromState, String toState) {
                            return (Boolean) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(),
                                    fromState, toState);

                        }

                        @Override
                        public String query(StatefulObject sm, String fromState) {
                            return null;
                        }
                    });
                } else if (StatefulObject.class.isAssignableFrom(m.getParameterTypes()[0])) {
                    regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                        @Override
                        public Boolean query(StatefulObject sm, String fromState, String toState) {
                            return (Boolean) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(),
                                    sm, toState);

                        }

                        @Override
                        public String query(StatefulObject sm, String fromState) {
                            return null;
                        }
                    });
                }
                break;
            case 3:
                regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                    @Override
                    public Boolean query(StatefulObject sm, String fromState, String toState) {
                        return (Boolean) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get(), sm,
                                fromState, toState);
                    }

                    @Override
                    public String query(StatefulObject sm, String fromState) {
                        return null;
                    }
                });
                break;
            default:
                regDecisionCbk(stcls, st, sl, prev, next, new DecisionCallback() {
                    @Override
                    public Boolean query(StatefulObject sm, String fromState, String toState) {
                        return (Boolean) invoke(m, Modifier.isStatic(m.getModifiers()) ? null : slRef.get());
                    }

                    @Override
                    public String query(StatefulObject sm, String fromState) {
                        return null;
                    }
                });
            }
        }
    }
}

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

private boolean hasMatchingAnnotation(final Annotation expectedAnnotation, final Annotation[] annotations)
        throws UnableToCompleteException {
    // See spec section 2.2. Applying multiple constraints of the same type
    for (final Annotation annotation : annotations) {
        // annotations not annotated by @Constraint
        if (annotation.annotationType().getAnnotation(Constraint.class) == null) {
            try {
                // value element has a return type of an array of constraint
                // annotations
                final Method valueMethod = annotation.annotationType().getMethod("value");
                final Class<?> valueType = valueMethod.getReturnType();
                if (valueType.isArray() && Annotation.class.isAssignableFrom(valueType.getComponentType())) {
                    if (Modifier.isAbstract(valueMethod.getModifiers())) {
                        // handle edge case where interface is marked "abstract"
                        valueMethod.setAccessible(true);
                    }/* w w w .ja  va2 s . c  o  m*/
                    final Annotation[] valueAnnotions = (Annotation[]) valueMethod.invoke(annotation);
                    for (final Annotation annotation2 : valueAnnotions) {
                        if (expectedAnnotation.equals(annotation2)) {
                            return true;
                        }
                    }
                }
            } catch (final NoSuchMethodException ignore) { // NOPMD
                // Expected Case.
            } catch (final Exception e) {
                throw error(this.logger, e);
            }
        }
    }
    return false;
}

From source file:org.apache.axis2.description.java2wsdl.DefaultSchemaGenerator.java

protected Method[] processMethods(Method[] declaredMethods) throws Exception {
    ArrayList<Method> list = new ArrayList<Method>();
    //short the elements in the array
    Arrays.sort(declaredMethods, new MathodComparator());

    // since we do not support overload
    HashMap<String, Method> uniqueMethods = new LinkedHashMap<String, Method>();
    XmlSchemaComplexType methodSchemaType;
    XmlSchemaSequence sequence = null;/*from  w w  w. ja  v a  2s  .  c  o  m*/

    for (Method jMethod : declaredMethods) {
        if (jMethod.isBridge()) {
            continue;
        }

        WebMethodAnnotation methodAnnon = JSR181Helper.INSTANCE.getWebMethodAnnotation(jMethod);
        String methodName = jMethod.getName();
        if (methodAnnon != null) {
            if (methodAnnon.isExclude()) {
                continue;
            }
            if (methodAnnon.getOperationName() != null) {
                methodName = methodAnnon.getOperationName();
            }
        }

        // no need to think abt this method , since that is system
        // config method
        if (excludeMethods.contains(methodName)) {
            continue;
        }

        if (!Modifier.isPublic(jMethod.getModifiers())) {
            // no need to generate Schema for non public methods
            continue;
        }

        if (uniqueMethods.get(methodName) != null) {
            log.warn("We don't support method overloading. Ignoring [" + methodName + "]");
            continue;
        }
        boolean addToService = false;
        AxisOperation axisOperation = service.getOperation(new QName(methodName));
        if (axisOperation == null) {
            axisOperation = Utils.getAxisOperationForJmethod(jMethod);
            //                if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(
            //                        axisOperation.getMessageExchangePattern())) {
            //                    AxisMessage outMessage = axisOperation.getMessage(
            //                            WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
            //                    if (outMessage != null) {
            //                        outMessage.setName(methodName + RESPONSE);
            //                    }
            //                }
            addToService = true;
        }
        // by now axis operation should be assigned but we better recheck & add the paramether
        if (axisOperation != null) {
            axisOperation.addParameter("JAXRSAnnotaion", JAXRSUtils.getMethodModel(this.classModel, jMethod));
        }
        // Maintain a list of methods we actually work with
        list.add(jMethod);

        processException(jMethod, axisOperation);
        uniqueMethods.put(methodName, jMethod);
        Class<?>[] parameters = jMethod.getParameterTypes();
        String parameterNames[] = null;
        AxisMessage inMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
        if (inMessage != null) {
            inMessage.setName(methodName + Java2WSDLConstants.MESSAGE_SUFFIX);
        }
        if (parameters.length > 0) {
            parameterNames = methodTable.getParameterNames(methodName);
            // put the parameter names to use it for parsing
            service.addParameter(methodName, parameterNames);
        }

        // we need to add the method opration wrapper part even to
        // empty parameter operations 
        sequence = new XmlSchemaSequence();

        String requestElementSuffix = getRequestElementSuffix();
        String requestLocalPart = methodName;
        if (requestElementSuffix != null) {
            requestLocalPart += requestElementSuffix;
        }

        methodSchemaType = createSchemaTypeForMethodPart(requestLocalPart);
        methodSchemaType.setParticle(sequence);
        inMessage.setElementQName(typeTable.getQNamefortheType(requestLocalPart));

        Parameter param = service.getParameter(Java2WSDLConstants.MESSAGE_PART_NAME_OPTION_LONG);
        if (param != null) {
            inMessage.setPartName((String) param.getValue());
        }

        service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation);

        Annotation[][] parameterAnnotation = jMethod.getParameterAnnotations();

        Type[] genericParameterTypes = jMethod.getGenericParameterTypes();
        for (int j = 0; j < parameters.length; j++) {
            Class<?> methodParameter = parameters[j];
            String parameterName = getParameterName(parameterAnnotation, j, parameterNames);
            if (nonRpcMethods.contains(jMethod.getName())) {
                generateSchemaForType(sequence, null, jMethod.getName());
                break;
            } else {
                Type genericParameterType = genericParameterTypes[j];
                Type genericType = null;
                if (genericParameterType instanceof ParameterizedType) {
                    ParameterizedType aType = (ParameterizedType) genericParameterType;
                    Type[] parameterArgTypes = aType.getActualTypeArguments();
                    genericType = parameterArgTypes[0];
                    generateSchemaForType(sequence, genericType, parameterName, true);
                } else {
                    generateSchemaForType(sequence, methodParameter, parameterName);
                }
            }
        }
        // for its return type
        Class<?> returnType = jMethod.getReturnType();
        if (!"void".equals(jMethod.getReturnType().getName())) {
            String partQname = methodName + RESPONSE;
            methodSchemaType = createSchemaTypeForMethodPart(partQname);
            sequence = new XmlSchemaSequence();
            methodSchemaType.setParticle(sequence);
            WebResultAnnotation returnAnnon = JSR181Helper.INSTANCE.getWebResultAnnotation(jMethod);
            String returnName = "return";
            if (returnAnnon != null) {
                returnName = returnAnnon.getName();
                if (returnName == null || "".equals(returnName)) {
                    returnName = "return";
                }
            }
            Type genericParameterType = jMethod.getGenericReturnType();
            if (nonRpcMethods.contains(jMethod.getName())) {
                generateSchemaForType(sequence, null, returnName);
            } else if (genericParameterType instanceof ParameterizedType) {
                ParameterizedType aType = (ParameterizedType) genericParameterType;
                Type[] parameterArgTypes = aType.getActualTypeArguments();
                generateSchemaForType(sequence, parameterArgTypes[0], returnName, true);
            } else {
                generateSchemaForType(sequence, returnType, returnName);
            }

            AxisMessage outMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
            outMessage.setElementQName(typeTable.getQNamefortheType(partQname));
            outMessage.setName(partQname);

            Parameter outparam = service.getParameter(Java2WSDLConstants.MESSAGE_PART_NAME_OPTION_LONG);
            if (outparam != null) {
                outMessage.setPartName((String) outparam.getValue());
            }

            service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation);
        }
        if (addToService) {
            service.addOperation(axisOperation);
        }
    }
    return list.toArray(new Method[list.size()]);
}

From source file:it.grid.storm.config.Configuration.java

@Override
public String toString() {

    StringBuilder configurationStringBuilder = new StringBuilder();
    try {//from   w  ww  . ja v a2s  .co m
        // This class methods
        Method methods[] = Configuration.instance.getClass().getDeclaredMethods();

        // This class fields
        Field[] fields = Configuration.instance.getClass().getDeclaredFields();
        HashMap<String, String> methodKeyMap = new HashMap<String, String>();
        for (Field field : fields) {
            String fieldName = field.getName();
            if (fieldName.endsWith("KEY") && field.getType().equals(String.class)) {
                // from a field like GROUP_TAPE_WRITE_BUFFER_KEY =
                // "tape.buffer.group.write"
                // puts in the map the pair
                // <getgrouptapewritebuffer,tape.buffer.group.write>
                String mapKey = "get"
                        + fieldName.substring(0, fieldName.lastIndexOf("_")).replaceAll("_", "").toLowerCase();
                if (methodKeyMap.containsKey(mapKey)) {
                    String value = methodKeyMap.get(mapKey);
                    methodKeyMap.put(mapKey, value + " , " + (String) field.get(Configuration.instance));
                } else {
                    methodKeyMap.put(mapKey, (String) field.get(Configuration.instance));
                }
            }
        }

        Object field = null;
        Object[] dummyArray = new Object[0];
        for (Method method : methods) {
            /*
             * with method.getModifiers() == 1 we check that the method is public
             * (otherwise he can request real parameters)
             */
            if (method.getName().substring(0, 3).equals("get") && (!method.getName().equals("getInstance"))
                    && method.getModifiers() == 1) {
                field = method.invoke(Configuration.instance, dummyArray);
                if (field.getClass().isArray()) {
                    field = ArrayUtils.toString(field);
                }
                String value = methodKeyMap.get(method.getName().toLowerCase());
                if (value == null) {
                    configurationStringBuilder.insert(0,
                            "!! Unable to find method " + method.getName() + " in methode key map!");
                } else {
                    configurationStringBuilder.append("Property " + value + " : ");
                }
                if (field.getClass().equals(String.class)) {
                    field = '\'' + ((String) field) + '\'';
                }
                configurationStringBuilder.append(method.getName() + "() == " + field.toString() + "\n");
            }
        }
        return configurationStringBuilder.toString();
    } catch (Exception e) {
        if (e.getClass().isAssignableFrom(java.lang.reflect.InvocationTargetException.class)) {
            configurationStringBuilder.insert(0,
                    "!!! Cannot do toString! Got an Exception: " + e.getCause() + "\n");
        } else {
            configurationStringBuilder.insert(0, "!!! Cannot do toString! Got an Exception: " + e + "\n");
        }
        return configurationStringBuilder.toString();
    }
}

From source file:org.evosuite.testcase.TestFactory.java

private boolean insertRandomReflectionCallOnObject(TestCase test, VariableReference callee, int position,
        int recursionDepth) throws ConstructionFailedException {

    logger.debug("Recursion depth: " + recursionDepth);
    if (recursionDepth > Properties.MAX_RECURSION) {
        logger.debug("Max recursion depth reached");
        throw new ConstructionFailedException("Max recursion depth reached");
    }/*from  w  w w . ja  v  a2 s.c  o  m*/

    if (!reflectionFactory.getReflectedClass().isAssignableFrom(callee.getVariableClass())) {
        logger.debug("Reflection not performed on class {}", callee.getVariableClass());
        return false;
    }

    int length = test.size();
    List<VariableReference> parameters = null;
    Statement st = null;

    if (reflectionFactory.nextUseField()) {
        Field field = reflectionFactory.nextField();

        /*
           In theory, there might be cases in which using null in PA might help increasing
           coverage. However, likely most of the time we ll end up in useless tests throwing
           NPE on the private fields. As we maximize the number of methods throwing exceptions,
           we could end up with a lot of useless tests
         */
        boolean allowNull = false;

        parameters = satisfyParameters(test, callee,
                //we need a reference to the SUT, and one to a variable of same type of chosen field
                Arrays.asList((Type) field.getType()), position, recursionDepth + 1, allowNull, false, true);

        try {
            st = new PrivateFieldStatement(test, reflectionFactory.getReflectedClass(), field.getName(), callee,
                    parameters.get(0));
        } catch (NoSuchFieldException e) {
            logger.error("Reflection problem: " + e, e);
            throw new ConstructionFailedException("Reflection problem");
        }
    } else {
        //method
        Method method = reflectionFactory.nextMethod();
        List<Type> list = new ArrayList<>();
        list.addAll(Arrays.asList(method.getParameterTypes()));

        parameters = satisfyParameters(test, callee, list, position, recursionDepth + 1, true, false, true);

        st = new PrivateMethodStatement(test, reflectionFactory.getReflectedClass(), method, callee, parameters,
                Modifier.isStatic(method.getModifiers()));
    }

    int newLength = test.size();
    position += (newLength - length);

    test.addStatement(st, position);
    return true;
}