Package com.google.gwt.core.ext.typeinfo

Examples of com.google.gwt.core.ext.typeinfo.JParameter


            // the last arg should be the callback.
            if (args.isEmpty()) {
                getLogger().log(ERROR, "Invalid rest method. Method must declare at least a callback argument: " + method.getReadableDeclaration());
                throw new UnableToCompleteException();
            }
            JParameter callbackArg = args.removeLast();
            JClassType callbackType = callbackArg.getType().isClassOrInterface();
            JClassType methodCallbackType = METHOD_CALLBACK_TYPE;
            if (callbackType == null || !callbackType.isAssignableTo(methodCallbackType)) {
                getLogger().log(ERROR, "Invalid rest method. Last argument must be a " + methodCallbackType.getName() + " type: " + method.getReadableDeclaration());
                throw new UnableToCompleteException();
            }
            JClassType resultType = getCallbackTypeGenericClass(callbackType);

            String pathExpression = null;
            Path pathAnnotation = getAnnotation(method, Path.class);
            if (pathAnnotation != null) {
                pathExpression = wrap(pathAnnotation.value());
            }

            JParameter contentArg = null;
            HashMap<String, JParameter> queryParams = new HashMap<String, JParameter>();
            HashMap<String, JParameter> formParams = new HashMap<String, JParameter>();
            HashMap<String, JParameter> headerParams = new HashMap<String, JParameter>();

            for (JParameter arg : args) {
                PathParam paramPath = getAnnotation(arg, PathParam.class);
                if (paramPath != null) {
                    if (pathExpression == null) {
                        getLogger().log(ERROR, "Invalid rest method.  Invalid @PathParam annotation. Method is missing the @Path annotation: " + method.getReadableDeclaration());
                        throw new UnableToCompleteException();
                    }
                    pathExpression = pathExpression(pathExpression, arg, paramPath);
                    //.replaceAll(Pattern.quote("{" + paramPath.value() + "}"), "\"+com.google.gwt.http.client.URL.encodePathSegment(" + toStringExpression(arg) + ")+\"");
                    if (getAnnotation(arg, Attribute.class) != null) {
                        // allow part of the arg-object participate in as PathParam and the object goes over the wire
                        contentArg = arg;
                    }
                    continue;
                }

                QueryParam queryParam = getAnnotation(arg, QueryParam.class);
                if (queryParam != null) {
                    queryParams.put(queryParam.value(), arg);
                    continue;
                }

                FormParam formParam = getAnnotation(arg, FormParam.class);
                if (formParam != null) {
                    formParams.put(formParam.value(), arg);
                    continue;
                }

                HeaderParam headerParam = getAnnotation(arg, HeaderParam.class);
                if (headerParam != null) {
                    headerParams.put(headerParam.value(), arg);
                    continue;
                }

                if (!formParams.isEmpty()) {
                    getLogger().log(ERROR, "You can not have both @FormParam parameters and a content parameter: " +
                                                method.getReadableDeclaration());
                    throw new UnableToCompleteException();
                }

                if (contentArg != null) {
                    getLogger().log(ERROR, "Invalid rest method. Only one content parameter is supported: " + method.getReadableDeclaration());
                    throw new UnableToCompleteException();
                }
                contentArg = arg;
            }

            String acceptTypeBuiltIn = null;
            if (callbackType.equals(TEXT_CALLBACK_TYPE)) {
                acceptTypeBuiltIn = "CONTENT_TYPE_TEXT";
            } else if (callbackType.equals(JSON_CALLBACK_TYPE)) {
                acceptTypeBuiltIn = "CONTENT_TYPE_JSON";
            } else if (callbackType.isAssignableTo(OVERLAY_CALLBACK_TYPE)) {
                acceptTypeBuiltIn = "CONTENT_TYPE_JSON";
            } else if (callbackType.equals(XML_CALLBACK_TYPE)) {
                acceptTypeBuiltIn = "CONTENT_TYPE_XML";
            }

            p("final " + METHOD_CLASS + " __method =");

            p("getResource()");
            if (pathExpression != null) {
                p(".resolve(" + pathExpression + ")");
            }
            for (Map.Entry<String, JParameter> entry : queryParams.entrySet()) {
                String expr = entry.getValue().getName();
                JClassType type = entry.getValue().getType().isClassOrInterface();
                if (type != null && isQueryParamListType(type)) {
                    p(".addQueryParams(" + wrap(entry.getKey()) + ", " +
                      toIteratedStringExpression(entry.getValue()) + ")");
                } else {
                    p(".addQueryParam(" + wrap(entry.getKey()) + ", " +
                      toStringExpression(entry.getValue().getType(), expr) + ")");
                }
            }
            // example: .get()
            p("." + restMethod + "();");

            // Handle JSONP specific configuration...
            JSONP jsonpAnnotation = getAnnotation(method, JSONP.class);

            final boolean isJsonp = restMethod.equals(METHOD_JSONP) && jsonpAnnotation!=null;
            if( isJsonp ) {
                if (returnRequest && !method.getReturnType().getQualifiedSourceName().equals(JsonpRequest.class.getName())) {
                    getLogger().log(ERROR, "Invalid rest method. JSONP method must have void or JsonpRequest return types: " + method.getReadableDeclaration());
                    throw new UnableToCompleteException();
                }
                if( jsonpAnnotation.callbackParam().length() > 0 ) {
                    p("(("+JSONP_METHOD_CLASS+")__method).callbackParam("+wrap(jsonpAnnotation.callbackParam())+");");
                }
                if( jsonpAnnotation.failureCallbackParam().length() > 0 ) {
                    p("(("+JSONP_METHOD_CLASS+")__method).failureCallbackParam("+wrap(jsonpAnnotation.failureCallbackParam())+");");
                }
            } else {
                if (returnRequest && !method.getReturnType().getQualifiedSourceName().equals(Request.class.getName())) {
                    getLogger().log(ERROR, "Invalid rest method. Non JSONP method must have void or Request return types: " + method.getReadableDeclaration());
                    throw new UnableToCompleteException();
                }
            }

            // configure the dispatcher
            if( options!=null && options.dispatcher()!=Dispatcher.class ) {
                // use the dispatcher configured for the method.
                p("__method.setDispatcher("+options.dispatcher().getName()+".INSTANCE);");
            } else {
                // use the default dispatcher configured for the service..
                p("__method.setDispatcher(this.dispatcher);");
            }

            // configure the expected statuses..
            if( options!=null && options.expect().length!=0 ) {
                // Using method level defined expected status
                p("__method.expect("+join(options.expect(), ", ")+");");
            } else if( classOptions!=null && classOptions.expect().length!=0 ) {
                // Using class level defined expected status
                p("__method.expect("+join(classOptions.expect(), ", ")+");");
            }

            // configure the timeout
            if( options!=null && options.timeout() >= 0 ) {
                // Using method level defined value
                p("__method.timeout("+options.timeout()+");");
            } else if( classOptions!=null && classOptions.timeout() >= 0 ) {
                // Using class level defined value
                p("__method.timeout("+classOptions.timeout()+");");
            }

            if(jsonpAnnotation == null) {
                Produces producesAnnotation = findAnnotationOnMethodOrEnclosingType(method, Produces.class);
                if (producesAnnotation != null) {
                    p("__method.header(" + RESOURCE_CLASS + ".HEADER_ACCEPT, "+wrap(producesAnnotation.value()[0])+");");
                } else {
                    // set the default accept header....
                    if (acceptTypeBuiltIn != null) {
                        p("__method.header(" + RESOURCE_CLASS + ".HEADER_ACCEPT, " + RESOURCE_CLASS + "." + acceptTypeBuiltIn + ");");
                    } else {
                        p("__method.header(" + RESOURCE_CLASS + ".HEADER_ACCEPT, " + RESOURCE_CLASS + ".CONTENT_TYPE_JSON);");
                    }
                }

                Consumes consumesAnnotation = findAnnotationOnMethodOrEnclosingType(method, Consumes.class);
                if (consumesAnnotation != null) {
                    p("__method.header(" + RESOURCE_CLASS + ".HEADER_CONTENT_TYPE, "+wrap(consumesAnnotation.value()[0])+");");
                }

                // and set the explicit headers now (could override the accept header)
                for (Map.Entry<String, JParameter> entry : headerParams.entrySet()) {
                    String expr = entry.getValue().getName();
                    p("__method.header(" + wrap(entry.getKey()) + ", " + toStringExpression(entry.getValue().getType(), expr) + ");");
                }
            }

            if (! formParams.isEmpty()) {
                p(FORM_POST_CONTENT_CLASS + " __formPostContent = new " + FORM_POST_CONTENT_CLASS + "();");

                for (Map.Entry<String, JParameter> entry : formParams.entrySet()) {
                    JClassType type = entry.getValue().getType()
                            .isClassOrInterface();
                    if (type != null && isQueryParamListType(type)) {
                        p("__formPostContent.addParameters(" +
                                wrap(entry.getKey()) + ", " +
                                toIteratedFormStringExpression(entry.getValue(), classStyle) +
                                ");");
                    } else {
                        p("__formPostContent.addParameter(" +
                                wrap(entry.getKey()) + ", " +
                                toFormStringExpression(entry.getValue(), classStyle) +
                                ");");
                    }
                }

                p("__method.form(__formPostContent.getTextContent());");
            }

            if (contentArg != null) {
                if (contentArg.getType() == STRING_TYPE) {
                    p("__method.text(" + contentArg.getName() + ");");
                } else if (contentArg.getType() == JSON_VALUE_TYPE) {
                    p("__method.json(" + contentArg.getName() + ");");
                } else if (contentArg.getType().isClass() != null &&
                           isOverlayArrayType(contentArg.getType().isClass())) {
                    p("__method.json(new " + JSON_ARRAY_CLASS + "(" + contentArg.getName() + "));");
                } else if (contentArg.getType().isClass() != null &&
                           contentArg.getType().isClass().isAssignableTo(OVERLAY_VALUE_TYPE)) {
                    p("__method.json(new " + JSON_OBJECT_CLASS + "(" + contentArg.getName() + "));");
                } else if (contentArg.getType() == DOCUMENT_TYPE) {
                    p("__method.xml(" + contentArg.getName() + ");");
                } else {
                    JClassType contentClass = contentArg.getType().isClass();
                    if (contentClass == null) {
                        contentClass = contentArg.getType().isClassOrInterface();
                        if (!locator.isCollectionType(contentClass)) {
                            getLogger().log(ERROR, "Content argument must be a class.");
                            throw new UnableToCompleteException();
                        }
                    }

                    jsonAnnotation = getAnnotation(contentArg, Json.class);
                    Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle;

                    // example:
                    // .json(Listings$_Generated_JsonEncoder_$.INSTANCE.encode(arg0)
                    // )
                    p("__method.json(" + locator.encodeExpression(contentClass, contentArg.getName(), style) + ");");
                }
            }


            List<AnnotationResolver> annotationResolvers = getAnnotationResolvers(context, getLogger());
View Full Code Here


            if (i > 0) {
                writer.print(", ");
            }
            writer.print("ginjector");

            JParameter parameter = parameters[i];
            final JClassType returnType = parameter.getType().isClassOrInterface();
            if (!returnType.equals(ginjectorInspector.getGinjectorClass())) {
                writer.print(".");
                writer.print(ginjectorInspector.findGetMethod(returnType));
                writer.print("()");
            }
View Full Code Here

    for (Entry<String, String> property : localizedValues.entrySet()) {
      String key = property.getKey();
      String value = property.getValue();

      JParameter param = unfilledRequiredParams.get(key);
      if (param != null) {
        if (!isString(writer, param)) {
          writer.die("In %s, cannot appply message attribute to non-string "
              + "constructor argument %s %s.", elem,
              param.getType().getSimpleSourceName(), key);
        }

        requiredValues.put(key, value);
        unfilledRequiredParams.remove(key);
     } else {
        JMethod setter = ownerFieldClass.getSetter(key);
        JParameter[] params = setter == null ? null : setter.getParameters();

        if (setter == null || !(params.length == 1)
            || !isString(writer, params[0])) {
          writer.die("In %s, no method found to apply message attribute %s",
              elem, key);
        } else {
          setterValues.put(key, value);
        }
      }
    }

    // Now go through the element and dispatch its attributes, remembering
    // that constructor arguments get first dibs
    for (int i = elem.getAttributeCount() - 1; i >= 0; i--) {
      // Backward traversal b/c we're deleting attributes from the xml element

      XMLAttribute attribute = elem.getAttribute(i);

      // Ignore xmlns attributes
      if (attribute.getName().startsWith("xmlns:")) {
        continue;
      }

      String propertyName = attribute.getLocalName();
      if (setterValues.keySet().contains(propertyName)
          || requiredValues.containsKey(propertyName)) {
        // TODO(rjrjr) A fine example of why res: namespace hack must die
        writer.die("Duplicate attribute name: %s", propertyName);
      }

      if (unfilledRequiredParams.keySet().contains(propertyName)) {
        JParameter parameter = unfilledRequiredParams.get(propertyName);
        AttributeParser parser =
            writer.getAttributeParser(attribute, parameter);
        if (parser == null) {
          writer.die("In %s, unable to parse %s as constructor argument "
              + "of type %s", elem, attribute,
              parameter.getType().getSimpleSourceName());
        }
        requiredValues.put(propertyName, parser.parse(attribute.consumeValue(),
            writer));
        unfilledRequiredParams.remove(propertyName);
      } else {
View Full Code Here

    boolean needsComma = false;
    NameFactory nameFactory = new NameFactory();
    JParameter[] asyncParams = asyncMethod.getParameters();
    for (int i = 0; i < asyncParams.length; ++i) {
      JParameter param = asyncParams[i];

      if (needsComma) {
        w.print(", ");
      } else {
        needsComma = true;
      }

      /*
       * Ignoring the AsyncCallback parameter, if any method requires a call to
       * SerializationStreamWriter.writeObject we need a try catch block
       */
      JType paramType = param.getType();
      paramType = paramType.getErasedType();

      w.print(paramType.getQualifiedSourceName());
      w.print(" ");

      String paramName = param.getName();
      nameFactory.addName(paramName);
      w.print(paramName);
    }

    w.println(") {");
    w.indent();

    String requestIdName = nameFactory.createName("requestId");
    w.println("int " + requestIdName + " = getNextRequestId();");

    String statsMethodExpr = getProxySimpleName() + "." + syncMethod.getName();
    String tossName = nameFactory.createName("toss");
    w.println("boolean " + tossName + " = isStatsAvailable() && stats("
        + "timeStat(\"" + statsMethodExpr + "\", " + requestIdName
        + ", \"begin\"));");

    w.print(SerializationStreamWriter.class.getSimpleName());
    w.print(" ");
    String streamWriterName = nameFactory.createName("streamWriter");
    w.println(streamWriterName + " = createStreamWriter();");
    w.println("// createStreamWriter() prepared the stream");
    w.println("try {");
    w.indent();

    w.println(streamWriterName + ".writeString(REMOTE_SERVICE_INTERFACE_NAME);");

    // Write the method name
    w.println(streamWriterName + ".writeString(\"" + syncMethod.getName()
        + "\");");

    // Write the parameter count followed by the parameter values
    JParameter[] syncParams = syncMethod.getParameters();
    w.println(streamWriterName + ".writeInt(" + syncParams.length + ");");
    for (JParameter param : syncParams) {
      JType paramType = param.getType().getErasedType();
      String typeNameExpression = computeTypeNameExpression(paramType);
      assert typeNameExpression != null : "Could not compute a type name for "
          + paramType.getQualifiedSourceName();
      w.println(streamWriterName + ".writeString(" + typeNameExpression + ");");
    }

    // Encode all of the arguments to the asynchronous method, but exclude the
    // last argument which is the callback instance.
    //
    for (int i = 0; i < asyncParams.length - 1; ++i) {
      JParameter asyncParam = asyncParams[i];
      w.print(streamWriterName + ".");
      w.print(Shared.getStreamWriteMethodNameFor(asyncParam.getType()));
      w.println("(" + asyncParam.getName() + ");");
    }

    String payloadName = nameFactory.createName("payload");
    w.println("String " + payloadName + " = " + streamWriterName
        + ".toString();");

    w.println(tossName + " = isStatsAvailable() && stats(" + "timeStat(\""
        + statsMethodExpr + "\", " + requestIdName
        + ", \"requestSerialized\"));");

    /*
     * Depending on the return type for the async method, return a
     * RequestBuilder, a Request, or nothing at all.
     */
    if (asyncReturnType == JPrimitiveType.VOID) {
      w.print("doInvoke(");
    } else if (asyncReturnType.getQualifiedSourceName().equals(
        RequestBuilder.class.getName())) {
      w.print("return doPrepareRequestBuilder(");
    } else if (asyncReturnType.getQualifiedSourceName().equals(
        Request.class.getName())) {
      w.print("return doInvoke(");
    } else {
      // This method should have been caught by RemoteServiceAsyncValidator
      throw new RuntimeException("Unhandled return type "
          + asyncReturnType.getQualifiedSourceName());
    }

    JParameter callbackParam = asyncParams[asyncParams.length - 1];
    String callbackName = callbackParam.getName();
    JType returnType = syncMethod.getReturnType();
    w.print("ResponseReader." + getResponseReaderFor(returnType).name());
    w.println(", \"" + getProxySimpleName() + "." + syncMethod.getName()
        + "\", " + requestIdName + ", " + payloadName + ", " + callbackName
        + ");");
View Full Code Here

        // Print the method decl
        sw.print("public " + method.getReturnType().getQualifiedSourceName()
            + " " + method.getName() + "(");
        for (Iterator<JParameter> i = Arrays.asList(method.getParameters()).iterator(); i.hasNext();) {
          JParameter param = i.next();
          sw.print("final " + param.getType().getQualifiedSourceName() + " "
              + param.getName());
          if (i.hasNext()) {
            sw.print(", ");
          }
        }
        sw.println(") {");
View Full Code Here

   */
  private void writeInvocation(SourceWriter sw, String qualifier, JMethod method) {
    sw.print(qualifier + "." + method.getName() + "(");

    for (Iterator<JParameter> i = Arrays.asList(method.getParameters()).iterator(); i.hasNext();) {
      JParameter param = i.next();
      sw.print(param.getName());
      if (i.hasNext()) {
        sw.print(", ");
      }
    }

View Full Code Here

    boolean needsComma = false;
    NameFactory nameFactory = new NameFactory();
    JParameter[] asyncParams = asyncMethod.getParameters();
    for (int i = 0; i < asyncParams.length; ++i) {
      JParameter param = asyncParams[i];

      if (needsComma) {
        w.print(", ");
      } else {
        needsComma = true;
      }

      /*
       * Ignoring the AsyncCallback parameter, if any method requires a call to
       * SerializationStreamWriter.writeObject we need a try catch block
       */
      JType paramType = param.getType();
      paramType = paramType.getErasedType();

      w.print(paramType.getQualifiedSourceName());
      w.print(" ");

      String paramName = param.getName();
      nameFactory.addName(paramName);
      w.print(paramName);
    }

    w.println(") {");
    w.indent();

    String requestIdName = nameFactory.createName("requestId");
    w.println("int " + requestIdName + " = getNextRequestId();");

    String statsMethodExpr = getProxySimpleName() + "." + syncMethod.getName();
    String tossName = nameFactory.createName("toss");
    w.println("boolean " + tossName + " = isStatsAvailable() && stats("
        + "timeStat(\"" + statsMethodExpr + "\", " + requestIdName
        + ", \"begin\"));");

    w.print(SerializationStreamWriter.class.getSimpleName());
    w.print(" ");
    String streamWriterName = nameFactory.createName("streamWriter");
    w.println(streamWriterName + " = createStreamWriter();");
    w.println("// createStreamWriter() prepared the stream");
    w.println("try {");
    w.indent();

    w.println(streamWriterName + ".writeString(REMOTE_SERVICE_INTERFACE_NAME);");

    // Write the method name
    w.println(streamWriterName + ".writeString(\"" + syncMethod.getName()
        + "\");");

    // Write the parameter count followed by the parameter values
    JParameter[] syncParams = syncMethod.getParameters();
    w.println(streamWriterName + ".writeInt(" + syncParams.length + ");");
    for (JParameter param : syncParams) {
      JType paramType = param.getType().getErasedType();
      String typeNameExpression = computeTypeNameExpression(paramType);
      assert typeNameExpression != null : "Could not compute a type name for "
          + paramType.getQualifiedSourceName();
      w.println(streamWriterName + ".writeString(" + typeNameExpression + ");");
    }

    // Encode all of the arguments to the asynchronous method, but exclude the
    // last argument which is the callback instance.
    //
    for (int i = 0; i < asyncParams.length - 1; ++i) {
      JParameter asyncParam = asyncParams[i];
      w.print(streamWriterName + ".");
      w.print(Shared.getStreamWriteMethodNameFor(asyncParam.getType()));
      w.println("(" + asyncParam.getName() + ");");
    }

    String payloadName = nameFactory.createName("payload");
    w.println("String " + payloadName + " = " + streamWriterName
        + ".toString();");

    w.println(tossName + " = isStatsAvailable() && stats(" + "timeStat(\""
        + statsMethodExpr + "\", " + requestIdName
        + ", \"requestSerialized\"));");

    /*
     * Depending on the return type for the async method, return a
     * RequestBuilder, a Request, or nothing at all.
     */
    if (asyncReturnType == JPrimitiveType.VOID) {
      w.print("doInvoke(");
    } else if (asyncReturnType.getQualifiedSourceName().equals(
        RequestBuilder.class.getName())) {
      w.print("return doPrepareRequestBuilder(");
    } else if (asyncReturnType.getQualifiedSourceName().equals(
        Request.class.getName())) {
      w.print("return doInvoke(");
    } else {
      // This method should have been caught by RemoteServiceAsyncValidator
      throw new RuntimeException("Unhandled return type "
          + asyncReturnType.getQualifiedSourceName());
    }

    JParameter callbackParam = asyncParams[asyncParams.length - 1];
    String callbackName = callbackParam.getName();
    JType returnType = syncMethod.getReturnType();
    w.print("ResponseReader." + getResponseReaderFor(returnType).name());
    w.println(", \"" + getProxySimpleName() + "." + syncMethod.getName()
        + "\", " + requestIdName + ", " + payloadName + ", " + callbackName
        + ");");
View Full Code Here

          && method.getParameters().length == 1) {
        String name = Introspector.decapitalize(method.getName().substring(3));
        String propertyType = null;
        JParameter[] parameters = method.getParameters();
        if (parameters.length == 1) {
          JParameter parameter = parameters[0];
          propertyType = parameter.getType().getErasedType().getQualifiedSourceName();
        } else {
          logger.log(Type.WARN, "Property '" + name + "' has "
              + parameters.length + " parameters: " + parameters + "!");
          continue;
        }
View Full Code Here

    for (int i = 0, n = params.length; i < n; ++i) {
      if (i > 0) {
        sb.append(", ");
      }

      JParameter param = params[i];
      sb.append('\"');
      sb.append(param.getName());
      sb.append('\"');
    }
    sb.append("}");
    return sb.toString();
  }
View Full Code Here

      //
      return false;
    }

    String name = String.valueOf(jparam.name);
    new JParameter(method, type, name);
    return true;
  }
View Full Code Here

TOP

Related Classes of com.google.gwt.core.ext.typeinfo.JParameter

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.