Package org.jboss.errai.marshalling.rebind.api.model

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


    constructor.finish();
  }

  public void addOrMarkMarshallerUnlazy(final MetaClass type) {
    final MappingDefinition definition = mappingContext.getDefinitionsFactory().getDefinition(type);
    if (definition == null) {
      unlazyMarshallers.add(type.getFullyQualifiedName());
    }
    else if (definition.isLazy()) {
      definition.setLazy(false);
      addMarshaller(type);
    }
  }
View Full Code Here


  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();

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

        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<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("Encountered non-marshallable type " + toMap +
                          " while building a marshaller for " + mappingDefinition.getMappingClass());
                }
              }
              else {
                if (context.canMarshal(type.getFullyQualifiedName())) {
                  Statement s = maybeAddAssumedTypes(builder,
                      "c" + constructorParameters.size(),
                      //    null,
                      mapping, fieldDemarshall(mapping, EJObject.class));

                  constructorParameters.add(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, constructorParameters.toArray(new Object[constructorParameters.size()]))));
              }
              else {
                PrivateAccessUtil.addPrivateAccessStubs(gwtTarget ? "jsni" : "reflection", context.getClassStructureBuilder(), constructor);
                builder.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) {
              builder.append(Stmt.declareVariable(toMap).named("entity")
                  .initializeWith(
                      Stmt.invokeStatic(toMap, ((FactoryMapping) instantiationMapping).getMember().getName(),
                          constructorParameters.toArray(new Object[constructorParameters.size()]))));
            }
          }
          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

    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

      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 (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 framework: "
                  + 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

    mappingDefinitions.put(key, value);
  }

  @Override
  public MappingDefinition getDefinition(final MetaClass clazz) {
    MappingDefinition def = getDefinition(clazz.getFullyQualifiedName());
    if (def == null) {
      def = getDefinition(clazz.getInternalName());
    }
    return def;
  }
View Full Code Here

        throw new RuntimeException("@CustomMapping class: " + cls.getName() + " does not inherit "
            + MappingDefinition.class.getName());
      }

      try {
        final MappingDefinition definition = (MappingDefinition) cls.newInstance();
        definition.setMarshallerInstance(new DefaultDefinitionMarshaller(definition));
        addDefinition(definition);

        if (!envExposedClasses.contains(definition.getMappingClass())) {
          definition.setLazy(true);
        }

        exposedClasses.add(definition.getMappingClass());

        if (log.isDebugEnabled())
          log.debug("loaded custom mapping class: " + cls.getName() + " (for mapping: "
              + definition.getMappingClass().getFullyQualifiedName() + ")");

        if (cls.isAnnotationPresent(InheritedMappings.class)) {
          final InheritedMappings inheritedMappings = cls.getAnnotation(InheritedMappings.class);

          for (final Class<?> c : inheritedMappings.value()) {
            final MetaClass metaClass = MetaClassFactory.get(c);
            final MappingDefinition aliasMappingDef = new MappingDefinition(metaClass, definition.alreadyGenerated());
            aliasMappingDef.setMarshallerInstance(new DefaultDefinitionMarshaller(aliasMappingDef));
            addDefinition(aliasMappingDef);

            if (!envExposedClasses.contains(metaClass)) {
              aliasMappingDef.setLazy(true);
            }

            exposedClasses.add(metaClass);

            if (log.isDebugEnabled())
              log.debug("mapping inherited mapping " + c.getName() + " -> " + cls.getName());
          }
        }
      }
      catch (Throwable t) {
        throw new RuntimeException("Failed to load definition", t);
      }
    }

    for (final MappingDefinition def : mappingDefinitions.values()) {
      mergeDefinition(def);
    }

    final Collection<MetaClass> cliMarshallers = ClassScanner.getTypesAnnotatedWith(ClientMarshaller.class, true);
    final MetaClass Marshaller_MC = MetaClassFactory.get(Marshaller.class);

    for (final MetaClass marshallerMetaClass : cliMarshallers) {
      if (Marshaller_MC.isAssignableFrom(marshallerMetaClass)) {
        final Class<? extends Marshaller> marshallerCls = marshallerMetaClass.asClass().asSubclass(Marshaller.class);
        try {
          final Class<?> type = marshallerMetaClass.getAnnotation(ClientMarshaller.class).value();

          final MappingDefinition marshallMappingDef = new MappingDefinition(type, true);
          marshallMappingDef.setClientMarshallerClass(marshallerCls);
          addDefinition(marshallMappingDef);

          exposedClasses.add(MetaClassFactory.get(type).asBoxed());

          if (marshallerCls.isAnnotationPresent(ImplementationAliases.class)) {
            for (final Class<?> aliasCls : marshallerCls.getAnnotation(ImplementationAliases.class).value()) {
              final MappingDefinition aliasMappingDef = new MappingDefinition(aliasCls, true);
              aliasMappingDef.setClientMarshallerClass(marshallerCls.asSubclass(Marshaller.class));
              addDefinition(aliasMappingDef);

              exposedClasses.add(MetaClassFactory.get(aliasCls).asBoxed());
              mappingAliases.put(aliasCls.getName(), type.getName());
            }
          }
        }
        catch (Throwable t) {
          throw new RuntimeException("could not instantiate marshaller class: " + marshallerCls.getName(), t);
        }
      }
      else {
        throw new RuntimeException("class annotated with " + ClientMarshaller.class.getCanonicalName()
            + " does not implement " + Marshaller.class.getName());
      }
    }

    final Set<Class<?>> serverMarshallers = scanner.getTypesAnnotatedWith(ServerMarshaller.class, true);

    for (final Class<?> marshallerCls : serverMarshallers) {
      if (Marshaller.class.isAssignableFrom(marshallerCls)) {
        try {
          final Class<?> type = marshallerCls.getAnnotation(ServerMarshaller.class).value();
          final MappingDefinition definition;

          if (hasDefinition(type)) {
            definition = getDefinition(type);
            definition.setServerMarshallerClass(marshallerCls.asSubclass(Marshaller.class));
          }
          else {
            definition = new MappingDefinition(type, true);
            definition.setServerMarshallerClass(marshallerCls.asSubclass(Marshaller.class));
            addDefinition(definition);

            exposedClasses.add(MetaClassFactory.get(type).asBoxed());
          }

          if (marshallerCls.isAnnotationPresent(ImplementationAliases.class)) {
            for (final Class<?> aliasCls : marshallerCls.getAnnotation(ImplementationAliases.class).value()) {
              if (hasDefinition(aliasCls)) {
                getDefinition(aliasCls).setServerMarshallerClass(marshallerCls.asSubclass(Marshaller.class));
              }
              else {
                final MappingDefinition aliasMappingDef = new MappingDefinition(aliasCls, true);
                aliasMappingDef.setServerMarshallerClass(marshallerCls.asSubclass(Marshaller.class));
                addDefinition(aliasMappingDef);

                exposedClasses.add(MetaClassFactory.get(aliasCls));
                mappingAliases.put(aliasCls.getName(), type.getName());
              }
            }
          }
        }
        catch (Throwable t) {
          throw new RuntimeException("could not instantiate marshaller class: " + marshallerCls.getName(), t);
        }
      }
      else {
        throw new RuntimeException("class annotated with " + ServerMarshaller.class.getCanonicalName()
            + " does not implement " + Marshaller.class.getName());
      }
    }


    exposedClasses.addAll(envExposedClasses);

    final Map<String, String> configuredMappingAliases = new HashMap<String, String>();
    configuredMappingAliases.putAll(environmentConfig.getMappingAliases());
    configuredMappingAliases.putAll(defaultMappingAliases());

    mappingAliases.putAll(configuredMappingAliases);

    final Map<MetaClass, MetaClass> aliasToMarshaller = new HashMap<MetaClass, MetaClass>();

    final List<MetaClass> enums = new ArrayList<MetaClass>();

    for (final MetaClass cls : exposedClasses) {
      MetaClass mappedClass;
      if (cls.isArray()) {
        arraySignatures.add(cls);
        mappedClass = cls.getOuterComponentType();
      }
      else {
        mappedClass = cls;
      }

      if (mappedClass.isSynthetic())
        continue;

      final Portable portable = mappedClass.getAnnotation(Portable.class);
      if (portable != null && !portable.aliasOf().equals(Object.class)) {
        aliasToMarshaller.put(mappedClass, MetaClassFactory.get(portable.aliasOf()));
      }
      else if (!hasDefinition(mappedClass)) {
        final MappingDefinition def = DefaultJavaDefinitionMapper.map(mappedClass, this);
        def.setMarshallerInstance(new DefaultDefinitionMarshaller(def));
        addDefinition(def);

        for (final Mapping mapping : def.getAllMappings()) {
          if (mapping.getType().isEnum()) {
            enums.add(mapping.getType());
          }
        }
      }
    }

    for (final MetaClass enumType : enums) {
      if (!hasDefinition(enumType)) {
        final MappingDefinition enumDef = DefaultJavaDefinitionMapper
            .map(MetaClassFactory.get(enumType.asClass()), this);
        enumDef.setMarshallerInstance(new DefaultDefinitionMarshaller(enumDef));
        addDefinition(enumDef);
        exposedClasses.add(MetaClassFactory.get(enumType.asClass()));
      }
    }

    for (final Map.Entry<String, String> entry : configuredMappingAliases.entrySet()) {
      try {
        aliasToMarshaller.put(MetaClassFactory.get(entry.getKey()), MetaClassFactory.get(entry.getValue()));
      }
      catch (Throwable t) {
        throw new RuntimeException("error loading mapping alias", t);
      }
    }


    for (final Map.Entry<MetaClass, MetaClass> entry : aliasToMarshaller.entrySet()) {
      final MappingDefinition def = getDefinition(entry.getValue());
      if (def == null) {
        throw new InvalidMappingException("cannot alias type " + entry.getKey().getName()
            + " to " + entry.getValue().getName() + ": the specified alias type does not exist ");
      }

      final MappingDefinition aliasDef = new MappingDefinition(
          def.getMarshallerInstance(), entry.getKey(), false
      );
      if (def.getMarshallerInstance() instanceof DefaultDefinitionMarshaller) {
        aliasDef.setMarshallerInstance(new DefaultDefinitionMarshaller(aliasDef));
      }
      else {
        aliasDef.setClientMarshallerClass(def.getClientMarshallerClass());
        aliasDef.setServerMarshallerClass(def.getServerMarshallerClass());
      }
      mergeDefinition(aliasDef);
      addDefinition(aliasDef);
    }

    for (final Map.Entry<String, MappingDefinition> entry : mappingDefinitions.entrySet()) {
      fillInheritanceMap(entry.getValue().getMappingClass());
    }

    final MetaClass javaLangObjectRef = MetaClassFactory.get(Object.class);

    for (final Map.Entry<String, MappingDefinition> entry : mappingDefinitions.entrySet()) {
      final MappingDefinition def = entry.getValue();

      final InstantiationMapping instantiationMapping = def.getInstantiationMapping();
      for (final Mapping mapping : instantiationMapping.getMappings()) {
        if (shouldUseObjectMarshaller(mapping.getType().getErased())) {
          mapping.setType(javaLangObjectRef);
        }
      }
View Full Code Here

  }

  @Override
  public boolean shouldUseObjectMarshaller(final MetaClass type) {
    final boolean hasPortableSubtypes = inheritanceMap.containsKey(type.getFullyQualifiedName());
    final MappingDefinition definition = getDefinition(type);
    final boolean hasMarshaller = definition != null;

    if (hasMarshaller) {
      if (definition.getClass().isAnnotationPresent(CustomMapping.class)
          || definition.getClientMarshallerClass() != null) {
        return false;
      }
    }

    final boolean isConcrete = !(type.isAbstract() || type.isInterface());
View Full Code Here

  public void mergeDefinition(final MappingDefinition def) {
    MetaClass cls = def.getMappingClass();

    while ((cls = cls.getSuperClass()) != null) {
      if (hasDefinition(cls) && cls.getParameterizedType() == null) {
        final MappingDefinition toMerge = getDefinition(cls);
        final Set<String> parentKeys = new HashSet<String>();

        for (final Mapping m : toMerge.getInstantiationMapping().getMappings())
          parentKeys.add(m.getKey());

        for (final MemberMapping m : toMerge.getMemberMappings())
          parentKeys.add(m.getKey());

        final Iterator<MemberMapping> defMappings = def.getMemberMappings().iterator();
        while (defMappings.hasNext()) {
          if (parentKeys.contains(defMappings.next().getKey()))
            defMappings.remove();
        }

        for (final MemberMapping memberMapping : toMerge.getMemberMappings()) {
          def.addInheritedMapping(memberMapping);
        }

        final InstantiationMapping instantiationMapping = def.getInstantiationMapping();

        if (instantiationMapping instanceof ConstructorMapping &&
            def.getInstantiationMapping().getMappings().length == 0 &&
            def.getMappingClass().getDeclaredConstructor(toMerge.getInstantiationMapping().getSignature()) != null) {

          final ConstructorMapping parentConstructorMapping = (ConstructorMapping) toMerge.getInstantiationMapping();
          final MetaClass mergingClass = def.getMappingClass();

          if (parentConstructorMapping instanceof SimpleConstructorMapping) {
            final ConstructorMapping newMapping = ((SimpleConstructorMapping) parentConstructorMapping)
                .getCopyForInheritance();
View Full Code Here

  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();

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

        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<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("Encountered non-marshallable type " + toMap +
                          " while building a marshaller for " + mappingDefinition.getMappingClass());
                }
              }
              else {
                if (context.canMarshal(type.getFullyQualifiedName())) {
                  Statement s = maybeAddAssumedTypes(builder,
                      "c" + constructorParameters.size(),
                      //    null,
                      mapping, fieldDemarshall(mapping, EJObject.class));

                  constructorParameters.add(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, constructorParameters.toArray(new Object[constructorParameters.size()]))));
              }
              else {
                PrivateAccessUtil.addPrivateAccessStubs(gwtTarget ? "jsni" : "reflection", context.getClassStructureBuilder(), constructor);
                builder.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) {
              builder.append(Stmt.declareVariable(toMap).named("entity")
                  .initializeWith(
                      Stmt.invokeStatic(toMap, ((FactoryMapping) instantiationMapping).getMember().getName(),
                          constructorParameters.toArray(new Object[constructorParameters.size()]))));
            }
          }
          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

    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

TOP

Related Classes of org.jboss.errai.marshalling.rebind.api.model.MappingDefinition

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.