Example usage for java.lang.reflect Method getParameterAnnotations

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

Introduction

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

Prototype

@Override
public Annotation[][] getParameterAnnotations() 

Source Link

Usage

From source file:org.apache.tuscany.sca.binding.rest.provider.RESTBindingInvoker.java

public Message invoke(Message msg) {

    Object entity = null;//from w  w w .  j a v a 2  s  .c o m
    Object[] args = msg.getBody();

    URI uri = URI.create(endpointReference.getDeployedURI());
    UriBuilder uriBuilder = UriBuilder.fromUri(uri);

    Method method = ((JavaOperation) operation).getJavaMethod();

    if (method.isAnnotationPresent(Path.class)) {
        // Only for resource method
        uriBuilder.path(method);
    }

    if (!JAXRSHelper.isResourceMethod(method)) {
        // This is RPC over GET
        uriBuilder.replaceQueryParam("method", method.getName());
    }

    Map<String, Object> pathParams = new HashMap<String, Object>();
    Map<String, Object> matrixParams = new HashMap<String, Object>();
    Map<String, Object> queryParams = new HashMap<String, Object>();
    Map<String, Object> headerParams = new HashMap<String, Object>();
    Map<String, Object> formParams = new HashMap<String, Object>();
    Map<String, Object> cookieParams = new HashMap<String, Object>();

    for (int i = 0; i < method.getParameterTypes().length; i++) {
        boolean isEntity = true;
        Annotation[] annotations = method.getParameterAnnotations()[i];
        PathParam pathParam = getAnnotation(annotations, PathParam.class);
        if (pathParam != null) {
            isEntity = false;
            pathParams.put(pathParam.value(), args[i]);
        }
        MatrixParam matrixParam = getAnnotation(annotations, MatrixParam.class);
        if (matrixParam != null) {
            isEntity = false;
            matrixParams.put(matrixParam.value(), args[i]);
        }
        QueryParam queryParam = getAnnotation(annotations, QueryParam.class);
        if (queryParam != null) {
            isEntity = false;
            queryParams.put(queryParam.value(), args[i]);
        }
        HeaderParam headerParam = getAnnotation(annotations, HeaderParam.class);
        if (headerParam != null) {
            isEntity = false;
            headerParams.put(headerParam.value(), args[i]);
        }
        FormParam formParam = getAnnotation(annotations, FormParam.class);
        if (formParam != null) {
            isEntity = false;
            formParams.put(formParam.value(), args[i]);
        }
        CookieParam cookieParam = getAnnotation(annotations, CookieParam.class);
        if (cookieParam != null) {
            isEntity = false;
            cookieParams.put(cookieParam.value(), args[i]);
        }
        isEntity = (getAnnotation(annotations, Context.class) == null);
        if (isEntity) {
            entity = args[i];
        }
    }

    for (Map.Entry<String, Object> p : queryParams.entrySet()) {
        uriBuilder.replaceQueryParam(p.getKey(), p.getValue());
    }
    for (Map.Entry<String, Object> p : matrixParams.entrySet()) {
        uriBuilder.replaceMatrixParam(p.getKey(), p.getValue());
    }

    uri = uriBuilder.buildFromMap(pathParams);
    Resource resource = restClient.resource(uri);

    for (Map.Entry<String, Object> p : headerParams.entrySet()) {
        resource.header(p.getKey(), String.valueOf(p.getValue()));
    }

    for (Map.Entry<String, Object> p : cookieParams.entrySet()) {
        Cookie cookie = new Cookie(p.getKey(), String.valueOf(p.getValue()));
        resource.cookie(cookie);
    }

    resource.contentType(getContentType());
    resource.accept(getAccepts());

    //handles declarative headers configured on the composite
    for (HTTPHeader header : binding.getHttpHeaders()) {
        //treat special headers that need to be calculated
        if (header.getName().equalsIgnoreCase("Expires")) {
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(new Date());

            calendar.add(Calendar.HOUR, Integer.parseInt(header.getValue()));

            resource.header("Expires", HTTPCacheContext.RFC822DateFormat.format(calendar.getTime()));
        } else {
            //default behaviour to pass the header value to HTTP response
            resource.header(header.getName(), header.getValue());
        }
    }

    Object result = resource.invoke(httpMethod, responseType, entity);
    msg.setBody(result);
    return msg;
}

From source file:dinistiq.Dinistiq.java

/**
 * Injects all available dependencies into a given bean and records all dependencies.
 *
 * @param key key / name/ id of the bean
 * @param bean bean instance/*from   w w w  . j  a  v  a  2 s.  co m*/
 * @param dependencies dependencies map where the dependecies of the bean are recorded with the given key
 * @throws Exception
 */
private void injectDependencies(Map<String, Set<Object>> dependencies, String key, Object bean)
        throws Exception {
    // Prepare values from properties files
    Properties beanProperties = getProperties(key);
    LOG.debug("injectDependencies({}) bean properties {}", key, beanProperties.keySet());

    // fill injected fields
    Class<? extends Object> beanClass = bean.getClass();
    String beanClassName = beanClass.getName();
    while (beanClass != Object.class) {
        if (bean instanceof Map) {
            fillMap(bean, getProperties(key));
            LOG.info("injectDependencies() filled map '{}' {}", key, bean);
            return; // If it's a map we don't need to inject anything beyond some map properties files.
        } // if
        for (Field field : beanClass.getDeclaredFields()) {
            LOG.debug("injectDependencies({}) field {}", key, field.getName());
            if (field.getAnnotation(Inject.class) != null) {
                Named named = field.getAnnotation(Named.class);
                String name = (named == null) ? null
                        : (StringUtils.isBlank(named.value()) ? field.getName() : named.value());
                LOG.info("injectDependencies({}) {} :{} needs injection with name {}", key, field.getName(),
                        field.getGenericType(), name);
                Object b = getValue(beanProperties, dependencies, key, field.getType(), field.getGenericType(),
                        name);
                final boolean accessible = field.isAccessible();
                try {
                    field.setAccessible(true);
                    field.set(bean, b);
                } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
                    LOG.error("injectDependencies() error setting field " + field.getName() + " :"
                            + field.getType().getName() + " at '" + key + "' :" + beanClassName, e);
                } finally {
                    field.setAccessible(accessible);
                } // try/catch
            } // if
        } // for
        beanClass = beanClass.getSuperclass();
    } // while

    // call methods with annotated injections
    for (Method m : bean.getClass().getMethods()) {
        if (m.getAnnotation(Inject.class) != null) {
            LOG.debug("injectDependencies({}) inject parameters on method {}", key, m.getName());
            Class<? extends Object>[] parameterTypes = m.getParameterTypes();
            Type[] genericParameterTypes = m.getGenericParameterTypes();
            Annotation[][] parameterAnnotations = m.getParameterAnnotations();
            Object[] parameters = getParameters(beanProperties, dependencies, key, parameterTypes,
                    genericParameterTypes, parameterAnnotations);
            try {
                m.invoke(bean, parameters);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                LOG.error("injectDependencies() error injecting for method " + m.getName() + " at '" + key
                        + "' :" + beanClassName, ex);
            } // try/catch
        } // if
    } // for

    // Fill in manually set values from properties file
    for (String property : beanProperties.stringPropertyNames()) {
        String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1);
        LOG.debug("injectDependencies({}) {} -> {}", key, property, methodName);
        Method m = null;
        // Have to find it just by name
        for (Method me : bean.getClass().getMethods()) {
            if (me.getName().equals(methodName) && (me.getParameterTypes().length > 0)) {
                m = me;
            } // if
        } // for
        if (m == null) {
            LOG.warn("injectDependencies({}) no setter method found for property {}", key, property);
        } else {
            String propertyName = Introspector.decapitalize(m.getName().substring(3));
            Class<?> parameterType = m.getParameterTypes()[0];
            Type genericType = m.getGenericParameterTypes()[0];
            LOG.debug("injectDependencies({}) writable property found {} :{} {}", key, propertyName,
                    parameterType, genericType);
            String propertyValue = beanProperties.getProperty(propertyName); // Must definetely be there without additional check
            boolean isBoolean = (parameterType == Boolean.class) || (m.getParameterTypes()[0] == Boolean.TYPE);
            boolean isCollection = Collection.class.isAssignableFrom(parameterType);
            Object[] parameters = new Object[1];
            LOG.debug("injectDependencies({}) trying to set value {} (bool {}) (collection {}) '{}'", key,
                    propertyName, isBoolean, isCollection, propertyValue);
            try {
                parameters[0] = getReferenceValue(propertyValue);
                if (isBoolean && (parameters[0] instanceof String)) {
                    parameters[0] = Boolean.valueOf(propertyValue);
                } // if
                if ("long".equals(parameterType.getName())) {
                    parameters[0] = new Long(propertyValue);
                } // if
                if ("int".equals(parameterType.getName())) {
                    parameters[0] = new Integer(propertyValue);
                } // if
                if ("float".equals(parameterType.getName())) {
                    parameters[0] = new Float(propertyValue);
                } // if
                if ("double".equals(parameterType.getName())) {
                    parameters[0] = new Double(propertyValue);
                } // if
                if (isCollection) {
                    if (!Collection.class.isAssignableFrom(parameters[0].getClass())) {
                        Collection<Object> values = List.class.isAssignableFrom(parameterType)
                                ? new ArrayList<>()
                                : new HashSet<>();
                        for (String value : propertyValue.split(",")) {
                            values.add(getReferenceValue(value));
                        } // for
                        parameters[0] = values;
                    } // if
                    if (dependencies != null) {
                        for (Object d : (Collection<?>) parameters[0]) {
                            if (beans.containsValue(d)) {
                                dependencies.get(key).add(d);
                            } // if
                        } // if
                    } // if
                } else {
                    if ((dependencies != null) && (beans.containsValue(parameters[0]))) {
                        dependencies.get(key).add(parameters[0]);
                    } // if
                } // if
                LOG.debug("injectDependencies({}) setting value {} '{}' :{}", key, propertyName, parameters[0],
                        parameters[0].getClass());
                m.invoke(bean, parameters);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                LOG.error("injectDependencies() error setting property " + propertyName + " to '"
                        + propertyValue + "' at " + key + " :" + beanClassName, ex);
            } // try/catch
        } // if
    } // for
}

From source file:org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.java

/**
 * @param executeMethod/*from www . j  a v a  2s  . c  o m*/
 * @param annotatedMethod
 * @param tlContext
 * @param leaveEncoded
 * @param jaxRsProviders
 * @param extensionBackwardMapping
 * @param entityAllowed
 * @param logger
 * @throws MissingAnnotationException
 * @throws IllegalTypeException
 *             if one of the parameters contains a &#64;{@link Context} on
 *             an type that must not be annotated with &#64;{@link Context}.
 * @throws IllegalPathParamTypeException
 */
public ParameterList(Method executeMethod, Method annotatedMethod, ThreadLocalizedContext tlContext,
        boolean leaveEncoded, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping,
        boolean entityAllowed, Logger logger)
        throws MissingAnnotationException, IllegalTypeException, IllegalPathParamTypeException {
    this(executeMethod.getParameterTypes(), executeMethod.getGenericParameterTypes(),
            annotatedMethod.getParameterAnnotations(), tlContext, leaveEncoded, jaxRsProviders,
            extensionBackwardMapping, true, entityAllowed, logger, true);
}

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.  j av a2  s.  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;
}

From source file:com.lhings.java.LhingsDevice.java

private com.lhings.java.model.Action autoconfigureAction(Method actionMethod) throws InitializationException {
    Action action = actionMethod.getAnnotation(Action.class);
    String actionName, actionDescription;
    String[] argumentNames;//from   w  w w  . j  av a 2 s. c  om
    actionName = action.name();
    actionDescription = action.description();
    if (actionName.isEmpty() || !actionName.matches("^[a-zA-Z0-9_]*$")) {
        actionName = actionMethod.getName();
    }

    Annotation[][] parameterAnnotations = actionMethod.getParameterAnnotations();
    if (parameterAnnotations.length == 1 && parameterAnnotations[0].length == 1) {
        // method has only one parameter and it is annotated, check if annotation is @Payload
        if (parameterAnnotations[0][0].annotationType().equals(Payload.class)) {
            com.lhings.java.model.Action returnAction = new com.lhings.java.model.Action(actionName, "",
                    new ArrayList<Argument>(), null);
            returnAction.setPayloadNeeded(true);
            // store method so that it is easier to access later
            if (!actionMethods.keySet().contains(actionName)) {
                actionMethods.put(actionName, actionMethod);
            } else {
                throw new InitializationException("Duplicated action names: methods " + actionMethod.getName()
                        + " and " + actionMethods.get(actionName).getName()
                        + " were both mapped to the same action name " + actionName + ".");
            }
            return returnAction;
        }
    }

    argumentNames = action.argumentNames();
    Class<?>[] arguments = actionMethod.getParameterTypes();
    if (argumentNames.length != arguments.length) {
        throw new InitializationException("Initialization failed for device with uuid " + uuid
                + ". Names were provided for " + argumentNames.length + " arguments but method "
                + actionMethod.getName() + " declares " + arguments.length + " arguments.");
    }
    List<Argument> modelArguments = new ArrayList<Argument>();
    for (int j = 0; j < arguments.length; j++) {
        String declaredType = arguments[j].getName();
        String argumentType;
        try {
            argumentType = tellLhingsType(declaredType);
        } catch (InitializationException ex) {
            // rethrow with appropriate message
            throw new InitializationException("Initialization failed for device with uuid " + uuid + ". Type "
                    + declaredType + " is not allowed for parameters in method " + actionMethod.getName()
                    + ". Methods annotated with @Action can only have parameters of the following types: int, float, double, boolean, String and java.util.Date.");
        }

        modelArguments.add(new Argument(argumentNames[j], argumentType));
    }

    // store method so that it is easier to access later
    if (!actionMethods.keySet().contains(actionName)) {
        actionMethods.put(actionName, actionMethod);
    } else {
        throw new InitializationException("Duplicated action names: methods " + actionMethod.getName() + " and "
                + actionMethods.get(actionName).getName() + " were both mapped to the same action name "
                + actionName + ".");
    }

    com.lhings.java.model.Action returnAction = new com.lhings.java.model.Action(actionName, actionDescription,
            modelArguments, null);

    return returnAction;
}

From source file:org.zkoss.zk.grails.composer.GrailsComposer.java

/**
 * <p>Overrides GenericEventListener to use InvokerHelper to call methods. Because of this the events are now
 * part of groovy's dynamic methods, e.g. metaClass.invokeMethod works for event methods. Without this the default java code
 * don't call the overriden invokeMethod</p>
 *
 * @param event Event object/*  w w  w  .j a  va2 s. c  o  m*/
 * @throws Exception
 */
@Override
public void onEvent(Event event) throws Exception {
    try {
        final Object controller = getController();
        final Method[] methods = getHandlerMethod(controller.getClass(), event);
        if (methods.length == 0)
            return;
        for (Method method : methods) {
            if (method != null) {
                if (method.getParameterTypes().length == 0) {
                    InvokerHelper.invokeMethod(controller, method.getName(), null);
                } else if (event instanceof ForwardEvent) { //ForwardEvent
                    final Class<?> paramcls = method.getParameterTypes()[0];
                    //paramcls is ForwardEvent || Event
                    if (ForwardEvent.class.isAssignableFrom(paramcls) || Event.class.equals(paramcls)) {
                        InvokerHelper.invokeMethod(controller, method.getName(), new Object[] { event });
                    } else {
                        do {
                            event = ((ForwardEvent) event).getOrigin();
                        } while (event instanceof ForwardEvent);
                        InvokerHelper.invokeMethod(controller, method.getName(), new Object[] { event });
                    }
                } else {
                    Annotation[][] anns = method.getParameterAnnotations();
                    // one parameter, and annotation-less
                    if (anns.length == 1 && anns[0].length == 0) {
                        InvokerHelper.invokeMethod(controller, method.getName(), new Object[] { event });
                    } /* else {
                      Object[] params = new Object[anns.length];
                      int i = 0;
                      for(Annotation[] paramAnno: anns) {
                          for(Annotation a: paramAnno) {
                              if(a instanceof Attr) {
                                  String attrName = ((Attr) a).value();
                                  params[i] = ComponentUtil.attr(event.getTarget(), attrName);
                                  break;
                              }
                          }
                          i++;
                      }
                      InvokerHelper.invokeMethod(controller, method.getName(), params);
                      }*/
                }
            }
        }
    } catch (Exception e) {
        // grails.util.GrailsUtil.printSanitizedStackTrace(e);
        throw e;
    }
}

From source file:com.strandls.alchemy.rest.client.RestInterfaceAnalyzer.java

/**
 * Get rest meta data for the method./*  ww w  . j  a v  a  2 s .c  o  m*/
 *
 * @param method
 *            the method to analyze.
 * @return the metadata for a method.
 */
private RestMethodMetadata analyzeMethod(final Method method) {
    String path = "";
    String httpMethod = null;
    final List<String> produced = new ArrayList<String>();
    final List<String> consumed = new ArrayList<String>();

    final Annotation[] annotations = method.getDeclaredAnnotations();
    for (final Annotation annotation : annotations) {
        if (annotation instanceof Path) {
            path = ((Path) annotation).value();
        } else if (annotation instanceof GET) {
            httpMethod = HttpMethod.GET;
        } else if (annotation instanceof PUT) {
            httpMethod = HttpMethod.PUT;
        } else if (annotation instanceof POST) {
            httpMethod = HttpMethod.POST;
        } else if (annotation instanceof DELETE) {
            httpMethod = HttpMethod.DELETE;
        } else if (annotation instanceof Produces) {
            final Produces produces = (Produces) annotation;
            produced.addAll(Arrays.asList(produces.value()));
        } else if (annotation instanceof Consumes) {
            final Consumes consumes = (Consumes) annotation;
            consumed.addAll(Arrays.asList(consumes.value()));
        }
    }

    if (StringUtils.isBlank(httpMethod)) {
        // no http method specified.
        return null;
    }
    return new RestMethodMetadata(path, httpMethod, produced, consumed, method.getParameterAnnotations());
}

From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSOperationBinding.java

/**
 * Loads the set of input properties for the specified operation.
 *
 * @param op The operation./*from w  w  w  .ja v a2s  . c  om*/
 * @return The input properties, or null if none were found.
 */
protected OperationBeanInfo getRequestInfo(OperationInfo op) throws XFireFault {
    Method method = op.getMethod();
    Class ei = method.getDeclaringClass();
    Package pckg = ei.getPackage();
    SOAPBinding.ParameterStyle paramStyle = SOAPBinding.ParameterStyle.WRAPPED;
    if (method.isAnnotationPresent(SOAPBinding.class)) {
        SOAPBinding annotation = method.getAnnotation(SOAPBinding.class);
        paramStyle = annotation.parameterStyle();
    } else if (ei.isAnnotationPresent(SOAPBinding.class)) {
        SOAPBinding annotation = ((SOAPBinding) ei.getAnnotation(SOAPBinding.class));
        paramStyle = annotation.parameterStyle();
    }

    boolean schemaValidate = method.isAnnotationPresent(SchemaValidate.class)
            || ei.isAnnotationPresent(SchemaValidate.class) || pckg.isAnnotationPresent(SchemaValidate.class);

    if (paramStyle == SOAPBinding.ParameterStyle.BARE) {
        //return a bare operation info.
        //it's not necessarily the first parameter type! there could be a header or OUT parameter...
        int paramIndex;
        WebParam annotation = null;
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        if (parameterAnnotations.length == 0) {
            throw new IllegalStateException("A BARE web service must have input parameters.");
        }

        PARAM_ANNOTATIONS: for (paramIndex = 0; paramIndex < parameterAnnotations.length; paramIndex++) {
            Annotation[] annotations = parameterAnnotations[paramIndex];
            for (Annotation candidate : annotations) {
                if (candidate instanceof WebParam && !((WebParam) candidate).header()) {
                    WebParam.Mode mode = ((WebParam) candidate).mode();
                    switch (mode) {
                    case OUT:
                    case INOUT:
                        annotation = (WebParam) candidate;
                        break PARAM_ANNOTATIONS;
                    }
                }
            }
        }

        if (annotation == null) {
            paramIndex = 0;
        }

        return new OperationBeanInfo(method.getParameterTypes()[paramIndex], null, op.getInputMessage(),
                schemaValidate);
    } else {
        String requestWrapperClassName;
        RequestWrapper requestWrapperInfo = method.getAnnotation(RequestWrapper.class);
        if ((requestWrapperInfo != null) && (requestWrapperInfo.className() != null)
                && (requestWrapperInfo.className().length() > 0)) {
            requestWrapperClassName = requestWrapperInfo.className();
        } else {
            StringBuilder builder = new StringBuilder(pckg == null ? "" : pckg.getName());
            if (builder.length() > 0) {
                builder.append(".");
            }

            builder.append("jaxws.");

            String methodName = method.getName();
            builder.append(capitalize(methodName));
            requestWrapperClassName = builder.toString();
        }

        Class wrapperClass;
        try {
            wrapperClass = ClassLoaderUtils.loadClass(requestWrapperClassName, getClass());
        } catch (ClassNotFoundException e) {
            LOG.error("Unabled to find request wrapper class " + requestWrapperClassName + "... Operation "
                    + op.getQName() + " will not be able to recieve...");
            return null;
        }

        return new OperationBeanInfo(wrapperClass, loadOrderedProperties(wrapperClass), op.getInputMessage(),
                schemaValidate);
    }

}

From source file:org.xframium.integrations.perfectoMobile.rest.services.RESTInvocationHandler.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    CloudDescriptor currentCloud = DeviceManager.instance().getCurrentCloud();
    if (currentCloud != null && !currentCloud.getProvider().equals("PERFECTO"))
        return null;

    StringBuilder urlBuilder = new StringBuilder();

    ////from  w  ww.j a  va2  s . co m
    // If the factory specified a cloud descriptor then use that URL
    //
    if (currentCloud != null)
        urlBuilder.append("https://" + currentCloud.getHostName()).append(SLASH);
    else {
        urlBuilder.append(PerfectoMobile.instance().getBaseUrl());

        if (!PerfectoMobile.instance().getBaseUrl().endsWith(SLASH))
            urlBuilder.append(SLASH);
    }

    urlBuilder.append("services/");

    ServiceDescriptor serviceDescriptor = proxy.getClass().getInterfaces()[0]
            .getAnnotation(ServiceDescriptor.class);
    if (serviceDescriptor == null)
        throw new IllegalArgumentException("Service Descriptor was NOT found");

    urlBuilder.append(serviceDescriptor.serviceName());

    String parameterId = "";
    Map parameterMap = null;
    Map<String, String> derivedMap = new HashMap<String, String>(10);

    Annotation[][] parameterAnnotations = method.getParameterAnnotations();

    for (int i = 0; i < method.getParameterTypes().length; i++) {
        if (getAnnotation(parameterAnnotations[i], ResourceID.class) != null)
            parameterId = parameterId + SLASH + args[i] + "";
        else if (getAnnotation(parameterAnnotations[i], ParameterMap.class) != null)
            parameterMap = (Map) parameterMap;
        else if (getAnnotation(parameterAnnotations[i], Parameter.class) != null) {
            if (args[i] != null) {
                Parameter paramAnnotation = (Parameter) getAnnotation(parameterAnnotations[i], Parameter.class);
                if (paramAnnotation.name().isEmpty())
                    derivedMap.put(PARAM + method.getParameterTypes()[i].getName(), args[i] + "");
                else
                    derivedMap.put(PARAM + paramAnnotation.name(), args[i] + "");
            }
        } else {
            if (args[i] != null) {
                String parameterName = method.getParameterTypes()[i].getName();
                NameOverride namedParameter = (NameOverride) getAnnotation(parameterAnnotations[i],
                        NameOverride.class);
                if (namedParameter != null && !namedParameter.name().isEmpty())
                    parameterName = namedParameter.name();

                derivedMap.put(parameterName, args[i] + "");
            }
        }
    }

    if (!parameterId.isEmpty())
        urlBuilder.append(parameterId);

    Method actualMethod = findMethod(proxy.getClass().getInterfaces()[0], method.getName(), args);

    Operation op = actualMethod.getAnnotation(Operation.class);
    if (op == null)
        throw new IllegalArgumentException("Operation was NOT found");

    urlBuilder.append("?operation=").append(op.operationName());

    //
    // If the factory specified a cloud descriptor then use those credentials
    //
    if (currentCloud != null) {
        urlBuilder.append("&user=").append(currentCloud.getUserName());
        urlBuilder.append("&password=").append(currentCloud.getPassword());
    } else {
        urlBuilder.append("&user=").append(PerfectoMobile.instance().getUserName());
        urlBuilder.append("&password=").append(PerfectoMobile.instance().getPassword());
    }

    PerfectoCommand command = actualMethod.getAnnotation(PerfectoCommand.class);
    if (command != null) {
        urlBuilder.append("&command=").append(command.commandName());
        if (command.subCommandName() != null && !command.subCommandName().isEmpty())
            urlBuilder.append("&subcommand=").append(command.subCommandName());
    }

    urlBuilder.append("&responseFormat=").append(PerfectoMobile.instance().getResponseMethod());

    for (String name : derivedMap.keySet())
        urlBuilder.append("&").append(name).append("=")
                .append(URLEncoder.encode(derivedMap.get(name), "UTF-8"));

    if (parameterMap != null) {
        for (Object name : parameterMap.keySet())
            urlBuilder.append("&").append(name).append("=")
                    .append(URLEncoder.encode(parameterMap.get(name) + "", "UTF-8"));
    }

    URL currentUrl = new URL(urlBuilder.toString());
    if (log.isInfoEnabled())
        log.info("Submitting REST call as " + urlBuilder.toString());

    if (method.getReturnType().isAssignableFrom(byte[].class)) {
        //
        // Byte Array is a special case that is not wrapped in XML
        //
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[512];
        int bytesRead = 0;
        InputStream inputStream = currentUrl.openStream();

        while ((bytesRead = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, bytesRead);
        }

        return outputStream.toByteArray();
    }

    try {
        Bean newBean = BeanManager.instance().createBean(method.getReturnType(), currentUrl.openStream());
        return newBean;
    } catch (IOException e) {
        log.error("Could not connect to the cloud instance - Verify your user name, password and Cloud URL", e);
        return null;
    }

}

From source file:org.statefulj.framework.binders.common.AbstractRestfulBinder.java

protected void addRequestParameters(boolean referencesId, Class<?> idType, boolean isDomainEntity,
        CtMethod ctMethod, Method method, ClassPool cp) throws NotFoundException, IllegalArgumentException,
        IllegalAccessException, InvocationTargetException, CannotCompileException {

    int fixedParmCnt = (isDomainEntity) ? 1 : 2;

    String[] parmNames = (method != null) ? parmDiscover.getParameterNames(method) : null;
    MethodInfo methodInfo = ctMethod.getMethodInfo();
    ParameterAnnotationsAttribute paramAtrributeInfo = new ParameterAnnotationsAttribute(
            methodInfo.getConstPool(), ParameterAnnotationsAttribute.visibleTag);

    Annotation[][] paramArrays = null;
    if (method != null) {

        int parmIndex = 0;

        // Does this event reference the stateful object?
        ////from w  w w.  j ava  2 s  .c om
        int additionalParmCnt = (referencesId) ? 2 : 1;
        int annotationCnt = method.getParameterTypes().length + additionalParmCnt - fixedParmCnt;
        annotationCnt = Math.max(annotationCnt, additionalParmCnt);

        // Pull the Parameter Annotations from the StatefulController - we're going to skip
        // over the first one (DomainEntity) or two (Controller) - but then we're going to 
        // add a parameter for the HttpServletRequest and "id" parameter
        //
        java.lang.annotation.Annotation[][] parmAnnotations = method.getParameterAnnotations();
        paramArrays = new Annotation[annotationCnt][];

        // Add an Id parameter at the beginning of the method - this will be 
        // used by the Harness to fetch the object 
        //
        if (referencesId) {
            paramArrays[parmIndex] = addIdParameter(ctMethod, idType, cp);
            parmIndex++;
        }

        // Add an HttpServletRequest - this will be passed in as a context to the finder/factory methods
        //
        paramArrays[parmIndex] = addHttpRequestParameter(ctMethod, cp);
        parmIndex++;

        int parmCnt = 0;
        for (Class<?> parm : method.getParameterTypes()) {

            // Skip first two parameters - they are the Stateful Object and event String.
            //
            if (parmCnt < fixedParmCnt) {
                parmCnt++;
                continue;
            }

            // Clone the parameter Class
            //
            CtClass ctParm = cp.get(parm.getName());

            // Add the parameter to the method
            //
            ctMethod.addParameter(ctParm);

            // Add the Parameter Annotations to the Method
            //
            String parmName = (parmNames != null && parmNames.length > parmCnt) ? parmNames[parmCnt] : null;
            paramArrays[parmIndex] = createParameterAnnotations(parmName, ctMethod.getMethodInfo(),
                    parmAnnotations[parmCnt], paramAtrributeInfo.getConstPool());
            parmCnt++;
            parmIndex++;
        }
    } else {
        // NOOP transitions always a require an object Id
        //
        paramArrays = new Annotation[2][];
        paramArrays[0] = addIdParameter(ctMethod, idType, cp);
        paramArrays[1] = addHttpRequestParameter(ctMethod, cp);
    }
    paramAtrributeInfo.setAnnotations(paramArrays);
    methodInfo.addAttribute(paramAtrributeInfo);
}