Examples of MappingDefinition


Examples of org.jboss.errai.marshalling.rebind.api.model.MappingDefinition

    if (!stack.contains(definition)) {
      stack.add(definition);

      for (MemberMapping mapping : definition.getMemberMappings()) {
        MappingDefinition def = context.getDefinitionsFactory().getDefinition(mapping.getType());

        if (def == null) {
          if (mapping.getType().isArray()) {
            def = context.getDefinitionsFactory().getDefinition(mapping.getType().getOuterComponentType().asBoxed());
View Full Code Here

Examples of org.jboss.errai.marshalling.rebind.api.model.MappingDefinition

            if (m.isAnnotationPresent(AlwaysQualify.class)) {
              marshaller = new QualifyingMarshallerWrapper(marshaller);
            }

            MappingDefinition def = new MappingDefinition(marshaller, true);

            if (m.isAnnotationPresent(ClientMarshaller.class)) {
              def.setClientMarshallerClass(m.asSubclass(Marshaller.class));
            }

            factory.addDefinition(def);

            if (m.isAnnotationPresent(ImplementationAliases.class)) {
              for (Class<?> inherits : m.getAnnotation(ImplementationAliases.class).value()) {
                factory.addDefinition(new MappingDefinition(marshaller, inherits, true));
              }
            }

            /**
             * Load the default array marshaller.
             */
            MetaClass arrayType = MetaClassFactory.get(marshaller.getTypeHandled()).asArrayOf(1);
            if (!factory.hasDefinition(arrayType)) {
              factory.addDefinition(new MappingDefinition(
                      EncDecUtil.qualifyMarshaller(new DefaultArrayMarshaller(arrayType, marshaller)), true));

              /**
               * If this a pirmitive wrapper, create a special case for it using the same marshaller.
               */
              if (MarshallUtil.isPrimitiveWrapper(marshaller.getTypeHandled())) {
                factory.addDefinition(new MappingDefinition(
                        EncDecUtil.qualifyMarshaller(new DefaultArrayMarshaller(
                                arrayType.getOuterComponentType().asUnboxed().asArrayOf(1), marshaller)), true));
              }
            }

          }
          catch (ClassCastException e) {
            throw new RuntimeException("@ServerMarshaller class "
                    + m.getName() + " is not an instance of " + Marshaller.class.getName());
          }
          catch (Throwable t) {
            throw new RuntimeException("Error instantiating " + m.getName(), t);
          }
        }

        for (Class<?> exposed : factory.getExposedClasses()) {
          if (exposed.isAnnotationPresent(Portable.class)) {
            Portable p = exposed.getAnnotation(Portable.class);

            if (!p.aliasOf().equals(Object.class)) {
              if (!factory.hasDefinition(p.aliasOf())) {
                throw new RuntimeException("cannot alias " + exposed.getName() + " to unmapped type: "
                        + p.aliasOf().getName());
              }

              factory.getDefinition(exposed)
                      .setMarshallerInstance(factory.getDefinition(p.aliasOf()).getMarshallerInstance());
            }

            if (exposed.isEnum()) {
              factory.getDefinition(exposed)
                      .setMarshallerInstance(new DefaultEnumMarshaller(exposed));
            }

            MappingDefinition definition = factory.getDefinition(exposed);

            for (MemberMapping mapping : definition.getMemberMappings()) {
              if (mapping.getType().isArray()) {
                MetaClass type = mapping.getType();
                MetaClass compType = type.getOuterComponentType();

                if (!factory.hasDefinition(type.getInternalName())) {
                  MappingDefinition outerDef = factory.getDefinition(compType);

                  Marshaller<Object> marshaller = outerDef.getMarshallerInstance();

                  MappingDefinition def = new MappingDefinition(EncDecUtil.qualifyMarshaller(
                          new DefaultArrayMarshaller(type, marshaller)), true);

                  def.setClientMarshallerClass(outerDef.getClientMarshallerClass());

                  factory.addDefinition(def);
                }
              }
            }
          }
        }

        for (Map.Entry<String, String> entry : factory.getMappingAliases().entrySet()) {
          MappingDefinition def = factory.getDefinition(entry.getValue());
          MappingDefinition aliasDef = new MappingDefinition(MetaClassFactory.get(entry.getKey()), true);
          aliasDef.setMarshallerInstance(def.getMarshallerInstance());

          factory.addDefinition(aliasDef);
        }
      }

      @Override
      public DefinitionsFactory getDefinitionsFactory() {
        return factory;
      }

      @Override
      public Marshaller<Object> getMarshaller(String clazz) {
        MappingDefinition def = factory.getDefinition(clazz);

        if (def == null) {
          throw new MarshallingException("class is not available to the marshaller framework: " + clazz);
        }

        return def.getMarshallerInstance();
      }

      @Override
      public boolean hasMarshaller(String clazzName) {
        return factory.hasDefinition(clazzName);
View Full Code Here

Examples of org.jboss.errai.marshalling.rebind.api.model.MappingDefinition

      return definitionsFactory.getDefinition(toMap.asBoxed());
    }

    final Set<MetaConstructor> constructors = new HashSet<MetaConstructor>();
    final SimpleConstructorMapping simpleConstructorMapping = new SimpleConstructorMapping();
    final MappingDefinition definition = new MappingDefinition(toMap, false);

    for (MetaConstructor c : toMap.getDeclaredConstructors()) {
      List<Boolean> hasMapsTos = new ArrayList<Boolean>();
      if (c.getParameters().length != 0) {
        for (int i = 0; i < c.getParameters().length; i++) {
          final Annotation[] annotations = c.getParameters()[i].getAnnotations();
          if (annotations.length == 0) {
            hasMapsTos.add(false);
          }
          else {
            boolean hasMapsTo = false;
            for (Annotation a : annotations) {
              if (MapsTo.class.isAssignableFrom(a.annotationType())) {
                hasMapsTo = true;
                MapsTo mapsTo = (MapsTo) a;
                String key = mapsTo.value();
                simpleConstructorMapping.mapParmToIndex(key, i, c.getParameters()[i].getType());
              }
            }
            hasMapsTos.add(hasMapsTo);
          }
        }
        if (hasMapsTos.contains(true) && hasMapsTos.contains(false)) {
          throw new InvalidMappingException("Not all parameters of constructor " + c.asConstructor()
              + " have a @" + MapsTo.class.getSimpleName() + " annotation");
        }

        if (hasMapsTos.contains(true)) {
          constructors.add(c);
        }
      }
    }

    final MetaConstructor constructor;
    if (constructors.isEmpty()) {
      constructor = toMap.getConstructor(new MetaClass[0]);
    }
    else if (constructors.size() > 1) {
      throw new InvalidMappingException("found more than one matching constructor for mapping: "
              + toMap.getFullyQualifiedName());
    }
    else {
      constructor = constructors.iterator().next();
    }

    simpleConstructorMapping.setConstructor(constructor);
    definition.setInstantiationMapping(simpleConstructorMapping);

    if (toMap.isEnum()) {
      return definition;
    }

    if (simpleConstructorMapping.getMappings().length == 0) {
      final Set<MetaMethod> factoryMethods = new HashSet<MetaMethod>();
      final SimpleFactoryMapping simpleFactoryMapping = new SimpleFactoryMapping();

      for (final MetaMethod method : toMap.getDeclaredMethods()) {
        if (method.isStatic()) {
          List<Boolean> hasMapsTos = new ArrayList<Boolean>();
          for (int i = 0; i < method.getParameters().length; i++) {
            final Annotation[] annotations = method.getParameters()[i].getAnnotations();
            if (annotations.length == 0) {
              hasMapsTos.add(false);
            }
            else {
              boolean hasMapsTo = false;
              for (Annotation a : annotations) {
                if (MapsTo.class.isAssignableFrom(a.annotationType())) {
                  hasMapsTo = true;
                  MapsTo mapsTo = (MapsTo) a;
                  String key = mapsTo.value();
                  simpleFactoryMapping.mapParmToIndex(key, i, method.getParameters()[i].getType());
                }
              }
              hasMapsTos.add(hasMapsTo);
            }
          }
          if (hasMapsTos.contains(true) && hasMapsTos.contains(false)) {
            throw new InvalidMappingException("Not all parameters of method " + method.asMethod()
                + " have a @" + MapsTo.class.getSimpleName() + " annotation");
          }

          if (hasMapsTos.contains(true)) {
            factoryMethods.add(method);
          }
        }
      }

      if (factoryMethods.size() > 1) {
        throw new InvalidMappingException("found more than one matching factory method for mapping: "
                + toMap.getFullyQualifiedName());
      }
      else if (factoryMethods.size() == 1) {
        final MetaMethod method = factoryMethods.iterator().next();
        simpleFactoryMapping.setMethod(method);
        definition.setInheritedInstantiationMapping(simpleFactoryMapping);
      }
    }

    if (definition.getInstantiationMapping() instanceof ConstructorMapping
            && definition.getInstantiationMapping().getMappings().length == 0) {

      final MetaConstructor defaultConstructor = toMap.getDeclaredConstructor();
      if (defaultConstructor == null || !defaultConstructor.isPublic()) {
        throw new InvalidMappingException("there is no custom mapping or default no-arg constructor to map: "
                + toMap.getFullyQualifiedName());
      }
    }

    final Set<String> writeKeys = new HashSet<String>();
    final Set<String> readKeys = new HashSet<String>();

    for (final Mapping m : simpleConstructorMapping.getMappings()) {
      writeKeys.add(m.getKey());
    }

    for (final MetaMethod method : toMap.getDeclaredMethods()) {
      if (method.isAnnotationPresent(Key.class)) {
        final String key = method.getAnnotation(Key.class).value();

        if (method.getParameters().length == 0) {
          // assume this is a getter

          definition.addMemberMapping(new ReadMapping(key, method.getReturnType(), method.getName()));
          readKeys.add(key);
        }
        else if (method.getParameters().length == 1) {
          // assume this is a setter

          definition.addMemberMapping(new WriteMapping(key, method.getParameters()[0].getType(), method.getName()));
          writeKeys.add(key);
        }
        else {
          throw new InvalidMappingException("annotated @Key method is unrecognizable as a setter or getter: "
                  + toMap.getFullyQualifiedName() + "#" + method.getName());
        }
      }
    }

    MetaClass c = toMap;

    do {
      for (final MetaField field : c.getDeclaredFields()) {
        if (definitionsFactory.hasDefinition(field.getDeclaringClass())
                || field.isTransient() || field.isStatic()) {
          continue;
        }

        try {
          final Field fld = field.asField();
          fld.setAccessible(true);
        }
        catch (IllegalStateException e) {
          // field is not known to the current classloader. continue anyway.
        }

        if (writeKeys.contains(field.getName()) && readKeys.contains(field.getName())) {
          continue;
        }

        final MetaClass type = field.getType().getErased();
        final MetaClass compType = type.isArray() ? type.getOuterComponentType().asBoxed() : type.asBoxed();

        if (!(compType.isAbstract() || compType.isInterface() || compType.isEnum()) && !definitionsFactory.isExposedClass(compType)) {
          throw new InvalidMappingException("portable entity " + toMap.getFullyQualifiedName()
                  + " contains a field (" + field.getName() + ") that is not known to the marshaller: "
                  + compType.getFullyQualifiedName());
        }

        /**
         * This case handles the case where a constructor mapping has mapped the value, and there is no manually mapped
         * reader on the key.
         */
        if (writeKeys.contains(field.getName()) && !readKeys.contains(field.getName())) {
          final MetaMethod getterMethod = MarshallingGenUtil.findGetterMethod(toMap, field.getName());

          if (getterMethod != null) {
            definition.addMemberMapping(new ReadMapping(field.getName(), field.getType(), getterMethod.getName()));
            continue;
          }
        }

        definition.addMemberMapping(new MemberMapping() {
          private MetaClass type = (field.getType().isArray() ? field.getType() : field.getType());
          private final MetaClass targetType = type.getErased().asBoxed();

          @Override
          public MetaClassMember getBindingMember() {
View Full Code Here

Examples of org.jboss.errai.marshalling.rebind.api.model.MappingDefinition

  public ObjectMapper getMapper() {
    return generateJavaBeanMapper();
  }

  private ObjectMapper generateJavaBeanMapper() {
    final MappingDefinition mappingDefinition = context.getDefinitionsFactory().getDefinition(toMap);

    if (mappingDefinition == null) {
      throw new InvalidMappingException("no definition for: " + toMap.getFullyQualifiedName());
    }

    if ((toMap.isAbstract() || toMap.isInterface()) && !toMap.isEnum()) {
      throw new RuntimeException("cannot map an abstract class or interface: " + toMap.getFullyQualifiedName());
    }

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

        final MetaClass arrayType = toMap.asArrayOf(1);
        classStructureBuilder.privateField("EMPTY_ARRAY", arrayType).initializesWith(Stmt.newArray(toMap, 0)).finish();

        classStructureBuilder.publicMethod(arrayType, "getEmptyArray")
            .append(Stmt.loadClassMember("EMPTY_ARRAY").returnValue())
            .finish();

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

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

        final 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"), loadVariable("a0"), 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("hasObject", loadVariable("objId"))))
                          .append(loadVariable("a1")
                                  .invoke("getObject", toMap, loadVariable("objId")).returnValue()).finish());

          final InstantiationMapping instantiationMapping = mappingDefinition.getInstantiationMapping();

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

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

            for (final Mapping mapping : mappingDefinition.getInstantiationMapping().getMappings()) {
              final MetaClass type = mapping.getType().asBoxed();
                if (type.isArray()) {
                  MetaClass toMap = type;
                  while (toMap.isArray()) {
                    toMap = toMap.getComponentType();
                  }
                  if (context.canMarshal(toMap.getFullyQualifiedName())) {
                    constructorParameters.add(context.getArrayMarshallerCallback()
                          .demarshall(type, extractJSONObjectProperty(mapping.getKey(), EJObject.class)));
                  }
                  else {
                    throw new MarshallingException("no marshaller for type: " + toMap);
                  }
                }
                else {
                  if (context.canMarshal(type.getFullyQualifiedName())) {
                    Statement s = maybeAddAssumedTypes(tryBuilder, "c" + constructorParameters.size(),
                        mapping, fieldDemarshall(mapping, EJObject.class));

                    constructorParameters.add(s);
                  }
                  else {
                    throw new MarshallingException("no marshaller for type: " + type);
                  }
                }
            }

            if (instantiationMapping instanceof ConstructorMapping) {
              final ConstructorMapping mapping = (ConstructorMapping) instantiationMapping;
              final MetaConstructor constructor = mapping.getMember();

              if (constructor.isPublic()) {
                tryBuilder.append(Stmt.declareVariable(toMap).named("entity")
                    .initializeWith(Stmt.newObject(toMap, constructorParameters.toArray(new Object[constructorParameters.size()]))));
              }
              else {
                PrivateAccessUtil.addPrivateAccessStubs(gwtTarget ? "jsni" : "reflection", context.getClassStructureBuilder(), constructor);
                tryBuilder.append(Stmt.declareVariable(toMap).named("entity")
                    .initializeWith(
                        Stmt.invokeStatic(
                            context.getClassStructureBuilder().getClassDefinition(),
                            PrivateAccessUtil.getPrivateMethodName(constructor),
                            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._(
                Stmt.declareVariable(toMap).named("entity").initializeWith(
                Stmt.nestedCall(Stmt.newObject(toMap))));
          }

          tryBuilder._(loadVariable("a1").invoke("recordObject",
                  loadVariable("objId"), loadVariable("entity")));
        }

        /**
         *
         * FIELD BINDINGS
         *
         */
        for (final MemberMapping memberMapping : mappingDefinition.getMemberMappings()) {
          if (!memberMapping.canWrite()) continue;

          if (memberMapping.getTargetType().isConcrete() && !context.isRendered(memberMapping.getTargetType())) {
             context.getMarshallerGeneratorFactory().addMarshaller(memberMapping.getTargetType());
          }
View Full Code Here

Examples of org.jboss.errai.marshalling.rebind.api.model.MappingDefinition

    if (!stack.contains(definition)) {
      stack.add(definition);

      for (final MemberMapping mapping : definition.getMemberMappings()) {
        MappingDefinition def = context.getDefinitionsFactory().getDefinition(mapping.getType());

        if (def == null) {
          if (mapping.getType().isArray()) {
            def = context.getDefinitionsFactory().getDefinition(mapping.getType().getOuterComponentType().asBoxed());
View Full Code Here

Examples of org.jboss.errai.marshalling.rebind.api.model.MappingDefinition

    }

    Set<MetaConstructor> constructors = new HashSet<MetaConstructor>();

    SimpleConstructorMapping simpleConstructorMapping = new SimpleConstructorMapping();
    MappingDefinition definition = new MappingDefinition(toMap);

    for (MetaConstructor c : toMap.getConstructors()) {
      if (c.getParameters().length != 0) {
        boolean satisifed = true;
        FieldScan:
        for (int i = 0; i < c.getParameters().length; i++) {
          Annotation[] annotations = c.getParameters()[i].getAnnotations();
          if (annotations.length == 0) {
            satisifed = false;
          }
          else {
            for (Annotation a : annotations) {
              if (!MapsTo.class.isAssignableFrom(a.annotationType())) {
                satisifed = false;
                break FieldScan;
              }
              else {
                MapsTo mapsTo = (MapsTo) a;
                String key = mapsTo.value();
                simpleConstructorMapping.mapParmToIndex(key, i, c.getParameters()[i].getType());
              }
            }
          }
        }

        if (satisifed) {
          constructors.add(c);
        }
      }
    }

    MetaConstructor constructor;
    if (constructors.isEmpty()) {
      constructor = toMap.getConstructor(new MetaClass[0]);
    }
    else if (constructors.size() > 1) {
      throw new InvalidMappingException("found more than one matching constructor for mapping: "
              + toMap.getFullyQualifiedName());
    }
    else {
      constructor = constructors.iterator().next();
      simpleConstructorMapping.setConstructor(constructor);
    }

    definition.setInstantiationMapping(simpleConstructorMapping);

    if (toMap.isEnum()) {
      return definition;
    }

    if (simpleConstructorMapping.getMappings().length == 0) {
      Set<MetaMethod> factoryMethods = new HashSet<MetaMethod>();

      SimpleFactoryMapping simpleFactoryMapping = new SimpleFactoryMapping();
      for (MetaMethod method : toMap.getDeclaredMethods()) {
        if (method.isStatic()) {
          boolean satisifed = true;
          FieldScan:
          for (int i = 0; i < method.getParameters().length; i++) {
            Annotation[] annotations = method.getParameters()[i].getAnnotations();
            if (annotations.length == 0) {
              satisifed = false;
            }
            else {
              for (Annotation a : annotations) {
                if (!MapsTo.class.isAssignableFrom(a.annotationType())) {
                  satisifed = false;
                  break FieldScan;
                }
                else {
                  MapsTo mapsTo = (MapsTo) a;
                  String key = mapsTo.value();
                  simpleFactoryMapping.mapParmToIndex(key, i, method.getParameters()[i].getType());
                }
              }
            }

            if (satisifed) {
              factoryMethods.add(method);
            }
          }
        }
      }

      if (factoryMethods.size() > 1) {
        throw new InvalidMappingException("found more than one matching factory method for mapping: "
                + toMap.getFullyQualifiedName());
      }
      else if (factoryMethods.size() == 1) {
        final MetaMethod meth = factoryMethods.iterator().next();
        simpleFactoryMapping.setMethod(meth);
        definition.setInheritedInstantiationMapping(simpleFactoryMapping);
      }
    }

    if (definition.getInstantiationMapping() instanceof ConstructorMapping
            && definition.getInstantiationMapping().getMappings().length == 0) {

      MetaConstructor defaultConstructor = toMap.getDeclaredConstructor();
      if (defaultConstructor == null || !defaultConstructor.isPublic()) {
        throw new InvalidMappingException("there is no custom mapping or default no-arg constructor to map: "
                + toMap.getFullyQualifiedName());
      }
    }

    Set<String> writeKeys = new HashSet<String>();
    Set<String> readKeys = new HashSet<String>();

    for (Mapping m : simpleConstructorMapping.getMappings()) {
      writeKeys.add(m.getKey());
    }

    for (MetaMethod method : toMap.getDeclaredMethods()) {
      if (method.isAnnotationPresent(Key.class)) {
        String key = method.getAnnotation(Key.class).value();

        if (method.getParameters().length == 0) {
          // assume this is a getter

          definition.addMemberMapping(new ReadMapping(key, method.getReturnType(), method.getName()));
          readKeys.add(key);
        }
        else if (method.getParameters().length == 1) {
          // assume this is a setter

          definition.addMemberMapping(new WriteMapping(key, method.getParameters()[0].getType(), method.getName()));
          writeKeys.add(key);
        }
        else {
          throw new InvalidMappingException("annotated @Key method is unrecognizable as a setter or getter: "
                  + toMap.getFullyQualifiedName() + "#" + method.getName());
        }
      }
    }

    MetaClass c = toMap;

    do {
      for (final MetaField field : c.getDeclaredFields()) {
        if (definitionsFactory.hasDefinition(field.getDeclaringClass())
                || field.isTransient() || field.isStatic()) {
          continue;
        }

        field.asField().setAccessible(true);

        if (writeKeys.contains(field.getName()) && readKeys.contains(field.getName())) {
          continue;
        }

        MetaClass type = field.getType();
        MetaClass compType = type.isArray() ? type.getOuterComponentType().asBoxed() : type.asBoxed();

        if (!type.isEnum() && !definitionsFactory.isExposedClass(compType.asClass())) {
          throw new InvalidMappingException("portable entity " + toMap.getFullyQualifiedName()
                  + " contains a field (" + field.getName() + ") that is not known to the marshaller: "
                  + compType.getFullyQualifiedName());
        }

        /**
         * This case handles the case where a constructor mapping has mapped the value, and there is no
         * manually mapped reader on the key.
         */
        if (writeKeys.contains(field.getName()) && !readKeys.contains(field.getName())) {
          MetaMethod getterMethod = MarshallingGenUtil.findGetterMethod(toMap, field.getName());

          if (getterMethod != null) {
            definition.addMemberMapping(new ReadMapping(field.getName(), field.getType(), getterMethod.getName()));
            continue;
          }
        }

        definition.addMemberMapping(new MemberMapping() {
          private MetaClass type = (field.getType().isArray() ? field.getType() : field.getType());
          private MetaClass targetType = type;

          @Override
          public MetaClassMember getBindingMember() {
View Full Code Here

Examples of org.jboss.errai.marshalling.rebind.api.model.MappingDefinition

            if (m.isAnnotationPresent(AlwaysQualify.class)) {
              marshaller = new QualifyingMarshallerWrapper(marshaller);
            }

            factory.addDefinition(new MappingDefinition(marshaller));

            if (m.isAnnotationPresent(ImplementationAliases.class)) {
              for (Class<?> inherits : m.getAnnotation(ImplementationAliases.class).value()) {
                factory.addDefinition(new MappingDefinition(marshaller, inherits));
              }
            }

            /**
             * Load the default array marshaller.
             */
            MetaClass arrayType = MetaClassFactory.get(marshaller.getTypeHandled()).asArrayOf(1);
            if (!factory.hasDefinition(arrayType)) {
              factory.addDefinition(new MappingDefinition(
                      EncDecUtil.qualifyMarshaller(new DefaultArrayMarshaller(arrayType, marshaller))));

              /**
               * If this a pirmitive wrapper, create a special case for it using the same marshaller.
               */
              if (MarshallUtil.isPrimitiveWrapper(marshaller.getTypeHandled())) {
                factory.addDefinition(new MappingDefinition(
                        EncDecUtil.qualifyMarshaller(new DefaultArrayMarshaller(
                                arrayType.getOuterComponentType().asUnboxed().asArrayOf(1), marshaller))));
              }
            }

          }
          catch (ClassCastException e) {
            throw new RuntimeException("@ServerMarshaller class "
                    + m.getName() + " is not an instance of " + Marshaller.class.getName());
          }
          catch (Throwable t) {
            throw new RuntimeException("Error instantiating " + m.getName(), t);
          }
        }

        for (Class<?> exposed : factory.getExposedClasses()) {
          if (exposed.isAnnotationPresent(Portable.class)) {
            Portable p = exposed.getAnnotation(Portable.class);

            if (!p.aliasOf().equals(Object.class)) {
              if (!factory.hasDefinition(p.aliasOf())) {
                throw new RuntimeException("cannot alias " + exposed.getName() + " to unmapped type: "
                        + p.aliasOf().getName());
              }

              factory.getDefinition(exposed)
                      .setMarshallerInstance(factory.getDefinition(p.aliasOf()).getMarshallerInstance());
            }

            if (exposed.isEnum()) {
              factory.getDefinition(exposed)
                      .setMarshallerInstance(new DefaultEnumMarshaller(exposed));
            }

            MappingDefinition definition = factory.getDefinition(exposed);

            for (MemberMapping mapping : definition.getMemberMappings()) {
              if (mapping.getType().isArray()) {
                MetaClass type = mapping.getType();
                MetaClass compType = type.getOuterComponentType();

                if (!factory.hasDefinition(type.getInternalName())) {
                  Marshaller<Object> marshaller = factory.getDefinition(compType).getMarshallerInstance();

                  MappingDefinition def = new MappingDefinition(EncDecUtil.qualifyMarshaller(
                          new DefaultArrayMarshaller(type, marshaller)));

                  factory.addDefinition(def);
                }
              }
            }
          }
        }

        for (Map.Entry<String, String> entry : factory.getMappingAliases().entrySet()) {
          MappingDefinition def = factory.getDefinition(entry.getValue());
          MappingDefinition aliasDef = new MappingDefinition(MetaClassFactory.get(entry.getKey()));
          aliasDef.setMarshallerInstance(def.getMarshallerInstance());

          factory.addDefinition(aliasDef);
        }
      }

      @Override
      public DefinitionsFactory getDefinitionsFactory() {
        return factory;
      }

      @Override
      public Marshaller<Object> getMarshaller(String clazz) {
        MappingDefinition def = factory.getDefinition(clazz);

        if (def == null) {
          throw new MarshallingException("class is not available to the marshaller framework: " + clazz);
        }

        return def.getMarshallerInstance();
      }

      @Override
      public boolean hasMarshaller(String clazzName) {
        return factory.hasDefinition(clazzName);
View Full Code Here

Examples of org.jboss.errai.marshalling.rebind.api.model.MappingDefinition

  public ObjectMapper getMapper() {
    return generateJavaBeanMapper();
  }

  private ObjectMapper generateJavaBeanMapper() {
    final MappingDefinition mappingDefinition = context.getDefinitionsFactory().getDefinition(toMap);

    if (mappingDefinition == null) {
      throw new InvalidMappingException("no definition for: " + toMap.getFullyQualifiedName());
    }

    if ((toMap.isAbstract() || toMap.isInterface()) && !toMap.isEnum()) {
      throw new RuntimeException("cannot map an abstract class or interface: " + toMap.getFullyQualifiedName());
    }

    return new ObjectMapper() {
      @Override
      public ClassStructureBuilder<?> getMarshaller(String marshallerClassName) {
        ClassDefinitionStaticOption<?> staticOption = ClassBuilder.define(marshallerClassName).publicScope();

        ClassStructureBuilder<?> classStructureBuilder = null;
        BlockBuilder<?> initMethod = null;
        if (!gwtTarget)
          classStructureBuilder = staticOption.staticClass().implementsInterface(
              parameterizedAs(GeneratedMarshaller.class, typeParametersOf(toMap))).body();
        else {
          classStructureBuilder = staticOption.implementsInterface(
              parameterizedAs(GeneratedMarshaller.class, typeParametersOf(toMap))).body();
        }
        initMethod = classStructureBuilder.privateMethod(void.class, "lazyInit");

        final MetaClass arrayType = toMap.asArrayOf(1);
        classStructureBuilder.privateField("EMPTY_ARRAY", arrayType).initializesWith(Stmt.newArray(toMap, 0)).finish();

        classStructureBuilder.publicMethod(arrayType, "getEmptyArray")
            .append(Stmt.loadClassMember("EMPTY_ARRAY").returnValue())
            .finish();

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

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

        if (toMap.isEnum()) {
          builder.append(Stmt.declareVariable(toMap).named("entity")
              .initializeWith(demarshallEnum(loadVariable("obj"), loadVariable("a0"), toMap)));
        }
        else {
          builder.append(If.cond(Bool.isNull(Refs.get("obj"))).append(Stmt.load(null).returnValue()).finish());

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

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

          final InstantiationMapping instantiationMapping = mappingDefinition.getInstantiationMapping();

          /**
           * Figure out how to construct this object.
           */
          final Mapping[] cMappings = instantiationMapping.getMappings();
          if (cMappings.length > 0) {
            // use constructor mapping.
            final List<String> memberKeys = new ArrayList<String>();
            for (MemberMapping memberMapping : mappingDefinition.getMemberMappings()) {
              memberKeys.add(memberMapping.getKey());
            }
           
            final Statement[] constructorParameters = new Statement[cMappings.length];

            for (final Mapping mapping : instantiationMapping.getMappingsInKeyOrder(memberKeys)) {
              int parmIndex = instantiationMapping.getIndex(mapping.getKey());
              final MetaClass type = mapping.getType().asBoxed();
              BlockBuilder<?> lazyInitMethod = (needsLazyInit(type)) ? initMethod : null;
              if (type.isArray()) {
                MetaClass toMap = type;
                while (toMap.isArray()) {
                  toMap = toMap.getComponentType();
                }
                if (context.canMarshal(toMap.getFullyQualifiedName())) {
                  if (gwtTarget) {
                    BuildMetaClass arrayMarshaller = MarshallerGeneratorFactory.createArrayMarshallerClass(type);
                   
                    if (!containsInnerClass(classStructureBuilder, arrayMarshaller)) {
                      classStructureBuilder.declaresInnerClass(new InnerClass(arrayMarshaller));
                    }
                    Statement deferred = context.getArrayMarshallerCallback().deferred(type, arrayMarshaller);
                    MarshallingGenUtil.ensureMarshallerFieldCreated(classStructureBuilder, toMap, type, lazyInitMethod,
                        deferred);
                    constructorParameters[parmIndex] =
                        Stmt.loadVariable(MarshallingGenUtil.getVarName(type)).invoke("demarshall",
                            extractJSONObjectProperty(mapping.getKey(), EJObject.class), Stmt.loadVariable("a1"));
                  }
                  else {
                    MarshallingGenUtil.ensureMarshallerFieldCreated(classStructureBuilder, toMap, type, lazyInitMethod);
                    constructorParameters[parmIndex] = context.getArrayMarshallerCallback()
                        .demarshall(type, extractJSONObjectProperty(mapping.getKey(), EJObject.class));
                  }
                }
                else {
                  throw new MarshallingException("Encountered non-marshallable type " + toMap +
                          " while building a marshaller for " + mappingDefinition.getMappingClass());
                }
              }
              else {
                MarshallingGenUtil.ensureMarshallerFieldCreated(classStructureBuilder, toMap, type, lazyInitMethod);
                if (context.canMarshal(type.getFullyQualifiedName())) {
                  Statement s = maybeAddAssumedTypes(builder,
                      "c" + parmIndex,
                      mapping, fieldDemarshall(mapping, EJObject.class));

                  constructorParameters[parmIndex] =  s;
                }
                else {
                  throw new MarshallingException("Encountered non-marshallable type " + type +
                          " while building a marshaller for " + mappingDefinition.getMappingClass());
                }
              }
            }

            if (instantiationMapping instanceof ConstructorMapping) {
              final ConstructorMapping mapping = (ConstructorMapping) instantiationMapping;
              final MetaConstructor constructor = mapping.getMember();

              if (constructor.isPublic()) {
                builder
                    .append(Stmt.declareVariable(toMap).named("entity")
                        .initializeWith(
                            Stmt.newObject(toMap, (Object[]) constructorParameters)));
              }
              else {
                PrivateAccessUtil.addPrivateAccessStubs(gwtTarget ? "jsni" : "reflection", classStructureBuilder,
                    constructor);
                builder.append(Stmt.declareVariable(toMap).named("entity")
                    .initializeWith(
                        Stmt.invokeStatic(
                            classStructureBuilder.getClassDefinition(),
                            PrivateAccessUtil.getPrivateMethodName(constructor),
                            (Object[]) constructorParameters)));
              }
            }
            else if (instantiationMapping instanceof FactoryMapping) {
              builder.append(Stmt.declareVariable(toMap).named("entity")
                  .initializeWith(
                      Stmt.invokeStatic(toMap, ((FactoryMapping) instantiationMapping).getMember().getName(),
                              (Object[]) constructorParameters)));
            }
          }
          else {
            // use default constructor

            builder._(
                Stmt.declareVariable(toMap).named("entity").initializeWith(
                    Stmt.nestedCall(Stmt.newObject(toMap))));
          }

          builder._(loadVariable("a1").invoke("recordObject",
              loadVariable("objId"), loadVariable("entity")));
        }

        /**
         *
         * FIELD BINDINGS
         *
         */
        for (final MemberMapping memberMapping : mappingDefinition.getMemberMappings()) {
          if (!memberMapping.canWrite())
            continue;
          if (memberMapping.getTargetType().isConcrete() && !context.isRendered(memberMapping.getTargetType())) {
            context.getMarshallerGeneratorFactory().addMarshaller(memberMapping.getTargetType());
          }
View Full Code Here

Examples of org.jboss.errai.marshalling.rebind.api.model.MappingDefinition

    if (!stack.contains(definition)) {
      stack.add(definition);

      for (final MemberMapping mapping : definition.getMemberMappings()) {
        MappingDefinition def = context.getDefinitionsFactory().getDefinition(mapping.getType());

        if (def == null) {
          if (mapping.getType().isArray()) {
            def = context.getDefinitionsFactory().getDefinition(mapping.getType().getOuterComponentType().asBoxed());
View Full Code Here

Examples of org.jboss.errai.marshalling.rebind.api.model.MappingDefinition

            if (m.isAnnotationPresent(AlwaysQualify.class)) {
              marshaller = new QualifyingMarshallerWrapper(marshaller);
            }

            MappingDefinition def = new MappingDefinition(marshaller, true);

            if (m.isAnnotationPresent(ClientMarshaller.class)) {
              def.setClientMarshallerClass(m.asSubclass(Marshaller.class));
            }

            factory.addDefinition(def);

            if (m.isAnnotationPresent(ImplementationAliases.class)) {
              for (Class<?> inherits : m.getAnnotation(ImplementationAliases.class).value()) {
                factory.addDefinition(new MappingDefinition(marshaller, inherits, true));
              }
            }

            /**
             * Load the default array marshaller.
             */
            MetaClass arrayType = MetaClassFactory.get(marshaller.getTypeHandled()).asArrayOf(1);
            if (!factory.hasDefinition(arrayType)) {
              factory.addDefinition(new MappingDefinition(
                      EncDecUtil.qualifyMarshaller(new DefaultArrayMarshaller(arrayType, marshaller)), true));

              /**
               * If this a pirmitive wrapper, create a special case for it using the same marshaller.
               */
              if (MarshallUtil.isPrimitiveWrapper(marshaller.getTypeHandled())) {
                factory.addDefinition(new MappingDefinition(
                        EncDecUtil.qualifyMarshaller(new DefaultArrayMarshaller(
                                arrayType.getOuterComponentType().asUnboxed().asArrayOf(1), marshaller)), true));
              }
            }

          }
          catch (ClassCastException e) {
            throw new RuntimeException("@ServerMarshaller class "
                    + m.getName() + " is not an instance of " + Marshaller.class.getName());
          }
          catch (Throwable t) {
            throw new RuntimeException("Error instantiating " + m.getName(), t);
          }
        }

        for (Class<?> exposed : factory.getExposedClasses()) {
          if (exposed.isAnnotationPresent(Portable.class)) {
            Portable p = exposed.getAnnotation(Portable.class);

            if (!p.aliasOf().equals(Object.class)) {
              if (!factory.hasDefinition(p.aliasOf())) {
                throw new RuntimeException("cannot alias " + exposed.getName() + " to unmapped type: "
                        + p.aliasOf().getName());
              }

              factory.getDefinition(exposed)
                      .setMarshallerInstance(factory.getDefinition(p.aliasOf()).getMarshallerInstance());
            }

            if (exposed.isEnum()) {
              factory.getDefinition(exposed)
                      .setMarshallerInstance(new DefaultEnumMarshaller(exposed));
            }

            MappingDefinition definition = factory.getDefinition(exposed);

            for (MemberMapping mapping : definition.getMemberMappings()) {
              if (mapping.getType().isArray()) {
                MetaClass type = mapping.getType();
                MetaClass compType = type.getOuterComponentType();

                if (!factory.hasDefinition(type.getInternalName())) {
                  MappingDefinition outerDef = factory.getDefinition(compType);

                  Marshaller<Object> marshaller = outerDef.getMarshallerInstance();

                  MappingDefinition def = new MappingDefinition(EncDecUtil.qualifyMarshaller(
                          new DefaultArrayMarshaller(type, marshaller)), true);

                  def.setClientMarshallerClass(outerDef.getClientMarshallerClass());

                  factory.addDefinition(def);
                }
              }
            }
          }
        }

        for (Map.Entry<String, String> entry : factory.getMappingAliases().entrySet()) {
          MappingDefinition def = factory.getDefinition(entry.getValue());
          MappingDefinition aliasDef = new MappingDefinition(MetaClassFactory.get(entry.getKey()), true);
          aliasDef.setMarshallerInstance(def.getMarshallerInstance());

          factory.addDefinition(aliasDef);
        }
      }

      @Override
      public DefinitionsFactory getDefinitionsFactory() {
        return factory;
      }

      @Override
      public Marshaller<Object> getMarshaller(String clazz) {
        MappingDefinition def = factory.getDefinition(clazz);

        if (def == null) {
          throw new MarshallingException("class is not available to the marshaller framework: " + clazz);
        }

        return def.getMarshallerInstance();
      }

      @Override
      public boolean hasMarshaller(String clazzName) {
        return factory.hasDefinition(clazzName);
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.