com.google.gwt.core.ext.typeinfo.JType Java Examples

The following examples show how to use com.google.gwt.core.ext.typeinfo.JType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InjectServiceCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
public InjectServiceCreator(JType viewType, JField serviceField) {
	this.viewType = viewType;
	this.serviceField = serviceField;

	this.serviceName = serviceField.getType().getQualifiedSourceName();

	Class fieldClass;
	try {
		fieldClass = this.getClass().getClassLoader().loadClass(serviceField.getType().getQualifiedBinaryName());
		if (ServiceProxy.class.isAssignableFrom(fieldClass)) {
			this.declareProxy = false;
			this.proxyTypeName = serviceField.getType().getQualifiedSourceName();
		} else {
			this.proxyTypeName = "_" + serviceField.getName() + "ServiceProxy";
		}
	} catch (ClassNotFoundException e) {
		throw new RuntimeException(e.getMessage(), e);
	}
}
 
Example #2
Source File: RestServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String typeAsString(JType type, boolean translatePrimitives) {
	StringBuilder sb = new StringBuilder();
	if (translatePrimitives && type instanceof JPrimitiveType) {
		sb.append(((JPrimitiveType) type).getQualifiedBoxedSourceName());
	} else {
		sb.append(type.getSimpleSourceName());
		if (type instanceof JParameterizedType) {
			JParameterizedType parameterizedType = (JParameterizedType) type;
			sb.append("<");
			int i = 0;
			for (JType paramType : parameterizedType.getTypeArgs()) {
				if (i++ > 0) {
					sb.append(", ");
				}
				sb.append(this.typeAsString(paramType, false));
			}
			sb.append(">");
		}
	}
	return sb.toString();
}
 
Example #3
Source File: XMLElement.java    From gwt-material-demo with Apache License 2.0 6 votes vote down vote up
/**
 * Like {@link #consumeAttributeWithDefault(String, String, JType)}, but
 * accommodates more complex type signatures.
 */
public String consumeAttributeWithDefault(String name, String defaultValue, JType... types)
    throws UnableToCompleteException {

  if (!hasAttribute(name)) {
    if (defaultValue != null) {
      designTime.putAttribute(this, name + ".default", defaultValue);
    }
    return defaultValue;
  }

  AttributeParser parser = attributeParsers.getParser(types);
  if (parser == null) {
    logger.die("Attribute '" + name + "' cannot be parsed, null parser. " +
        "Please ensure the content of this attribute matches its assignment method.");
  }
  return consumeAttributeWithParser(name, parser);
}
 
Example #4
Source File: RestServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void collectImports() {
	Collection<JType> toImports = Sets.newHashSet();
	for (JMethod method : this.serviceType.getOverridableMethods()) {
		toImports.add(method.getReturnType());
		for (JParameter parameter : method.getParameters()) {
			toImports.add(parameter.getType());
		}
	}
	this.imports.addAll(toImports);
	for (JType importType : this.imports) {
		if (importType instanceof JParameterizedType) {
			JParameterizedType parameterizedType = (JParameterizedType) importType;
			for (JType paramType : parameterizedType.getTypeArgs()) {
				toImports.add(paramType);
			}
		}
	}
	this.imports.addAll(toImports);
}
 
Example #5
Source File: JTypeName.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
/**
 * @param boxed true if the primitive should be boxed. Useful when use in a parameterized type.
 * @param type the type
 *
 * @return the {@link TypeName}
 */
public TypeName typeName( boolean boxed, JType type ) {
    if ( null != type.isPrimitive() ) {
        return primitiveName( type.isPrimitive(), boxed );
    } else if ( null != type.isParameterized() ) {
        return parameterizedName( type.isParameterized() );
    } else if ( null != type.isGenericType() ) {
        return genericName( type.isGenericType() );
    } else if ( null != type.isArray() ) {
        return arrayName( type.isArray() );
    } else if ( null != type.isTypeParameter() ) {
        return typeVariableName( type.isTypeParameter() );
    } else if ( null != type.isWildcard() ) {
        return wildcardName( type.isWildcard() );
    } else {
        return className( type.isClassOrInterface() );
    }
}
 
Example #6
Source File: InjectPresenterCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void initComposer(ClassSourceFileComposerFactory composerFactory) {
	composerFactory.addImport(Place.class.getName());
	composerFactory.addImport(Presenter.class.getName());
	for (JMethod presenterMethod : this.presenterMethods) {
		if (presenterMethod.getParameters().length > 0) {
			JType placeType = presenterMethod.getParameters()[0].getType();
			composerFactory.addImport(placeType.getQualifiedSourceName());
			if (placeType instanceof JParameterizedType) {
				JParameterizedType parameterizedType = (JParameterizedType) placeType;
				for (JType paramType : parameterizedType.getTypeArgs()) {
					composerFactory.addImport(paramType.getQualifiedSourceName());
				}
			}
		}
	}

	composerFactory.addImplementedInterface(Presenter.class.getSimpleName());
	composerFactory.addImport(AcceptsOneWidget.class.getName());
}
 
Example #7
Source File: PropertyProcessor.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
private static JType findType( TreeLogger logger, PropertyAccessors fieldAccessors, JacksonTypeOracle typeOracle,
		boolean getterAutoDetected, boolean setterAutoDetected, boolean fieldAutoDetected ) throws UnableToCompleteException {
    JType type;
    if ( getterAutoDetected && fieldAccessors.getGetter().isPresent() ) {
        type = fieldAccessors.getGetter().get().getReturnType();
    } else if ( setterAutoDetected && fieldAccessors.getSetter().isPresent() ) {
        type = fieldAccessors.getSetter().get().getParameters()[0].getType();
    } else if ( fieldAutoDetected && fieldAccessors.getField().isPresent() ) {
        type = fieldAccessors.getField().get().getType();
    } else if ( fieldAccessors.getParameter().isPresent() ) {
        type = fieldAccessors.getParameter().get().getType();
    } else {
        logger.log( Type.ERROR, "Cannot find the type of the property " + fieldAccessors.getPropertyName() );
        throw new UnableToCompleteException();
    }

    Optional<Annotation> jd = fieldAccessors.getAnnotation( "com.fasterxml.jackson.databind.annotation.JsonDeserialize" );
    if ( jd.isPresent() ) {
        return typeOracle.replaceType( logger, type, jd.get() );
    }

    return type;
}
 
Example #8
Source File: RebindConfiguration.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
/**
 * @param clazz class to find the type
 *
 * @return the {@link JType} denoted by the class given in parameter
 */

private JType findType( Class<?> clazz ) {
    if ( clazz.isPrimitive() ) {

        return JPrimitiveType.parse( clazz.getCanonicalName() );

    } else if ( clazz.isArray() ) {

        try {
            return context.getTypeOracle().parse( clazz.getCanonicalName() );
        } catch ( TypeOracleException e ) {
            logger.log( TreeLogger.WARN, "Cannot find the array denoted by the class " + clazz.getCanonicalName() );
            return null;
        }

    } else {
        return findClassType( clazz );
    }
}
 
Example #9
Source File: PropertyProcessor.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
private static boolean isPropertyIgnored( RebindConfiguration configuration, PropertyAccessors propertyAccessors, BeanInfo beanInfo,
                                          JType type, String propertyName ) {
    // we first check if the property is ignored
    Optional<JsonIgnore> jsonIgnore = propertyAccessors.getAnnotation( JsonIgnore.class );
    if ( jsonIgnore.isPresent() && jsonIgnore.get().value() ) {
        return true;
    }

    // if type is ignored, we ignore the property
    if ( null != type.isClassOrInterface() ) {
        Optional<JsonIgnoreType> jsonIgnoreType = findFirstEncounteredAnnotationsOnAllHierarchy( configuration, type
                .isClassOrInterface(), JsonIgnoreType.class );
        if ( jsonIgnoreType.isPresent() && jsonIgnoreType.get().value() ) {
            return true;
        }
    }

    // we check if it's not in the ignored properties
    return beanInfo.getIgnoredFields().contains( propertyName );

}
 
Example #10
Source File: ServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void collectImports() {
	Collection<JType> toImports = Sets.newHashSet();
	for (JMethod method : this.serviceType.getOverridableMethods()) {
		toImports.add(method.getReturnType());
		for (JParameter parameter : method.getParameters()) {
			toImports.add(parameter.getType());
		}
	}
	this.imports.addAll(toImports);
	for (JType importType : this.imports) {
		if (importType instanceof JParameterizedType) {
			JParameterizedType parameterizedType = (JParameterizedType) importType;
			for (JType paramType : parameterizedType.getTypeArgs()) {
				toImports.add(paramType);
			}
		}
	}
	this.imports.addAll(toImports);
}
 
Example #11
Source File: ServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String typeAsString(JType type, boolean translatePrimitives) {
	StringBuilder sb = new StringBuilder();
	if (translatePrimitives && type instanceof JPrimitiveType) {
		sb.append(((JPrimitiveType) type).getQualifiedBoxedSourceName());
	} else {
		sb.append(type.getSimpleSourceName());
		if (type instanceof JParameterizedType) {
			JParameterizedType parameterizedType = (JParameterizedType) type;
			sb.append("<");
			int i = 0;
			for (JType paramType : parameterizedType.getTypeArgs()) {
				if (i++ > 0) {
					sb.append(", ");
				}
				sb.append(this.typeAsString(paramType, false));
			}
			sb.append(">");
		}
	}
	return sb.toString();
}
 
Example #12
Source File: ModelCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 5 votes vote down vote up
private SourceWriter getSourceWriter(PrintWriter printWriter, GeneratorContext ctx) {
	String packageName =
		this.proxyModelQualifiedName.indexOf('.') == -1 ? "" : this.proxyModelQualifiedName.substring(0,
			this.proxyModelQualifiedName.lastIndexOf('.'));
	String className =
		this.proxyModelQualifiedName.indexOf('.') == -1 ? this.proxyModelQualifiedName
			: this.proxyModelQualifiedName
				.substring(this.proxyModelQualifiedName.lastIndexOf('.') + 1,
					this.proxyModelQualifiedName.length());

	ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, className);

	composerFactory.addImport(Map.class.getName());
	composerFactory.addImport(Maps.class.getName());
	composerFactory.addImport(GWT.class.getName());
	composerFactory.addImport(Model.class.getName());
	composerFactory.addImport(AbstractModel.class.getName());
	composerFactory.addImport(ModelCollection.class.getName());
	composerFactory.addImport(PropertyDescription.class.getName());
	composerFactory.addImport(PrimitiveUtils.class.getName());
	composerFactory.addImport(this.beanType.getQualifiedSourceName());
	composerFactory.addImport("fr.putnami.pwt.core.editor.client.validator.*");

	for (JType jType : this.imports) {
		if (jType.isPrimitive() != null) {
			continue;
		}
		composerFactory.addImport(jType.getQualifiedSourceName());
	}
	for (String submodel : this.subModels.values()) {
		composerFactory.addImport(submodel);
	}

	composerFactory
		.setSuperclass(AbstractModel.class.getSimpleName() + "<" + this.beanType.getSimpleSourceName() + ">");
	return composerFactory.createSourceWriter(ctx, printWriter);
}
 
Example #13
Source File: ServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 5 votes vote down vote up
private SourceWriter getSourceWriter(PrintWriter printWriter, GeneratorContext ctx) {

		String packageName = this.handlerType.getPackage().getName();
		String className =
			this.proxyModelQualifiedName.indexOf('.') == -1 ?
				this.proxyModelQualifiedName : this.proxyModelQualifiedName.substring(
					this.proxyModelQualifiedName.lastIndexOf('.') + 1, this.proxyModelQualifiedName.length());

		ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, className);

		composerFactory.addImport(AsyncCallback.class.getName());

		composerFactory.addImport(AbstractServiceBinder.class.getName());
		composerFactory.addImport(Arrays.class.getName());
		composerFactory.addImport(Lists.class.getName());
		composerFactory.addImport(CommandDefinition.class.getName());
		composerFactory.addImport(CommandParam.class.getName());
		composerFactory.addImport(CallbackAdapter.class.getName());
		composerFactory.addImport(CommandController.class.getName());

		composerFactory.addImport(this.serviceType.getQualifiedSourceName());
		composerFactory.addImport(this.serviceBinderType.getQualifiedSourceName());

		for (JType jType : this.imports) {
			if (jType.isPrimitive() != null) {
				continue;
			}
			composerFactory.addImport(jType.getQualifiedSourceName());
		}

		composerFactory.setSuperclass(AbstractServiceBinder.class.getSimpleName()
			+ "<" + this.handlerType.getSimpleSourceName() + ", " + this.serviceType.getSimpleSourceName() + ">");

		composerFactory.addImplementedInterface(this.serviceType.getSimpleSourceName());
		composerFactory.addImplementedInterface(this.serviceBinderType.getSimpleSourceName());

		return composerFactory.createSourceWriter(ctx, printWriter);
	}
 
Example #14
Source File: RestServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 5 votes vote down vote up
private SourceWriter getSourceWriter(PrintWriter printWriter, GeneratorContext ctx) {

		String packageName = this.handlerType.getPackage().getName();
		String className =
			this.proxyModelQualifiedName.indexOf('.') == -1 ?
				this.proxyModelQualifiedName : this.proxyModelQualifiedName.substring(
					this.proxyModelQualifiedName.lastIndexOf('.') + 1, this.proxyModelQualifiedName.length());

		ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, className);

		composerFactory.addImport(AbstractServiceBinder.class.getName());
		composerFactory.addImport(Arrays.class.getName());
		composerFactory.addImport(Lists.class.getName());
		composerFactory.addImport(MethodCallbackAdapter.class.getName());
		composerFactory.addImport(Method.class.getName());
		composerFactory.addImport(CompositeMethodCallback.class.getName());
		composerFactory.addImport(CallbackAdapter.class.getName());
		composerFactory.addImport(REST.class.getName());
		composerFactory.addImport(GWT.class.getName());

		composerFactory.addImport(this.serviceType.getQualifiedSourceName());
		composerFactory.addImport(this.serviceBinderType.getQualifiedSourceName());

		for (JType jType : this.imports) {
			if (jType.isPrimitive() != null) {
				continue;
			}
			composerFactory.addImport(jType.getQualifiedSourceName());
		}

		composerFactory.setSuperclass(AbstractServiceBinder.class.getSimpleName()
			+ "<" + this.handlerType.getSimpleSourceName() + ", " + this.serviceType.getSimpleSourceName() + ">");

		composerFactory.addImplementedInterface(this.serviceType.getSimpleSourceName());
		composerFactory.addImplementedInterface(this.serviceBinderType.getSimpleSourceName());

		return composerFactory.createSourceWriter(ctx, printWriter);
	}
 
Example #15
Source File: BeanIdentityInfo.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
BeanIdentityInfo( String propertyName, boolean alwaysAsId, Class<? extends ObjectIdGenerator<?>> generator, Class<?> scope,
                  JType type ) {
    this.propertyName = propertyName;
    this.alwaysAsId = alwaysAsId;
    this.generator = generator;
    this.scope = scope;
    this.idABeanProperty = false;
    this.type = Optional.of( type );
}
 
Example #16
Source File: XMLElement.java    From gwt-material-demo with Apache License 2.0 5 votes vote down vote up
private JType getDoubleType() {
  if (doubleType == null) {
    try {
      doubleType = oracle.parse("double");
    } catch (TypeOracleException e) {
      throw new RuntimeException(e);
    }
  }
  return doubleType;
}
 
Example #17
Source File: StubClassType.java    From mvp4g with Apache License 2.0 5 votes vote down vote up
@Override
public JMethod getMethod(String name,
                         JType[] paramTypes)
  throws NotFoundException {

  return null;
}
 
Example #18
Source File: RebindConfiguration.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
private MapperType[] getParameters( JType mappedType, JAbstractMethod method, boolean isSerializers ) {
    if ( !isSerializers && typeOracle.isEnumSupertype( mappedType ) ) {
        // For enums, the constructor requires the enum class. We just return an empty array and will handle it later
        if ( method.getParameters().length == 1 && Class.class.getName().equals( method.getParameters()[0].getType()
                .getQualifiedSourceName() ) ) {
            return new MapperType[0];
        } else {
            // Not a valid method to create enum deserializer
            return null;
        }
    }

    MapperType[] parameters = new MapperType[method.getParameters().length];
    for ( int i = 0; i < method.getParameters().length; i++ ) {
        JParameter parameter = method.getParameters()[i];
        if ( isSerializers ) {
            if ( typeOracle.isKeySerializer( parameter.getType() ) ) {
                parameters[i] = MapperType.KEY_SERIALIZER;
            } else if ( typeOracle.isJsonSerializer( parameter.getType() ) ) {
                parameters[i] = MapperType.JSON_SERIALIZER;
            } else {
                // the parameter is unknown, we ignore this method
                return null;
            }
        } else {
            if ( typeOracle.isKeyDeserializer( parameter.getType() ) ) {
                parameters[i] = MapperType.KEY_DESERIALIZER;
            } else if ( typeOracle.isJsonDeserializer( parameter.getType() ) ) {
                parameters[i] = MapperType.JSON_DESERIALIZER;
            } else {
                // the parameter is unknown, we ignore this method
                return null;
            }
        }
    }
    return parameters;
}
 
Example #19
Source File: ModelCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void generateInternalSet(TreeLogger logger, SourceWriter srcWriter) {
	srcWriter.println("protected <P> void internalSet(%s bean, String fieldName, P value){",
		this.beanType.getSimpleSourceName());
	srcWriter.indent();
	for (String propertyName : this.propertyTypes.keySet()) {
		JType propertyType = this.propertyTypes.get(propertyName);
		JPrimitiveType primitiveType = propertyType.isPrimitive();
		JMethod setter = this.setters.get(propertyName);
		if (setter != null) {
			if (primitiveType != null) {
				srcWriter.println(
					"if(\"%s\".equals(fieldName)){  bean.%s((%s) PrimitiveUtils.asPrimitive((%s)value)); }",
					propertyName, setter.getName(), propertyType.getSimpleSourceName(),
					primitiveType.getQualifiedBoxedSourceName());
			} else {
				srcWriter.println("if(\"%s\".equals(fieldName)){  bean.%s((%s) value); }", propertyName,
					setter.getName(),
					propertyType.getSimpleSourceName());
			}
		} else if (this.publicFields.containsKey(propertyName)) {
			if (primitiveType != null) {
				srcWriter
					.println("if(\"%s\".equals(fieldName)){ bean.%s = PrimitiveUtils.asPrimitive((%s) value); }",
						propertyName, propertyName, primitiveType.getQualifiedBoxedSourceName());
			} else {
				srcWriter
					.println("if(\"%s\".equals(fieldName)){  bean.%s = (%s) value; }", propertyName, propertyName,
						propertyType.getSimpleSourceName());
			}
		}
	}
	srcWriter.outdent();
	srcWriter.println("}");
}
 
Example #20
Source File: InjectorModuleCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void doCreate(TreeLogger logger, GeneratorContext context, SourceWriter srcWriter) {
	super.doCreate(logger, context, srcWriter);

	srcWriter.println("@Override public void onModuleLoad() {");
	srcWriter.indent();

	try {
		if (this.injectableType.getMethod("onModuleLoad", new JType[] {}) != null) {
			srcWriter.println("super.onModuleLoad();");
		}
	} catch (NotFoundException e) {
		srcWriter.println("");
	}

	for (InjectorWritterEntryPoint delegate : Iterables.filter(this.delegates, InjectorWritterEntryPoint.class)) {
		delegate.writeEntryPoint(srcWriter);
		srcWriter.println();
	}

	for (JMethod method : InjectCreatorUtil.listMethod(this.injectableType, EntryPointHandler.class)) {
		srcWriter.println("super.%s();", method.getName());
	}

	srcWriter.println();
	MvpDescription mvpAnnotation = this.injectableType.getAnnotation(MvpDescription.class);
	if (mvpAnnotation != null && mvpAnnotation.handleCurrentHistory()) {
		srcWriter.println("MvpController.get().handleCurrentHistory();");
	}
	srcWriter.outdent();
	srcWriter.println("}");
}
 
Example #21
Source File: EventBinderWriterTest.java    From gwteventbinder with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldWriteDoBindEventHandler() throws Exception {
  JClassType eventType1 = getEventType(MyEvent1.class);
  JClassType eventType2 = getEventType(MyEvent2.class);
  JMethod method1 = newMethod("method1", eventType1);
  JMethod method2 = newMethod("method2", eventType2);
  JMethod method3 = newMethod("method3", new JType[] {genericEventType},
      new Class[] {MyEvent1.class, MyEvent2.class});
  JMethod method4 = newMethod("method4", new JType[] {},
      new Class[] {MyEvent1.class});

  when(target.getQualifiedSourceName()).thenReturn("MyTarget");
  when(target.getInheritableMethods()).thenReturn(new JMethod[] {method1, method2, method3, method4});

  writer.writeDoBindEventHandlers(target, output, typeOracle);

  assertEquals(join(
      "protected List<HandlerRegistration> doBindEventHandlers("
          + "final MyTarget target, EventBus eventBus) {",
      "  List<HandlerRegistration> registrations = new LinkedList<HandlerRegistration>();",
      "  bind(eventBus, registrations, " + className(MyEvent1.class) + ".class, new GenericEventHandler() {",
      "    public void handleEvent(GenericEvent event) { target.method1((" + className(MyEvent1.class) + ") event); }",
      "  });",
      "  bind(eventBus, registrations, " + className(MyEvent2.class) +".class, new GenericEventHandler() {",
      "    public void handleEvent(GenericEvent event) { target.method2((" + className(MyEvent2.class) + ") event); }",
      "  });",
      "  bind(eventBus, registrations, " + className(MyEvent1.class) + ".class, new GenericEventHandler() {",
      "    public void handleEvent(GenericEvent event) { target.method3((" + className(MyEvent1.class) +") event); }",
      "  });",
      "  bind(eventBus, registrations, " + className(MyEvent2.class) + ".class, new GenericEventHandler() {",
      "    public void handleEvent(GenericEvent event) { target.method3((" + className(MyEvent2.class) + ") event); }",
      "  });",
      "  bind(eventBus, registrations, " + className(MyEvent1.class) + ".class, new GenericEventHandler() {",
      "    public void handleEvent(GenericEvent event) { target.method4(); }",
      "  });",
      "  return registrations;",
      "}"), output.toString());
}
 
Example #22
Source File: PropertyProcessor.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
private static void processBeanAnnotation( TreeLogger logger, JacksonTypeOracle typeOracle, RebindConfiguration configuration, JType
        type, PropertyAccessors propertyAccessors, PropertyInfoBuilder builder ) throws UnableToCompleteException {

    // identity
    Optional<JsonIdentityInfo> jsonIdentityInfo = propertyAccessors.getAnnotation( JsonIdentityInfo.class );
    Optional<JsonIdentityReference> jsonIdentityReference = propertyAccessors.getAnnotation( JsonIdentityReference.class );

    // type info
    Optional<JsonTypeInfo> jsonTypeInfo = propertyAccessors.getAnnotation( JsonTypeInfo.class );
    Optional<JsonSubTypes> propertySubTypes = propertyAccessors.getAnnotation( JsonSubTypes.class );

    // if no annotation is present that overrides bean processing, we just stop now
    if ( !jsonIdentityInfo.isPresent() && !jsonIdentityReference.isPresent() && !jsonTypeInfo.isPresent() && !propertySubTypes
            .isPresent() ) {
        // no override on field
        return;
    }

    // we need to find the bean to apply annotation on
    Optional<JClassType> beanType = extractBeanType( logger, typeOracle, type, builder.getPropertyName() );

    if ( beanType.isPresent() ) {
        if ( jsonIdentityInfo.isPresent() || jsonIdentityReference.isPresent() ) {
            builder.setIdentityInfo( BeanProcessor.processIdentity( logger, typeOracle, configuration, beanType
                    .get(), jsonIdentityInfo, jsonIdentityReference ) );
        }

        if ( jsonTypeInfo.isPresent() || propertySubTypes.isPresent() ) {
            builder.setTypeInfo( BeanProcessor.processType( logger, typeOracle, configuration, beanType
                    .get(), jsonTypeInfo, propertySubTypes ) );
        }
    } else {
        logger.log( Type.WARN, "Annotation present on property " + builder.getPropertyName() + " but no valid bean has been found." );
    }
}
 
Example #23
Source File: FieldReadAccessor.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
protected Accessor getAccessor( final String beanName, final boolean useMethod, final boolean useJsni, Object... params ) {
    if ( !useJsni ) {
        if ( useMethod ) {
            return new Accessor( CodeBlock.builder().add( beanName + "." + method.get().getName() + "()" ).build() );
        } else {
            return new Accessor( CodeBlock.builder().add( beanName + "." + field.get().getName() ).build() );
        }
    }

    // field/getter has not been detected or is private or is in a different package. We use JSNI to access getter/field.
    final JType fieldType;
    final JClassType enclosingType;
    if ( useMethod ) {
        fieldType = method.get().getReturnType();
        enclosingType = method.get().getEnclosingType();
    } else {
        fieldType = field.get().getType();
        enclosingType = field.get().getEnclosingType();
    }

    JsniCodeBlockBuilder jsniCode = JsniCodeBlockBuilder.builder();
    if ( useMethod ) {
        jsniCode.addStatement( "return bean.@$L::$L()()", enclosingType.getQualifiedSourceName(), method.get().getName() );
    } else {
        jsniCode.addStatement( "return bean.@$L::$L", enclosingType.getQualifiedSourceName(), field.get().getName() );
    }

    MethodSpec additionalMethod = MethodSpec.methodBuilder( "getValueWithJsni" )
            .addModifiers( Modifier.PRIVATE, Modifier.NATIVE )
            .returns( typeName( fieldType ) )
            .addParameter( typeName( enclosingType ), "bean" )
            .addCode( jsniCode.build() )
            .build();

    CodeBlock accessor = CodeBlock.builder().add( "$N($L)", additionalMethod, beanName ).build();

    return new Accessor( accessor, additionalMethod );
}
 
Example #24
Source File: EventBinderWriterTest.java    From gwteventbinder with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFailForEventWhichIsNotAssignableToParameter() throws Exception {
  JClassType eventType1 = getEventType(MyEvent1.class);

  JMethod method = newMethod("myMethod", new JType[] {eventType1}, new Class[] {MyEvent2.class});
  when(target.getInheritableMethods()).thenReturn(new JMethod[] {method});

  try {
    writer.writeDoBindEventHandlers(target, output, typeOracle);
    fail("Exception not thrown");
  } catch (UnableToCompleteException expected) {}

  verify(logger).log(
      eq(Type.ERROR), contains("myMethod"), isNull(Throwable.class), isNull(HelpInfo.class));
}
 
Example #25
Source File: FieldWriteAccessor.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
private String parametersToString( JType[] types, String separator, Converter converter ) {
    StringBuilder builder = new StringBuilder();

    for ( int i = 0; i < types.length; i++ ) {
        if ( i > 0 && null != separator ) {
            builder.append( separator );
        }
        builder.append( converter.convert( i, types[i] ) );
    }
    return builder.toString();
}
 
Example #26
Source File: PropertyInfo.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
PropertyInfo( String propertyName, JType type, boolean ignored, boolean required, boolean rawValue, boolean value, boolean
        anyGetter, boolean anySetter, boolean unwrapped, Optional<String> managedReference, Optional<String> backReference,
              Optional<? extends
                      FieldAccessor> getterAccessor, Optional<? extends FieldAccessor> setterAccessor, Optional<BeanIdentityInfo>
        identityInfo,
              Optional<BeanTypeInfo> typeInfo, Optional<JsonFormat> format, Optional<Include> include, Optional<Boolean>
                      ignoreUnknown, Optional<String[]> ignoredProperties ) {
    this.propertyName = propertyName;
    this.type = type;
    this.ignored = ignored;
    this.required = required;
    this.rawValue = rawValue;
    this.value = value;
    this.anyGetter = anyGetter;
    this.anySetter = anySetter;
    this.unwrapped = unwrapped;
    this.managedReference = managedReference;
    this.backReference = backReference;
    this.getterAccessor = getterAccessor;
    this.setterAccessor = setterAccessor;
    this.identityInfo = identityInfo;
    this.typeInfo = typeInfo;
    this.format = format;
    this.include = include;
    this.ignoreUnknown = ignoreUnknown;
    this.ignoredProperties = ignoredProperties;
}
 
Example #27
Source File: EventBinderWriterTest.java    From gwteventbinder with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private JMethod newMethod(String name, JType[] params, Class[] events) {
  EventHandler eventHandler = mock(EventHandler.class);
  when(eventHandler.handles()).thenReturn(events);

  JMethod method = mock(JMethod.class);
  when(method.getAnnotation(EventHandler.class)).thenReturn(eventHandler);
  when(method.getName()).thenReturn(name);
  when(method.getParameterTypes()).thenReturn(params);
  return method;
}
 
Example #28
Source File: JTypeName.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
private TypeName[] typeName( boolean boxed, JType... types ) {
    TypeName[] result = new TypeName[types.length];
    for ( int i = 0; i < types.length; i++ ) {
        result[i] = typeName( boxed, types[i] );
    }
    return result;
}
 
Example #29
Source File: EventBinderWriterTest.java    From gwteventbinder with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFailOnTwoParameters() throws Exception {
  JMethod method = newMethod("myMethod", mock(JType.class), mock(JType.class));
  when(target.getInheritableMethods()).thenReturn(new JMethod[] {method});

  try {
    writer.writeDoBindEventHandlers(target, output, typeOracle);
    fail("Exception not thrown");
  } catch (UnableToCompleteException expected) {}

  verify(logger).log(
      eq(Type.ERROR), contains("myMethod"), isNull(Throwable.class), isNull(HelpInfo.class));
}
 
Example #30
Source File: AbstractCreator.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
/**
 * Build the code to create a mapper.
 *
 * @param instance the class to call
 * @param parameters the parameters of the method
 *
 * @return the code to create the mapper
 */
private CodeBlock methodCallCodeWithClassParameters( MapperInstance instance, ImmutableList<? extends JType> parameters ) {
    CodeBlock.Builder builder = initMethodCallCode( instance );
    return methodCallParametersCode( builder, Lists.transform( parameters, new Function<JType, CodeBlock>() {

        @Override
        public CodeBlock apply( JType jType ) {
            return CodeBlock.builder().add( "$T.class", typeName( jType ) ).build();
        }
    } ) );
}