Package org.jboss.errai.codegen

Examples of org.jboss.errai.codegen.BlockStatement


  /**
   * Generates code to collect all existing properties and their types.
   */
  private Statement generatePropertiesMap() {
    BlockStatement block = new BlockStatement();
    for (String property : bindable.getBeanDescriptor().getProperties()) {
      MetaMethod readMethod = bindable.getBeanDescriptor().getReadMethodForProperty(property);
      if (readMethod != null && !readMethod.isFinal()) {
        block.addStatement(agent("propertyTypes").invoke(
            "put",
            property,
            Stmt.newObject(PropertyType.class, readMethod.getReturnType().asBoxed().asClass(),
                DataBindingUtil.isBindableType(readMethod.getReturnType()),
                readMethod.getReturnType().isAssignableTo(List.class))
            )
        );
      }
    }
    return (block.isEmpty()) ? EmptyStatement.INSTANCE : block;
  }
View Full Code Here


  /**
   * Generates method body for recursively unwrapping a {@link BindableProxy}.
   */
  private Statement generateDeepUnwrapMethodBody(final String methodName) {
    final String cloneVar = "clone";
    final BlockStatement block = new BlockStatement();
    block.addStatement(Stmt.declareFinalVariable(cloneVar, bindable, Stmt.newObject(bindable)));
   
    for (final String property : bindable.getBeanDescriptor().getProperties()) {
      final MetaMethod readMethod = bindable.getBeanDescriptor().getReadMethodForProperty(property);
      final MetaMethod writeMethod = bindable.getBeanDescriptor().getWriteMethodForProperty(property);
      if (readMethod != null && writeMethod != null) {
        MetaClass type = readMethod.getReturnType();
        if (!DataBindingUtil.isBindableType(type)) {
          // If we find a collection we copy its elements and unwrap them if necessary
          // TODO support map types
          if (type.isAssignableTo(Collection.class)) {
            String colVarName = property + "Clone";
            String elemVarName = property + "Elem";
           
            if ((type.isInterface() || type.isAbstract()) &&
                    (type.isAssignableTo(List.class) || type.isAssignableTo(Set.class))) {
              MetaClass clazz = (type.isAssignableTo(Set.class))
                      ? MetaClassFactory.get(HashSet.class) : MetaClassFactory.get(ArrayList.class);
              block.addStatement(Stmt.declareFinalVariable(colVarName, type.getErased(), Stmt.newObject(clazz)));
            }
            else {
              if (!type.isInterface() && !type.isAbstract()) {
                block.addStatement(Stmt.declareFinalVariable(colVarName, type.getErased(), Stmt.newObject(type.getErased())));
              }
              else {
                logger.log(TreeLogger.WARN, "Bean validation on collection " + property + " in class " + bindable +
                        " won't work. Change to either List or Set or use a concrete type instead.");
                continue;
              }
            }
            // Check if the collection element is proxied and unwrap if necessary
            block.addStatement(
              Stmt.nestedCall(target().invoke(readMethod)).foreach(elemVarName, Object.class)
               .append (
                 If.instanceOf(Refs.get(elemVarName), BindableProxy.class)
                  .append (Stmt.loadVariable(colVarName)
                    .invoke("add", Stmt.castTo(BindableProxy.class, Stmt.loadVariable(elemVarName)).invoke(methodName))
                  )
               .finish()
               .else_()
                 .append(Stmt.loadVariable(colVarName).invoke("add", Refs.get(elemVarName)))
               .finish()
             )
             .finish());
           
            block.addStatement(Stmt.loadVariable(cloneVar).invoke(writeMethod, Refs.get(colVarName)));
          }
          else {
            block.addStatement(Stmt.loadVariable(cloneVar).invoke(writeMethod,target().invoke(readMethod)));
          }
        }
        // Found a bindable property: Generate code to unwrap for the case the instance is proxied
        else {
          final Statement field = target().invoke(readMethod);
          block.addStatement (
            If.instanceOf(field, BindableProxy.class)
              .append(Stmt.loadVariable(cloneVar).invoke(writeMethod,
                        Cast.to (
                            readMethod.getReturnType(),
                            Stmt.castTo(BindableProxy.class, Stmt.loadVariable("this").invoke(readMethod))
                            .invoke(methodName)
                        )
                    )
                )
              .finish()
              .else_()
                .append(Stmt.loadVariable(cloneVar).invoke(writeMethod, target().invoke(readMethod)))
              .finish()
          );
        }
      }
    }
   
    block.addStatement(Stmt.loadVariable(cloneVar).returnValue());
   
    return block;
  }
View Full Code Here

  /**
   * Generates the code to collect all existing properties and their types.
   */
  private Statement generatePropertiesMap() {
    BlockStatement block = new BlockStatement();
    for (String property : bindable.getBeanDescriptor().getProperties()) {
      MetaMethod readMethod = bindable.getBeanDescriptor().getReadMethodForProperty(property);
      if (readMethod != null && !readMethod.isFinal()) {
        block.addStatement(agent("propertyTypes").invoke(
            "put",
            property,
            Stmt.newObject(PropertyType.class, readMethod.getReturnType().asBoxed().asClass(),
                readMethod.getReturnType().isAnnotationPresent(Bindable.class))
            )
            );
      }
    }
    return (block.isEmpty()) ? EmptyStatement.INSTANCE : block;
  }
View Full Code Here

    context.getBootstrapClass().getInstanceInitializer().addStatement(Stmt.nestedCall(Stmt.newObject(CDI.class))
            .invoke("initLookupTable", Stmt.invokeStatic(CDIEventTypeLookup.class, "get")));
  }

  public static void addTypeHeirarchyFor(IOCProcessingContext context, final Set<MetaClass> classes) {
    final BlockStatement instanceInitializer = context.getBootstrapClass().getInstanceInitializer();
    for (final MetaClass subClass : classes) {
      MetaClass cls = subClass;
      do {
        if (cls != subClass) {
          instanceInitializer.addStatement(Stmt.invokeStatic(CDIEventTypeLookup.class, "get")
                  .invoke("addLookup", subClass.getFullyQualifiedName(), cls.getFullyQualifiedName()));
        }

        for (MetaClass interfaceClass : cls.getInterfaces()) {
          instanceInitializer.addStatement(Stmt.invokeStatic(CDIEventTypeLookup.class, "get")
                  .invoke("addLookup", subClass.getFullyQualifiedName(), interfaceClass.getFullyQualifiedName()));

        }
      }
      while ((cls = cls.getSuperClass()) != null);
View Full Code Here

  /**
   * Generates the code to collect all existing properties and their type.
   */
  private Statement generatePropertiesMap() {
    BlockStatement block = new BlockStatement();
    for (String property : bindable.getBeanDescriptor().getProperties()) {
      MetaMethod readMethod = bindable.getBeanDescriptor().getReadMethodForProperty(property);
      if (readMethod != null && !readMethod.isFinal()) {
        block.addStatement(agent("propertyTypes").invoke(
            "put",
            property,
            Stmt.newObject(PropertyType.class, readMethod.getReturnType().asBoxed().asClass(),
                readMethod.getReturnType().isAnnotationPresent(Bindable.class))
            )
View Full Code Here

   * @param params
   *          the resource method's parameters
   * @return the URL statement
   */
  private Statement generateUrl(final JaxrsResourceMethodParameters params) {
    BlockStatement block = new BlockStatement();
    block.addStatement(Stmt.declareVariable("url", StringBuilder.class,
        Stmt.newObject(StringBuilder.class, new StringStatement("getBaseUrl()"))));

    // construct path using @PathParams and @MatrixParams
    String path = resourceMethod.getPath();
    ContextualStatementBuilder pathValue = Stmt.loadLiteral(path);

    for (String pathParamName : JaxrsResourceMethodParameters.getPathParameterNames(path)) {
      String pathParamId = pathParamName;
      if (pathParamName.contains(":")) {
        pathParamId = pathParamName.split(":")[0];
      }
      Statement pathParam = marshal(params.getPathParameter(pathParamId));
      if (params.needsEncoding(pathParamId)) {
        pathParam = encodePath(pathParam);
      }
      pathValue = pathValue.invoke("replace", "{" + pathParamName + "}", pathParam);
    }

    if (params.getMatrixParameters() != null) {
      for (String matrixParamName : params.getMatrixParameters().keySet()) {
        pathValue = pathValue.invoke("concat", ";" + matrixParamName + "=")
            .invoke("concat", encodePath(marshal(params.getMatrixParameter(matrixParamName))));
      }
    }

    ContextualStatementBuilder urlBuilder = Stmt.loadVariable("url").invoke(APPEND, pathValue);
    block.addStatement(urlBuilder);

    // construct query using @QueryParams
    if (params.getQueryParameters() != null) {
      urlBuilder = urlBuilder.invoke(APPEND, "?");
      int i = 0;
      for (String queryParamName : params.getQueryParameters().keySet()) {
        for (Statement queryParam : params.getQueryParameters(queryParamName)) {

          MetaClass queryParamType = queryParam.getType();
          if (isListOrSet(queryParamType)) {
            MetaClass paramType = assertValidCollectionParam(queryParamType, queryParamName, QueryParam.class);
            ContextualStatementBuilder listParam = (queryParam instanceof Parameter) ?
                Stmt.loadVariable(((Parameter) queryParam).getName()) : Stmt.nestedCall(queryParam);

            block.addStatement(listParam.foreach("p")
                .append(If.not(Stmt.loadVariable("url").invoke("toString").invoke("endsWith", "?"))
                    .append(Stmt.loadVariable("url").invoke(APPEND, "&")).finish())
                .append(Stmt.loadVariable("url").invoke(APPEND, queryParamName).invoke(APPEND, "=")
                    .invoke(APPEND, encodeQuery(marshal(paramType, Stmt.loadVariable("p")))))
                .finish()
View Full Code Here

   *          the resource method's parameters
   * @return a block statement with the corresponding calls to
   *         {@link RequestBuilder#setHeader(String, String)}
   */
  private Statement generateHeaders(final JaxrsResourceMethodParameters params) {
    BlockStatement block = new BlockStatement();

    // set headers based on method and class
    for (String key : resourceMethod.getHeaders().keySet()) {
      block.addStatement(Stmt.loadVariable("requestBuilder").invoke("setHeader", key,
          resourceMethod.getHeaders().get(key)));
    }

    // set headers based on @HeaderParams
    if (params.getHeaderParameters() != null) {
      for (String headerParamName : params.getHeaderParameters().keySet()) {
        ContextualStatementBuilder headerValueBuilder = Stmt.nestedCall(Stmt.newObject(StringBuilder.class));

        int i = 0;
        for (Statement headerParam : params.getHeaderParameters(headerParamName)) {
          if (i++ > 0) {
            headerValueBuilder = headerValueBuilder.invoke(APPEND, ",");
          }
          headerValueBuilder = headerValueBuilder.invoke(APPEND, marshal(headerParam));
        }

        block.addStatement(Stmt.loadVariable("requestBuilder").invoke("setHeader", headerParamName,
            headerValueBuilder.invoke("toString")));
      }
    }

    // set cookies based on @CookieParams
    if (params.getCookieParameters() != null) {
      for (String cookieName : params.getCookieParameters().keySet()) {
        Statement cookieParam = params.getCookieParameters().get(cookieName).get(0);

        ContextualStatementBuilder setCookie = (cookieParam instanceof Parameter) ?
            Stmt.loadVariable(((Parameter) cookieParam).getName()) :
              Stmt.nestedCall(cookieParam);

        setCookie.if_(BooleanOperator.NotEquals, null)
            .append(Stmt.invokeStatic(Cookies.class, "setCookie", cookieName, marshal(cookieParam)))
            .finish();

        block.addStatement(setCookie);
      }
    }
    return block.isEmpty() ? null : block;
  }
View Full Code Here

   * @param params
   *          the resource method's parameters
   * @return the URL statement
   */
  private Statement generateUrl(final JaxrsResourceMethodParameters params) {
    BlockStatement block = new BlockStatement();
    block.addStatement(Stmt.declareVariable("url", StringBuilder.class,
        Stmt.newObject(StringBuilder.class, new StringStatement("getBaseUrl()"))));

    // construct path using @PathParams and @MatrixParams
    String path = resourceMethod.getPath();
    ContextualStatementBuilder pathValue = Stmt.loadLiteral(path);

    for (String pathParamName : JaxrsResourceMethodParameters.getPathParameterNames(path)) {
      String pathParamId = pathParamName;
      if (pathParamName.contains(":")) {
        pathParamId = pathParamName.split(":")[0];
      }
      Statement pathParam = marshal(params.getPathParameter(pathParamId));
      if (params.needsEncoding(pathParamId)) {
        pathParam = encodePath(pathParam);
      }
      pathValue = pathValue.invoke("replace", "{" + pathParamName + "}", pathParam);
    }

    if (params.getMatrixParameters() != null) {
      for (String matrixParamName : params.getMatrixParameters().keySet()) {
        pathValue = pathValue.invoke("concat", ";" + matrixParamName + "=")
            .invoke("concat", encodePath(marshal(params.getMatrixParameter(matrixParamName))));
      }
    }
    ContextualStatementBuilder urlBuilder = Stmt.loadVariable("url").invoke(APPEND, pathValue);

    // construct query using @QueryParams
    if (params.getQueryParameters() != null) {
      urlBuilder = urlBuilder.invoke(APPEND, "?");

      int i = 0;
      for (String queryParamName : params.getQueryParameters().keySet()) {
        for (Statement queryParam : params.getQueryParameters(queryParamName)) {
          if (i++ > 0)
            urlBuilder = urlBuilder.invoke(APPEND, "&");

          urlBuilder = urlBuilder.invoke(APPEND, queryParamName).invoke(APPEND, "=")
              .invoke(APPEND, encodeQuery(marshal(queryParam)));
        }
      }
    }

    if (urlBuilder != null)
      block.addStatement(urlBuilder);

    return block;
  }
View Full Code Here

   * @param params
   *          the resource method's parameters
   * @return a block statement with the corresponding calls to {@link RequestBuilder#setHeader(String, String)}
   */
  private Statement generateHeaders(final JaxrsResourceMethodParameters params) {
    BlockStatement block = new BlockStatement();

    // set headers based on method and class
    for (String key : resourceMethod.getHeaders().keySet()) {
      block.addStatement(Stmt.loadVariable("requestBuilder").invoke("setHeader", key,
          resourceMethod.getHeaders().get(key)));
    }

    // set headers based on @HeaderParams
    if (params.getHeaderParameters() != null) {
      for (String headerParamName : params.getHeaderParameters().keySet()) {
        ContextualStatementBuilder headerValueBuilder = Stmt.nestedCall(Stmt.newObject(StringBuilder.class));

        int i = 0;
        for (Statement headerParam : params.getHeaderParameters(headerParamName)) {
          if (i++ > 0) {
            headerValueBuilder = headerValueBuilder.invoke(APPEND, ",");
          }
          headerValueBuilder = headerValueBuilder.invoke(APPEND, marshal(headerParam));
        }

        block.addStatement(Stmt.loadVariable("requestBuilder").invoke("setHeader", headerParamName,
            headerValueBuilder.invoke("toString")));
      }
    }

    // set cookies based on @CookieParams
    if (params.getCookieParameters() != null) {
      for (String cookieName : params.getCookieParameters().keySet()) {
        Statement cookieParam = params.getCookieParameters().get(cookieName).get(0);

        ContextualStatementBuilder setCookie = (cookieParam instanceof Parameter) ?
            Stmt.loadVariable(((Parameter) cookieParam).getName()) :
              Stmt.nestedCall(cookieParam);

        setCookie.if_(BooleanOperator.NotEquals, null)
            .append(Stmt.invokeStatic(Cookies.class, "setCookie", cookieName, marshal(cookieParam)))
            .finish();

        block.addStatement(setCookie);
      }
    }
    return block.isEmpty() ? null : block;
  }
View Full Code Here

  public BlockBuilderImpl() {
    this(null);
  }

  public BlockBuilderImpl(final BuildCallback<T> callback) {
    this(new BlockStatement(), callback);
  }
View Full Code Here

TOP

Related Classes of org.jboss.errai.codegen.BlockStatement

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.