Example usage for java.lang.reflect Method getAnnotations

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

Introduction

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

Prototype

public Annotation[] getAnnotations() 

Source Link

Usage

From source file:com.msopentech.odatajclient.proxy.api.impl.EntityTypeInvocationHandler.java

@Override
@SuppressWarnings("unchecked")
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    final Annotation[] methodAnnots = method.getAnnotations();

    if (isSelfMethod(method, args)) {
        return invokeSelfMethod(method, args);
    } else if (!ArrayUtils.isEmpty(methodAnnots) && methodAnnots[0] instanceof Operation) {
        final ODataOperation operation = this.entity.getOperation(((Operation) methodAnnots[0]).name());
        if (operation == null) {
            throw new IllegalArgumentException(
                    "Could not find any FunctionImport named " + ((Operation) methodAnnots[0]).name());
        }/*from w  w w .  j  a  v a2  s.  c  om*/

        final com.msopentech.odatajclient.engine.metadata.edm.v3.EntityContainer container = containerHandler
                .getFactory().getMetadata().getSchema(ClassUtils.getNamespace(typeRef))
                .getEntityContainer(entityContainerName);
        final com.msopentech.odatajclient.engine.metadata.edm.v3.FunctionImport funcImp = container
                .getFunctionImport(((Operation) methodAnnots[0]).name());

        return functionImport((Operation) methodAnnots[0], method, args, operation.getTarget(), funcImp);
    } // Assumption: for each getter will always exist a setter and viceversa.
    else if (method.getName().startsWith("get")) {
        // get method annotation and check if it exists as expected
        final Object res;

        final Method getter = typeRef.getMethod(method.getName());

        final Property property = ClassUtils.getAnnotation(Property.class, getter);
        if (property == null) {
            final NavigationProperty navProp = ClassUtils.getAnnotation(NavigationProperty.class, getter);
            if (navProp == null) {
                throw new UnsupportedOperationException("Unsupported method " + method.getName());
            } else {
                // if the getter refers to a navigation property ... navigate and follow link if necessary
                res = getNavigationPropertyValue(navProp, getter);
            }
        } else {
            // if the getter refers to a property .... get property from wrapped entity
            res = getPropertyValue(property, getter.getGenericReturnType());
        }

        // attach the current handler
        attach();

        return res;
    } else if (method.getName().startsWith("set")) {
        // get the corresponding getter method (see assumption above)
        final String getterName = method.getName().replaceFirst("set", "get");
        final Method getter = typeRef.getMethod(getterName);

        final Property property = ClassUtils.getAnnotation(Property.class, getter);
        if (property == null) {
            final NavigationProperty navProp = ClassUtils.getAnnotation(NavigationProperty.class, getter);
            if (navProp == null) {
                throw new UnsupportedOperationException("Unsupported method " + method.getName());
            } else {
                // if the getter refers to a navigation property ... 
                if (ArrayUtils.isEmpty(args) || args.length != 1) {
                    throw new IllegalArgumentException("Invalid argument");
                }

                setNavigationPropertyValue(navProp, args[0]);
            }
        } else {
            setPropertyValue(property, args[0]);
        }

        return ClassUtils.returnVoid();
    } else {
        throw new UnsupportedOperationException("Method not found: " + method);
    }
}

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

@Test
public final void testWithXmlElements() {
    Class<WithXmlElements> clazz = WithXmlElements.class;
    Assert.assertFalse(clazz.isEnum());/*from  www. java2  s. co m*/
    Assert.assertNotNull(fieldAnnotationProcessingService);
    Field[] fields = clazz.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        JaxbFieldNature fi = new JaxbFieldNature(new FieldInfo(field.getName()));
        fieldAnnotationProcessingService.processAnnotations(fi, field.getAnnotations());
        if ("anythingInAList".equals(field.getName())) {
            Assert.assertTrue(fi.hasXmlElements());
            //                List<XmlElement> xmlElements = fi.getXmlElements();
            //                Assert.assertNotNull(xmlElements);

        }
    }
    Method[] methods = clazz.getDeclaredMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        JaxbFieldNature fi = new JaxbFieldNature(new FieldInfo(method.getName()));
        fieldAnnotationProcessingService.processAnnotations(fi, method.getAnnotations());
    }
}

From source file:com.agimatec.validation.jsr303.extensions.MethodValidatorMetaBeanFactory.java

private void buildMethodConstraints(MethodBeanDescriptorImpl beanDesc)
        throws InvocationTargetException, IllegalAccessException {
    beanDesc.setMethodConstraints(new HashMap());

    for (Method method : beanDesc.getMetaBean().getBeanClass().getDeclaredMethods()) {
        if (!factoryContext.getFactory().getAnnotationIgnores().isIgnoreAnnotations(method)) {

            MethodDescriptorImpl methodDesc = new MethodDescriptorImpl(beanDesc.getMetaBean(),
                    new Validation[0]);
            beanDesc.putMethodDescriptor(method, methodDesc);

            // return value validations
            AppendValidationToList validations = new AppendValidationToList();
            for (Annotation anno : method.getAnnotations()) {
                if (anno instanceof Valid) {
                    methodDesc.setCascaded(true);
                } else {
                    processAnnotation(anno, methodDesc.getMetaBean().getClass(), validations);
                }//from  www .j  av  a  2s  . c o m
            }
            methodDesc.getConstraintDescriptors().addAll((List) validations.getValidations());

            // parameter validations
            Annotation[][] paramsAnnos = method.getParameterAnnotations();
            Class[] paramTypes = method.getParameterTypes();
            int idx = 0;
            for (Annotation[] paramAnnos : paramsAnnos) {
                processAnnotations(methodDesc, paramAnnos, paramTypes[idx], idx);
                idx++;
            }
        }
    }
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkConverter.java

/**
 * Looks for converter mappings for the specified class and adds it to an existing map.  Only new converters are
 * added.  If a converter is defined on a key that already exists, the converter is ignored.
 *
 * @param mapping an existing map to add new converter mappings to
 * @param clazz   class to look for converter mappings for
 *///from www.  ja v a  2s  . c om
protected void addConverterMapping(Map<String, Object> mapping, Class clazz) {
    // Process <clazz>-conversion.properties file
    String converterFilename = buildConverterFilename(clazz);
    fileProcessor.process(mapping, clazz, converterFilename);

    // Process annotations
    Annotation[] annotations = clazz.getAnnotations();

    for (Annotation annotation : annotations) {
        if (annotation instanceof Conversion) {
            Conversion conversion = (Conversion) annotation;
            for (TypeConversion tc : conversion.conversions()) {
                if (mapping.containsKey(tc.key())) {
                    break;
                }
                if (LOG.isDebugEnabled()) {
                    if (StringUtils.isEmpty(tc.key())) {
                        LOG.debug("WARNING! key of @TypeConversion [#0] applied to [#1] is empty!",
                                tc.converter(), clazz.getName());
                    } else {
                        LOG.debug("TypeConversion [#0] with key: [#1]", tc.converter(), tc.key());
                    }
                }
                annotationProcessor.process(mapping, tc, tc.key());
            }
        }
    }

    // Process annotated methods
    for (Method method : clazz.getMethods()) {
        annotations = method.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof TypeConversion) {
                TypeConversion tc = (TypeConversion) annotation;
                if (mapping.containsKey(tc.key())) {
                    break;
                }
                String key = tc.key();
                // Default to the property name
                if (StringUtils.isEmpty(key)) {
                    key = AnnotationUtils.resolvePropertyName(method);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Retrieved key [#0] from method name [#1]", key, method.getName());
                    }
                }
                annotationProcessor.process(mapping, tc, key);
            }
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration.java

private ClassConfiguration processClass(final Class<? extends SimpleScriptable> klass,
        final BrowserVersion browser) {
    if (browser != null) {
        final JsxClass jsxClass = klass.getAnnotation(JsxClass.class);
        final String expectedBrowserName;
        if (browser.isIE()) {
            expectedBrowserName = "IE";
        } else if (browser.isFirefox()) {
            expectedBrowserName = "FF";
        } else {/*from  w w  w  . j  a va2 s  . c  o m*/
            expectedBrowserName = "CHROME";
        }
        final float browserVersionNumeric = browser.getBrowserVersionNumeric();
        if (jsxClass != null && isSupported(jsxClass.browsers(), expectedBrowserName, browserVersionNumeric)) {
            final String hostClassName = klass.getName();

            final Class<?>[] domClasses = jsxClass.domClasses();

            final boolean isJsObject = jsxClass.isJSObject();
            final ClassConfiguration classConfiguration = new ClassConfiguration(klass, domClasses, isJsObject);

            final String simpleClassName = hostClassName.substring(hostClassName.lastIndexOf('.') + 1);
            ClassnameMap_.put(hostClassName, simpleClassName);
            final Map<String, Method> allGetters = new HashMap<String, Method>();
            final Map<String, Method> allSetters = new HashMap<String, Method>();
            for (final Method method : classConfiguration.getHostClass().getDeclaredMethods()) {
                for (final Annotation annotation : method.getAnnotations()) {
                    if (annotation instanceof JsxGetter) {
                        final JsxGetter jsxGetter = (JsxGetter) annotation;
                        if (isSupported(jsxGetter.value(), expectedBrowserName, browserVersionNumeric)) {
                            String property;
                            if (jsxGetter.propertyName().isEmpty()) {
                                property = method.getName().substring(3);
                                property = Character.toLowerCase(property.charAt(0)) + property.substring(1);
                            } else {
                                property = jsxGetter.propertyName();
                            }
                            allGetters.put(property, method);
                        }
                    } else if (annotation instanceof JsxSetter) {
                        final JsxSetter jsxSetter = (JsxSetter) annotation;
                        if (isSupported(jsxSetter.value(), expectedBrowserName, browserVersionNumeric)) {
                            String property;
                            if (jsxSetter.propertyName().isEmpty()) {
                                property = method.getName().substring(3);
                                property = Character.toLowerCase(property.charAt(0)) + property.substring(1);
                            } else {
                                property = jsxSetter.propertyName();
                            }
                            allSetters.put(property, method);
                        }
                    } else if (annotation instanceof JsxFunction) {
                        if (isSupported(((JsxFunction) annotation).value(), expectedBrowserName,
                                browserVersionNumeric)) {
                            classConfiguration.addFunction(method);
                        }
                    } else if (annotation instanceof JsxConstructor) {
                        classConfiguration.setJSConstructor(method);
                    }
                }
            }
            for (final Field field : classConfiguration.getHostClass().getDeclaredFields()) {
                final JsxConstant jsxConstant = field.getAnnotation(JsxConstant.class);
                if (jsxConstant != null
                        && isSupported(jsxConstant.value(), expectedBrowserName, browserVersionNumeric)) {
                    classConfiguration.addConstant(field.getName());
                }
            }
            for (final Entry<String, Method> getterEntry : allGetters.entrySet()) {
                final String property = getterEntry.getKey();
                classConfiguration.addProperty(property, getterEntry.getValue(), allSetters.get(property));
            }
            return classConfiguration;
        }
    }
    return null;
}

From source file:com.all.app.DefaultContext.java

private void checkInvokePredestroy(Method method, Object ob) {
    boolean annotationPresent = false;
    boolean noArguments = method.getParameterTypes().length == 0;
    boolean isVoid = method.getReturnType().equals(void.class);
    boolean isPublic = (method.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC;
    boolean isNotStatic = (method.getModifiers() & Modifier.STATIC) != Modifier.STATIC;
    Annotation[] annotations = method.getAnnotations();
    for (Annotation annotation : annotations) {
        if (annotation.getClass().getName().contains("PreDestroy")
                || annotation.toString().contains("PreDestroy")) {
            annotationPresent = true;//ww w. ja  v a  2s .  c  o  m
        }
    }
    if (annotationPresent && noArguments && isPublic && isNotStatic && isVoid) {
        try {
            method.invoke(ob);
        } catch (Exception e) {
            log.error(e, e);
        }
    }

}

From source file:net.minecraftforge.fml.common.FMLModContainer.java

@SuppressWarnings("unchecked")
private Method gatherAnnotations(Class<?> clazz) throws Exception {
    Method factoryMethod = null;/*from   w w  w . j av  a  2s .c o  m*/
    for (Method m : clazz.getDeclaredMethods()) {
        for (Annotation a : m.getAnnotations()) {
            if (a.annotationType().equals(Mod.EventHandler.class)) {
                if (m.getParameterTypes().length == 1
                        && FMLEvent.class.isAssignableFrom(m.getParameterTypes()[0])) {
                    m.setAccessible(true);
                    eventMethods.put((Class<? extends FMLEvent>) m.getParameterTypes()[0], m);
                } else {
                    FMLLog.log(getModId(), Level.ERROR,
                            "The mod %s appears to have an invalid event annotation %s. This annotation can only apply to methods with recognized event arguments - it will not be called",
                            getModId(), a.annotationType().getSimpleName());
                }
            } else if (a.annotationType().equals(Mod.InstanceFactory.class)) {
                if (Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0
                        && factoryMethod == null) {
                    m.setAccessible(true);
                    factoryMethod = m;
                } else if (!(Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0)) {
                    FMLLog.log(getModId(), Level.ERROR,
                            "The InstanceFactory annotation can only apply to a static method, taking zero arguments - it will be ignored on %s(%s)",
                            m.getName(), Arrays.asList(m.getParameterTypes()));
                } else if (factoryMethod != null) {
                    FMLLog.log(getModId(), Level.ERROR,
                            "The InstanceFactory annotation can only be used once, the application to %s(%s) will be ignored",
                            m.getName(), Arrays.asList(m.getParameterTypes()));
                }
            }
        }
    }
    return factoryMethod;
}

From source file:de.terrestris.shogun.dao.DatabaseDao.java

/**
 * TODO move to a better place or use existing functionality elsewhere.
 * TODO we have a very similar method in {@link HibernateFilterItem}.
 *
 * @param fields/*from w  w w.j a va  2s .c  o m*/
 * @param type
 * @return
 * @throws NoSuchFieldException
 * @throws SecurityException
 * @throws IntrospectionException
 */
public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
    for (Field field : type.getDeclaredFields()) {

        // check if the filed is not a constant
        if (Modifier.isStatic(field.getModifiers()) == false
                && Modifier.isFinal(field.getModifiers()) == false) {

            // now we check if the readmethod of the field
            // has NOT a transient annotation
            try {
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), type);
                Method readmethod = pd.getReadMethod();
                Annotation[] annotationsArr = readmethod.getAnnotations();
                if (annotationsArr.length == 0) {
                    fields.add(field);
                } else {
                    for (Annotation annotation : annotationsArr) {
                        if (annotation.annotationType().equals(javax.persistence.Transient.class) == false) {
                            fields.add(field);
                        }
                    }
                }
            } catch (IntrospectionException e) {
                LOGGER.error("Trying to determine the getter for field '" + field.getName() + "' in "
                        + type.getSimpleName() + " threw IntrospectionException."
                        + " Is there a getter following the Java-Beans" + " Specification?");
            }
        }

    }

    if (type.getSuperclass() != null) {
        fields = getAllFields(fields, type.getSuperclass());
    }

    return fields;
}

From source file:org.apache.pig.scripting.groovy.GroovyScriptEngine.java

@Override
public void registerFunctions(String path, String namespace, PigContext pigContext) throws IOException {

    if (!isInitialized) {
        pigContext.addScriptJar(getJarPath(groovy.util.GroovyScriptEngine.class));
        isInitialized = true;//from   w ww. j  a  va2s. c  o  m
    }

    try {
        //
        // Read file
        //

        Class c = gse.loadScriptByName(new File(path).toURI().toString());

        //
        // Keep track of initial/intermed/final methods of Albegraic UDFs
        //

        Map<String, Method[]> algebraicMethods = new HashMap<String, Method[]>();

        //
        // Keep track of accumulate/getValue/cleanup methods of Accumulator UDFs
        //

        Map<String, Method[]> accumulatorMethods = new HashMap<String, Method[]>();

        //
        // Loop over the methods
        //

        Method[] methods = c.getMethods();

        for (Method method : methods) {
            Annotation[] annotations = method.getAnnotations();

            boolean isAccumulator = false;

            if (annotations.length > 0) {
                Schema schema = null;
                String schemaFunction = null;

                for (Annotation annotation : annotations) {
                    if (annotation.annotationType().equals(OutputSchema.class)) {
                        schema = Utils.getSchemaFromString(((OutputSchema) annotation).value());
                    } else if (annotation.annotationType().equals(OutputSchemaFunction.class)) {
                        schemaFunction = ((OutputSchemaFunction) annotation).value();
                    } else if (isAlgebraic(annotation)) {

                        String algebraic = null;

                        int idx = 0;

                        if (annotation.annotationType().equals(AlgebraicInitial.class)) {
                            //
                            // Check that method accepts a single Tuple as parameter.
                            //
                            Class<?>[] params = method.getParameterTypes();
                            if (1 != params.length || !Tuple.class.equals(params[0])) {
                                throw new IOException(path
                                        + ": methods annotated with @AlgebraicInitial MUST take a single groovy.lang.Tuple as parameter.");
                            }
                            if (!method.getReturnType().equals(Tuple.class)
                                    && !method.getReturnType().equals(Object[].class)) {
                                throw new IOException(path + ":" + method.getName()
                                        + " Algebraic UDF Initial method MUST return type groovy.lang.Tuple or Object[].");
                            }
                            algebraic = ((AlgebraicInitial) annotation).value();
                            idx = 0;
                        } else if (annotation.annotationType().equals(AlgebraicIntermed.class)) {
                            //
                            // Check that method accepts a single Tuple as parameter.
                            //
                            Class<?>[] params = method.getParameterTypes();
                            if (1 != params.length || !Tuple.class.equals(params[0])) {
                                throw new IOException(path
                                        + ": methods annotated with @AlgebraicIntermed MUST take a single groovy.lang.Tuple as parameter.");
                            }
                            if (!method.getReturnType().equals(Tuple.class)
                                    && !method.getReturnType().equals(Object[].class)) {
                                throw new IOException(path + ":" + method.getName()
                                        + " Algebraic UDF Intermed method MUST return type groovy.lang.Tuple or Object[].");
                            }
                            algebraic = ((AlgebraicIntermed) annotation).value();
                            idx = 1;
                        } else {
                            //
                            // Check that method accepts a single Tuple as parameter.
                            //
                            Class<?>[] params = method.getParameterTypes();
                            if (1 != params.length || !Tuple.class.equals(params[0])) {
                                throw new IOException(path
                                        + ": methods annotated with @AlgebraicFinal MUST take a single groovy.lang.Tuple as parameter.");
                            }
                            algebraic = ((AlgebraicFinal) annotation).value();
                            idx = 2;
                        }

                        Method[] algmethods = algebraicMethods.get(algebraic);

                        if (null == algmethods) {
                            algmethods = new Method[3];
                            algebraicMethods.put(algebraic, algmethods);
                        }

                        if (null != algmethods[idx]) {
                            throw new IOException(path + ": Algebraic UDF '" + algebraic + "' already has an "
                                    + annotation.annotationType().getSimpleName() + " method defined ('"
                                    + algmethods[idx] + "')");
                        }

                        algmethods[idx] = method;
                    } else if (isAccumulator(annotation)) {
                        String accumulator = null;

                        int idx = 0;

                        if (annotation.annotationType().equals(AccumulatorAccumulate.class)) {
                            //
                            // Check that method accepts a single Tuple as parameter.
                            //
                            Class<?>[] params = method.getParameterTypes();
                            if (1 != params.length || !Tuple.class.equals(params[0])) {
                                throw new IOException(path
                                        + ": methods annotated with @AccumulatorAccumulate MUST take a single groovy.lang.Tuple as parameter.");
                            }
                            accumulator = ((AccumulatorAccumulate) annotation).value();
                            idx = 0;
                        } else if (annotation.annotationType().equals(AccumulatorGetValue.class)) {
                            //
                            // Check that method does not accept any parameters.
                            //
                            Class<?>[] params = method.getParameterTypes();
                            if (0 != params.length) {
                                throw new IOException(path
                                        + ": methods annotated with @AccumulatorGetValue take no parameters.");
                            }
                            accumulator = ((AccumulatorGetValue) annotation).value();
                            isAccumulator = true;
                            idx = 1;
                        } else if (annotation.annotationType().equals(AccumulatorCleanup.class)) {
                            //
                            // Check that method does not accept any parameters.
                            //
                            Class<?>[] params = method.getParameterTypes();
                            if (0 != params.length) {
                                throw new IOException(path
                                        + ": methods annotated with @AccumulatorCleanup take no parameters and return void.");
                            }
                            accumulator = ((AccumulatorCleanup) annotation).value();
                            idx = 2;
                        }

                        Method[] accumethods = accumulatorMethods.get(accumulator);

                        if (null == accumethods) {
                            accumethods = new Method[3];
                            accumulatorMethods.put(accumulator, accumethods);
                        }

                        if (null != accumethods[idx]) {
                            throw new IOException(path + ": Accumulator UDF '" + accumulator
                                    + "' already has an " + annotation.annotationType().getSimpleName()
                                    + " method defined ('" + accumethods[idx] + "')");
                        }

                        accumethods[idx] = method;
                    }
                }

                //
                // Only register functions which have an output schema declared
                //

                if (null == schema && null == schemaFunction) {
                    LOG.info(path
                            + ": Only methods annotated with @OutputSchema or @OutputSchemaFunction (but not with @AccumulatorGetValue are exposed to Pig, skipping method '"
                            + method.getName() + "'");
                    continue;
                }

                //
                // Only one of OutputSchema / OutputSchemaFunction can be defined
                //

                if (null != schema && null != schemaFunction) {
                    LOG.info("Annotation @OutputSchemaFunction has precedence over @OutputSchema for method '"
                            + method.getName() + "'");
                }

                //
                // Register methods annotated with 'OutputSchema' or
                // 'OutputSchemaFunction, unless they are accumulators' getValue
                // methods
                //

                if (!isAccumulator) {
                    namespace = (namespace == null) ? "" : namespace;
                    FuncSpec spec = new FuncSpec(GroovyEvalFuncObject.class.getCanonicalName() + "('" + path
                            + "','" + namespace + "','" + method.getName() + "')");
                    pigContext.registerFunction(
                            ("".equals(namespace) ? "" : (namespace + NAMESPACE_SEPARATOR)) + method.getName(),
                            spec);
                    LOG.info(path + ": Register Groovy UDF: "
                            + ("".equals(namespace) ? "" : (namespace + NAMESPACE_SEPARATOR))
                            + method.getName());
                }
            }
        }

        //
        // Now register algebraic methods
        //

        for (String algebraic : algebraicMethods.keySet()) {

            Method[] algmethods = algebraicMethods.get(algebraic);

            if (null == algmethods[0]) {
                throw new IOException(
                        path + ": Algebratic UDF '" + algebraic + "' does not have an Initial method defined.");
            } else if (null == algmethods[1]) {
                throw new IOException(path + ": Algebratic UDF '" + algebraic
                        + "' does not have an Intermed method defined.");
            } else if (null == algmethods[2]) {
                throw new IOException(
                        path + ": Algebratic UDF '" + algebraic + "' does not have a Final method defined.");
            }

            //
            // Retrieve schema of 'Final' method
            //

            String className = null;

            Class<?> returnType = algmethods[2].getReturnType();

            if (returnType.equals(Tuple.class) || returnType.equals(Object[].class)
                    || returnType.equals(org.apache.pig.data.Tuple.class)) {
                className = TupleGroovyAlgebraicEvalFunc.class.getName();
            } else if (returnType.equals(List.class) || returnType.equals(DataBag.class)) {
                className = DataBagGroovyAlgebraicEvalFunc.class.getName();
            } else if (returnType.equals(org.joda.time.DateTime.class)) {
                className = DateTimeGroovyAlgebraicEvalFunc.class.getName();
            } else if (returnType.equals(Boolean.class) || returnType.equals(boolean.class)) {
                className = BooleanGroovyAlgebraicEvalFunc.class.getName();
            } else if (returnType.equals(byte[].class) || returnType.equals(DataByteArray.class)) {
                className = DataByteArrayGroovyAlgebraicEvalFunc.class.getName();
            } else if (returnType.equals(String.class)) {
                className = ChararrayGroovyAlgebraicEvalFunc.class.getName();
            } else if (returnType.equals(Double.class) || returnType.equals(double.class)
                    || returnType.equals(BigDecimal.class)) {
                className = DoubleGroovyAlgebraicEvalFunc.class.getName();
            } else if (returnType.equals(Float.class) || returnType.equals(float.class)) {
                className = FloatGroovyAlgebraicEvalFunc.class.getName();
            } else if (returnType.equals(Byte.class) || returnType.equals(byte.class)
                    || returnType.equals(Short.class) || returnType.equals(short.class)
                    || returnType.equals(Integer.class) || returnType.equals(int.class)) {
                className = IntegerGroovyAlgebraicEvalFunc.class.getName();
            } else if (returnType.equals(Long.class) || returnType.equals(long.class)
                    || returnType.equals(BigInteger.class)) {
                className = LongGroovyAlgebraicEvalFunc.class.getName();
            } else if (returnType.equals(Map.class)) {
                className = MapGroovyAlgebraicEvalFunc.class.getName();
            } else if (returnType.equals(BigDecimal.class)) {
                className = BigDecimalGroovyAlgebraicEvalFunc.class.getName();
            } else if (returnType.equals(BigInteger.class)) {
                className = BigIntegerGroovyAlgebraicEvalFunc.class.getName();
            } else {
                throw new RuntimeException(
                        path + ": Unknown return type for Algebraic UDF '" + algebraic + "'");
            }

            FuncSpec spec = new FuncSpec(className + "('" + path + "','" + namespace + "','" + algebraic + "','"
                    + algmethods[0].getName() + "','" + algmethods[1].getName() + "','"
                    + algmethods[2].getName() + "')");
            pigContext.registerFunction(
                    ("".equals(namespace) ? "" : (namespace + NAMESPACE_SEPARATOR)) + algebraic, spec);

            LOG.info("Register Groovy Algebraic UDF: "
                    + ("".equals(namespace) ? "" : (namespace + NAMESPACE_SEPARATOR)) + algebraic);
        }

        //
        // Now register Accumulator UDFs
        //

        for (String accumulator : accumulatorMethods.keySet()) {

            Method[] accumethods = accumulatorMethods.get(accumulator);

            if (null == accumethods[0]) {
                throw new IOException(path + ": Accumulator UDF '" + accumulator
                        + "' does not have an Accumulate method defined.");
            } else if (null == accumethods[1]) {
                throw new IOException(path + ": Accumulator UDF '" + accumulator
                        + "' does not have a GetValue method defined.");
            } else if (null == accumethods[2]) {
                throw new IOException(path + ": Accumulator UDF '" + accumulator
                        + "' does not have a Cleanup method defined.");
            }

            FuncSpec spec = new FuncSpec(GroovyAccumulatorEvalFunc.class.getName() + "('" + path + "','"
                    + namespace + "','" + accumulator + "','" + accumethods[0].getName() + "','"
                    + accumethods[1].getName() + "','" + accumethods[2].getName() + "')");
            pigContext.registerFunction(
                    ("".equals(namespace) ? "" : (namespace + NAMESPACE_SEPARATOR)) + accumulator, spec);

            LOG.info("Register Groovy Accumulator UDF: "
                    + ("".equals(namespace) ? "" : (namespace + NAMESPACE_SEPARATOR)) + accumulator);
        }
    } catch (ResourceException re) {
        throw new IOException(re);
    } catch (ScriptException se) {
        throw new IOException(se);
    }

}

From source file:edu.utah.further.core.cxf.UtilServiceRestImpl.java

/**
 * Return the list of all known RESTful services' meta data objects.
 *
 * @return a composite MD object containing a list of service meta data objects
 * @see edu.utah.further.core.metadata.service.UtilServiceRest#getAllRestServiceMd()
 *//*from  w ww.  ja  va 2s.  c  o  m*/
@Override
public MetaData getAllRestServiceMd() {
    final WsType webServiceType = WsType.REST;
    if (restServiceMd == null) {
        restServiceMd = new MetaData();

        // Build class meta data elements
        for (final Class<?> serviceClass : getRestClasses()) {
            // Process only interfaces, not implementations
            if (serviceClass.getAnnotation(Implementation.class) != null) {
                continue;
            }

            final WsElementMd classMd = new WsClassMdBuilder(webServiceType, null, serviceClass)
                    .setType(serviceClass.getName()).build();
            if (classMd == null) {
                continue;
            }
            restServiceMd.addChild(classMd);

            // Build method meta data elements
            for (final Method method : serviceClass.getMethods()) {
                final WsElementMd methodMd = new WsMethodMdBuilder(webServiceType, classMd, method)
                        .setHttpMethod(method.getAnnotations())
                        .setDocumentation(method.getAnnotation(Documentation.class))
                        .setPath(method.getAnnotation(Path.class))
                        .setExamplePath(method.getAnnotation(ExamplePath.class)).build();
                if (methodMd == null) {
                    continue;
                }
                classMd.addChild(methodMd);

                // Build field meta data elements
                final Class<?>[] parameterTypes = method.getParameterTypes();
                final Annotation[][] parameterAnnotations = method.getParameterAnnotations();
                for (int i = 0; i < parameterTypes.length; i++) {
                    final WsElementMd parameterMd = new WsParameterMdBuilder(webServiceType, methodMd)
                            .setParameterAnnotations(parameterAnnotations[i])
                            .setType(parameterTypes[i].getSimpleName()).build();
                    if (parameterMd == null) {
                        continue;
                    }
                    methodMd.addChild(parameterMd);
                }
            }
        }
    }
    return restServiceMd;
}