Examples of AnonymousClassStructureBuilder


Examples of org.jboss.errai.codegen.builder.AnonymousClassStructureBuilder

        // create a subcontext and record the types we will allow the LiteralFactory to create automatic
        // snapshots for.
        final Context subContext = Context.create(context);
        subContext.addLiteralizableMetaClasses(typesToRecurseOn);

        final AnonymousClassStructureBuilder builder = ObjectBuilder.newInstanceOf(typeToExtend, context)
            .extend();
        unfinishedSnapshots.add(o);
        for (MetaMethod method : sortedMethods) {
          if (method.isFinal() || method.getName().equals("toString")) continue;

          if (logger.isDebugEnabled()) {
            logger.debug("  method " + method.getName());
            logger.debug("    return type " + method.getReturnType());
          }

          if (methodBodyCallback != null) {
            Statement providedMethod = methodBodyCallback.generateMethodBody(method, o, builder);
            if (providedMethod != null) {
              logger.debug("    body provided by callback");
              builder
                  .publicOverridesMethod(method.getName(), Parameter.of(method.getParameters()))
                  .append(providedMethod)
                  .finish();
              continue;
            }
          }

          if (method.getName().equals("equals") || method.getName().equals("hashCode")) {
            // we skip these if not provided by the callback
            if (logger.isDebugEnabled()) {
              logger.debug("    skipping special-case method " + method.getName());
            }
            continue;
          }

          if (method.getParameters().length > 0) {
            throw new GenerationException("Method " + method + " in " + typeToSnapshot +
                    " takes parameters. Such methods must be handled by the MethodBodyCallback," +
                    " because they cannot be snapshotted.");
          }

          if (method.getReturnType().equals(void.class)) {
            builder.publicOverridesMethod(method.getName()).finish();
            if (logger.isDebugEnabled()) {
              logger.debug("  finished method " + method.getName());
            }
            continue;
          }
          try {

            final Object retval = typeToExtend.asClass().getMethod(method.getName()).invoke(o);
            methodReturnVals.put(retval, method);

            if (logger.isDebugEnabled()) {
              logger.debug("    retval=" + retval);
            }

            Statement methodBody;
            if (existingSnapshots.containsKey(retval)) {
              logger.debug("    using existing snapshot");
              methodBody = existingSnapshots.get(retval);
            }
            else if (subContext.isLiteralizableClass(method.getReturnType().getErased())) {
              if (unfinishedSnapshots.contains(retval)) {
                throw new CyclicalObjectGraphException(unfinishedSnapshots);
              }

              // use Stmt.create(context) to pass the context along.
              if (logger.isDebugEnabled()) {
                logger.debug("    >> recursing for " + retval);
              }

              methodBody = Stmt.create(subContext).nestedCall(makeSnapshotAsSubclass(
                  retval, method.getReturnType(), method.getReturnType(),
                  methodBodyCallback, typesToRecurseOn, existingSnapshots, unfinishedSnapshots)).returnValue();
            }
            else {
              logger.debug("    relying on literal factory");
              methodBody = Stmt.load(retval).returnValue();
            }

            if (logger.isDebugEnabled()) {
              logger.debug("  finished method " + method.getName());
            }

            builder.publicOverridesMethod(method.getName()).append(methodBody).finish();
            existingSnapshots.put(retval, methodBody);
          }
          catch (GenerationException e) {
            e.appendFailureInfo("In attempt to snapshot return value of "
                + typeToExtend.getFullyQualifiedName() + "." + method.getName() + "()");
            throw e;
          }
          catch (RuntimeException e) {
            throw e;
          }
          catch (Exception e) {
            throw new GenerationException("Failed to extract value for snapshot", e);
          }
        }

        if (logger.isDebugEnabled()) {
          logger.debug("    finished: " + builder);
        }

        try {
          generatedCache = prettyPrintJava(builder.finish().toJavaString());
        } catch (NotLiteralizableException e) {
          MetaMethod m = methodReturnVals.get(e.getNonLiteralizableObject());
          if (m != null) {
            e.appendFailureInfo("This value came from method " +
                  m.getDeclaringClass().getFullyQualifiedNameWithTypeParms() + "." + m.getName() +
View Full Code Here

Examples of org.jboss.errai.codegen.builder.AnonymousClassStructureBuilder

    // anonQueryClassBuilder comes out as a statement that looks like this:
    // new ErraiTypedQuery(entityManager, actualResultType, parameters) {
    //   public void matches(JSONObject object) { ... }
    //   public void sort(List<T> resultList) { ... }
    // }
    AnonymousClassStructureBuilder anonQueryClassBuilder = ObjectBuilder.newInstanceOf(ErraiTypedQuery.class, context).extend(
            Stmt.loadVariable("entityManager"),
            Stmt.loadVariable("actualResultType"),
            Stmt.loadVariable("parameters"));
    appendMatchesMethod(anonQueryClassBuilder);
    appendComparatorMethod(anonQueryClassBuilder, context);

    AnonymousClassStructureBuilder factoryBuilder = ObjectBuilder.newInstanceOf(TypedQueryFactory.class, context).extend(
            Stmt.loadLiteral(resultType),
            Stmt.newArray(ErraiParameter.class).initialize((Object[]) generateQueryParamArray()));

    BlockBuilder<AnonymousClassStructureBuilder> createQueryMethod =
            factoryBuilder.protectedMethod(
                    TypedQuery.class, "createQuery", Parameter.finalOf(ErraiEntityManager.class, "entityManager"))
            .body();
    createQueryMethod.append(Stmt.nestedCall(anonQueryClassBuilder.finish()).returnValue());
    createQueryMethod.finish();

    return factoryBuilder.finish();
  }
View Full Code Here

Examples of org.jboss.errai.codegen.builder.AnonymousClassStructureBuilder

    Statement comparator;
    if (orderByParentNode == null) {
      comparator = Stmt.loadLiteral(null);
    }
    else {
      AnonymousClassStructureBuilder comparatorClassBuilder = ObjectBuilder.newInstanceOf(Comparator.class, context).extend();
      BlockBuilder<AnonymousClassStructureBuilder> compareMethod = comparatorClassBuilder
              .publicOverridesMethod("compare", Parameter.of(Object.class, "o1"), Parameter.of(Object.class, "o2"));

      // create "lhs" and "rhs" local vars of the query's result type; cast and assign Object args
      compareMethod
              .append(Stmt.declareFinalVariable("lhs", resultType, Cast.to(resultType, Stmt.loadVariable("o1"))))
View Full Code Here

Examples of org.jboss.errai.codegen.builder.AnonymousClassStructureBuilder

      qualifierNames.remove(Any.class.getName());
    }

    final MetaClass callBackType = parameterizedAs(AbstractCDIEventCallback.class, typeParametersOf(parm.getType()));

    AnonymousClassStructureBuilder callBack = Stmt.newObject(callBackType).extend();

    BlockBuilder<AnonymousClassStructureBuilder> callBackBlock;

    if (!qualifierNames.isEmpty()) {
      callBackBlock = callBack.initialize();
      for (final String qualifierName : qualifierNames) {
        callBackBlock.append(Stmt.loadClassMember("qualifierSet").invoke("add", qualifierName));
      }
      callBack = callBackBlock.finish();
    }

    callBackBlock = callBack.publicOverridesMethod("fireEvent", Parameter.finalOf(parm, "event"))
        ._(instance.callOrBind(Refs.get("event")))
        .finish()
        .publicOverridesMethod("toString")
        ._(Stmt.load("Observer: " + parmClassName + " " + Arrays.toString(qualifiers)).returnValue());
View Full Code Here

Examples of org.jboss.errai.codegen.builder.AnonymousClassStructureBuilder

    final Statement bus = instance.getInjectionContext().getInjector(MessageBus.class).getBeanInstance(instance);
    final List<Annotation> annotations = InjectUtil.extractQualifiers(instance);
    final Annotation[] qualifiers = annotations.toArray(new Annotation[annotations.size()]);
    final List<String> qualifierNames = CDI.getQualifiersPart(qualifiers);

    AnonymousClassStructureBuilder callBack = Stmt.newObject(AbstractCDIEventCallback.class).extend();

    BlockBuilder<AnonymousClassStructureBuilder> callBackBlock;
    if (qualifierNames != null) {
      callBackBlock = callBack.initialize();
      for (String qualifierName : qualifierNames) {
        callBackBlock.append(Stmt.loadClassMember("qualifierSet").invoke("add", qualifierName));
      }
      callBack = callBackBlock.finish();
    }

    callBackBlock = callBack.publicOverridesMethod("callback", Parameter.of(Message.class, "message", true))
            ._(Stmt.declareVariable("msgQualifiers", new TypeLiteral<Set<String>>() {
            },
                    Stmt.loadVariable("message").invoke("get", Set.class, CDIProtocol.Qualifiers)))
            ._(Stmt
                    .if_(Bool.or(
View Full Code Here

Examples of org.jboss.errai.codegen.builder.AnonymousClassStructureBuilder

   *          The class providing the widget content for the page.
   * @param pageName
   *          The name of the page (to be used in the URL history fragment).
   */
  private ObjectBuilder generateNewInstanceOfPageImpl(MetaClass pageClass, String pageName) {
    AnonymousClassStructureBuilder pageImplBuilder = ObjectBuilder.newInstanceOf(
            MetaClassFactory.parameterizedAs(PageNode.class, MetaClassFactory.typeParametersOf(pageClass))).extend();

    pageImplBuilder
        .publicMethod(String.class, "name")
            .append(Stmt.loadLiteral(pageName).returnValue()).finish()
        .publicMethod(Class.class, "contentType")
            .append(Stmt.loadLiteral(pageClass).returnValue()).finish()
        .publicMethod(void.class, "produceContent", Parameter.of(CreationalCallback.class, "callback"))
            .append(Stmt.nestedCall(Refs.get("bm"))
                    .invoke("lookupBean", Stmt.loadLiteral(pageClass))
                    .invoke("getInstance", Stmt.loadVariable("callback")))
                    .finish();

    appendPageHidingMethod(pageImplBuilder, pageClass);
    appendPageHiddenMethod(pageImplBuilder, pageClass);

    appendPageShowingMethod(pageImplBuilder, pageClass);
    appendPageShownMethod(pageImplBuilder, pageClass);

    return pageImplBuilder.finish();
  }
View Full Code Here

Examples of org.jboss.errai.codegen.builder.AnonymousClassStructureBuilder

   *          The class providing the widget content for the page.
   * @param pageName
   *          The name of the page (to be used in the URL history fragment).
   */
  private ObjectBuilder generateNewInstanceOfPageImpl(MetaClass pageClass, String pageName) {
    AnonymousClassStructureBuilder pageImplBuilder = ObjectBuilder.newInstanceOf(
            MetaClassFactory.parameterizedAs(PageNode.class, MetaClassFactory.typeParametersOf(pageClass))).extend();

    pageImplBuilder
        .publicMethod(String.class, "name")
            .append(Stmt.loadLiteral(pageName).returnValue()).finish()
        .publicMethod(Class.class, "contentType")
            .append(Stmt.loadLiteral(pageClass).returnValue()).finish()
        .publicMethod(pageClass, "content")
            .append(Stmt.nestedCall(Refs.get("bm"))
                    .invoke("lookupBean", Stmt.loadLiteral(pageClass)).invoke("getInstance").returnValue()).finish();

    appendPageHidingMethod(pageImplBuilder, pageClass);
    appendPageShowingMethod(pageImplBuilder, pageClass);

    return pageImplBuilder.finish();
  }
View Full Code Here

Examples of org.jboss.errai.codegen.builder.AnonymousClassStructureBuilder

    while (toMap.isArray()) {
      toMap = toMap.getComponentType();
    }
    final int dimensions = GenUtil.getArrayDimensions(arrayType);

    final AnonymousClassStructureBuilder classStructureBuilder
            = Stmt.create(mappingContext.getCodegenContext())
            .newObject(parameterizedAs(Marshaller.class, typeParametersOf(arrayType))).extend();

    classStructureBuilder.publicOverridesMethod("getTypeHandled")
            .append(Stmt.load(toMap).returnValue())
            .finish();

    final BlockBuilder<?> bBuilder = classStructureBuilder.publicOverridesMethod("demarshall",
            Parameter.of(EJValue.class, "a0"), Parameter.of(MarshallingSession.class, "a1"));

    bBuilder.append(
            Stmt.if_(Bool.isNull(loadVariable("a0")))
                    .append(Stmt.load(null).returnValue())
                    .finish()
                    .else_()
                    .append(Stmt.declareVariable(EJArray.class).named("arr")
                            .initializeWith(Stmt.loadVariable("a0").invoke("isArray")))
                    .append(Stmt.nestedCall(Stmt.loadVariable("this")).invoke("_demarshall" + dimensions,
                            loadVariable("arr"), loadVariable("a1")).returnValue())
                    .finish());
    bBuilder.finish();

    arrayDemarshallCode(toMap, dimensions, classStructureBuilder);

    BlockBuilder<?> marshallMethodBlock = classStructureBuilder.publicOverridesMethod("marshall",
            Parameter.of(toMap.asArrayOf(dimensions), "a0"), Parameter.of(MarshallingSession.class, "a1"));

    marshallMethodBlock.append(
            Stmt.if_(Bool.isNull(loadVariable("a0")))
                    .append(Stmt.load(null).returnValue())
                    .finish()
                    .else_()
                    .append(Stmt.nestedCall(Stmt.loadVariable("this")).invoke("_marshall" + dimensions,
                            loadVariable("a0"), loadVariable("a1")).returnValue())
                    .finish()
    );

    marshallMethodBlock.finish();

    return classStructureBuilder.finish();
  }
View Full Code Here

Examples of org.jboss.errai.codegen.builder.AnonymousClassStructureBuilder

    }

    return new ObjectMapper() {
      @Override
      public Statement getMarshaller() {
        AnonymousClassStructureBuilder classStructureBuilder
                = Stmt.create(context.getCodegenContext())
                .newObject(parameterizedAs(Marshaller.class, typeParametersOf(toMap))).extend();

        classStructureBuilder.publicOverridesMethod("getTypeHandled")
                .append(Stmt.load(toMap).returnValue())
                .finish();

        /**
         *
         * DEMARSHALL METHOD
         *
         */
        BlockBuilder<?> builder =
                classStructureBuilder.publicOverridesMethod("demarshall",
                        Parameter.of(EJValue.class, "a0"), Parameter.of(MarshallingSession.class, "a1"));

        BlockBuilder<CatchBlockBuilder> tryBuilder = Stmt.try_();

        tryBuilder.append(Stmt.if_(Bool.expr(Stmt.loadVariable("a0").invoke("isNull")))
                .append(Stmt.load(null).returnValue()).finish());


        tryBuilder.append(Stmt.declareVariable(EJObject.class).named("obj")
                .initializeWith(loadVariable("a0").invoke("isObject")));


        if (toMap.isEnum()) {
          tryBuilder.append(Stmt.declareVariable(toMap).named("entity")
                  .initializeWith(demarshallEnum(loadVariable("obj"), toMap)));
        }
        else {

          tryBuilder.append(Stmt.declareVariable(String.class).named("objId")
                  .initializeWith(loadVariable("obj")
                          .invoke("get", SerializationParts.OBJECT_ID)
                          .invoke("isString").invoke("stringValue")));


          tryBuilder.append(
                  Stmt.if_(Bool.expr(loadVariable("a1").invoke("hasObjectHash", loadVariable("objId"))))
                          .append(loadVariable("a1").invoke("getObject", toMap, loadVariable("objId")).returnValue()).finish());

          InstantiationMapping instantiationMapping = mapping.getInstantiationMapping();


          /**
           * Figure out how to construct this object.
           */
          Mapping[] cMappings = instantiationMapping.getMappings();
          if (cMappings.length > 0) {
            // use constructor mapping.

            final List<Statement> constructorParameters = new ArrayList<Statement>();

            for (Mapping m : mapping.getInstantiationMapping().getMappings()) {
              MetaClass type = m.getType().asBoxed();
              if (context.canMarshal(type.getFullyQualifiedName())) {
                if (type.isArray()) {
                  constructorParameters.add(context.getArrayMarshallerCallback()
                          .demarshall(type, extractJSONObjectProperty(m.getKey(), EJObject.class)));
                }
                else {
                  constructorParameters.add(fieldDemarshall(m, EJObject.class));
                }
              }
              else {
                throw new MarshallingException("no marshaller for type: " + type);
              }
            }

            if (instantiationMapping instanceof ConstructorMapping) {
              tryBuilder.append(Stmt.declareVariable(toMap).named("entity")
                      .initializeWith(Stmt.newObject(toMap)
                              .withParameters(constructorParameters.toArray(new Object[constructorParameters.size()]))));
            }
            else if (instantiationMapping instanceof FactoryMapping) {
              tryBuilder.append(Stmt.declareVariable(toMap).named("entity")
                      .initializeWith(Stmt.invokeStatic(toMap, ((FactoryMapping) instantiationMapping).getMember().getName(),
                              constructorParameters.toArray(new Object[constructorParameters.size()]))));
            }
          }
          else {
            // use default constructor

            tryBuilder.append(Stmt.declareVariable(toMap).named("entity").initializeWith(Stmt.nestedCall(Stmt.newObject(toMap))));
          }

          tryBuilder.append(loadVariable("a1").invoke("recordObjectHash",
                  loadVariable("objId"), loadVariable("entity")));
        }

        /**
         * Start binding of fields here.
         */
        for (MemberMapping memberMapping : mapping.getMemberMappings()) {
          if (!memberMapping.canWrite()) continue;

          Statement bindingStatement;
          Statement val;
          if (memberMapping.getType().isArray()) {
            val = context.getArrayMarshallerCallback()
                    .demarshall(memberMapping.getType(), extractJSONObjectProperty(memberMapping.getKey(), EJObject.class));
          }
          else {
            val = fieldDemarshall(memberMapping, MetaClassFactory.get(EJObject.class));
          }

          if (memberMapping.getBindingMember() instanceof MetaField) {
            MetaField field = (MetaField) memberMapping.getBindingMember();

            // handle long case -- GWT does not support long in JSNI
            if (field.isPublic()) {
              tryBuilder.append(loadVariable("entity").loadField(field.getName()).assignValue(val));
              continue;
            }
            else {
              MetaMethod setterMeth = GenUtil.findCaseInsensitiveMatch(null,
                      field.getDeclaringClass(), "set" + field.getName(),
                      field.getType());

              if (setterMeth != null && !setterMeth.isPrivate()) {
                // Bind via setter
                bindingStatement = loadVariable("entity").invoke(setterMeth, Cast.to(memberMapping.getTargetType(), val));
              }
              else if (field.getType().getCanonicalName().equals("long")) {
                throw new RuntimeException("cannot support private field marshalling of long type" +
                        " (not supported by JSNI) for field: "
                        + field.getDeclaringClass().getFullyQualifiedName() + "#" + field.getName());
              }
              else {
                if (!context.isExposed(field)) {
                  PrivateAccessUtil.addPrivateAccessStubs(gwtTarget, context.getClassStructureBuilder(), field);
                  context.markExposed(field);
                }

                // Bind via JSNI
                bindingStatement = Stmt.invokeStatic(context.getGeneratedBootstrapClass(),
                        PrivateAccessUtil.getPrivateFieldInjectorName(field),
                        loadVariable("entity"), val);
              }

            }
          }
          else if (memberMapping.getBindingMember() instanceof MetaMethod) {
            bindingStatement = loadVariable("entity").invoke(((MetaMethod) memberMapping.getBindingMember()),
                    Cast.to(memberMapping.getTargetType(), val));
          }
          else {
            throw new RuntimeException("unknown member mapping type: " + memberMapping.getType());
          }

          tryBuilder.append(
                  Stmt.if_(Bool.and(
                          Bool.expr(loadVariable("obj").invoke("containsKey", memberMapping.getKey())),
                          Bool.notExpr(loadVariable("obj").invoke("get", memberMapping.getKey()).invoke("isNull"))

                  )).append(bindingStatement).finish());

        }

        tryBuilder.append(loadVariable("entity").returnValue());

        tryBuilder.finish()
                .catch_(Throwable.class, "t")
                .append(loadVariable("t").invoke("printStackTrace"))
                .append(Stmt.throw_(RuntimeException.class,
                        "error demarshalling entity: " + toMap.getFullyQualifiedName(), loadVariable("t")))
                .finish();

        builder.append(tryBuilder.finish()).finish();


        /**
         *
         * MARSHAL METHOD
         *
         */
        BlockBuilder<?> marshallMethodBlock = classStructureBuilder.publicOverridesMethod("marshall",
                Parameter.of(toMap, "a0"), Parameter.of(MarshallingSession.class, "a1"));

        marshallToJSON(marshallMethodBlock, toMap, mapping);

        marshallMethodBlock.finish();

        return classStructureBuilder.finish();
      }
    };
  }
View Full Code Here

Examples of org.jboss.errai.codegen.builder.AnonymousClassStructureBuilder

    while (toMap.isArray()) {
      toMap = toMap.getComponentType();
    }
    final int dimensions = GenUtil.getArrayDimensions(arrayType);

    final AnonymousClassStructureBuilder classStructureBuilder
            = Stmt.create(mappingContext.getCodegenContext())
            .newObject(parameterizedAs(Marshaller.class, typeParametersOf(arrayType))).extend();

    classStructureBuilder.publicOverridesMethod("getTypeHandled")
            .append(Stmt.load(toMap).returnValue())
            .finish();

    final BlockBuilder<?> bBuilder = classStructureBuilder.publicOverridesMethod("demarshall",
            Parameter.of(EJValue.class, "a0"), Parameter.of(MarshallingSession.class, "a1"));

    bBuilder.append(
            Stmt.if_(Bool.isNull(loadVariable("a0")))
                    .append(Stmt.load(null).returnValue())
                    .finish()
                    .else_()
                    .append(Stmt.declareVariable(EJArray.class).named("arr")
                            .initializeWith(Stmt.loadVariable("a0").invoke("isArray")))
                    .append(Stmt.nestedCall(Stmt.loadVariable("this")).invoke("_demarshall" + dimensions,
                            loadVariable("arr"), loadVariable("a1")).returnValue())
                    .finish());
    bBuilder.finish();

    arrayDemarshallCode(toMap, dimensions, classStructureBuilder);

    BlockBuilder<?> marshallMethodBlock = classStructureBuilder.publicOverridesMethod("marshall",
            Parameter.of(toMap.asArrayOf(dimensions), "a0"), Parameter.of(MarshallingSession.class, "a1"));

    marshallMethodBlock.append(
            Stmt.if_(Bool.isNull(loadVariable("a0")))
                    .append(Stmt.load(null).returnValue())
                    .finish()
                    .else_()
                    .append(Stmt.nestedCall(Stmt.loadVariable("this")).invoke("_marshall" + dimensions,
                            loadVariable("a0"), loadVariable("a1")).returnValue())
                    .finish()
    );

    marshallMethodBlock.finish();

    return classStructureBuilder.finish();
  }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.