Example #1
0
 private static WebTarget addPathFromAnnotation(AnnotatedElement ae, WebTarget target) {
   Path p = ae.getAnnotation(Path.class);
   if (p != null) {
     target = target.path(p.value());
   }
   return target;
 }
  @Override
  public void parse(ApiDefinition api, OperationDefinition operation, Method method) {
    HttpMethod httpMethod = getHttpMethod(method);
    if (httpMethod != null) {
      operation.setHttpMethod(httpMethod.value());
    }

    Path path = AnnotationUtils.findAnnotation(method, Path.class);
    String methodPath = null;
    if (path != null) {
      methodPath = path.value();
    }
    operation.setPath(buildFullPath(api.getPath(), methodPath));

    Consumes consumes = AnnotationUtils.findAnnotation(method, Consumes.class);
    if (consumes != null) {
      for (String consume : consumes.value()) {
        if (operation.getConsumes() == null) {
          operation.setConsumes(new ArrayList<String>());
        }
        operation.getConsumes().add(consume);
      }
    }

    Produces produces = AnnotationUtils.findAnnotation(method, Produces.class);
    if (produces != null) {
      for (String produce : produces.value()) {
        if (operation.getProduces() == null) {
          operation.setProduces(new ArrayList<String>());
        }
        operation.getProduces().add(produce);
      }
    }
  }
Example #3
0
  private void scanBindings() throws IOException {
    for (Map.Entry<Key<?>, Binding<?>> e : globalInjector.getAllBindings().entrySet()) {
      Key<?> bindingKey = e.getKey();
      Binding<?> binding = e.getValue();
      TypeLiteral boundTypeLiteral = bindingKey.getTypeLiteral();
      Type boundType = boundTypeLiteral.getType();
      if (boundType instanceof Class) {
        final Class boundClass = (Class) boundType;
        for (Method method : boundClass.getMethods()) {
          if ((method.getModifiers() & Modifier.STATIC) == 0) {
            for (Annotation annotation : method.getAnnotations()) {
              if (annotation instanceof Path) {
                Path pathSpec = (Path) annotation;
                RouteSpec routeIn = Routes.parse(pathSpec.value(), true);
                endPointMethods.add(new EndPointMethod(routeIn, bindingKey, boundClass, method));
              }
            }
          }
        }

        if (MessageBodyReader.class.isAssignableFrom(boundClass)) {
          messageBodyReaders.add(0, (MessageBodyReader) globalInjector.getInstance(bindingKey));
        }
        if (MessageBodyWriter.class.isAssignableFrom(boundClass)) {
          messageBodyWriters.add(0, (MessageBodyWriter) globalInjector.getInstance(bindingKey));
        }
      }
    }
  }
 /**
  * Adds to the container the given paths and set for each the lowest role to access the behind
  * method.
  *
  * @param paths the paths to register.
  * @param lowestRoleAccess the lowest role that permits the access to the resourceMethod.
  * @param resourceMethod the method that has to be called for the path.
  * @param navigationStep the identifier of the navigation step associated to the path.
  * @param redirectTo the redirection to be performed after the end of the treatment.
  * @param invokeBefore the list of identifiers of methods to invoke before the treatment of HTTP
  *     method.
  * @param invokeAfter the list of identifiers of methods to invoke before the treatment of HTTP
  *     method.
  * @return registred paths.
  */
 List<Path> addPaths(
     Set<javax.ws.rs.Path> paths,
     LowestRoleAccess lowestRoleAccess,
     Method resourceMethod,
     final NavigationStep navigationStep,
     final Annotation redirectTo,
     final InvokeBefore invokeBefore,
     final InvokeAfter invokeAfter) {
   List<Path> registredPaths = new ArrayList<Path>();
   if (paths.isEmpty()) {
     registredPaths.add(
         addPath(
             "/",
             lowestRoleAccess,
             resourceMethod,
             navigationStep,
             redirectTo,
             invokeBefore,
             invokeAfter));
   } else {
     for (javax.ws.rs.Path path : paths) {
       registredPaths.add(
           addPath(
               path.value(),
               lowestRoleAccess,
               resourceMethod,
               navigationStep,
               redirectTo,
               invokeBefore,
               invokeAfter));
     }
   }
   return registredPaths;
 }
Example #5
0
 private static String loadPath(TypeDeclaration delegate) {
   Path path = delegate.getAnnotation(Path.class);
   if (path == null) {
     throw new IllegalArgumentException(
         "A JAX-RS root resource must be annotated with @javax.ws.rs.Path.");
   }
   return path.value();
 }
Example #6
0
 static {
   for (Method m : AccountService.class.getMethods()) {
     Path p = m.getAnnotation(Path.class);
     if (p != null) {
       VALID_PATHS.add(p.value());
     }
   }
 }
  /**
   * 解析 Uri Mapping 的前部分
   *
   * @param cls
   * @param moduleName
   * @return
   */
  private static String parseUriMappingPrefix(Class<?> cls, String moduleName) {
    Path cls_path = cls.getAnnotation(Path.class);
    String clazzUriMapping = cls_path == null ? moduleName : cls_path.value();

    clazzUriMapping = CommonUtil.parsePropValue(clazzUriMapping);

    return clazzUriMapping;
  }
Example #8
0
 @Override
 public String getResourceUri() {
   if (resourceUri == null) {
     Path path = getClass().getAnnotation(Path.class);
     if (path != null) {
       resourceUri = path.value();
     }
   }
   return resourceUri;
 }
  @Test
  public void shouldFindPathAnnotatedClassesInPackage() {
    ClassPathScanner scanner = new ClassPathScanner(PACKAGE_ORG_CAMUNDA_BPM_ENGINE_REST);
    Set<Class<?>> classes = scanner.getClassesWithAnnotation(Path.class);

    assertEquals(16, classes.size());

    for (Class<?> clazz : classes) {
      Path annotation = clazz.getAnnotation(Path.class);
      System.out.println(clazz + " path: " + annotation.value());
    }
  }
Example #10
0
  @Test
  public void testGetFromMethodOrClass() throws Exception {
    Path path =
        AnnotationUtils.getFromMethodOrClass(
            ExampleService.class.getMethod("getTicker", String.class, String.class), Path.class);
    assertThat("Wrong path.", path.value(), equalTo("{ident}_{currency}/ticker"));

    Path pathFromIntf =
        AnnotationUtils.getFromMethodOrClass(
            ExampleService.class.getMethod("getInfo", Long.class, Long.class), Path.class);
    assertThat("Wrong path.", pathFromIntf.value(), equalTo("api/2"));
  }
Example #11
0
  public static List<String> getPaths(Class<?> clazz) {
    List<String> paths = new ArrayList<String>();

    Path classPathAnnotation = clazz.getAnnotation(Path.class);
    // 类上必须有Path注解,否则整个类不会被认为是rest资源,即使方法上有Path注解
    if (classPathAnnotation == null) {
      return paths;
    }

    String classPath = classPathAnnotation.value();

    for (Method m : clazz.getDeclaredMethods()) {
      String methodType = StringUtils.EMPTY;

      GET get = m.getAnnotation(GET.class);
      POST post = m.getAnnotation(POST.class);
      PUT put = m.getAnnotation(PUT.class);
      DELETE delete = m.getAnnotation(DELETE.class);
      if (get != null) {
        methodType = "GET ";
      }
      if (post != null) {
        methodType = "POST ";
      }
      if (put != null) {
        methodType = "PUT ";
      }
      if (delete != null) {
        methodType = "DELETE ";
      }

      // 方法类型为空,说明此方法不是资源的操作方法
      if (StringUtils.isEmpty(methodType)) {
        continue;
      }

      String methodPath = StringUtils.EMPTY;

      Path methodPathAnnotation = m.getAnnotation(Path.class);
      if (methodPathAnnotation != null) {
        methodPath = methodPathAnnotation.value();
      }

      String fullPath = String.format("%-8s/%s/%s", methodType, classPath, methodPath);
      fullPath = StringUtils.replace(fullPath, "//", "/");
      fullPath = StringUtils.removeEnd(fullPath, "/");

      paths.add(fullPath);
    }

    return paths;
  }
  private void writeSubresourceLocatorImpl(JMethod method) throws UnableToCompleteException {
    JClassType iface = method.getReturnType().isInterface();
    if (iface == null || !REST_SERVICE_TYPE.isAssignableFrom(iface)) {
      getLogger()
          .log(
              ERROR,
              "Invalid subresource locator method. Method must have return type of an interface that extends RestService: "
                  + method.getReadableDeclaration());
      throw new UnableToCompleteException();
    }

    Path pathAnnotation = method.getAnnotation(Path.class);
    if (pathAnnotation == null) {
      getLogger()
          .log(
              ERROR,
              "Invalid subresource locator method. Method must have @Path annotation: "
                  + method.getReadableDeclaration());
      throw new UnableToCompleteException();
    }
    String pathExpression = wrap(pathAnnotation.value());

    for (JParameter arg : method.getParameters()) {
      PathParam paramPath = arg.getAnnotation(PathParam.class);
      if (paramPath != null) {
        pathExpression = pathExpression(pathExpression, arg, paramPath);
      }
    }

    p(method.getReadableDeclaration(false, false, false, false, true) + " {").i(1);
    {
      JType type = method.getReturnType();
      String name;
      if (type instanceof JClassType) {
        JClassType restService = (JClassType) type;
        RestServiceClassCreator generator =
            new RestServiceClassCreator(getLogger(), context, restService);
        name = generator.create();
      } else {
        throw new UnsupportedOperationException("Subresource method may not return: " + type);
      }
      p(method.getReturnType().getQualifiedSourceName() + " __subresource = new " + name + "();");
      p(
          "(("
              + RestServiceProxy.class.getName()
              + ")__subresource).setResource(getResource().resolve("
              + pathExpression
              + "));");
      p("return __subresource;");
    }
    i(-1).p("}");
  }
  private String getFullPath(Class<?> resourceClass, Method resourceMethod) {
    Path resourcePath = resourceClass.getAnnotation(Path.class);
    Path methodPath = resourceMethod.getAnnotation(Path.class);

    StringBuilder fullPath = new StringBuilder();

    if (resourcePath != null) {
      fullPath.append(resourcePath.value());
    }

    if (methodPath != null) {
      fullPath.append(methodPath.value());
    }

    return fullPath.toString();
  }
  private void appendPath(Path t) {
    if (t == null) {
      throw new IllegalArgumentException("Path is null");
    }

    appendPath(t.value());
  }
Example #15
0
  @Override
  public final ResourceDocument generateResourceDocument(
      UriInfo uriInfo, Class<?> classOfResource) {
    final ResourceDocument document = new ResourceDocument();

    // Read the path.
    final Path path = this.findAnnotationInClass(Path.class, classOfResource);
    if (null == path)
      throw new IllegalStateException(
          "Couldn't find any class/superclass/interface annotated with @Path for "
              + classOfResource);
    document.setPath(uriInfo.getPath() + path.value());

    this.doWithResourceDocument(document, classOfResource);

    // Process its methods
    for (Method method : classOfResource.getDeclaredMethods()) {
      // Skip methods that are not annotated with @HttpGet
      if (!isHttpMethod(method)) {
        LOG.debug("Skipping method {}, it is not annotated with @HttpMethod", method.getName());
        continue;
      }

      // IllegalStateException is thrown if the method iterated is not
      // annotated with any of the @HttpMethod annotations. This can happen
      // for utility/helper methods found within classOfResource.
      try {
        document.addMethodDocument(this.generateMethodDocument(uriInfo, method));
      } catch (IllegalStateException e) {
        // Ignoring specific methods, as they aren't annotated with @HttpMethod.
        LOG.debug("Skipping method {}, it isn't annotated with any @HttpMethod", method.getName());
      }
    }

    return document;
  }
    @Override
    public boolean preCall(HttpRequest request, HttpResponder responder, HandlerInfo handlerInfo) {
      HTTPMonitoringEvent httpMonitoringEvent = new HTTPMonitoringEvent();
      httpMonitoringEvent.setTimestamp(System.currentTimeMillis());
      httpMonitoringEvent.setStartNanoTime(System.nanoTime());
      if (serviceClass == null) {
        Method method = handlerInfo.getMethod();
        Class<?> serviceClass = method.getDeclaringClass();
        this.serviceClass = serviceClass.getName();
        serviceName = serviceClass.getSimpleName();
        serviceMethod = method.getName();
        if (serviceClass.isAnnotationPresent(Path.class)) {
          Path path = serviceClass.getAnnotation(Path.class);
          servicePath = path.value();
        }
      }
      httpMonitoringEvent.setServiceClass(serviceClass);
      httpMonitoringEvent.setServiceName(serviceName);
      httpMonitoringEvent.setServiceMethod(serviceMethod);
      httpMonitoringEvent.setRequestUri(request.getUri());
      httpMonitoringEvent.setServiceContext(servicePath);

      HttpHeaders httpHeaders = request.headers();

      httpMonitoringEvent.setHttpMethod(request.getMethod().name());
      httpMonitoringEvent.setContentType(httpHeaders.get(HttpHeaders.Names.CONTENT_TYPE));
      String contentLength = httpHeaders.get(HttpHeaders.Names.CONTENT_LENGTH);
      if (contentLength != null) {
        httpMonitoringEvent.setRequestSizeBytes(Long.parseLong(contentLength));
      }
      httpMonitoringEvent.setReferrer(httpHeaders.get(HttpHeaders.Names.REFERER));

      handlerInfo.setAttribute(MONITORING_EVENT, httpMonitoringEvent);

      return true;
    }
Example #17
0
  /**
   * @author Bing Ran ([email protected])
   * @param rootPath
   * @param uri
   * @param methods
   * @param contentType
   * @return a tuple of method and its param name-value map
   */
  static Tuple<Method, Map<String, String>> findMethodAndGenerateContext(
      String rootPath, String uri, java.util.Set<Method> methods, String contentType) {
    // include rootPath only for non root slash class level @Path values or
    // if the uri is root slash
    String[] consumeTypes = new String[] {contentType};
    String rootPathPrefix = (rootPath == "/" && uri != "/") ? "" : rootPath;

    for (Method m : methods) {

      Consumes consumes = m.getAnnotation(Consumes.class);
      if (consumes != null) {
        consumeTypes = consumes.value();
      }

      boolean contained = false;
      for (String c : consumeTypes) {
        if (c.equals(contentType)) {
          contained = true;
          break;
        }
      }
      if (contained) {
        Path p = m.getAnnotation(Path.class);
        String mPath = p == null ? "" : JaxrsRouter.prefixSlash(p.value());
        String fullMethodPath = (rootPathPrefix + mPath).replace("//", "/");

        // List<String> matches =
        // RegMatch.findAllIn(Pattern.compile(fullMethodPath), uri );
        // if (matches.size() > 0) {
        // matches = RegMatch.findAllIn(Pattern.compile(uri),
        // fullMethodPath);
        // if (matches.size() > 0) {
        // return new Tuple<Method, Map<String, String>>(m, new
        // HashMap<String, String>());
        // }
        // }

        // bran let's do exact match
        if (uri.equals(fullMethodPath)) {
          return new Tuple<Method, Map<String, String>>(m, new HashMap<String, String>());
        } else // any variables?
        if (fullMethodPath.contains("{") && fullMethodPath.contains("}")) {
          String combinedReg =
              fullMethodPath.replaceAll(JaxrsRouter.urlParamCapture, "\\\\{(.*)\\\\}"); // .r;
          Pattern r = Pattern.compile(combinedReg);
          List<RegMatch> rootParamNameMatches = RegMatch.findAllMatchesIn(r, fullMethodPath);
          List<String> rootParamNames = new ArrayList<String>();
          for (RegMatch rm : rootParamNameMatches) {
            rootParamNames.addAll(rm.subgroups);
          }

          combinedReg = fullMethodPath.replaceAll(JaxrsRouter.urlParamCapture, "(.*)");
          r = Pattern.compile(combinedReg);
          List<RegMatch> rootParamValueMatches = RegMatch.findAllMatchesIn(r, uri);
          List<String> rootParamValues = new ArrayList<String>();
          for (RegMatch rm : rootParamValueMatches) {
            rootParamValues.addAll(rm.subgroups);
          }

          Map<String, String> methodMetaData = new java.util.HashMap<String, String>();
          int c = 0;
          for (String name : rootParamNames) {
            try {
              methodMetaData.put(name, rootParamValues.get(c++));
            } catch (Exception e) {
              methodMetaData.put(name, "");
            }
          }

          if (rootParamValues.size() > 0) {
            return new Tuple<Method, Map<String, String>>(m, methodMetaData);
          }
        }
      }
    }
    return null;
  }
  @Override
  protected void generate() throws UnableToCompleteException {

    if (source.isInterface() == null) {
      getLogger().log(ERROR, "Type is not an interface.");
      throw new UnableToCompleteException();
    }

    locator = new JsonEncoderDecoderInstanceLocator(context, getLogger());

    this.XML_CALLBACK_TYPE = find(XmlCallback.class, getLogger(), context);
    this.METHOD_CALLBACK_TYPE = find(MethodCallback.class, getLogger(), context);
    this.TEXT_CALLBACK_TYPE = find(TextCallback.class, getLogger(), context);
    this.JSON_CALLBACK_TYPE = find(JsonCallback.class, getLogger(), context);
    this.OVERLAY_CALLBACK_TYPE = find(OverlayCallback.class, getLogger(), context);
    this.DOCUMENT_TYPE = find(Document.class, getLogger(), context);
    this.METHOD_TYPE = find(Method.class, getLogger(), context);
    this.STRING_TYPE = find(String.class, getLogger(), context);
    this.JSON_VALUE_TYPE = find(JSONValue.class, getLogger(), context);
    this.OVERLAY_VALUE_TYPE = find(JavaScriptObject.class, getLogger(), context);
    this.OVERLAY_ARRAY_TYPES = new HashSet<JClassType>();
    this.OVERLAY_ARRAY_TYPES.add(find(JsArray.class, getLogger(), context));
    this.OVERLAY_ARRAY_TYPES.add(find(JsArrayBoolean.class, getLogger(), context));
    this.OVERLAY_ARRAY_TYPES.add(find(JsArrayInteger.class, getLogger(), context));
    this.OVERLAY_ARRAY_TYPES.add(find(JsArrayNumber.class, getLogger(), context));
    this.OVERLAY_ARRAY_TYPES.add(find(JsArrayString.class, getLogger(), context));
    this.QUERY_PARAM_LIST_TYPES = new HashSet<JClassType>();
    this.QUERY_PARAM_LIST_TYPES.add(find(List.class, getLogger(), context));
    this.QUERY_PARAM_LIST_TYPES.add(find(Set.class, getLogger(), context));
    this.REST_SERVICE_TYPE = find(RestService.class, getLogger(), context);

    String path = null;
    Path pathAnnotation = source.getAnnotation(Path.class);
    if (pathAnnotation != null) {
      path = pathAnnotation.value();
    }

    RemoteServiceRelativePath relativePath = source.getAnnotation(RemoteServiceRelativePath.class);
    if (relativePath != null) {
      path = relativePath.value();
    }

    p("private " + RESOURCE_CLASS + " resource = null;");
    p();

    p("public void setResource(" + RESOURCE_CLASS + " resource) {").i(1);
    {
      p("this.resource = resource;");
    }
    i(-1).p("}");

    p("public " + RESOURCE_CLASS + " getResource() {").i(1);
    {
      p("if (this.resource == null) {").i(1);
      if (path == null) {
        p("this.resource = new " + RESOURCE_CLASS + "(" + DEFAULTS_CLASS + ".getServiceRoot());");
      } else {
        p(
            "this.resource = new "
                + RESOURCE_CLASS
                + "("
                + DEFAULTS_CLASS
                + ".getServiceRoot()).resolve("
                + quote(path)
                + ");");
      }
      i(-1).p("}");
      p("return this.resource;");
    }
    i(-1).p("}");

    Options options = source.getAnnotation(Options.class);
    if (options != null && options.dispatcher() != Dispatcher.class) {
      p(
          "private "
              + DISPATCHER_CLASS
              + " dispatcher = "
              + options.dispatcher().getName()
              + ".INSTANCE;");
    } else {
      p("private " + DISPATCHER_CLASS + " dispatcher = null;");
    }

    p();
    p("public void setDispatcher(" + DISPATCHER_CLASS + " dispatcher) {").i(1);
    {
      p("this.dispatcher = dispatcher;");
    }
    i(-1).p("}");

    p();
    p("public " + DISPATCHER_CLASS + " getDispatcher() {").i(1);
    {
      p("return this.dispatcher;");
    }
    i(-1).p("}");

    for (JMethod method : source.getInheritableMethods()) {
      JClassType iface = method.getReturnType().isInterface();
      if (iface != null && REST_SERVICE_TYPE.isAssignableFrom(iface))
        writeSubresourceLocatorImpl(method);
      else writeMethodImpl(method);
    }
  }
  private void writeMethodImpl(JMethod method) throws UnableToCompleteException {
    if (method.getReturnType().isPrimitive() != JPrimitiveType.VOID) {
      error(
          "Invalid rest method. Method must have void return type: "
              + method.getReadableDeclaration());
    }

    Json jsonAnnotation = source.getAnnotation(Json.class);
    final Style classStyle = jsonAnnotation != null ? jsonAnnotation.style() : Style.DEFAULT;

    Options classOptions = source.getAnnotation(Options.class);
    Options options = method.getAnnotation(Options.class);

    p(method.getReadableDeclaration(false, false, false, false, true) + " {").i(1);
    {
      String restMethod = getRestMethod(method);
      LinkedList<JParameter> args =
          new LinkedList<JParameter>(Arrays.asList(method.getParameters()));

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

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

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

      for (JParameter arg : args) {
        PathParam paramPath = arg.getAnnotation(PathParam.class);
        if (paramPath != null) {
          if (pathExpression == null) {
            error(
                "Invalid rest method.  Invalid @PathParam annotation. Method is missing the @Path annotation: "
                    + method.getReadableDeclaration());
          }
          pathExpression =
              pathExpression.replaceAll(
                  Pattern.quote("{" + paramPath.value() + "}"),
                  "\"+" + toStringExpression(arg) + "+\"");
          continue;
        }

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

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

        if (contentArg != null) {
          error(
              "Invalid rest method. Only one content parameter is supported: "
                  + method.getReadableDeclaration());
        }
        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("this.resource");
      if (pathExpression != null) {
        p(".resolve(" + pathExpression + ")");
      }
      for (Map.Entry<String, JParameter> entry : queryParams.entrySet()) {
        String expr = entry.getValue().getName();
        p(
            ".addQueryParam("
                + wrap(entry.getKey())
                + ", "
                + toStringExpression(entry.getValue().getType(), expr)
                + ")");
      }
      // example: .get()
      p("." + restMethod + "();");

      // Handle JSONP specific configuration...
      JSONP jsonpAnnotation = method.getAnnotation(JSONP.class);
      if (restMethod.equals(METHOD_JSONP) && jsonpAnnotation != null) {
        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())
                  + ");");
        }
      }

      // 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() + ");");
      }

      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 (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) {
            error("Content argument must be a class.");
          }

          jsonAnnotation = contentArg.getAnnotation(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)
                  + ");");
        }
      }

      if (acceptTypeBuiltIn != null) {
        p("__method.send(" + callbackArg.getName() + ");");
      } else {
        p("try {").i(1);
        {
          p("__method.send(new "
                  + ABSTRACT_REQUEST_CALLBACK_CLASS
                  + "<"
                  + resultType.getParameterizedQualifiedSourceName()
                  + ">(__method, "
                  + callbackArg.getName()
                  + ") {")
              .i(1);
          {
            p("protected "
                    + resultType.getParameterizedQualifiedSourceName()
                    + " parseResult() throws Exception {")
                .i(1);
            {
              if (resultType.getParameterizedQualifiedSourceName().equals("java.lang.Void")) {
                p("return (java.lang.Void) new java.lang.Object();");
              } else {
                p("try {").i(1);
                {
                  jsonAnnotation = method.getAnnotation(Json.class);
                  Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle;
                  p(
                      "return "
                          + locator.decodeExpression(
                              resultType,
                              JSON_PARSER_CLASS + ".parse(__method.getResponse().getText())",
                              style)
                          + ";");
                }
                i(-1).p("} catch (Throwable __e) {").i(1);
                {
                  p(
                      "throw new "
                          + RESPONSE_FORMAT_EXCEPTION_CLASS
                          + "(\"Response was NOT a valid JSON document\", __e);");
                }
                i(-1).p("}");
              }
            }
            i(-1).p("}");
          }
          i(-1).p("});");
        }
        i(-1).p("} catch (" + REQUEST_EXCEPTION_CLASS + " __e) {").i(1);
        {
          p(callbackArg.getName() + ".onFailure(__method,__e);");
        }
        i(-1).p("}");
      }
    }
    i(-1).p("}");
  }
  /**
   * 解析 URI Mapping 后部分
   *
   * @param moduleName
   * @param m
   * @return
   */
  private ActionConfigBean parseUriMappingSuffix(String moduleName, Method m) {
    ActionConfigBean acb = new ActionConfigBean();

    String methodName = m.getName();
    String fullName = m.toString();
    log.debug("parse action.method --> " + fullName);

    String uriMapping = null;
    Path m_path = m.getAnnotation(Path.class);
    if (methodName.startsWith(ActionMethod.PREFIX)) {
      uriMapping = methodName.substring(ActionMethod.PREFIX.length());
      // doUriBindParam1AndParam2JoinUriAtPostOrGet
      String at = null;
      int indexOfAt = methodName.indexOf(ActionMethod.AT);
      if (indexOfAt != -1) {
        at = methodName.substring(indexOfAt + ActionMethod.AT.length());
        if (methodName.startsWith(ActionMethod.PREFIX))
          uriMapping = uriMapping.substring(0, uriMapping.indexOf(ActionMethod.AT));
        String[] httpMethods = at.split(ActionMethod.OR);
        StringBuilder sb = new StringBuilder();
        for (String httpMethod : httpMethods) {
          if (sb.length() > 0) sb.append("|");

          sb.append(httpMethod.toUpperCase());
        }
        if (sb.length() > 0) {
          acb.setHttpMethod(sb.toString());
        }
      }
      String join = "";
      String bind;
      int indexOfBind = methodName.indexOf(ActionMethod.BIND);
      if (indexOfBind != -1) {
        if (indexOfAt != -1 && indexOfAt > indexOfBind) {
          bind = methodName.substring(indexOfBind + ActionMethod.BIND.length(), indexOfAt);
        } else {
          bind = methodName.substring(indexOfBind + ActionMethod.BIND.length());
        }

        uriMapping = uriMapping.substring(0, uriMapping.indexOf(ActionMethod.BIND));

        int indexOfJoin = bind.indexOf(ActionMethod.JOIN);
        if (indexOfJoin != -1) {
          String[] joins = bind.split(ActionMethod.JOIN);
          if (joins.length > 1) {
            bind = joins[0];
            join = joins[1];
          }
        }

        String[] pathParams = bind.split(ActionMethod.AND);
        StringBuilder pathParamSB = new StringBuilder();
        for (int i = 0; i < pathParams.length; i++) {
          pathParams[i] = CommonUtil.toLowCaseFirst(pathParams[i]);
          pathParamSB.append("/{").append(pathParams[i]).append("}");
        }

        if (pathParamSB.length() > 0) uriMapping = uriMapping + pathParamSB.toString();

        acb.setPathParams(pathParams);
      }

      uriMapping = CommonUtil.toLowCaseFirst(uriMapping);
      uriMapping = CommonUtil.hump2ohter(uriMapping, "-");

      if (join.length() > 0) {
        join = CommonUtil.toLowCaseFirst(join);
        join = CommonUtil.hump2ohter(join, "-");
        uriMapping = uriMapping + "/" + join;
      }

    } else if (m_path == null) {
      /* 8 个默认方法 */
      ActionConfigBean defaultAcb = parseDefaultActionConfig(methodName, moduleName);
      if (defaultAcb != null) {
        acb.setHttpMethod(defaultAcb.getHttpMethod());
        acb.getResult().addAll(defaultAcb.getResult());

        uriMapping = defaultAcb.getUriMapping();
      } else {

        String info =
            fullName
                + " does not starts with '"
                + ActionMethod.PREFIX
                + "' so that can not be a valid action uri mapping";
        log.debug(info);
        return null;
      }
    }

    if (m_path != null) {
      uriMapping = CommonUtil.parsePropValue(m_path.value());
    }

    acb.setUriMapping(uriMapping);
    return acb;
  }
Example #21
0
 public static String getPath(Path ann) {
   if (ann == null) {
     return "";
   }
   return getPath(ann.value());
 }
  public static void main(String[] args) throws Exception {
    StringBuilder sb = new StringBuilder();
    sb.append("insert into popedom (id, id_parent, code, name, menu, idx");
    for (int i = 0; i < ACTIONS; i++) {
      sb.append(",action" + i);
      sb.append(",action" + i + "_name");
    }
    sb.append(") values (?, null, ?, ?, true, ?");
    for (int i = 0; i < ACTIONS; i++) {
      sb.append(",?");
      sb.append(",?");
    }
    sb.append(")");

    Class.forName("org.postgresql.Driver");
    Connection conn = null;
    try {
      conn =
          DriverManager.getConnection(
              "jdbc:postgresql://192.168.2.250:5432/child", "postgres", "1234");
      conn.createStatement().executeUpdate("delete from popedom ");
      PreparedStatement ps = conn.prepareStatement(sb.toString());

      WinkApplication wa = new WinkApplication();
      int i = 0;
      for (Class c : wa.getClasses()) {
        Path path = (Path) c.getAnnotation(Path.class);
        ps.setLong(1, i + 1);
        ps.setString(2, path.value());

        if (c.isAnnotationPresent(Description.class)) {
          Description description = (Description) c.getAnnotation(Description.class);
          ps.setString(3, description.value());
        } else {
          ps.setString(3, path.value());
        }

        ps.setLong(4, i + 1);

        System.out.println(path.value());

        Map<String, String> methodMap = new TreeMap<String, String>();
        for (Method method : c.getDeclaredMethods()) {
          String code = null;
          if (method.isAnnotationPresent(GET.class)) {
            code = "GET";
          } else if (method.isAnnotationPresent(POST.class)) {
            code = "POST";
          } else if (method.isAnnotationPresent(PUT.class)) {
            code = "PUT";
          } else if (method.isAnnotationPresent(DELETE.class)) {
            code = "DELETE";
          } else {
            continue;
          }
          boolean isAnn = method.isAnnotationPresent(Path.class);
          if (isAnn) {
            code += " " + method.getAnnotation(Path.class).value();
          }

          String name = null;

          if (method.isAnnotationPresent(Description.class)) {
            Description description = method.getAnnotation(Description.class);
            name = description.value();
          } else {
            name = code;
          }
          methodMap.put(code, name);
        }

        int j = 0;
        for (Map.Entry<String, String> entry : methodMap.entrySet()) {
          ps.setString(5 + j * 2, entry.getKey());
          ps.setString(5 + j * 2 + 1, entry.getValue());
          j++;
        }
        for (int k = j; k < ACTIONS; k++) {
          ps.setString(5 + k * 2, null);
          ps.setString(5 + k * 2 + 1, null);
        }
        ps.executeUpdate();
        i++;
      }
      ps.close();
    } finally {
      try {
        conn.close();
      } finally {
        conn = null;
      }
    }
  }
Example #23
0
  public ResourceMethod(MethodDeclaration delegate, Resource parent) {
    super(delegate);

    Set<String> httpMethods = new TreeSet<String>();
    Collection<AnnotationMirror> mirrors = delegate.getAnnotationMirrors();
    for (AnnotationMirror mirror : mirrors) {
      AnnotationTypeDeclaration annotationDeclaration = mirror.getAnnotationType().getDeclaration();
      HttpMethod httpMethodInfo = annotationDeclaration.getAnnotation(HttpMethod.class);
      if (httpMethodInfo != null) {
        // request method designator found.
        httpMethods.add(httpMethodInfo.value());
      }
    }

    if (httpMethods.isEmpty()) {
      throw new IllegalStateException(
          "A resource method must specify an HTTP method by using a request method designator annotation.");
    }

    this.httpMethods = httpMethods;

    Set<String> consumes;
    Consumes consumesInfo = delegate.getAnnotation(Consumes.class);
    if (consumesInfo != null) {
      consumes = new TreeSet<String>(Arrays.asList(JAXRSUtils.value(consumesInfo)));
    } else {
      consumes = new TreeSet<String>(parent.getConsumesMime());
    }
    this.consumesMime = consumes;

    Set<String> produces;
    Produces producesInfo = delegate.getAnnotation(Produces.class);
    if (producesInfo != null) {
      produces = new TreeSet<String>(Arrays.asList(JAXRSUtils.value(producesInfo)));
    } else {
      produces = new TreeSet<String>(parent.getProducesMime());
    }
    this.producesMime = produces;

    String subpath = null;
    Path pathInfo = delegate.getAnnotation(Path.class);
    if (pathInfo != null) {
      subpath = pathInfo.value();
    }

    ResourceEntityParameter entityParameter;
    List<ResourceEntityParameter> declaredEntityParameters =
        new ArrayList<ResourceEntityParameter>();
    List<ResourceParameter> resourceParameters;
    ResourceRepresentationMetadata outputPayload;
    ResourceMethodSignature signatureOverride =
        delegate.getAnnotation(ResourceMethodSignature.class);
    if (signatureOverride == null) {
      entityParameter = null;
      resourceParameters = new ArrayList<ResourceParameter>();
      // if we're not overriding the signature, assume we use the real method signature.
      for (ParameterDeclaration parameterDeclaration : getParameters()) {
        if (ResourceParameter.isResourceParameter(parameterDeclaration)) {
          resourceParameters.add(new ResourceParameter(parameterDeclaration));
        } else if (ResourceParameter.isFormBeanParameter(parameterDeclaration)) {
          resourceParameters.addAll(ResourceParameter.getFormBeanParameters(parameterDeclaration));
        } else if (parameterDeclaration.getAnnotation(Context.class) == null) {
          entityParameter = new ResourceEntityParameter(this, parameterDeclaration);
          declaredEntityParameters.add(entityParameter);
        }
      }

      DecoratedTypeMirror returnTypeMirror;
      TypeHint hintInfo = getAnnotation(TypeHint.class);
      if (hintInfo != null) {
        try {
          Class hint = hintInfo.value();
          AnnotationProcessorEnvironment env = net.sf.jelly.apt.Context.getCurrentEnvironment();
          if (TypeHint.NO_CONTENT.class.equals(hint)) {
            returnTypeMirror =
                (DecoratedTypeMirror)
                    TypeMirrorDecorator.decorate(env.getTypeUtils().getVoidType());
          } else {
            String hintName = hint.getName();

            if (TypeHint.NONE.class.equals(hint)) {
              hintName = hintInfo.qualifiedName();
            }

            if (!"##NONE".equals(hintName)) {
              TypeDeclaration type = env.getTypeDeclaration(hintName);
              returnTypeMirror =
                  (DecoratedTypeMirror)
                      TypeMirrorDecorator.decorate(env.getTypeUtils().getDeclaredType(type));
            } else {
              returnTypeMirror = (DecoratedTypeMirror) getReturnType();
            }
          }
        } catch (MirroredTypeException e) {
          returnTypeMirror = (DecoratedTypeMirror) TypeMirrorDecorator.decorate(e.getTypeMirror());
        }
        returnTypeMirror.setDocComment(((DecoratedTypeMirror) getReturnType()).getDocComment());
      } else {
        returnTypeMirror = (DecoratedTypeMirror) getReturnType();

        if (getJavaDoc().get("returnWrapped")
            != null) { // support jax-doclets. see http://jira.codehaus.org/browse/ENUNCIATE-690
          String fqn = getJavaDoc().get("returnWrapped").get(0);
          AnnotationProcessorEnvironment env = net.sf.jelly.apt.Context.getCurrentEnvironment();
          TypeDeclaration type = env.getTypeDeclaration(fqn);
          if (type != null) {
            returnTypeMirror =
                (DecoratedTypeMirror)
                    TypeMirrorDecorator.decorate(env.getTypeUtils().getDeclaredType(type));
          }
        }

        // in the case where the return type is com.sun.jersey.api.JResponse,
        // we can use the type argument to get the entity type
        if (returnTypeMirror.isClass()
            && returnTypeMirror.isInstanceOf("com.sun.jersey.api.JResponse")) {
          DecoratedClassType jresponse = (DecoratedClassType) returnTypeMirror;
          if (!jresponse.getActualTypeArguments().isEmpty()) {
            DecoratedTypeMirror responseType =
                (DecoratedTypeMirror)
                    TypeMirrorDecorator.decorate(
                        jresponse.getActualTypeArguments().iterator().next());
            if (responseType.isDeclared()) {
              responseType.setDocComment(returnTypeMirror.getDocComment());
              returnTypeMirror = responseType;
            }
          }
        }
      }

      outputPayload =
          returnTypeMirror.isVoid() ? null : new ResourceRepresentationMetadata(returnTypeMirror);
    } else {
      entityParameter = loadEntityParameter(signatureOverride);
      declaredEntityParameters.add(entityParameter);
      resourceParameters = loadResourceParameters(signatureOverride);
      outputPayload = loadOutputPayload(signatureOverride);
    }

    JavaDoc.JavaDocTagList doclets =
        getJavaDoc()
            .get(
                "RequestHeader"); // support jax-doclets. see
                                  // http://jira.codehaus.org/browse/ENUNCIATE-690
    if (doclets != null) {
      for (String doclet : doclets) {
        int firstspace = doclet.indexOf(' ');
        String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet;
        String doc =
            ((firstspace > 0) && (firstspace + 1 < doclet.length()))
                ? doclet.substring(firstspace + 1)
                : "";
        resourceParameters.add(
            new ExplicitResourceParameter(this, doc, header, ResourceParameterType.HEADER));
      }
    }

    ArrayList<ResponseCode> statusCodes = new ArrayList<ResponseCode>();
    ArrayList<ResponseCode> warnings = new ArrayList<ResponseCode>();
    StatusCodes codes = getAnnotation(StatusCodes.class);
    if (codes != null) {
      for (org.codehaus.enunciate.jaxrs.ResponseCode code : codes.value()) {
        ResponseCode rc = new ResponseCode();
        rc.setCode(code.code());
        rc.setCondition(code.condition());
        statusCodes.add(rc);
      }
    }

    doclets =
        getJavaDoc()
            .get("HTTP"); // support jax-doclets. see http://jira.codehaus.org/browse/ENUNCIATE-690
    if (doclets != null) {
      for (String doclet : doclets) {
        int firstspace = doclet.indexOf(' ');
        String code = firstspace > 0 ? doclet.substring(0, firstspace) : doclet;
        String doc =
            ((firstspace > 0) && (firstspace + 1 < doclet.length()))
                ? doclet.substring(firstspace + 1)
                : "";
        try {
          ResponseCode rc = new ResponseCode();
          rc.setCode(Integer.parseInt(code));
          rc.setCondition(doc);
          statusCodes.add(rc);
        } catch (NumberFormatException e) {
          // fall through...
        }
      }
    }

    Warnings warningInfo = getAnnotation(Warnings.class);
    if (warningInfo != null) {
      for (org.codehaus.enunciate.jaxrs.ResponseCode code : warningInfo.value()) {
        ResponseCode rc = new ResponseCode();
        rc.setCode(code.code());
        rc.setCondition(code.condition());
        warnings.add(rc);
      }
    }

    codes = parent.getAnnotation(StatusCodes.class);
    if (codes != null) {
      for (org.codehaus.enunciate.jaxrs.ResponseCode code : codes.value()) {
        ResponseCode rc = new ResponseCode();
        rc.setCode(code.code());
        rc.setCondition(code.condition());
        statusCodes.add(rc);
      }
    }

    warningInfo = parent.getAnnotation(Warnings.class);
    if (warningInfo != null) {
      for (org.codehaus.enunciate.jaxrs.ResponseCode code : warningInfo.value()) {
        ResponseCode rc = new ResponseCode();
        rc.setCode(code.code());
        rc.setCondition(code.condition());
        warnings.add(rc);
      }
    }

    ResponseHeaders responseHeaders = parent.getAnnotation(ResponseHeaders.class);
    if (responseHeaders != null) {
      for (ResponseHeader header : responseHeaders.value()) {
        this.responseHeaders.put(header.name(), header.description());
      }
    }

    responseHeaders = getAnnotation(ResponseHeaders.class);
    if (responseHeaders != null) {
      for (ResponseHeader header : responseHeaders.value()) {
        this.responseHeaders.put(header.name(), header.description());
      }
    }

    doclets =
        getJavaDoc()
            .get(
                "ResponseHeader"); // support jax-doclets. see
                                   // http://jira.codehaus.org/browse/ENUNCIATE-690
    if (doclets != null) {
      for (String doclet : doclets) {
        int firstspace = doclet.indexOf(' ');
        String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet;
        String doc =
            ((firstspace > 0) && (firstspace + 1 < doclet.length()))
                ? doclet.substring(firstspace + 1)
                : "";
        this.responseHeaders.put(header, doc);
      }
    }

    this.entityParameter = entityParameter;
    this.resourceParameters = resourceParameters;
    this.subpath = subpath;
    this.parent = parent;
    this.statusCodes = statusCodes;
    this.warnings = warnings;
    this.representationMetadata = outputPayload;
    this.declaredEntityParameters = declaredEntityParameters;
  }
  private void writeMethodImpl(JMethod method) throws UnableToCompleteException {
    boolean returnRequest = false;
    if (method.getReturnType() != JPrimitiveType.VOID) {
      if (!method.getReturnType().getQualifiedSourceName().equals(Request.class.getName())
          && !method
              .getReturnType()
              .getQualifiedSourceName()
              .equals(JsonpRequest.class.getName())) {
        getLogger()
            .log(
                ERROR,
                "Invalid rest method. Method must have void, Request or JsonpRequest return types: "
                    + method.getReadableDeclaration());
        throw new UnableToCompleteException();
      } else {
        returnRequest = true;
      }
    }

    Json jsonAnnotation = source.getAnnotation(Json.class);
    final Style classStyle = jsonAnnotation != null ? jsonAnnotation.style() : Style.DEFAULT;

    Options classOptions = source.getAnnotation(Options.class);
    Options options = method.getAnnotation(Options.class);

    p(method.getReadableDeclaration(false, false, false, false, true) + " {").i(1);
    {
      String restMethod = getRestMethod(method);
      LinkedList<JParameter> args =
          new LinkedList<JParameter>(Arrays.asList(method.getParameters()));

      // 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 = method.getAnnotation(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 = arg.getAnnotation(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 (arg.getAnnotation(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 = arg.getAnnotation(QueryParam.class);
        if (queryParam != null) {
          queryParams.put(queryParam.value(), arg);
          continue;
        }

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

        HeaderParam headerParam = arg.getAnnotation(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 = method.getAnnotation(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()) {
          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 = contentArg.getAnnotation(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());
      getLogger()
          .log(
              TreeLogger.DEBUG,
              "found " + annotationResolvers.size() + " additional AnnotationResolvers");

      for (AnnotationResolver a : annotationResolvers) {
        getLogger()
            .log(
                TreeLogger.DEBUG,
                "("
                    + a.getClass().getName()
                    + ") resolve `"
                    + source.getName()
                    + "#"
                    + method.getName()
                    + "´ ...");
        final Map<String, String[]> addDataParams =
            a.resolveAnnotation(getLogger(), source, method, restMethod);

        if (addDataParams != null) {
          for (String s : addDataParams.keySet()) {
            final StringBuilder sb = new StringBuilder();
            final List<String> classList = Arrays.asList(addDataParams.get(s));

            sb.append("[");
            for (int i = 0; i < classList.size(); ++i) {
              sb.append("\\\"").append(classList.get(i)).append("\\\"");

              if ((i + 1) < classList.size()) {
                sb.append(",");
              }
            }
            sb.append("]");

            getLogger()
                .log(TreeLogger.DEBUG, "add call with (\"" + s + "\", \"" + sb.toString() + "\")");
            p("__method.addData(\"" + s + "\", \"" + sb.toString() + "\");");
          }
        }
      }

      if (acceptTypeBuiltIn != null) {
        // TODO: shouldn't we also have a cach in here?
        p(returnRequest(returnRequest, isJsonp) + "__method.send(" + callbackArg.getName() + ");");
      } else if (isJsonp) {
        p(returnRequest(returnRequest, isJsonp)
                + "(("
                + JSONP_METHOD_CLASS
                + ")__method).send(new "
                + ABSTRACT_ASYNC_CALLBACK_CLASS
                + "<"
                + resultType.getParameterizedQualifiedSourceName()
                + ">(("
                + JSONP_METHOD_CLASS
                + ")__method, "
                + callbackArg.getName()
                + ") {")
            .i(1);
        {
          p("protected "
                  + resultType.getParameterizedQualifiedSourceName()
                  + " parseResult("
                  + JSON_VALUE_CLASS
                  + " result) throws Exception {")
              .i(1);
          {
            if (resultType.getParameterizedQualifiedSourceName().equals("java.lang.Void")) {
              p("return (java.lang.Void) null;");
            } else {
              p("try {").i(1);
              {
                if (resultType.isAssignableTo(locator.LIST_TYPE)) {
                  p("result = new " + JSON_ARRAY_CLASS + "(result.getJavaScriptObject());");
                }
                jsonAnnotation = method.getAnnotation(Json.class);
                Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle;
                p("return " + locator.decodeExpression(resultType, "result", style) + ";");
              }
              i(-1).p("} catch (Throwable __e) {").i(1);
              {
                p(
                    "throw new "
                        + RESPONSE_FORMAT_EXCEPTION_CLASS
                        + "(\"Response was NOT a valid JSON document\", __e);");
              }
              i(-1).p("}");
            }
          }
          i(-1).p("}");
        }
        i(-1).p("});");
      } else {
        p("try {").i(1);
        {
          p(returnRequest(returnRequest, isJsonp)
                  + "__method.send(new "
                  + ABSTRACT_REQUEST_CALLBACK_CLASS
                  + "<"
                  + resultType.getParameterizedQualifiedSourceName()
                  + ">(__method, "
                  + callbackArg.getName()
                  + ") {")
              .i(1);
          {
            p("protected "
                    + resultType.getParameterizedQualifiedSourceName()
                    + " parseResult() throws Exception {")
                .i(1);
            {
              if (resultType.getParameterizedQualifiedSourceName().equals("java.lang.Void")) {
                p("return (java.lang.Void) null;");
              } else {
                p("try {").i(1);
                {
                  jsonAnnotation = method.getAnnotation(Json.class);
                  Style style = jsonAnnotation != null ? jsonAnnotation.style() : classStyle;
                  p(
                      "return "
                          + locator.decodeExpression(
                              resultType,
                              JSON_PARSER_CLASS + ".parse(__method.getResponse().getText())",
                              style)
                          + ";");
                }
                i(-1).p("} catch (Throwable __e) {").i(1);
                {
                  p(
                      "throw new "
                          + RESPONSE_FORMAT_EXCEPTION_CLASS
                          + "(\"Response was NOT a valid JSON document\", __e);");
                }
                i(-1).p("}");
              }
            }
            i(-1).p("}");
          }
          i(-1).p("});");
        }
        i(-1).p("} catch (" + REQUEST_EXCEPTION_CLASS + " __e) {").i(1);
        {
          p(callbackArg.getName() + ".onFailure(__method,__e);");
          if (returnRequest) {
            p("return null;");
          }
        }
        i(-1).p("}");
      }
    }
    i(-1).p("}");
  }
Example #25
0
 private String getPath(Class<?> clazz) {
   Path pathAnnotation = clazz.getAnnotation(Path.class);
   return pathAnnotation == null ? null : pathAnnotation.value();
 }
  private Resource.Builder doCreateResourceBuilder() {
    if (!disableValidation) {
      checkForNonPublicMethodIssues();
    }

    final Class<?> annotatedResourceClass = ModelHelper.getAnnotatedResourceClass(handlerClass);
    final Path rPathAnnotation = annotatedResourceClass.getAnnotation(Path.class);

    final boolean keepEncodedParams = (null != annotatedResourceClass.getAnnotation(Encoded.class));

    final List<MediaType> defaultConsumedTypes =
        extractMediaTypes(annotatedResourceClass.getAnnotation(Consumes.class));
    final List<MediaType> defaultProducedTypes =
        extractMediaTypes(annotatedResourceClass.getAnnotation(Produces.class));
    final Collection<Class<? extends Annotation>> defaultNameBindings =
        ReflectionHelper.getAnnotationTypes(annotatedResourceClass, NameBinding.class);

    final MethodList methodList = new MethodList(handlerClass);

    checkResourceClassSetters(methodList, keepEncodedParams);
    checkResourceClassFields(keepEncodedParams, InvocableValidator.isSingleton(handlerClass));

    Resource.Builder resourceBuilder;

    if (null != rPathAnnotation) {
      resourceBuilder = Resource.builder(rPathAnnotation.value());
    } else {
      resourceBuilder = Resource.builder();
    }

    boolean extended = false;
    if (handlerClass.isAnnotationPresent(ExtendedResource.class)) {
      resourceBuilder.extended(true);
      extended = true;
    }

    resourceBuilder.name(handlerClass.getName());

    addResourceMethods(
        resourceBuilder,
        methodList,
        keepEncodedParams,
        defaultConsumedTypes,
        defaultProducedTypes,
        defaultNameBindings,
        extended);
    addSubResourceMethods(
        resourceBuilder,
        methodList,
        keepEncodedParams,
        defaultConsumedTypes,
        defaultProducedTypes,
        defaultNameBindings,
        extended);
    addSubResourceLocators(resourceBuilder, methodList, keepEncodedParams, extended);

    if (LOGGER.isLoggable(Level.FINEST)) {
      LOGGER.finest(
          LocalizationMessages.NEW_AR_CREATED_BY_INTROSPECTION_MODELER(resourceBuilder.toString()));
    }

    return resourceBuilder;
  }
 static {
   Path annotation = ClusterResource.class.getAnnotation(Path.class);
   clusterResourcePath = annotation.value();
 }
Example #28
0
  public BaseResourceTest() {
    Path path = m_resource.getClass().getAnnotation(Path.class);
    m_resourcePath = path.value();

    JsonUtils.disableMapperAutoDetection(m_resourceRule.getObjectMapper());
  }
  private void loadPathPatterns() throws ClassNotFoundException {
    String pkg = "com.xasecure.service";
    // List<Class> cList = findClasses(new File(dir), pkg);
    @SuppressWarnings("rawtypes")
    List<Class> cList = findClasses(pkg);
    for (@SuppressWarnings("rawtypes") Class klass : cList) {
      Annotation[] annotations = klass.getAnnotations();
      for (Annotation annotation : annotations) {
        if (!(annotation instanceof Path)) {
          continue;
        }
        Path path = (Path) annotation;
        if (path.value().startsWith("crud")) {
          continue;
        }
        // logger.info("path=" + path.value());
        // Loop over the class methods
        for (Method m : klass.getMethods()) {
          Annotation[] methodAnnotations = m.getAnnotations();
          String httpMethod = null;
          String servicePath = null;
          for (int ma = 0; ma < methodAnnotations.length; ma++) {
            if (methodAnnotations[ma] instanceof GET) {
              httpMethod = "GET";
            } else if (methodAnnotations[ma] instanceof PUT) {
              httpMethod = "PUT";
            } else if (methodAnnotations[ma] instanceof POST) {
              httpMethod = "POST";
            } else if (methodAnnotations[ma] instanceof DELETE) {
              httpMethod = "DELETE";
            } else if (methodAnnotations[ma] instanceof Path) {
              servicePath = ((Path) methodAnnotations[ma]).value();
            }
          }

          if (httpMethod == null) {
            continue;
          }

          String fullPath = path.value();
          String regEx = httpMethod + ":" + path.value();
          if (servicePath != null) {
            if (!servicePath.startsWith("/")) {
              servicePath = "/" + servicePath;
            }
            UriTemplate ut = new UriTemplate(servicePath);
            regEx = httpMethod + ":" + path.value() + ut.getPattern().getRegex();
            fullPath += servicePath;
          }
          Pattern regexPattern = Pattern.compile(regEx);

          if (regexPatternMap.containsKey(regEx)) {
            logger.warn("Duplicate regex=" + regEx + ", fullPath=" + fullPath);
          }
          regexList.add(regEx);
          regexPathMap.put(regEx, fullPath);
          regexPatternMap.put(regEx, regexPattern);

          logger.info(
              "path="
                  + path.value()
                  + ", servicePath="
                  + servicePath
                  + ", fullPath="
                  + fullPath
                  + ", regEx="
                  + regEx);
        }
      }
    }
    // ReOrder list
    int i = 0;
    for (i = 0; i < 10; i++) {
      boolean foundMatches = false;
      List<String> tmpList = new ArrayList<String>();
      for (int x = 0; x < regexList.size(); x++) {
        boolean foundMatch = false;
        String rX = regexList.get(x);
        for (int y = 0; y < x; y++) {
          String rY = regexList.get(y);
          Matcher matcher = regexPatternMap.get(rY).matcher(rX);
          if (matcher.matches()) {
            foundMatch = true;
            foundMatches = true;
            // logger.info("rX " + rX + " matched with rY=" + rY
            // + ". Moving rX to the top. Loop count=" + i);
            break;
          }
        }
        if (foundMatch) {
          tmpList.add(0, rX);
        } else {
          tmpList.add(rX);
        }
      }
      regexList = tmpList;
      if (!foundMatches) {
        logger.info("Done rearranging. loopCount=" + i);
        break;
      }
    }
    if (i == 10) {
      logger.warn("Couldn't rearrange even after " + i + " loops");
    }

    logger.info("Loaded " + regexList.size() + " API methods.");
    // for (String regEx : regexList) {
    // logger.info("regEx=" + regEx);
    // }
  }