Java Code Examples for com.squareup.javapoet.TypeName#equals()

The following examples show how to use com.squareup.javapoet.TypeName#equals() . 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: DefaultConfigProviderGenerator.java    From aircon with MIT License 6 votes vote down vote up
protected CodeBlock getResId(final ResourcesClassDescriptor resourcesClassDescriptor, int resId) {
	ClassDescriptor classDescriptor;
	final TypeName rawType = mElement.getUnboxedRawType();
	if (rawType.equals(TypeName.INT) || rawType.equals(TypeName.LONG)) {
		classDescriptor = resourcesClassDescriptor.getInteger(resId);
	}
	else if (rawType.equals(TypeName.FLOAT)) {
		classDescriptor = resourcesClassDescriptor.getFraction(resId);
	}
	else if (rawType.equals(TypeName.BOOLEAN)) {
		classDescriptor = resourcesClassDescriptor.getBoolean(resId);
	}
	else {
		classDescriptor = resourcesClassDescriptor.getString(resId);
	}

	return classDescriptor.build();
}
 
Example 2
Source File: NodeRule.java    From caffeine with Apache License 2.0 6 votes vote down vote up
/** Creates a mutator to the variable. */
protected final MethodSpec newSetter(TypeName varType, String varName, Visibility visibility) {
  String methodName = "set" + Character.toUpperCase(varName.charAt(0)) + varName.substring(1);
  String type;
  if (varType.isPrimitive()) {
    type = varType.equals(TypeName.INT) ? "Int" : "Long";
  } else {
    type = "Object";
  }
  MethodSpec.Builder setter = MethodSpec.methodBuilder(methodName)
      .addModifiers(context.publicFinalModifiers())
      .addParameter(varType, varName);
  if (visibility.isRelaxed) {
    setter.addStatement("$T.UNSAFE.put$L(this, $N, $N)",
        UNSAFE_ACCESS, type, offsetName(varName), varName);
  } else {
    setter.addStatement("this.$N = $N", varName, varName);
  }

  return setter.build();
}
 
Example 3
Source File: SQLiteDAOClass.java    From HighLite with Apache License 2.0 6 votes vote down vote up
private String getCursorMethodFromTypeName(final TypeName typeName) {
    if (typeName.equals(TypeName.FLOAT)
            || typeName.equals(ClassName.get(Float.class))) {
        return "getFloat";
    } else if (typeName.equals(TypeName.DOUBLE)
            || typeName.equals(ClassName.get(Double.class))) {
        return "getDouble";
    } else if (typeName.equals(TypeName.SHORT)
            || typeName.equals(ClassName.get(Short.class))) {
        return "getShort";
    } else if (typeName.equals(TypeName.INT)
            || typeName.equals(ClassName.get(Integer.class))) {
        return "getInt";
    } else if (typeName.equals(TypeName.LONG)
            || typeName.equals(ClassName.get(Long.class))) {
        return "getLong";
    } else {
        return "getString";
    }
}
 
Example 4
Source File: BindTypeContext.java    From kripton with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the bind mapper name.
 *
 * @param context the context
 * @param typeName the type name
 * @return the bind mapper name
 */
public String getBindMapperName(BindTypeContext context, TypeName typeName) {
	Converter<String, String> format = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
	TypeName bindMapperName=TypeUtility.mergeTypeNameWithSuffix(typeName,BindTypeBuilder.SUFFIX);
	String simpleName=format.convert(TypeUtility.simpleName(bindMapperName));

	if (!alreadyGeneratedMethods.contains(simpleName))
	{
		alreadyGeneratedMethods.add(simpleName);
		if (bindMapperName.equals(beanTypeName))
		{
			context.builder.addField(FieldSpec.builder(bindMapperName, simpleName, modifiers)					
					.addJavadoc("$T", bindMapperName)
					.initializer("this")
					.build());
		} else {				
			context.builder.addField(FieldSpec.builder(bindMapperName, simpleName, modifiers)					
					.addJavadoc("$T", bindMapperName)
					.initializer("$T.mapperFor($T.class)", BinderUtils.class, typeName)
					.build());	
		}		
	}
	
	return simpleName;
}
 
Example 5
Source File: NodeRule.java    From caffeine with Apache License 2.0 5 votes vote down vote up
/** Creates an accessor that returns the unwrapped variable. */
protected final MethodSpec newGetter(Strength strength, TypeName varType,
    String varName, Visibility visibility) {
  MethodSpec.Builder getter = MethodSpec.methodBuilder("get" + capitalize(varName))
      .addModifiers(context.publicFinalModifiers())
      .returns(varType);
  String type;
  if (varType.isPrimitive()) {
    type = varType.equals(TypeName.INT) ? "Int" : "Long";
  } else {
    type = "Object";
  }
  if (strength == Strength.STRONG) {
    if (visibility.isRelaxed) {
      if (varType.isPrimitive()) {
        getter.addStatement("return $T.UNSAFE.get$N(this, $N)",
            UNSAFE_ACCESS, type, offsetName(varName));
      } else {
        getter.addStatement("return ($T) $T.UNSAFE.get$N(this, $N)",
            varType, UNSAFE_ACCESS, type, offsetName(varName));
      }
    } else {
      getter.addStatement("return $N", varName);
    }
  } else {
    if (visibility.isRelaxed) {
      getter.addStatement("return (($T<$T>) $T.UNSAFE.get$N(this, $N)).get()",
          Reference.class, varType, UNSAFE_ACCESS, type, offsetName(varName));
    } else {
      getter.addStatement("return $N.get()", varName);
    }
  }
  return getter.build();
}
 
Example 6
Source File: AnnotatedDurableEntityClass.java    From mnemonic with Apache License 2.0 5 votes vote down vote up
protected String getIntialValueLiteral(TypeName tname) throws AnnotationProcessingException {
  String ret = null;
  if (isUnboxPrimitive(tname)) {
    TypeName tn = unboxTypeName(tname);
    if (tn.equals(TypeName.BOOLEAN)) {
      ret = "false";
    }
    if (tn.equals(TypeName.BYTE)) {
      ret = "(byte)0";
    }
    if (tn.equals(TypeName.CHAR)) {
      ret = "(char)0";
    }
    if (tn.equals(TypeName.DOUBLE)) {
      ret = "(double)0.0";
    }
    if (tn.equals(TypeName.FLOAT)) {
      ret = "(float)0.0";
    }
    if (tn.equals(TypeName.INT)) {
      ret = "(int)0";
    }
    if (tn.equals(TypeName.LONG)) {
      ret = "(long)0";
    }
    if (tn.equals(TypeName.SHORT)) {
      ret = "(short)0";
    }
  } else {
    ret = null;
  }
  if (null == ret) {
    throw new AnnotationProcessingException(null, "%s is not supported to determine the inital value.",
        tname.toString());
  }
  return ret;
}
 
Example 7
Source File: TypeUtility.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if is type included in.
 *
 * @param value
 *            the value
 * @param types
 *            the types
 * @return true, if is type included in
 */
public static boolean isTypeIncludedIn(TypeName value, Type... types) {
	for (Type item : types) {
		if (value.equals(typeName(item))) {
			return true;
		}
	}

	return false;
}
 
Example 8
Source File: EventValidation.java    From litho with Apache License 2.0 5 votes vote down vote up
private static boolean isFromEventTypeSpecifiedInAnnotation(
    MethodParamModel methodParamModel, TypeName eventFieldType) {
  FromEvent fromEvent =
      (FromEvent) MethodParamModelUtils.getAnnotation(methodParamModel, FromEvent.class);
  TypeName baseClassType;
  try {
    baseClassType = ClassName.get(fromEvent.baseClass());
  } catch (MirroredTypeException mte) {
    baseClassType = ClassName.get(mte.getTypeMirror());
  }
  return baseClassType.equals(eventFieldType);
}
 
Example 9
Source File: AnnotatedDurableEntityClass.java    From mnemonic with Apache License 2.0 5 votes vote down vote up
protected String transTypeToUnsafeMethod(TypeName tname, boolean isget) throws AnnotationProcessingException {
  String ret = null;
  if (isUnboxPrimitive(tname)) {
    TypeName tn = unboxTypeName(tname);
    if (tn.equals(TypeName.BOOLEAN)) {
      ret = isget ? "getByte" : "putByte";
    }
    if (tn.equals(TypeName.BYTE)) {
      ret = isget ? "getByte" : "putByte";
    }
    if (tn.equals(TypeName.CHAR)) {
      ret = isget ? "getChar" : "putChar";
    }
    if (tn.equals(TypeName.DOUBLE)) {
      ret = isget ? "getDouble" : "putDouble";
    }
    if (tn.equals(TypeName.FLOAT)) {
      ret = isget ? "getFloat" : "putFloat";
    }
    if (tn.equals(TypeName.INT)) {
      ret = isget ? "getInt" : "putInt";
    }
    if (tn.equals(TypeName.LONG)) {
      ret = isget ? "getLong" : "putLong";
    }
    if (tn.equals(TypeName.SHORT)) {
      ret = isget ? "getShort" : "putShort";
    }
  } else {
    ret = isget ? "getAddress" : "putAddress";
  }
  if (null == ret) {
    throw new AnnotationProcessingException(null, "%s is not supported by getters or setters.", tname.toString());
  }
  return ret;
}
 
Example 10
Source File: DelegateMethodGenerator.java    From litho with Apache License 2.0 5 votes vote down vote up
private static CodeBlock getDelegationMethod(
    SpecModel specModel,
    CharSequence methodName,
    TypeName returnType,
    ImmutableList<ParamTypeAndName> methodParams) {
  final CodeBlock.Builder delegation = CodeBlock.builder();
  final String sourceDelegateAccessor = SpecModelUtils.getSpecAccessor(specModel);
  if (returnType.equals(TypeName.VOID)) {
    delegation.add("$L.$L(\n", sourceDelegateAccessor, methodName);
  } else {
    delegation.add("_result = ($T) $L.$L(\n", returnType, sourceDelegateAccessor, methodName);
  }

  delegation.indent();
  for (int i = 0; i < methodParams.size(); i++) {
    delegation.add("($T) $L", methodParams.get(i).type, methodParams.get(i).name);

    if (i < methodParams.size() - 1) {
      delegation.add(",\n");
    }
  }

  delegation.add(");\n");
  delegation.unindent();

  return delegation.build();
}
 
Example 11
Source File: PropertySchemaAnnotationSupport.java    From anno4j with Apache License 2.0 5 votes vote down vote up
/**
 * Embeds the given annotations in container annotations if necessary.
 * If the given collection contains multiple annotations of the same type then those are "wrapped"
 * in the corresponding container annotation (e.g. multiple {@link MinCardinality} annotations are embedded
 * in a single {@link MinCardinalities}).
 * Annotations which type occurs only once are not embedded even if they would be embeddable.
 * @param annotations The annotations to embed if necessary.
 * @return Returns the collection of embedded annotations. If multiple annotations of a non-embeddable type
 * they are considered equivalent and an arbitrary annotation is picked.
 */
private Collection<AnnotationSpec> embedAnnotations(Collection<AnnotationSpec> annotations) {
    // Map all annotations by their type:
    Map<TypeName, List<AnnotationSpec>> annotationsByType = new HashMap<>();
    for (AnnotationSpec annotation : annotations) {
        // Initialize bucket if not yet exists:
        if(!annotationsByType.containsKey(annotation.type)) {
            annotationsByType.put(annotation.type, new LinkedList<AnnotationSpec>());
        }

        annotationsByType.get(annotation.type).add(annotation);
    }

    // Do the embedding:
    Collection<AnnotationSpec> embedded = new HashSet<>();
    for (TypeName annotationType : annotationsByType.keySet()) {
        // Embed if multiple values of this type exist:
        if(annotationsByType.get(annotationType).size() > 1) {
            Collection<AnnotationSpec> values = annotationsByType.get(annotationType);

            AnnotationSpec container = null;
            if(annotationType.equals(ClassName.get(MinCardinality.class))) {
                embedded.add(buildContainer(MinCardinalities.class, values));
            } else if(annotationType.equals(ClassName.get(MaxCardinality.class))) {
                embedded.add(buildContainer(MaxCardinalities.class, values));
            } else if(annotationType.equals(ClassName.get(Cardinality.class))) {
                embedded.add(buildContainer(Cardinalities.class, values));
            } else {
                // Type not embeddable, only add first one (equivalence assumption):
                embedded.add(annotationsByType.get(annotationType).get(0));
            }

        } else {
            // If there's only a single annotation of this type, no embedding necessary:
            embedded.addAll(annotationsByType.get(annotationType));
        }
    }

    return embedded;
}
 
Example 12
Source File: ColumnProperty.java    From auto-value-cursor with Apache License 2.0 5 votes vote down vote up
public String cursorMethod() {
    if (!supportedType) {
        return null;
    }
    TypeName type = type();
    if (type.equals(TypeName.get(byte[].class)) || type.equals(TypeName.get(Byte[].class))) {
        return "cursor.getBlob($L)";
    }
    if (type.equals(TypeName.DOUBLE) || type.equals(TypeName.DOUBLE.box())) {
        return "cursor.getDouble($L)";
    }
    if (type.equals(TypeName.FLOAT) || type.equals(TypeName.FLOAT.box())) {
        return "cursor.getFloat($L)";
    }
    if (type.equals(TypeName.INT) || type.equals(TypeName.INT.box())) {
        return "cursor.getInt($L)";
    }
    if (type.equals(TypeName.LONG) || type.equals(TypeName.LONG.box())) {
        return "cursor.getLong($L)";
    }
    if (type.equals(TypeName.SHORT) || type.equals(TypeName.SHORT.box())) {
        return "cursor.getShort($L)";
    }
    if (type.equals(TypeName.get(String.class))) {
        return "cursor.getString($L)";
    }
    if (type.equals(TypeName.BOOLEAN) || type.equals(TypeName.BOOLEAN.box())) {
        return "cursor.getInt($L) == 1";
    }
    throw new AssertionError(
            String.format("supportedType is true but type %s isn't handled", type));
}
 
Example 13
Source File: Parcelables.java    From auto-parcel with Apache License 2.0 4 votes vote down vote up
static void readValue(CodeBlock.Builder block, AutoParcelProcessor.Property property, final TypeName parcelableType) {

        if (property.isNullable()) {
            block.add("in.readInt() == 0 ? ");
        }

        if (parcelableType.equals(STRING)) {
            block.add("in.readString()");
        } else if (parcelableType.equals(TypeName.BYTE) || parcelableType.equals(TypeName.BYTE.box())) {
            block.add("in.readByte()");
        } else if (parcelableType.equals(TypeName.INT) || parcelableType.equals(TypeName.INT.box())) {
            block.add("in.readInt()");
        } else if (parcelableType.equals(TypeName.SHORT) || parcelableType.equals(TypeName.SHORT.box())) {
            block.add("(short) in.readInt()");
        } else if (parcelableType.equals(TypeName.CHAR) || parcelableType.equals(TypeName.CHAR.box())) {
            block.add("(char) in.readInt()");
        } else if (parcelableType.equals(TypeName.LONG) || parcelableType.equals(TypeName.LONG.box())) {
            block.add("in.readLong()");
        } else if (parcelableType.equals(TypeName.FLOAT) || parcelableType.equals(TypeName.FLOAT.box())) {
            block.add("in.readFloat()");
        } else if (parcelableType.equals(TypeName.DOUBLE) || parcelableType.equals(TypeName.DOUBLE.box())) {
            block.add("in.readDouble()");
        } else if (parcelableType.equals(TypeName.BOOLEAN) || parcelableType.equals(TypeName.BOOLEAN.box())) {
            block.add("in.readInt() == 1");
        } else if (parcelableType.equals(PARCELABLE)) {
            if (property.typeName.equals(PARCELABLE)) {
                block.add("in.readParcelable($T.class.getClassLoader())", parcelableType);
            } else {
                block.add("($T) in.readParcelable($T.class.getClassLoader())", property.typeName, property.typeName);
            }
        } else if (parcelableType.equals(CHARSEQUENCE)) {
            block.add("$T.CHAR_SEQUENCE_CREATOR.createFromParcel(in)", TEXTUTILS);
//        } else if (parcelableType.equals(MAP)) {
//            block.add("($T) in.readHashMap($T.class.getClassLoader())", property.typeName, parcelableType);
        } else if (parcelableType.equals(LIST)) {
            block.add("($T) in.readArrayList($T.class.getClassLoader())", property.typeName, parcelableType);
        } else if (parcelableType.equals(BOOLEANARRAY)) {
            block.add("in.createBooleanArray()");
        } else if (parcelableType.equals(BYTEARRAY)) {
            block.add("in.createByteArray()");
        } else if (parcelableType.equals(CHARARRAY)) {
            block.add("in.createCharArray()");
        } else if (parcelableType.equals(STRINGARRAY)) {
            block.add("in.readStringArray()");
        } else if (parcelableType.equals(IBINDER)) {
            if (property.typeName.equals(IBINDER)) {
                block.add("in.readStrongBinder()");
            } else {
                block.add("($T) in.readStrongBinder()", property.typeName);
            }
        } else if (parcelableType.equals(OBJECTARRAY)) {
            block.add("in.readArray($T.class.getClassLoader())", parcelableType);
        } else if (parcelableType.equals(INTARRAY)) {
            block.add("in.createIntArray()");
        } else if (parcelableType.equals(LONGARRAY)) {
            block.add("in.createLongArray()");
        } else if (parcelableType.equals(SERIALIZABLE)) {
            if (property.typeName.equals(SERIALIZABLE)) {
                block.add("in.readSerializable()");
            } else {
                block.add("($T) in.readSerializable()", property.typeName);
            }
        } else if (parcelableType.equals(PARCELABLEARRAY)) {
            ArrayTypeName atype = (ArrayTypeName) property.typeName;
            if (atype.componentType.equals(PARCELABLE)) {
                block.add("in.readParcelableArray($T.class.getClassLoader())", parcelableType);
            } else {
                // FIXME: 31/07/16 not sure if this works
                block.add("($T) in.readParcelableArray($T.class.getClassLoader())", atype, parcelableType);
            }
        } else if (parcelableType.equals(SPARSEARRAY)) {
            block.add("in.readSparseArray($T.class.getClassLoader())", parcelableType);
        } else if (parcelableType.equals(SPARSEBOOLEANARRAY)) {
            block.add("in.readSparseBooleanArray()");
        } else if (parcelableType.equals(BUNDLE)) {
            block.add("in.readBundle($T.class.getClassLoader())", property.typeName);
        } else if (parcelableType.equals(PERSISTABLEBUNDLE)) {
            block.add("in.readPersistableBundle($T.class.getClassLoader())", property.typeName);
        } else if (parcelableType.equals(SIZE)) {
            block.add("in.readSize()");
        } else if (parcelableType.equals(SIZEF)) {
            block.add("in.readSizeF()");
        } else if (parcelableType.equals(ENUM)) {
            block.add("$T.valueOf(in.readString())", property.typeName);
        } else {
            block.add("($T) in.readValue($T.class.getClassLoader())", property.typeName, parcelableType);
        }

        if (property.isNullable()) {
            block.add(" : null");
        }
    }
 
Example 14
Source File: DelegateMethodGenerator.java    From litho with Apache License 2.0 4 votes vote down vote up
private static boolean isStateValueType(TypeName type) {
  return type.equals(STATE_VALUE)
      || (type instanceof ParameterizedTypeName
          && ((ParameterizedTypeName) type).rawType.equals(STATE_VALUE));
}
 
Example 15
Source File: ReactPropertyProcessor.java    From react-native-GPay with MIT License 4 votes vote down vote up
private static CodeBlock.Builder getPropertyExtractor(
    PropertyInfo info,
    CodeBlock.Builder builder) {
  TypeName propertyType = info.propertyType;
  if (propertyType.equals(STRING_TYPE)) {
    return builder.add("props.getString(name)");
  } else if (propertyType.equals(READABLE_ARRAY_TYPE)) {
    return builder.add("props.getArray(name)");
  } else if (propertyType.equals(READABLE_MAP_TYPE)) {
    return builder.add("props.getMap(name)");
  } else if (propertyType.equals(DYNAMIC_TYPE)) {
    return builder.add("props.getDynamic(name)");
  }

  if (BOXED_PRIMITIVES.contains(propertyType)) {
    propertyType = propertyType.unbox();
  }

  if (propertyType.equals(TypeName.BOOLEAN)) {
    return builder.add("props.getBoolean(name, $L)", info.mProperty.defaultBoolean());
  } if (propertyType.equals(TypeName.DOUBLE)) {
    double defaultDouble = info.mProperty.defaultDouble();
    if (Double.isNaN(defaultDouble)) {
      return builder.add("props.getDouble(name, $T.NaN)", Double.class);
    } else {
      return builder.add("props.getDouble(name, $Lf)", defaultDouble);
    }
  }
  if (propertyType.equals(TypeName.FLOAT)) {
    float defaultFloat = info.mProperty.defaultFloat();
    if (Float.isNaN(defaultFloat)) {
      return builder.add("props.getFloat(name, $T.NaN)", Float.class);
    } else {
      return builder.add("props.getFloat(name, $Lf)", defaultFloat);
    }
  }
  if (propertyType.equals(TypeName.INT)) {
    return builder.add("props.getInt(name, $L)", info.mProperty.defaultInt());
  }

  throw new IllegalArgumentException();
}
 
Example 16
Source File: TriggerValidation.java    From litho with Apache License 2.0 4 votes vote down vote up
static List<SpecModelValidationError> validateOnTriggerMethods(
    SpecModel specModel, EnumSet<RunMode> runMode) {
  final List<SpecModelValidationError> validationErrors = new ArrayList<>();

  final ImmutableList<SpecMethodModel<EventMethod, EventDeclarationModel>> triggerMethods =
      specModel.getTriggerMethods();

  for (int i = 0, size = triggerMethods.size(); i < size - 1; i++) {
    for (int j = i + 1; j < size; j++) {
      if (triggerMethods.get(i).name.equals(triggerMethods.get(j).name)) {
        validationErrors.add(
            new SpecModelValidationError(
                triggerMethods.get(i).representedObject,
                "Two methods annotated with @OnTrigger should not have the same name "
                    + "("
                    + triggerMethods.get(i).name
                    + ")."));
      }
    }
  }

  if (!runMode.contains(RunMode.ABI)) {
    for (SpecMethodModel<EventMethod, EventDeclarationModel> triggerMethod : triggerMethods) {
      validationErrors.addAll(validateMethodIsStatic(specModel, triggerMethod));

      TypeName returnType =
          triggerMethod.returnType instanceof ParameterizedTypeName
              ? ((ParameterizedTypeName) triggerMethod.returnType).rawType
              : triggerMethod.returnType;

      if (!returnType.equals(triggerMethod.typeModel.returnType)) {
        validationErrors.add(
            new SpecModelValidationError(
                triggerMethod.representedObject,
                "Method must return "
                    + triggerMethod.typeModel.returnType
                    + " since that is what "
                    + triggerMethod.typeModel.name
                    + " expects."));
      }

      if (triggerMethod.methodParams.isEmpty()
          || !triggerMethod
              .methodParams
              .get(0)
              .getTypeName()
              .equals(specModel.getContextClass())) {
        validationErrors.add(
            new SpecModelValidationError(
                triggerMethod.representedObject,
                "The first parameter for a method annotated with @OnTrigger should be of type "
                    + specModel.getContextClass()
                    + "."));
      }
    }
  }

  return validationErrors;
}
 
Example 17
Source File: ReactPropertyProcessor.java    From react-native-GPay with MIT License 4 votes vote down vote up
private boolean isShadowNodeType(TypeName typeName) {
  return typeName.equals(SHADOW_NODE_IMPL_TYPE);
}
 
Example 18
Source File: Parcelables.java    From auto-parcel with Apache License 2.0 4 votes vote down vote up
public static CodeBlock writeValue(AutoParcelProcessor.Property property, ParameterSpec out, ParameterSpec flags, Types typeUtils) {
        CodeBlock.Builder block = CodeBlock.builder();

        if (property.isNullable()) {
            block.beginControlFlow("if ($N == null)", property.fieldName);
            block.addStatement("$N.writeInt(1)", out);
            block.nextControlFlow("else");
            block.addStatement("$N.writeInt(0)", out);
        }

        TypeName type = getTypeNameFromProperty(property, typeUtils);

        if (type.equals(STRING))
            block.add("$N.writeString($N)", out, property.fieldName);
        else if (type.equals(TypeName.BYTE) || type.equals(TypeName.BYTE.box()))
            block.add("$N.writeInt($N)", out, property.fieldName);
        else if (type.equals(TypeName.INT) || type.equals(TypeName.INT.box()))
            block.add("$N.writeInt($N)", out, property.fieldName);
        else if (type.equals(TypeName.SHORT))
            block.add("$N.writeInt(((Short) $N).intValue())", out, property.fieldName);
        else if (type.equals(TypeName.SHORT.box()))
            block.add("$N.writeInt($N.intValue())", out, property.fieldName);
        else if (type.equals(TypeName.CHAR) || type.equals(TypeName.CHAR.box()))
            block.add("$N.writeInt($N)", out, property.fieldName);
        else if (type.equals(TypeName.LONG) || type.equals(TypeName.LONG.box()))
            block.add("$N.writeLong($N)", out, property.fieldName);
        else if (type.equals(TypeName.FLOAT) || type.equals(TypeName.FLOAT.box()))
            block.add("$N.writeFloat($N)", out, property.fieldName);
        else if (type.equals(TypeName.DOUBLE) || type.equals(TypeName.DOUBLE.box()))
            block.add("$N.writeDouble($N)", out, property.fieldName);
        else if (type.equals(TypeName.BOOLEAN) || type.equals(TypeName.BOOLEAN.box()))
            block.add("$N.writeInt($N ? 1 : 0)", out, property.fieldName);
        else if (type.equals(PARCELABLE))
            block.add("$N.writeParcelable($N, $N)", out, property.fieldName, flags);
        else if (type.equals(CHARSEQUENCE))
            block.add("$T.writeToParcel($N, $N, $N)", TEXTUTILS, property.fieldName, out, flags);
//        else if (type.equals(MAP))
//            block.add("$N.writeMap($N)", out, property.fieldName);
        else if (type.equals(LIST))
            block.add("$N.writeList($N)", out, property.fieldName);
        else if (type.equals(BOOLEANARRAY))
            block.add("$N.writeBooleanArray($N)", out, property.fieldName);
        else if (type.equals(BYTEARRAY))
            block.add("$N.writeByteArray($N)", out, property.fieldName);
        else if (type.equals(CHARARRAY))
            block.add("$N.writeCharArray($N)", out, property.fieldName);
        else if (type.equals(STRINGARRAY))
            block.add("$N.writeStringArray($N)", out, property.fieldName);
        else if (type.equals(IBINDER))
            block.add("$N.writeStrongBinder($N)", out, property.fieldName);
        else if (type.equals(OBJECTARRAY))
            block.add("$N.writeArray($N)", out, property.fieldName);
        else if (type.equals(INTARRAY))
            block.add("$N.writeIntArray($N)", out, property.fieldName);
        else if (type.equals(LONGARRAY))
            block.add("$N.writeLongArray($N)", out, property.fieldName);
        else if (type.equals(SERIALIZABLE))
            block.add("$N.writeSerializable($N)", out, property.fieldName);
        else if (type.equals(PARCELABLEARRAY))
            block.add("$N.writeParcelableArray($N)", out, property.fieldName);
        else if (type.equals(SPARSEARRAY))
            block.add("$N.writeSparseArray($N)", out, property.fieldName);
        else if (type.equals(SPARSEBOOLEANARRAY))
            block.add("$N.writeSparseBooleanArray($N)", out, property.fieldName);
        else if (type.equals(BUNDLE))
            block.add("$N.writeBundle($N)", out, property.fieldName);
        else if (type.equals(PERSISTABLEBUNDLE))
            block.add("$N.writePersistableBundle($N)", out, property.fieldName);
        else if (type.equals(SIZE))
            block.add("$N.writeSize($N)", out, property.fieldName);
        else if (type.equals(SIZEF))
            block.add("$N.writeSizeF($N)", out, property.fieldName);
        else if (type.equals(ENUM))
            block.add("$N.writeString($N.name())", out, property.fieldName);
        else
            block.add("$N.writeValue($N)", out, property.fieldName);

        block.add(";\n");

        if (property.isNullable()) {
            block.endControlFlow();
        }
        return block.build();
    }
 
Example 19
Source File: Bundlables.java    From auto-value-bundle with MIT License 4 votes vote down vote up
/**
 * Read a value from a bundle which was stored as serialized JSON.
 *
 * @param bundleElement the bundle variable
 * @param deserializerElement the deserializer variable
 * @param type the type of the object to be read
 * @param key the key which was used to store the object
 * @return a string that represents the statement which reads from the bundle
 */
String parseFromString(
        VariableElement bundleElement,
        VariableElement deserializerElement,
        TypeName type,
        String key,
        boolean isEnum) {
    String readFromBundle = readType(bundleElement, STRING, key, deserializerElement, isEnum);

    if (isEnum) {
        return readFromBundle;
    }

    if (type.equals(TypeName.BYTE) || type.equals(TypeName.BYTE.box())) {
        return parsePrimitive(Byte.class, "parseByte", readFromBundle);
    } else if (type.equals(TypeName.BOOLEAN) || type.equals(TypeName.BOOLEAN.box())) {
        return parsePrimitive(Boolean.class, "parseBoolean", readFromBundle);
    } else if (type.equals(TypeName.INT) || type.equals(TypeName.INT.box())) {
        return parsePrimitive(Integer.class, "parseInt", readFromBundle);
    } else if (type.equals(TypeName.LONG) || type.equals(TypeName.LONG.box())) {
        return parsePrimitive(Long.class, "parseLong", readFromBundle);
    } else if (type.equals(TypeName.DOUBLE) || type.equals(TypeName.DOUBLE.box())) {
        return parsePrimitive(Double.class, "parseDouble", readFromBundle);
    } else if (type.equals(TypeName.CHAR) || type.equals(TypeName.CHAR.box())) {
        return readFromBundle + ".charAt(0)";
    } else if (type.equals(TypeName.SHORT) || type.equals(TypeName.SHORT.box())) {
        return parsePrimitive(Short.class, "parseShort", readFromBundle);
    } else if (type.equals(TypeName.FLOAT) || type.equals(TypeName.FLOAT.box())) {
        return parsePrimitive(Float.class, "parseFloat", readFromBundle);
    } else if (type.equals(STRING)
            || type.equals(CHAR_SEQUENCE)) {
        return readFromBundle;
    } else if (type.equals(BUNDLE)) {
        return deserializer.deserializeSimpleObject(readFromBundle, (ClassName) BUNDLE, deserializerElement);
    } else if (type.equals(PARCELABLE)) {
        return deserializer.deserializeSimpleObject(readFromBundle, (ClassName) PARCELABLE, deserializerElement);
    } else if (type.equals(PARCELABLE_ARRAY)) {
        return deserializer.deserializeArrayOfObjects(readFromBundle, (ClassName) PARCELABLE, deserializerElement);
    } else if (type.equals(PARCELABLE_ARRAY_LIST)) {
        return deserializer.deserializeArrayListOfObjects(readFromBundle, (ClassName) PARCELABLE,
                deserializerElement);
    } else if (type.equals(PARCELABLE_SPARSE_ARRAY)) {
        return deserializer.deserializeSparseArrayListOfParcelable(readFromBundle, deserializerElement);
    } else if (type.equals(SERIALIZABLE)) {
        return deserializer.deserializeSimpleObject(readFromBundle, (ClassName) SERIALIZABLE, deserializerElement);
    } else if (type.equals(INTEGER_ARRAY_LIST)) {
        return deserializer.deserializeArrayListOfObjects(readFromBundle, INTEGER_CLASS, deserializerElement);
    } else if (type.equals(STRING_ARRAY_LIST)) {
        return deserializer.deserializeArrayListOfObjects(readFromBundle, (ClassName) STRING, deserializerElement);
    } else if (type.equals(CHAR_SEQUENCE_ARRAY_LIST)) {
        return deserializer.deserializeArrayListOfObjects(readFromBundle, (ClassName) CHAR_SEQUENCE,
                deserializerElement);
    } else if (type.equals(BYTE_ARRAY)) {
        return "toPrimitive(" + deserializer.deserializeArrayOfObjects(readFromBundle,
                (ClassName) TypeName.BYTE.box(), deserializerElement) + ")";
    } else if (type.equals(SHORT_ARRAY)) {
        return "toPrimitive(" + deserializer.deserializeArrayOfObjects(readFromBundle,
                (ClassName) TypeName.SHORT.box(), deserializerElement) + ")";
    } else if (type.equals(CHAR_ARRAY)) {
        return "toPrimitive(" + deserializer.deserializeArrayOfObjects(readFromBundle,
                (ClassName) TypeName.CHAR.box(), deserializerElement) + ")";
    } else if (type.equals(FLOAT_ARRAY)) {
        return "toPrimitive(" + deserializer.deserializeArrayOfObjects(readFromBundle,
                (ClassName) TypeName.FLOAT.box(), deserializerElement) + ")";
    } else if (type.equals(CHAR_SEQUENCE_ARRAY)) {
        return deserializer.deserializeArrayOfObjects(readFromBundle, (ClassName) CHAR_SEQUENCE,
                deserializerElement);
    } else {
        if (type instanceof ParameterizedTypeName) {
            return deserializer.deserializeUnknownParameterizedObject(readFromBundle, (ParameterizedTypeName) type,
                    deserializerElement);
        } else {
            return deserializer.deserializeUnknownObject(readFromBundle, (ClassName) type, deserializerElement);
        }
    }
}
 
Example 20
Source File: SolidityFunctionWrapper.java    From client-sdk-java with Apache License 2.0 4 votes vote down vote up
private void buildConstantFunction(
        AbiDefinition functionDefinition,
        MethodSpec.Builder methodBuilder,
        List<TypeName> outputParameterTypes,
        String inputParams) throws ClassNotFoundException {

    String functionName = functionDefinition.getName();

    if (outputParameterTypes.isEmpty()) {
        methodBuilder.addStatement("throw new RuntimeException"
                + "(\"cannot call constant function with void return type\")");
    } else if (outputParameterTypes.size() == 1) {

        TypeName typeName = outputParameterTypes.get(0);
        TypeName nativeReturnTypeName;
        if (useNativeJavaTypes) {
            nativeReturnTypeName = getWrapperRawType(typeName);
        } else {
            nativeReturnTypeName = getWrapperType(typeName);
        }
        methodBuilder.returns(buildRemoteCall(nativeReturnTypeName));

        methodBuilder.addStatement("final $T function = "
                        + "new $T($N, \n$T.<$T>asList($L), "
                        + "\n$T.<$T<?>>asList(new $T<$T>() {}))",
                Function.class, Function.class, funcNameToConst(functionName),
                Arrays.class, Type.class, inputParams,
                Arrays.class, TypeReference.class,
                TypeReference.class, typeName);

        if (useNativeJavaTypes) {
            if (nativeReturnTypeName.equals(ClassName.get(List.class))) {
                // We return list. So all the list elements should
                // also be converted to native types
                TypeName listType = ParameterizedTypeName.get(List.class, Type.class);

                CodeBlock.Builder callCode = CodeBlock.builder();
                callCode.addStatement(
                        "$T result = "
                                + "($T) executeCallSingleValueReturn(function, $T.class)",
                        listType, listType, nativeReturnTypeName);
                callCode.addStatement("return convertToNative(result)");

                TypeSpec callableType = TypeSpec.anonymousClassBuilder("")
                        .addSuperinterface(ParameterizedTypeName.get(
                                ClassName.get(Callable.class), nativeReturnTypeName))
                        .addMethod(MethodSpec.methodBuilder("call")
                                .addAnnotation(Override.class)
                                .addAnnotation(AnnotationSpec.builder(SuppressWarnings.class)
                                        .addMember("value", "$S", "unchecked")
                                        .build())
                                .addModifiers(Modifier.PUBLIC)
                                .addException(Exception.class)
                                .returns(nativeReturnTypeName)
                                .addCode(callCode.build())
                                .build())
                        .build();

                methodBuilder.addStatement("return new $T(\n$L)",
                        buildRemoteCall(nativeReturnTypeName), callableType);
            } else {
                methodBuilder.addStatement(
                        "return executeRemoteCallSingleValueReturn(function, $T.class)",
                        nativeReturnTypeName);
            }
        } else {
            methodBuilder.addStatement("return executeRemoteCallSingleValueReturn(function)");
        }
    } else {
        List<TypeName> returnTypes = buildReturnTypes(outputParameterTypes);

        ParameterizedTypeName parameterizedTupleType = ParameterizedTypeName.get(
                ClassName.get(
                        "org.web3j.tuples.generated",
                        "Tuple" + returnTypes.size()),
                returnTypes.toArray(
                        new TypeName[returnTypes.size()]));

        methodBuilder.returns(buildRemoteCall(parameterizedTupleType));

        buildVariableLengthReturnFunctionConstructor(
                methodBuilder, functionName, inputParams, outputParameterTypes);

        buildTupleResultContainer(methodBuilder, parameterizedTupleType, outputParameterTypes);
    }
}