Java Code Examples for org.apache.beam.sdk.values.TypeDescriptor#resolveType()

The following examples show how to use org.apache.beam.sdk.values.TypeDescriptor#resolveType() . 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: AvroCoder.java    From beam with Apache License 2.0 6 votes vote down vote up
private void checkRecord(TypeDescriptor<?> type, Schema schema) {
  // For a record, we want to make sure that all the fields are deterministic.
  Class<?> clazz = type.getRawType();
  for (Schema.Field fieldSchema : schema.getFields()) {
    Field field = getField(clazz, fieldSchema.name());
    String fieldContext = field.getDeclaringClass().getName() + "#" + field.getName();

    if (field.isAnnotationPresent(AvroEncode.class)) {
      reportError(
          fieldContext, "Custom encoders may be non-deterministic -- remove @AvroEncode");
      continue;
    }

    if (!IndexedRecord.class.isAssignableFrom(field.getType())
        && field.isAnnotationPresent(AvroSchema.class)) {
      // TODO: We should be able to support custom schemas on POJO fields, but we shouldn't
      // need to, so we just allow it in the case of IndexedRecords.
      reportError(
          fieldContext, "Custom schemas are only supported for subtypes of IndexedRecord.");
      continue;
    }

    TypeDescriptor<?> fieldType = type.resolveType(field.getGenericType());
    recurse(fieldContext, fieldType, fieldSchema.schema());
  }
}
 
Example 2
Source File: AvroCoder.java    From beam with Apache License 2.0 6 votes vote down vote up
private void checkArray(String context, TypeDescriptor<?> type, Schema schema) {
  TypeDescriptor<?> elementType = null;
  if (type.isArray()) {
    // The type is an array (with ordering)-> deterministic iff the element is deterministic.
    elementType = type.getComponentType();
  } else if (isSubtypeOf(type, Collection.class)) {
    if (isSubtypeOf(type, List.class, SortedSet.class)) {
      // Ordered collection -> deterministic iff the element is deterministic
      elementType = type.resolveType(Collection.class.getTypeParameters()[0]);
    } else {
      // Not an ordered collection -> not deterministic
      reportError(context, "%s may not be deterministically ordered", type);
      return;
    }
  } else {
    // If it was an unknown type encoded as an array, be conservative and assume
    // that we don't know anything about the order.
    reportError(context, "encoding %s as an ARRAY was unexpected", type);
    return;
  }

  // If we get here, it's either a deterministically-ordered Collection, or
  // an array. Either way, the type is deterministic iff the element type is
  // deterministic.
  recurse(context, elementType, schema.getElementType());
}
 
Example 3
Source File: TypePropagationAssert.java    From beam with Apache License 2.0 5 votes vote down vote up
public static <KeyT, ValueT, OutputT> void assertOperatorTypeAwareness(
    Operator<OutputT> operator,
    @Nullable TypeDescriptor<KeyT> keyType,
    @Nullable TypeDescriptor<ValueT> valueType,
    TypeDescriptor<OutputT> outputType) {
  if (keyType != null || operator instanceof TypeAware.Key) {
    @SuppressWarnings("unchecked")
    final TypeAware.Key<KeyT> keyAware = (TypeAware.Key) operator;
    assertTrue(keyAware.getKeyType().isPresent());
    assertEquals(keyType, keyAware.getKeyType().get());
    assertTrue(operator.getOutputType().isPresent());
    @SuppressWarnings("unchecked")
    final TypeDescriptor<KV<KeyT, OutputT>> kvOutputType =
        (TypeDescriptor) operator.getOutputType().get();
    final TypeVariable<Class<KV>>[] kvParameters = KV.class.getTypeParameters();
    final TypeDescriptor<?> firstType = kvOutputType.resolveType(kvParameters[0]);
    final TypeDescriptor<?> secondType = kvOutputType.resolveType(kvParameters[1]);
    assertEquals(keyType, firstType);
    assertEquals(outputType, secondType);
  } else {
    // assert output of non keyed operator
    assertEquals(outputType, operator.getOutputType().get());
  }
  if (valueType != null || operator instanceof TypeAware.Value) {
    @SuppressWarnings("unchecked")
    final TypeAware.Value<KeyT> valueAware = (TypeAware.Value) operator;
    assertTrue(valueAware.getValueType().isPresent());
    assertEquals(valueType, valueAware.getValueType().get());
  }
}
 
Example 4
Source File: DoFnSignatures.java    From beam with Apache License 2.0 5 votes vote down vote up
@Nullable
private static TypeDescriptor<? extends BoundedWindow> getWindowType(
    TypeDescriptor<?> fnClass, Method method) {
  Type[] params = method.getGenericParameterTypes();
  for (Type param : params) {
    TypeDescriptor<?> paramT = fnClass.resolveType(param);
    if (BoundedWindow.class.isAssignableFrom(paramT.getRawType())) {
      return (TypeDescriptor<? extends BoundedWindow>) paramT;
    }
  }
  return null;
}
 
Example 5
Source File: DoFnSignatures.java    From beam with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static DoFnSignature.GetRestrictionCoderMethod analyzeGetRestrictionCoderMethod(
    ErrorReporter errors, TypeDescriptor<? extends DoFn> fnT, Method m) {
  errors.checkArgument(m.getParameterTypes().length == 0, "Must have zero arguments");
  TypeDescriptor<?> resT = fnT.resolveType(m.getGenericReturnType());
  errors.checkArgument(
      resT.isSubtypeOf(TypeDescriptor.of(Coder.class)),
      "Must return a Coder, but returns %s",
      format(resT));
  return DoFnSignature.GetRestrictionCoderMethod.create(m, resT);
}
 
Example 6
Source File: DoFnSignatures.java    From beam with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static DoFnSignature.GetWatermarkEstimatorStateCoderMethod
    analyzeGetWatermarkEstimatorStateCoderMethod(
        ErrorReporter errors, TypeDescriptor<? extends DoFn> fnT, Method m) {
  errors.checkArgument(m.getParameterTypes().length == 0, "Must have zero arguments");
  TypeDescriptor<?> resT = fnT.resolveType(m.getGenericReturnType());
  errors.checkArgument(
      resT.isSubtypeOf(TypeDescriptor.of(Coder.class)),
      "Must return a Coder, but returns %s",
      format(resT));
  return DoFnSignature.GetWatermarkEstimatorStateCoderMethod.create(m, resT);
}
 
Example 7
Source File: DoFnSignatures.java    From beam with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static DoFnSignature.NewTrackerMethod analyzeNewTrackerMethod(
    ErrorReporter errors,
    TypeDescriptor<? extends DoFn<?, ?>> fnT,
    Method m,
    TypeDescriptor<?> inputT,
    TypeDescriptor<?> outputT,
    TypeDescriptor<?> restrictionT,
    FnAnalysisContext fnContext) {
  // Method is of the form:
  // @NewTracker
  // TrackerT newTracker(... parameters ...);
  Type[] params = m.getGenericParameterTypes();
  TypeDescriptor<?> trackerT = fnT.resolveType(m.getGenericReturnType());
  TypeDescriptor<?> expectedTrackerT = restrictionTrackerTypeOf(restrictionT);
  errors.checkArgument(
      trackerT.isSubtypeOf(expectedTrackerT),
      "Returns %s, but must return a subtype of %s",
      format(trackerT),
      format(expectedTrackerT));

  MethodAnalysisContext methodContext = MethodAnalysisContext.create();
  TypeDescriptor<? extends BoundedWindow> windowT = getWindowType(fnT, m);
  for (int i = 0; i < params.length; ++i) {
    Parameter extraParam =
        analyzeExtraParameter(
            errors,
            fnContext,
            methodContext,
            fnT,
            ParameterDescription.of(
                m, i, fnT.resolveType(params[i]), Arrays.asList(m.getParameterAnnotations()[i])),
            inputT,
            outputT);
    if (extraParam instanceof SchemaElementParameter) {
      errors.throwIllegalArgument(
          "Schema @%s are not supported for @%s method. Found %s, did you mean to use %s?",
          format(DoFn.Element.class),
          format(DoFn.NewTracker.class),
          format(((SchemaElementParameter) extraParam).elementT()),
          format(inputT));
    } else if (extraParam instanceof RestrictionParameter) {
      errors.checkArgument(
          restrictionT.equals(((RestrictionParameter) extraParam).restrictionT()),
          "Uses restriction type %s, but @%s method uses restriction type %s",
          format(((RestrictionParameter) extraParam).restrictionT()),
          format(DoFn.GetInitialRestriction.class),
          format(restrictionT));
    }
    methodContext.addParameter(extraParam);
  }

  for (Parameter parameter : methodContext.getExtraParameters()) {
    checkParameterOneOf(errors, parameter, ALLOWED_NEW_TRACKER_PARAMETERS);
  }

  return DoFnSignature.NewTrackerMethod.create(
      m, fnT.resolveType(m.getGenericReturnType()), windowT, methodContext.getExtraParameters());
}
 
Example 8
Source File: DoFnSignatures.java    From beam with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static DoFnSignature.NewWatermarkEstimatorMethod analyzeNewWatermarkEstimatorMethod(
    ErrorReporter errors,
    TypeDescriptor<? extends DoFn<?, ?>> fnT,
    Method m,
    TypeDescriptor<?> inputT,
    TypeDescriptor<?> outputT,
    TypeDescriptor<?> restrictionT,
    TypeDescriptor<?> watermarkEstimatorStateT,
    FnAnalysisContext fnContext) {
  // Method is of the form:
  // @NewWatermarkEstimator
  // WatermarkEstimatorT newWatermarkEstimator(... parameters ...);
  Type[] params = m.getGenericParameterTypes();
  TypeDescriptor<?> watermarkEstimatorT = fnT.resolveType(m.getGenericReturnType());
  TypeDescriptor<?> expectedWatermarkEstimatorT =
      watermarkEstimatorTypeOf(watermarkEstimatorStateT);
  errors.checkArgument(
      watermarkEstimatorT.isSubtypeOf(expectedWatermarkEstimatorT),
      "Returns %s, but must return a subtype of %s",
      format(watermarkEstimatorT),
      format(expectedWatermarkEstimatorT));

  MethodAnalysisContext methodContext = MethodAnalysisContext.create();
  TypeDescriptor<? extends BoundedWindow> windowT = getWindowType(fnT, m);
  for (int i = 0; i < params.length; ++i) {
    Parameter extraParam =
        analyzeExtraParameter(
            errors,
            fnContext,
            methodContext,
            fnT,
            ParameterDescription.of(
                m, i, fnT.resolveType(params[i]), Arrays.asList(m.getParameterAnnotations()[i])),
            inputT,
            outputT);
    if (extraParam instanceof SchemaElementParameter) {
      errors.throwIllegalArgument(
          "Schema @%s are not supported for @%s method. Found %s, did you mean to use %s?",
          format(DoFn.Element.class),
          format(DoFn.NewWatermarkEstimator.class),
          format(((SchemaElementParameter) extraParam).elementT()),
          format(inputT));
    } else if (extraParam instanceof RestrictionParameter) {
      errors.checkArgument(
          restrictionT.equals(((RestrictionParameter) extraParam).restrictionT()),
          "Uses restriction type %s, but @%s method uses restriction type %s",
          format(((RestrictionParameter) extraParam).restrictionT()),
          format(DoFn.GetInitialWatermarkEstimatorState.class),
          format(restrictionT));
    } else if (extraParam instanceof WatermarkEstimatorStateParameter) {
      errors.checkArgument(
          watermarkEstimatorStateT.equals(
              ((WatermarkEstimatorStateParameter) extraParam).estimatorStateT()),
          "Uses watermark estimator state type %s, but @%s method uses watermark estimator state type %s",
          format(((WatermarkEstimatorStateParameter) extraParam).estimatorStateT()),
          format(DoFn.GetInitialWatermarkEstimatorState.class),
          format(watermarkEstimatorStateT));
    }
    methodContext.addParameter(extraParam);
  }

  for (Parameter parameter : methodContext.getExtraParameters()) {
    checkParameterOneOf(errors, parameter, ALLOWED_NEW_WATERMARK_ESTIMATOR_PARAMETERS);
  }

  return DoFnSignature.NewWatermarkEstimatorMethod.create(
      m, fnT.resolveType(m.getGenericReturnType()), windowT, methodContext.getExtraParameters());
}