Exemplo n.º 1
0
  public void handle(MethodCallExpression methodCall, TypeResolutionContext context) {
    if (methodCall.getArguments().size() == 1) { // there should only be one argument
      CollectionType targetType =
          (CollectionType)
              methodCall
                  .getTarget()
                  .getResolvedType(); // obtain target type, at this stage, preliminary examination
                                      // should already have the conclusion that the type is of type
                                      // Collection
      Type contentType = targetType.getContentType(); // obtain content type from the collection

      if (contentType == null) {
        // this means the operation is performed on a collection of any, so no need for further
        // actions
      } else {
        LiteralExpression argument =
            (LiteralExpression) methodCall.getArguments().get(0); // get the argument
        Type argumentType = argument.getResolvedType(); // get the type of the argument
        if (contentType.getClass() == argumentType.getClass()) {
          // match, no further actions
        } else {
          // handle type mismatch
        }
      }

      methodCall.setResolvedType(null); // in either case, remove() does not have a return type

    } else {
      // handle arguments number incorrect
    }
  }
Exemplo n.º 2
0
  @Test
  public void testTerserGetPrimitive_VariesCompositeFirstComponent() throws HL7Exception {
    final Varies variesField = new Varies(mshOnly);
    final Primitive comp1Sub1 = Terser.getPrimitive(variesField, 1, 1);
    comp1Sub1.setValue("comp1Sub1");
    final Primitive comp1Sub2 = Terser.getPrimitive(variesField, 1, 2);
    comp1Sub2.setValue("comp1Sub2");
    final Primitive comp2Sub1 = Terser.getPrimitive(variesField, 2, 1);
    comp2Sub1.setValue("comp2Sub1");

    assertEquals(GenericComposite.class, variesField.getData().getClass());

    final GenericComposite field = (GenericComposite) variesField.getData();
    final Type typeComp1 = field.getComponent(0);
    assertEquals(typeComp1.getClass(), Varies.class);

    final Varies variesComp1 = (Varies) typeComp1;
    assertEquals(GenericComposite.class, variesComp1.getData().getClass());

    final GenericComposite comp1 = (GenericComposite) variesComp1.getData();
    final Type typeSub1 = comp1.getComponent(1);
    assertEquals(typeSub1.getClass(), Varies.class);

    final Varies variesSub1 = (Varies) typeSub1;
    assertEquals(GenericPrimitive.class, variesSub1.getData().getClass());

    assertEquals("comp1Sub1&comp1Sub2^comp2Sub1", PipeParser.encode(variesField, encoders));
  }
Exemplo n.º 3
0
  protected List<ValidationException> testField(
      Type type, SegmentType.Field profile, boolean escape) {
    List<ValidationException> exList = new ArrayList<>();

    UsageInfo usage = new UsageInfo(profile);

    // account for MSH 1 & 2 which aren't escaped
    String encoded = null;
    if (!escape && Primitive.class.isAssignableFrom(type.getClass()))
      encoded = ((Primitive) type).getValue();

    exList.addAll(testType(type, profile.getDatatype(), usage, encoded, false));

    // test children
    if (validateChildren) {
      if (profile.getComponents().size() > 0 && !usage.disallowed()) {
        if (Composite.class.isAssignableFrom(type.getClass())) {
          Composite comp = (Composite) type;
          int i = 1;
          boolean nullContext = false;
          for (SegmentType.Field.Component component : profile.getComponents()) {
            try {
              SegmentType.Field.Component component2;
              if (nullContext) {
                component2 = new SegmentType.Field.Component();
                try {
                  BeanUtils.copyProperties(component2, component);
                } catch (InvocationTargetException | IllegalAccessException e) {
                  // nop
                }
                component2.setUsage("NULL");
              } else {
                component2 = component;
                if ((i == 1)
                    && profile.isNullable()
                    && PipeParser.encode(comp.getComponent(0), this.enc).equals("\"\"")) {
                  nullContext = true;
                }
              }

              exList.addAll(testComponent(comp.getComponent(i - 1), component2));
            } catch (DataTypeException de) {
              profileNotHL7Compliant(exList, COMPONENT_TYPE_MISMATCH, type.getName(), i);
            }
            ++i;
          }
          exList.addAll(checkUndefinedComponents(comp, profile.getComponents().size()));
        } else {
          profileNotHL7Compliant(exList, WRONG_FIELD_TYPE, type.getClass().getName());
        }
      }
    }
    return exList;
  }
Exemplo n.º 4
0
  /**
   * Tests a Type against the corresponding section of a profile.
   *
   * @param encoded optional encoded form of type (if you want to specify this -- if null, default
   *     pipe-encoded form is used to check length and constant val)
   */
  protected List<ValidationException> testType(
      Type type, String dataType, UsageInfo usage, String encoded, boolean testUsage) {
    ArrayList<ValidationException> exList = new ArrayList<>();
    if (encoded == null) encoded = PipeParser.encode(type, this.enc);

    if (testUsage) {
      testUsage(exList, encoded, usage);
    }

    if (!usage.disallowed() && !encoded.isEmpty()) {
      // check datatype
      if ((type instanceof ca.uhn.hl7v2.model.v231.datatype.TSComponentOne
              || type instanceof ca.uhn.hl7v2.model.v24.datatype.TSComponentOne)
          && !dataType.equals("ST")) {
        profileNotHL7Compliant(exList, HL7_DATATYPE_MISMATCH, type.getName(), dataType);
      } else if (!(type instanceof TSComponentOne) && !type.getName().contains(dataType)) {
        profileViolatedWhen(
            !(type.getClass().getSimpleName().equals("Varies")
                || type.getClass().getSimpleName().equals("QIP")),
            exList,
            HL7_DATATYPE_MISMATCH,
            type.getName(),
            dataType);
      }

      // check length
      profileViolatedWhen(
          encoded.length() > usage.length,
          exList,
          LENGTH_EXCEEDED,
          usage.name,
          encoded.length(),
          usage.length);

      // check constant value
      if (usage.constantValue != null && usage.constantValue.length() > 0) {
        profileViolatedWhen(
            !encoded.equals(usage.constantValue),
            exList,
            WRONG_CONSTANT_VALUE,
            encoded,
            usage.constantValue);
      }

      // TODO : check against table, or do we need this check?
      // Gazelle checks code system and issues a WARNING if a check fails
    }

    return exList;
  }
Exemplo n.º 5
0
 @Nullable
 private static TypeWrapper wrap(Type type) {
   if (type == null) {
     return null;
   } else if (type instanceof Class) {
     return new ClassTypeWrapper((Class<?>) type);
   } else if (type instanceof ParameterizedType) {
     ParameterizedType parameterizedType = (ParameterizedType) type;
     return new ParameterizedTypeWrapper(
         toWrappers(parameterizedType.getActualTypeArguments()),
         (ClassTypeWrapper) wrap(parameterizedType.getRawType()),
         wrap(parameterizedType.getOwnerType()));
   } else if (type instanceof WildcardType) {
     WildcardType wildcardType = (WildcardType) type;
     return new WildcardTypeWrapper(
         toWrappers(wildcardType.getUpperBounds()),
         toWrappers(wildcardType.getLowerBounds()),
         type.hashCode());
   } else if (type instanceof TypeVariable) {
     TypeVariable<?> typeVariable = (TypeVariable<?>) type;
     return new TypeVariableTypeWrapper(
         typeVariable.getName(), toWrappers(typeVariable.getBounds()), type.hashCode());
   } else if (type instanceof GenericArrayType) {
     GenericArrayType genericArrayType = (GenericArrayType) type;
     return new GenericArrayTypeWrapper(
         wrap(genericArrayType.getGenericComponentType()), type.hashCode());
   } else {
     throw new IllegalArgumentException("cannot wrap type of type " + type.getClass());
   }
 }
  /**
   * Resolve current method generic return type to a {@link GenericMetadataSupport}.
   *
   * @param method Method to resolve the return type.
   * @return {@link GenericMetadataSupport} representing this generic return type.
   */
  public GenericMetadataSupport resolveGenericReturnType(Method method) {
    Type genericReturnType = method.getGenericReturnType();
    // logger.log("Method '" + method.toGenericString() + "' has return type : " +
    // genericReturnType.getClass().getInterfaces()[0].getSimpleName() + " : " + genericReturnType);

    if (genericReturnType instanceof Class) {
      return new NotGenericReturnTypeSupport(genericReturnType);
    }
    if (genericReturnType instanceof ParameterizedType) {
      return new ParameterizedReturnType(
          this, method.getTypeParameters(), (ParameterizedType) method.getGenericReturnType());
    }
    if (genericReturnType instanceof TypeVariable) {
      return new TypeVariableReturnType(
          this, method.getTypeParameters(), (TypeVariable) genericReturnType);
    }

    throw new MockitoException(
        "Ouch, it shouldn't happen, type '"
            + genericReturnType.getClass().getCanonicalName()
            + "' on method : '"
            + method.toGenericString()
            + "' is not supported : "
            + genericReturnType);
  }
Exemplo n.º 7
0
  static Class<?> getTypeClass(Type type) {

    if (type instanceof Class<?>) {
      return (Class<?>) type;
    }
    if (type instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) type;
      Class<?> c = (Class<?>) pt.getRawType();
      if (ValuedEnum.class.isAssignableFrom(c)) {
        Type[] types = pt.getActualTypeArguments();
        if (types == null || types.length != 1) {
          c = int.class;
        } else {
          c = getTypeClass(pt.getActualTypeArguments()[0]);
        }
      }
      return c;
    }
    if (type instanceof GenericArrayType) {
      if (Object.class.isAssignableFrom(
          getTypeClass(((GenericArrayType) type).getGenericComponentType()))) {
        return Object[].class;
      }
    }
    throw new UnsupportedOperationException("Unknown type type : " + type.getClass().getName());
  }
Exemplo n.º 8
0
 /**
  * Returns the datatype and attempts to pipe-encode it. For example, a string implementation might
  * return "ST[Value^Value2]". This is only intended for logging/debugging purposes.
  */
 static String toString(Type theType) {
   StringBuilder b = new StringBuilder();
   b.append(theType.getClass().getSimpleName());
   b.append("[");
   b.append(PipeParser.encode(theType, EncodingCharacters.defaultInstance()));
   b.append("]");
   return b.toString();
 }
Exemplo n.º 9
0
 public Constraints unify(Type t, List<Equation> es) throws NoType {
   if (t.getClass().equals(FunType.class)) {
     FunType f = (FunType) t;
     Constraints unifiedDom = domain.unify(f.domain, es);
     return codomain.unify(f.codomain, Assignment.asEquations(unifiedDom.assignments));
   } else {
     return t.unifyVar(this, es);
   }
 }
 private TypeUsage toTypeUsage(Type parameterType) {
   if (parameterType instanceof Class) {
     TypeDefinition typeDefinition = new ReflectionBasedTypeDefinition(clazz);
     ReferenceTypeUsage referenceTypeUsage = new ReferenceTypeUsage(typeDefinition);
     return referenceTypeUsage;
   } else {
     throw new UnsupportedOperationException(parameterType.getClass().getCanonicalName());
   }
 }
Exemplo n.º 11
0
 public static Class<?> determineGenericsType(Type type) {
   Class<?> result = null;
   if (type != null && ParameterizedType.class.isAssignableFrom(type.getClass())) {
     Type genericType = ((ParameterizedType) type).getActualTypeArguments()[0];
     if (genericType != null) {
       result = (Class<?>) genericType;
     }
   }
   return result;
 }
  @Override
  public Boolean visit(Eq ast) {
    boolean checkLhs = ast.getLhs().accept(this);
    boolean checkRhs = ast.getRhs().accept(this);

    if (!(checkLhs && checkRhs)) return false;
    Type lhsType = ast.getLhs().typeOf(env);
    Type rhsType = ast.getRhs().typeOf(env);

    if (!lhsType.isCompatibleTo(rhsType)) {
      addToErrorList(
          ast,
          "the operator == can not be applied to instances of type "
              + lhsType.getClass()
              + " and type "
              + rhsType.getClass());
      return false;
    }
    return true;
  }
Exemplo n.º 13
0
  protected List<ValidationException> testComponent(
      Type type, SegmentType.Field.Component profile) {
    List<ValidationException> exList = new ArrayList<>();
    UsageInfo usage = new UsageInfo(profile);
    exList.addAll(testType(type, profile.getDatatype(), usage, null));

    // test children
    try {
      if (profile.getSubComponents().size() > 0 && !usage.disallowed() && !isEmpty(type)) {
        if (Composite.class.isAssignableFrom(type.getClass())) {
          Composite comp = (Composite) type;

          if (validateChildren) {
            int i = 1;
            for (SegmentType.Field.Component.SubComponent subComponent :
                profile.getSubComponents()) {
              UsageInfo scUsage = new UsageInfo(subComponent);
              try {
                Type sub = comp.getComponent(i - 1);
                exList.addAll(testType(sub, subComponent.getDatatype(), scUsage, null));
              } catch (DataTypeException de) {
                profileNotHL7Compliant(exList, SUBCOMPONENT_TYPE_MISMATCH, type.getName(), i);
              }
              ++i;
            }
          }

          exList.addAll(checkUndefinedComponents(comp, profile.getSubComponents().size()));
        } else {
          profileViolatedWhen(true, exList, WRONG_COMPONENT_TYPE, type.getClass().getName());
        }
      }
    } catch (HL7Exception e) {
      exList.add(new ValidationException(e));
    }

    return exList;
  }
  /**
   * Create an new instance of {@link GenericMetadataSupport} inferred from a {@link Type}.
   *
   * <p>At the moment <code>type</code> can only be a {@link Class} or a {@link ParameterizedType},
   * otherwise it'll throw a {@link MockitoException}.
   *
   * @param type The class from which the {@link GenericMetadataSupport} should be built.
   * @return The new {@link GenericMetadataSupport}.
   * @throws MockitoException Raised if type is not a {@link Class} or a {@link ParameterizedType}.
   */
  public static GenericMetadataSupport inferFrom(Type type) {
    Checks.checkNotNull(type, "type");
    if (type instanceof Class) {
      return new FromClassGenericMetadataSupport((Class<?>) type);
    }
    if (type instanceof ParameterizedType) {
      return new FromParameterizedTypeGenericMetadataSupport((ParameterizedType) type);
    }

    throw new MockitoException(
        "Type meta-data for this Type ("
            + type.getClass().getCanonicalName()
            + ") is not supported : "
            + type);
  }
Exemplo n.º 15
0
 private ClassNode configureType(Type type) {
   if (type instanceof WildcardType) {
     return configureWildcardType((WildcardType) type);
   } else if (type instanceof ParameterizedType) {
     return configureParameterizedType((ParameterizedType) type);
   } else if (type instanceof GenericArrayType) {
     return configureGenericArray((GenericArrayType) type);
   } else if (type instanceof TypeVariable) {
     return configureTypeVariableReference((TypeVariable) type);
   } else if (type instanceof Class) {
     return configureClass((Class) type);
   } else {
     throw new GroovyBugError("unknown type: " + type + " := " + type.getClass());
   }
 }
  @Override
  public Boolean visit(Not ast) {
    boolean checkArg = ast.getArg().accept(this);

    if (!checkArg) return false;

    Type argType = ast.getArg().typeOf(env);

    if (!argType.isCompatibleToBool()) {
      addToErrorList(
          ast,
          "the unary operator ! can not be applied to instances of type " + argType.getClass());
      return false;
    }
    return true;
  }
Exemplo n.º 17
0
 /** @return the wrapper of the given {@link Type} with given {@link TypeQuality}. */
 public static Type makeInferred(Type type, TypeQuality quality) {
   if (type == null) {
     return null;
   }
   if (type.getQuality().ordinal() > quality.ordinal()) {
     return type;
   }
   if (quality == TypeQuality.EXACT) {
     return type;
   }
   Set<Class<?>> interfaceSet = getAllImplementedInterfaces(type.getClass());
   if (!interfaceSet.isEmpty()) {
     Class<?>[] interfaces = interfaceSet.toArray(new Class[interfaceSet.size()]);
     return makeInferred(type, interfaces, quality);
   }
   return type;
 }
Exemplo n.º 18
0
  public static Class<?> getActualType(Type genericType, final int pos) {

    if (genericType == null) return null;
    if (!ParameterizedType.class.isAssignableFrom(genericType.getClass())) {
      if (genericType instanceof TypeVariable)
        genericType = getType(((TypeVariable<?>) genericType).getBounds(), pos);
      else if (genericType instanceof WildcardType) {
        final WildcardType wildcardType = (WildcardType) genericType;
        Type[] bounds = wildcardType.getLowerBounds();
        if (bounds.length == 0) bounds = wildcardType.getUpperBounds();
        genericType = getType(bounds, pos);
      }

      final Class<?> cls = (Class<?>) genericType;
      return cls.isArray() ? cls.getComponentType() : cls;
    }
    final ParameterizedType paramType = (ParameterizedType) genericType;
    final Type t = getType(paramType.getActualTypeArguments(), pos);
    return t instanceof Class ? (Class<?>) t : getActualType(t, pos);
  }
Exemplo n.º 19
0
 private static Type makeInferred(
     final Type type, Class<?>[] interfaces, final TypeQuality quality) {
   Map<TypeQuality, Type> inferredMap = inferredTypes.get(type);
   if (inferredMap == null) {
     inferredMap = new MapMaker().weakValues().makeMap();
     inferredTypes.put(type, inferredMap);
   }
   Type inferred = inferredMap.get(quality);
   if (inferred == null) {
     inferred =
         (Type)
             Proxy.newProxyInstance(
                 type.getClass().getClassLoader(),
                 interfaces,
                 new InvocationHandler() {
                   @Override
                   @SuppressWarnings("unchecked")
                   public Object invoke(Object proxy, Method method, Object[] args)
                       throws Throwable {
                     if (args == null && method.getName().equals("getQuality")) {
                       return quality;
                     }
                     if (type instanceof FunctionType) {
                       if (args == null && method.getName().equals("getParameterTypes")) {
                         List<Type> originalTypes = (List<Type>) method.invoke(type, args);
                         return Lists.transform(
                             originalTypes,
                             new Function<Type, Type>() {
                               public Type apply(Type input) {
                                 return makeInferred(input, quality);
                               }
                             });
                       }
                     }
                     return method.invoke(type, args);
                   }
                 });
     inferredMap.put(quality, inferred);
   }
   return inferred;
 }
Exemplo n.º 20
0
 public TypeList(Type t) {
   myclass = t.getClass();
   instances = new SafeArrayList<Type>(Type.class);
   hash = new Hashtable<String, Type>();
 }
Exemplo n.º 21
0
 /** Returns true if s is assignable to t. */
 public boolean isAssignable(Type t, Type s) {
   t.getClass(); // Quick null check.
   s.getClass(); // Quick null check.
   return isSubtype(t, s) || isSubtype(s, t);
 }