예제 #1
0
파일: TypeUtils.java 프로젝트: mfwzan/astor
  /**
   * @param cls
   * @param toClass
   * @param subtypeVarAssigns
   * @return
   */
  private static Map<TypeVariable<?>, Type> getTypeArguments(
      Class<?> cls, Class<?> toClass, Map<TypeVariable<?>, Type> subtypeVarAssigns) {
    // make sure they're assignable
    if (!isAssignable(cls, toClass)) {
      return null;
    }

    // can't work with primitives
    if (cls.isPrimitive()) {
      // both classes are primitives?
      if (toClass.isPrimitive()) {
        // dealing with widening here. No type arguments to be
        // harvested with these two types.
        return new HashMap<TypeVariable<?>, Type>();
      }

      // work with wrapper the wrapper class instead of the primitive
      cls = ClassUtils.primitiveToWrapper(cls);
    }

    // create a copy of the incoming map, or an empty one if it's null
    HashMap<TypeVariable<?>, Type> typeVarAssigns =
        subtypeVarAssigns == null
            ? new HashMap<TypeVariable<?>, Type>()
            : new HashMap<TypeVariable<?>, Type>(subtypeVarAssigns);

    // no arguments for the parameters, or target class has been reached
    if (cls.getTypeParameters().length > 0 || toClass.equals(cls)) {
      return typeVarAssigns;
    }

    // walk the inheritance hierarchy until the target class is reached
    return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns);
  }
  /*
   * (non-Javadoc)
   * @see org.openl.binding.INodeBinder#bind(org.openl.parser.ISyntaxNode, org.openl.env.IOpenEnv,
   * org.openl.binding.IBindingContext)
   */
  public IBoundNode bind(ISyntaxNode node, IBindingContext bindingContext) throws Exception {

    if (node.getNumberOfChildren() != 1) {
      BindHelper.processError("Suffix node should have 1 subnode", node, bindingContext);

      return new ErrorBoundNode(node);
    }

    int index = node.getType().lastIndexOf('.');
    String methodName = node.getType().substring(index + 1);
    IBoundNode[] children = bindChildren(node, bindingContext);

    if (!children[0].isLvalue()) {
      BindHelper.processError(
          "The node is not an Lvalue", children[0].getSyntaxNode(), bindingContext, false);

      return new ErrorBoundNode(node);
    }

    IOpenClass[] types = getTypes(children);
    IMethodCaller methodCaller =
        UnaryOperatorNodeBinder.findUnaryOperatorMethodCaller(methodName, types, bindingContext);

    if (methodCaller == null) {

      String message = UnaryOperatorNodeBinder.errorMsg(methodName, types[0]);
      BindHelper.processError(message, node, bindingContext);

      return new ErrorBoundNode(node);
    }

    IOpenClass methodType = methodCaller.getMethod().getType();

    if (ClassUtils.primitiveToWrapper(methodType.getInstanceClass())
        != ClassUtils.primitiveToWrapper(types[0].getInstanceClass())) {
      //        if (!methodCaller.getMethod().getType().equals(types[0])) {
      BindHelper.processError(
          "Suffix operator must return the same type as an argument", node, bindingContext);

      return new ErrorBoundNode(node);
    }

    return new SuffixNode(node, children, methodCaller);
  }
예제 #3
0
 private static Map getTypeArguments(Class paramClass1, Class paramClass2, Map paramMap) {
   Object localObject;
   if (!isAssignable(paramClass1, paramClass2)) localObject = null;
   while (true) {
     return localObject;
     if (paramClass1.isPrimitive()) {
       if (paramClass2.isPrimitive()) return new HashMap();
       paramClass1 = ClassUtils.primitiveToWrapper(paramClass1);
     }
     if (paramMap == null) ;
     for (localObject = new HashMap();
         (paramClass1.getTypeParameters().length <= 0) && (!paramClass2.equals(paramClass1));
         localObject = new HashMap(paramMap))
       return getTypeArguments(
           getClosestParentType(paramClass1, paramClass2), paramClass2, (Map) localObject);
   }
 }
예제 #4
0
 @Override
 public Class<?> getType(Object propertyId) {
   final String pName = propertyId.toString();
   try {
     final DynaProperty dynaProperty = getDynaClass().getDynaProperty(pName);
     final Class<?> type = dynaProperty.getType();
     if (type.isPrimitive()) {
       // Vaadin can't handle primitive types in _all_ places, so use
       // wrappers instead. FieldGroup works, but e.g. Table in _editable_
       // mode fails for some reason
       return ClassUtils.primitiveToWrapper(type);
     }
     return type;
   } catch (Exception e) {
     // If type can't be found via dynaClass, it is most likely
     // nested/indexed/mapped property
     try {
       return getNestedPropertyType(getDynaClass(), pName);
     } catch (Exception ex) {
       throw new RuntimeException(ex);
     }
   }
 }
예제 #5
0
  /**
   * kdb result conversions to standard beaker types.
   *
   * <p>TODO it would be better if this was handled by customizing a serializer module, but I don't
   * see a clean way of doing that.
   */
  private Object convert(Object o) {
    // Convert flips of simple lists into TableDisplays.
    if (c.t(o) == 98)
      to_tabledisplay:
      {
        Flip f = (Flip) o;

        // Make sure each column is an array and a type we can handle.
        List<String> columns = Arrays.asList(f.x);
        List<String> classes = new ArrayList<>();
        List<List<?>> colLists = new ArrayList<>();
        for (Object c : f.y) {
          List<?> values = toList(c);
          if (values == null) {
            break to_tabledisplay;
          }
          String type =
              objConv.convertType(
                  ClassUtils.primitiveToWrapper(c.getClass().getComponentType()).getName());
          if (type == null) {
            break to_tabledisplay;
          }

          // Special case - convert Dates to nanosecond times.
          if (BasicObjectSerializer.TYPE_TIME.equals(type)) {
            List<Long> timestamps = new ArrayList<>(values.size());
            for (Object d : values) {
              timestamps.add(
                  TimeUnit.NANOSECONDS.convert(((Date) d).getTime(), TimeUnit.MILLISECONDS));
            }
            values = timestamps;
          }

          classes.add(type);
          colLists.add(values);
        }

        // Columns to rows.
        int rows = colLists.get(0).size();
        List<List<?>> values = new ArrayList<>();
        for (int row = 0; row < rows; ++row) {
          List<Object> rowValues = new ArrayList<>();
          for (List<?> col : colLists) {
            rowValues.add(col.get(row));
          }
          values.add(rowValues);
        }

        return new TableDisplay(values, columns, classes);
      }

    // Convert Dicts to maps.
    if (c.t(o) == 99)
      to_map:
      {
        Dict f = (Dict) o;

        // Special case - keyed tables are dicts of flips.
        if ((c.t(f.x) == 98) && (c.t(f.y) == 98))
          to_table:
          {
            Flip keys = (Flip) f.x;
            Flip cols = (Flip) f.y;
            return convert(
                new Flip(
                    new Dict(
                        ArrayUtils.addAll(keys.x, cols.x), ArrayUtils.addAll(keys.y, cols.y))));
          }

        List<?> keys = toList(f.x);
        if (keys == null) break to_map;
        List<?> values = toList(f.y);
        if (values == null) break to_map;
        Map<Object, Object> map = new HashMap<>();
        for (int i = 0; i < values.size(); ++i) {
          map.put(keys.get(i), values.get(i));
        }
        return map;
      }

    // No conversion.
    return o;
  }
  @Override
  @SuppressWarnings({"unchecked", "rawtypes"})
  protected void populateItem(final ListItem<ConnConfProperty> item) {
    final ConnConfProperty property = item.getModelObject();

    final Label label =
        new Label(
            "connPropAttrSchema",
            StringUtils.isBlank(property.getSchema().getDisplayName())
                ? property.getSchema().getName()
                : property.getSchema().getDisplayName());
    item.add(label);

    FieldPanel<? extends Serializable> field;
    boolean required = false;
    boolean isArray = false;

    if (property.getSchema().isConfidential()
        || Constants.GUARDED_STRING.equalsIgnoreCase(property.getSchema().getType())
        || Constants.GUARDED_BYTE_ARRAY.equalsIgnoreCase(property.getSchema().getType())) {

      field =
          new AjaxPasswordFieldPanel(
              "panel", label.getDefaultModelObjectAsString(), new Model<String>());
      ((PasswordTextField) field.getField()).setResetPassword(false);

      required = property.getSchema().isRequired();
    } else {
      Class<?> propertySchemaClass;
      try {
        propertySchemaClass =
            ClassUtils.forName(property.getSchema().getType(), ClassUtils.getDefaultClassLoader());
        if (ClassUtils.isPrimitiveOrWrapper(propertySchemaClass)) {
          propertySchemaClass =
              org.apache.commons.lang3.ClassUtils.primitiveToWrapper(propertySchemaClass);
        }
      } catch (Exception e) {
        LOG.error("Error parsing attribute type", e);
        propertySchemaClass = String.class;
      }

      if (ClassUtils.isAssignable(Number.class, propertySchemaClass)) {
        @SuppressWarnings("unchecked")
        final Class<Number> numberClass = (Class<Number>) propertySchemaClass;
        field =
            new SpinnerFieldPanel<Number>(
                "panel",
                label.getDefaultModelObjectAsString(),
                numberClass,
                new Model<Number>(),
                null,
                null);

        required = property.getSchema().isRequired();
      } else if (ClassUtils.isAssignable(Boolean.class, propertySchemaClass)) {
        field =
            new AjaxCheckBoxPanel(
                "panel", label.getDefaultModelObjectAsString(), new Model<Boolean>());
      } else {
        field =
            new AjaxTextFieldPanel(
                "panel", label.getDefaultModelObjectAsString(), new Model<String>());

        required = property.getSchema().isRequired();
      }

      if (propertySchemaClass.isArray()) {
        isArray = true;
      }
    }

    field.setTitle(property.getSchema().getHelpMessage());

    if (required) {
      field.addRequiredLabel();
    }

    if (isArray) {
      if (property.getValues().isEmpty()) {
        property.getValues().add(null);
      }

      final MultiFieldPanel multiFieldPanel =
          new MultiFieldPanel("panel", new PropertyModel<List<String>>(property, "values"), field);
      item.add(multiFieldPanel);
    } else {
      setNewFieldModel(field, property.getValues());
      item.add(field);
    }

    if (withOverridable) {
      item.add(
          new AjaxCheckBoxPanel(
              "connPropAttrOverridable",
              "connPropAttrOverridable",
              new PropertyModel<Boolean>(property, "overridable")));
    }

    configuration.add(property);
  }