예제 #1
0
 private static Field locateField(Class<?> fromClass, String expectedName, Class<?> type) {
   Field found = null;
   // First: let's see if we can find exact match:
   Field[] fields = fromClass.getDeclaredFields();
   for (Field f : fields) {
     if (expectedName.equals(f.getName()) && f.getType() == type) {
       found = f;
       break;
     }
   }
   // And if not, if there is just one field with the type, that field
   if (found == null) {
     for (Field f : fields) {
       if (f.getType() == type) {
         // If more than one, can't choose
         if (found != null) return null;
         found = f;
       }
     }
   }
   if (found != null) { // it's non-public, need to force accessible
     try {
       found.setAccessible(true);
     } catch (Throwable t) {
     }
   }
   return found;
 }
예제 #2
0
 @Override
 public Map parse() {
   if (field.getType().compareTo("json") == 0
       // if the signature is *-> * then guess using {
       || field.getType().startsWith("{")) {
     if (jsonObject instanceof String) {
       logger.debug("json object is string " + jsonObject);
       return null;
     } else return (Map) jsonObject;
   } else return null;
 }
예제 #3
0
 @NotNull
 public static String getDefaultInitializer(@NotNull Field f) {
   if (f.getType().isNullable()) {
     return "null";
   } else {
     String typeToKotlin = f.getType().toKotlin();
     if (typeToKotlin.equals("Boolean")) return "false";
     if (typeToKotlin.equals("Char")) return "' '";
     if (typeToKotlin.equals("Double")) return "0." + OperatorConventions.DOUBLE + "()";
     if (typeToKotlin.equals("Float")) return "0." + OperatorConventions.FLOAT + "()";
     return "0";
   }
 }
예제 #4
0
  void buildConfigPanel() {
    try {
      Config config = playerObjects.getConfig();
      for (Field field : config.getClass().getDeclaredFields()) {
        Annotation excludeAnnotation = field.getAnnotation(ReflectionHelper.Exclude.class);
        if (excludeAnnotation == null) { // so, this field is not excluded
          Class<?> fieldType = field.getType();
          Method getMethod = getGetMethod(config.getClass(), field.getType(), field.getName());
          if (getMethod != null) {
            Object value = getMethod.invoke(config);
            if (fieldType == String.class) {
              addTextBox(field.getName(), (String) value);
            }
            if (fieldType == boolean.class || fieldType == Boolean.class) {
              addBooleanComponent(field.getName(), (Boolean) value);
            }
            if (fieldType == float.class || fieldType == Float.class) {
              addTextBox(field.getName(), "" + value);
            }
            if (fieldType == int.class || fieldType == Integer.class) {
              addTextBox(field.getName(), "" + value);
            }
          } else {
            playerObjects
                .getLogFile()
                .WriteLine("No get accessor method for config field " + field.getName());
          }
        }
      }
    } catch (Exception e) {
      playerObjects.getLogFile().WriteLine(Formatting.exceptionToStackTrace(e));
    }

    configGridLayout.setRows(configGridLayout.getRows() + 2);

    configRevertButton = new JButton("Revert");
    configReloadButton = new JButton("Reload");
    configApplyButton = new JButton("Apply");
    configSaveButton = new JButton("Save");

    configRevertButton.addActionListener(new ConfigRevert());
    configReloadButton.addActionListener(new ConfigReload());
    configApplyButton.addActionListener(new ConfigApply());
    configSaveButton.addActionListener(new ConfigSave());

    configPanel.add(configRevertButton);
    configPanel.add(configReloadButton);
    configPanel.add(configApplyButton);
    configPanel.add(configSaveButton);
  }
    public int compare(Field a, Field b) {
      if (a == b) return 0;
      else if (a == null) return -1;
      else if (b == null) return 1;
      else if (a.equals(b)) return 0;

      int cmp = a.getName().compareTo(b.getName());
      if (cmp != 0) return cmp;

      cmp = a.getDeclaringClass().getName().compareTo(b.getDeclaringClass().getName());
      if (cmp != 0) return cmp;

      return a.getType().getName().compareTo(b.getType().getName());
    }
예제 #6
0
  void instantiateWithInjectableValues(@Nonnull Object testClassInstance) {
    if (isAvailableDuringSetup() && getFieldValue(testedField, testClassInstance) != null) {
      return;
    }

    injectionState.setTestedField(testedField);

    Object testedObject = getTestedObjectFromFieldInTestClassIfApplicable(testClassInstance);
    Class<?> testedClass = testedField.getType();

    if (testedObject == null && createAutomatically) {
      if (reusePreviouslyCreatedInstance(testClassInstance, testedClass)) {
        return;
      }

      if (testedObjectCreation != null) {
        testedObject = testedObjectCreation.create();
        setFieldValue(testedField, testClassInstance, testedObject);
        injectionState.saveTestedObject(testedClass, testedObject);
      }
    } else if (testedObject != null) {
      String dependencyKey = InjectionPoint.dependencyKey(testedClass, testedField.getName());
      injectionState.saveTestedObject(dependencyKey, testedObject);
      testedClass = testedObject.getClass();
    }

    if (testedObject != null) {
      performFieldInjection(testedClass, testedObject);
      executeInitializationMethodsIfAny(testedClass, testedObject);
    }
  }
예제 #7
0
 private ArrayList<Element> serializeFields(
     Field[] fields, Object object, Document doc) // serializes the fields
     {
   Class currentClass = object.getClass();
   ArrayList<Element> elements = new ArrayList<Element>();
   for (Field f : fields) {
     try {
       if (!f.getType().isPrimitive()) // Field not primitive, is a reference to another object
       {
       } else // field is primitive
       {
         Element newField = new Element("field");
         newField.setAttribute("name", f.getName());
         newField.setAttribute("declaringclass", f.getDeclaringClass().getName());
         Element newValue = new Element("value");
         newValue.addContent(f.get(object).toString());
         newField.addContent(newValue);
         elements.add(newField);
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return elements;
 }
예제 #8
0
  @Override
  public String getString() throws SQLException {
    int type = JSONTypes.jsonTypes.get(field.getType());
    switch (type) {
      case JSONTypes.JSON_ARRAY:
      case JSONTypes.JSON_OBJECT:
      case JSONTypes.JSON_MAP:
        toJson();
        return sqlJson;
      case JSONTypes.JSON_NULL:
        return null;
      case JSONTypes.JSON_STRING:
        if (sqlJson != null) return sqlJson;
        if (jsonObject != null) return (String) jsonObject;
        isNull = true;
        return null;

        // let the default implementation of toString figure it out
      case JSONTypes.JSON_BOOLEAN:
      case JSONTypes.JSON_NUMBER:
        return jsonObject.toString();
      default:
        return "";
    }
  }
 /**
  * This method returns the maximum representation size of an object. <code>sizeSoFar</code> is the
  * object's size measured so far. <code>f</code> is the field being probed.
  *
  * <p>The returned offset will be the maximum of whatever was measured so far and <code>f</code>
  * field's offset and representation size (unaligned).
  */
 private static long adjustForField(long sizeSoFar, final Field f) {
   final Class<?> type = f.getType();
   final int fsize = type.isPrimitive() ? primitiveSizes.get(type) : NUM_BYTES_OBJECT_REF;
   if (objectFieldOffsetMethod != null) {
     try {
       final long offsetPlusSize =
           ((Number) objectFieldOffsetMethod.invoke(theUnsafe, f)).longValue() + fsize;
       return Math.max(sizeSoFar, offsetPlusSize);
     } catch (IllegalAccessException ex) {
       throw new RuntimeException("Access problem with sun.misc.Unsafe", ex);
     } catch (InvocationTargetException ite) {
       final Throwable cause = ite.getCause();
       if (cause instanceof RuntimeException) throw (RuntimeException) cause;
       if (cause instanceof Error) throw (Error) cause;
       // this should never happen (Unsafe does not declare
       // checked Exceptions for this method), but who knows?
       throw new RuntimeException(
           "Call to Unsafe's objectFieldOffset() throwed "
               + "checked Exception when accessing field "
               + f.getDeclaringClass().getName()
               + "#"
               + f.getName(),
           cause);
     }
   } else {
     // TODO: No alignments based on field type/ subclass fields alignments?
     return sizeSoFar + fsize;
   }
 }
예제 #10
0
  void put(Scriptable scope, String name, Object javaObject, Object value, boolean isStatic) {
    Map<String, Object> ht = isStatic ? staticMembers : members;
    Object member = ht.get(name);
    if (!isStatic && member == null) {
      // Try to get static member from instance (LC3)
      member = staticMembers.get(name);
    }
    if (member == null) throw reportMemberNotFound(name);
    if (member instanceof FieldAndMethods) {
      FieldAndMethods fam = (FieldAndMethods) ht.get(name);
      member = fam.field;
    }

    // Is this a bean property "set"?
    if (member instanceof BeanProperty) {
      BeanProperty bp = (BeanProperty) member;
      if (bp.setter == null) {
        throw reportMemberNotFound(name);
      }
      // If there's only one setter or if the value is null, use the
      // main setter. Otherwise, let the NativeJavaMethod decide which
      // setter to use:
      if (bp.setters == null || value == null) {
        Class<?> setType = bp.setter.argTypes[0];
        Object[] args = {Context.jsToJava(value, setType)};
        try {
          bp.setter.invoke(javaObject, args);
        } catch (Exception ex) {
          throw Context.throwAsScriptRuntimeEx(ex);
        }
      } else {
        Object[] args = {value};
        bp.setters.call(
            Context.getContext(), ScriptableObject.getTopLevelScope(scope), scope, args);
      }
    } else {
      if (!(member instanceof Field)) {
        String str = (member == null) ? "msg.java.internal.private" : "msg.java.method.assign";
        throw Context.reportRuntimeError1(str, name);
      }
      Field field = (Field) member;
      Object javaValue = Context.jsToJava(value, field.getType());
      try {
        field.set(javaObject, javaValue);
      } catch (IllegalAccessException accessEx) {
        if ((field.getModifiers() & Modifier.FINAL) != 0) {
          // treat Java final the same as JavaScript [[READONLY]]
          return;
        }
        throw Context.throwAsScriptRuntimeEx(accessEx);
      } catch (IllegalArgumentException argEx) {
        throw Context.reportRuntimeError3(
            "msg.java.internal.field.type",
            value.getClass().getName(),
            field,
            javaObject.getClass().getName());
      }
    }
  }
 public Object getChild(Object parent, int index) {
   ArrayList<Field> fields = ((Variable) parent).getFields();
   Field f = (Field) fields.get(index);
   Object parentValue = ((Variable) parent).getValue();
   try {
     return new Variable(f.getType(), f.getName(), f.get(parentValue));
   } catch (IllegalAccessException e) {
     return null;
   }
 }
예제 #12
0
 @SuppressWarnings("unchecked")
 private void addFields(List list, boolean isStatic) {
   int count = klass.getFieldCount(isStatic);
   for (int i = 0; i != count; ++i) {
     Field field = klass.getField(i, isStatic);
     FieldID fid = new FieldID(JDWP.getTag(field.getType()), field.getOffset(), isStatic, getID());
     ProxyField proxyField = new ProxyField(fid, field);
     list.add(proxyField);
   }
 }
예제 #13
0
파일: Neat.java 프로젝트: njustesen/hero-ai
  public static boolean readParam(String xNomeFile) {

    boolean ret = true;
    String xline;
    IOseq xFile;
    StringTokenizer st;
    String s1;
    String s2;
    Object m1;

    xFile = new IOseq("parameters.ne");
    ret = xFile.IOseqOpenR();
    if (ret) {
      try {
        Class c = Class.forName("jneat.Neat");
        Field[] fieldlist = c.getDeclaredFields();

        int number_params = fieldlist.length / 2;

        for (int i = 0; i < number_params; i++) {
          Field f1 = fieldlist[i];
          String x1 = f1.getName();
          Object x2 = f1.getType();
          xline = xFile.IOseqRead();

          st = new StringTokenizer(xline);
          // skip comment

          s1 = st.nextToken();
          // real value
          s1 = st.nextToken();

          if (x1.startsWith("p_")) {
            if (x2.toString().equals("double")) {
              double n1 = Double.parseDouble(s1);
              f1.set(c, (new Double(n1)));
            }
            if (x2.toString().equals("int")) {
              int n1 = Integer.parseInt(s1);
              f1.set(c, (new Integer(n1)));
            }
          }
        }

      } catch (Throwable e) {
        System.err.println(e);
      }

      xFile.IOseqCloseR();

    } else System.err.print("\n : error during open " + xNomeFile);

    return ret;
  }
예제 #14
0
파일: Graph.java 프로젝트: safdariqbal/frex
 public void checki(boolean basic, Var x, Field f, Var y, Field g) {
   fail = false;
   if (!basic) {
     if (x.getType().getKind() == TypeIR.Kind.VOID) fail = true;
     if (y.getType().getKind() == TypeIR.Kind.VOID) fail = true;
     if (fail) {
       assert (false);
     }
   }
   assertion(basic, x, f);
   assertion(basic, y, g);
   if (fail) {
     assert (false);
     System.out.println(" Overall ! ");
     System.out.println(x.getType());
     if (f != null) System.out.println(" f " + f.getType());
     System.out.println(y.getType());
     if (g != null) System.out.println(" g " + g.getType());
   }
 }
예제 #15
0
 void revertConfig() {
   try {
     debug("reverting config panel");
     Config config = playerObjects.getConfig();
     for (Field field : config.getClass().getDeclaredFields()) {
       Annotation excludeAnnotation = field.getAnnotation(ReflectionHelper.Exclude.class);
       if (excludeAnnotation == null) { // so, this field is not excluded
         debug("field " + field.getName());
         Class<?> fieldType = field.getType();
         Method getMethod = getGetMethod(config.getClass(), field.getType(), field.getName());
         if (getMethod != null) {
           debug(" ... found accessor method");
           Object value = getMethod.invoke(config);
           String fieldname = field.getName();
           Component component = componentByName.get(fieldname);
           if (component != null) {
             debug(" ... found component");
             if (fieldType == String.class) {
               ((JTextField) component).setText((String) value);
             }
             if (fieldType == boolean.class || fieldType == Boolean.class) {
               ((JCheckBox) component).setSelected((Boolean) value);
             }
             if (fieldType == float.class || fieldType == Float.class) {
               ((JTextField) component).setText("" + value);
             }
             if (fieldType == int.class || fieldType == Integer.class) {
               ((JTextField) component).setText("" + value);
             }
           }
         } else {
           playerObjects
               .getLogFile()
               .WriteLine("No get accessor method for config field " + field.getName());
         }
       }
     }
   } catch (Exception e) {
     playerObjects.getLogFile().WriteLine(Formatting.exceptionToStackTrace(e));
   }
 }
예제 #16
0
  /**
   * Prints all fields of a class
   *
   * @param cl a class
   */
  public static void printFields(Class cl) {
    Field[] fields = cl.getDeclaredFields();

    for (Field f : fields) {
      Class type = f.getType();
      String name = f.getName();
      System.out.print("   ");
      String modifiers = Modifier.toString(f.getModifiers());
      if (modifiers.length() > 0) System.out.print(modifiers + " ");
      System.out.println(type.getName() + " " + name + ";");
    }
  }
예제 #17
0
파일: Graph.java 프로젝트: safdariqbal/frex
 private void assertion(boolean basic, Var x, Field f) {
   if (basic) {
     if (x.getType().getKind() != TypeIR.Kind.BASIC) {
       if (f == null) {
         System.out.println(" 1mm " + x.getType());
         fail = true;
       }
       if (f.getType().getKind() != TypeIR.Kind.BASIC) {
         System.out.println(" xxmm " + x.getType());
         System.out.println(" 2mm " + f.getName() + " " + f.getType());
         fail = true;
       }
     }
   } else {
     if (x.getType().getKind() == TypeIR.Kind.BASIC) {
       System.out.println(" 3mm " + x.getType());
       fail = true;
     }
     if (f != null && f.getType().getKind() == TypeIR.Kind.BASIC) {
       System.out.println(" 4mm " + f.getName() + " " + f.getType());
       fail = true;
     }
   }
 }
예제 #18
0
  TestedField(
      @Nonnull InjectionState injectionState, @Nonnull Field field, @Nonnull Tested metadata) {
    this.injectionState = injectionState;
    testedField = field;
    this.metadata = metadata;
    fullInjection = metadata.fullyInitialized() ? new FullInjection(injectionState) : null;

    Class<?> fieldType = field.getType();

    if (fieldType.isInterface()) {
      testedObjectCreation = null;
    } else {
      testedObjectCreation = new TestedObjectCreation(injectionState, fullInjection, field);
      injectionState.lifecycleMethods.findLifecycleMethods(fieldType);
    }
  }
  private void importField(DbJVClass dbClaz, Field field) throws DbException {
    if (dbClaz == null) {
      return;
    }

    DbJVDataMember member = new DbJVDataMember(dbClaz);
    member.setName(field.getName());

    // set field type
    Type type = field.getType();
    member.setType(toAdt(type));
    member.setTypeUse(toTypeUse(type));

    // set field modifiers
    member.setFinal(field.isFinal());
    member.setStatic(field.isStatic());
    member.setTransient(field.isTransient());
    member.setVisibility(toVisibility(field));
    member.setVolatile(field.isVolatile());
  }
예제 #20
0
  protected void generateView(Map<String, org.ektorp.support.DesignDocument.View> views, Field f) {
    DocumentReferences referenceMetaData = f.getAnnotation(DocumentReferences.class);
    if (referenceMetaData == null) {
      LOG.warn("No DocumentReferences annotation found in field: ", f.getName());
      return;
    }

    if (referenceMetaData.view().length() > 0) {
      LOG.debug("Skipping view generation for field {} as view is already specified", f.getName());
      return;
    }

    if (Set.class.isAssignableFrom(f.getType())) {
      generateSetBasedDocRefView(views, f, referenceMetaData);
    } else {
      throw new ViewGenerationException(
          String.format(
              "The type of the field: %s in %s annotated with DocumentReferences is not supported. (Must be assignable from java.util.Set)",
              f.getName(), f.getDeclaringClass()));
    }
  }
예제 #21
0
 private static void linkChildren(RArray parentRealView, ViewTrace parentTrace) {
   Class viewClass = parentRealView.getClass();
   Field[] fields = getAllFields(viewClass);
   for (Field f : fields) {
     if (f.isSynthetic()) {
       continue;
     }
     Class fieldClass = f.getType();
     if (RArray.class.isAssignableFrom(fieldClass)) {
       try {
         f.setAccessible(true);
         Object o = f.get(parentRealView);
         if (o instanceof TracingView) {
           ((TracingView) o).getTrace().parentView = parentTrace;
         }
       } catch (IllegalAccessException e) {
         assert Utils.check(false, "can't read a view field " + e);
       }
     }
   }
 }
예제 #22
0
  public Predicted(DataFrame<M> f, String pfn) {
    frame = f;
    numericField = null;

    Class<M> mcls = frame.getModelClass();

    try {
      Field mf = mcls.getField(pfn);
      Class t = mf.getType();
      if (Model.isSubclass(t, Number.class)) {
        numericField = mf;
      } else {
        throw new IllegalArgumentException(
            String.format("Field %s is not numeric", pfn, t.getName()));
      }

    } catch (NoSuchFieldException e) {
      e.printStackTrace();
      throw new IllegalArgumentException(String.format("Unknown field name: %s", pfn));
    }
  }
예제 #23
0
 Object get(Scriptable scope, String name, Object javaObject, boolean isStatic) {
   Map<String, Object> ht = isStatic ? staticMembers : members;
   Object member = ht.get(name);
   if (!isStatic && member == null) {
     // Try to get static member from instance (LC3)
     member = staticMembers.get(name);
   }
   if (member == null) {
     member =
         this.getExplicitFunction(
             scope, name,
             javaObject, isStatic);
     if (member == null) return Scriptable.NOT_FOUND;
   }
   if (member instanceof Scriptable) {
     return member;
   }
   Context cx = Context.getContext();
   Object rval;
   Class<?> type;
   try {
     if (member instanceof BeanProperty) {
       BeanProperty bp = (BeanProperty) member;
       if (bp.getter == null) return Scriptable.NOT_FOUND;
       rval = bp.getter.invoke(javaObject, Context.emptyArgs);
       type = bp.getter.method().getReturnType();
     } else {
       Field field = (Field) member;
       rval = field.get(isStatic ? null : javaObject);
       type = field.getType();
     }
   } catch (Exception ex) {
     throw Context.throwAsScriptRuntimeEx(ex);
   }
   // Need to wrap the object before we return it.
   scope = ScriptableObject.getTopLevelScope(scope);
   return cx.getWrapFactory().wrap(cx, scope, rval, type);
 }
예제 #24
0
  public boolean getBoolean() throws SQLException {
    int type = JSONTypes.jsonTypes.get(field.getType());

    switch (type) {
      case JSONTypes.JSON_BOOLEAN:
        return (boolean) jsonObject;
      case JSONTypes.JSON_NUMBER:
        Number number = (Number) jsonObject;
        return !number.equals((Number) 0);
      case JSONTypes.JSON_STRING:
        String string = (String) jsonObject;
        return !string.isEmpty();
      case JSONTypes.JSON_MAP:
      case JSONTypes.JSON_OBJECT:
        Map map = (Map) jsonObject;
        return !map.isEmpty();
      case JSONTypes.JSON_ARRAY:
        List list = (List) jsonObject;
        return !list.isEmpty();

      default:
        return false;
    }
  }
예제 #25
0
파일: Neat.java 프로젝트: njustesen/hero-ai
  public static void updateParam(vectTableModel _model) {
    //
    // write to file xpar all parameters.....
    //

    for (int j = 0; j < _model.data.size(); j++) {
      try {
        Class c = Class.forName("jneat.Neat");
        ParamValue ox = (ParamValue) _model.data.elementAt(j);

        Object k = _model.getValueAt(j, 0);
        Object kv = _model.getValueAt(j, 1);

        String xkey = k.toString();
        String xval = kv.toString();
        /*
        System.out.print("\n j = "+j+" xkey = "+xkey);
        System.out.print(" xval = "+xval);
        */
        Field f1 = c.getField("p_" + xkey);
        Object fty = f1.getType();

        if (fty.toString().equals("double")) {
          double n1 = Double.parseDouble(xval);
          f1.set(c, (new Double(n1)));
        }
        if (fty.toString().equals("int")) {
          int n1 = Integer.parseInt(xval);
          f1.set(c, (new Integer(n1)));
        }

      } catch (Throwable e) {
        System.out.print("\n errore su jneat.updateParam = " + e);
      }
    }
  }
  /** Create a cached information about shallow size and reference fields for a given class. */
  private static ClassCache createCacheEntry(final Class<?> clazz) {
    ClassCache cachedInfo;
    long shallowInstanceSize = NUM_BYTES_OBJECT_HEADER;
    final ArrayList<Field> referenceFields = new ArrayList<Field>(32);
    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
      final Field[] fields = c.getDeclaredFields();
      for (final Field f : fields) {
        if (!Modifier.isStatic(f.getModifiers())) {
          shallowInstanceSize = adjustForField(shallowInstanceSize, f);

          if (!f.getType().isPrimitive()) {
            f.setAccessible(true);
            referenceFields.add(f);
          }
        }
      }
    }

    cachedInfo =
        new ClassCache(
            alignObjectSize(shallowInstanceSize),
            referenceFields.toArray(new Field[referenceFields.size()]));
    return cachedInfo;
  }
예제 #27
0
  @SuppressWarnings("unchecked")
  LDAPObjectHandler(final Class<T> type) throws LDAPPersistException {
    this.type = type;

    final Class<? super T> superclassType = type.getSuperclass();
    if (superclassType == null) {
      superclassHandler = null;
    } else {
      final LDAPObject superclassAnnotation = superclassType.getAnnotation(LDAPObject.class);
      if (superclassAnnotation == null) {
        superclassHandler = null;
      } else {
        superclassHandler = new LDAPObjectHandler(superclassType);
      }
    }

    final TreeMap<String, FieldInfo> fields = new TreeMap<String, FieldInfo>();
    final TreeMap<String, GetterInfo> getters = new TreeMap<String, GetterInfo>();
    final TreeMap<String, SetterInfo> setters = new TreeMap<String, SetterInfo>();

    ldapObject = type.getAnnotation(LDAPObject.class);
    if (ldapObject == null) {
      throw new LDAPPersistException(ERR_OBJECT_HANDLER_OBJECT_NOT_ANNOTATED.get(type.getName()));
    }

    final LinkedHashMap<String, String> objectClasses = new LinkedHashMap<String, String>(10);

    final String oc = ldapObject.structuralClass();
    if (oc.length() == 0) {
      structuralClass = getUnqualifiedClassName(type);
    } else {
      structuralClass = oc;
    }

    final StringBuilder invalidReason = new StringBuilder();
    if (PersistUtils.isValidLDAPName(structuralClass, invalidReason)) {
      objectClasses.put(toLowerCase(structuralClass), structuralClass);
    } else {
      throw new LDAPPersistException(
          ERR_OBJECT_HANDLER_INVALID_STRUCTURAL_CLASS.get(
              type.getName(), structuralClass, invalidReason.toString()));
    }

    auxiliaryClasses = ldapObject.auxiliaryClass();
    for (final String auxiliaryClass : auxiliaryClasses) {
      if (PersistUtils.isValidLDAPName(auxiliaryClass, invalidReason)) {
        objectClasses.put(toLowerCase(auxiliaryClass), auxiliaryClass);
      } else {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_AUXILIARY_CLASS.get(
                type.getName(), auxiliaryClass, invalidReason.toString()));
      }
    }

    superiorClasses = ldapObject.superiorClass();
    for (final String superiorClass : superiorClasses) {
      if (PersistUtils.isValidLDAPName(superiorClass, invalidReason)) {
        objectClasses.put(toLowerCase(superiorClass), superiorClass);
      } else {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_SUPERIOR_CLASS.get(
                type.getName(), superiorClass, invalidReason.toString()));
      }
    }

    if (superclassHandler != null) {
      for (final String s : superclassHandler.objectClassAttribute.getValues()) {
        objectClasses.put(toLowerCase(s), s);
      }
    }

    objectClassAttribute = new Attribute("objectClass", objectClasses.values());

    final String parentDNStr = ldapObject.defaultParentDN();
    try {
      defaultParentDN = new DN(parentDNStr);
    } catch (LDAPException le) {
      throw new LDAPPersistException(
          ERR_OBJECT_HANDLER_INVALID_DEFAULT_PARENT.get(
              type.getName(), parentDNStr, le.getMessage()),
          le);
    }

    final String postDecodeMethodName = ldapObject.postDecodeMethod();
    if (postDecodeMethodName.length() > 0) {
      try {
        postDecodeMethod = type.getDeclaredMethod(postDecodeMethodName);
        postDecodeMethod.setAccessible(true);
      } catch (Exception e) {
        debugException(e);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_POST_DECODE_METHOD.get(
                type.getName(), postDecodeMethodName, getExceptionMessage(e)),
            e);
      }
    } else {
      postDecodeMethod = null;
    }

    final String postEncodeMethodName = ldapObject.postEncodeMethod();
    if (postEncodeMethodName.length() > 0) {
      try {
        postEncodeMethod = type.getDeclaredMethod(postEncodeMethodName, Entry.class);
        postEncodeMethod.setAccessible(true);
      } catch (Exception e) {
        debugException(e);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_POST_ENCODE_METHOD.get(
                type.getName(), postEncodeMethodName, getExceptionMessage(e)),
            e);
      }
    } else {
      postEncodeMethod = null;
    }

    try {
      constructor = type.getDeclaredConstructor();
      constructor.setAccessible(true);
    } catch (Exception e) {
      debugException(e);
      throw new LDAPPersistException(
          ERR_OBJECT_HANDLER_NO_DEFAULT_CONSTRUCTOR.get(type.getName()), e);
    }

    Field tmpDNField = null;
    Field tmpEntryField = null;
    final LinkedList<FieldInfo> tmpRFilterFields = new LinkedList<FieldInfo>();
    final LinkedList<FieldInfo> tmpAAFilterFields = new LinkedList<FieldInfo>();
    final LinkedList<FieldInfo> tmpCAFilterFields = new LinkedList<FieldInfo>();
    final LinkedList<FieldInfo> tmpRDNFields = new LinkedList<FieldInfo>();
    for (final Field f : type.getDeclaredFields()) {
      final LDAPField fieldAnnotation = f.getAnnotation(LDAPField.class);
      final LDAPDNField dnFieldAnnotation = f.getAnnotation(LDAPDNField.class);
      final LDAPEntryField entryFieldAnnotation = f.getAnnotation(LDAPEntryField.class);

      if (fieldAnnotation != null) {
        f.setAccessible(true);

        final FieldInfo fieldInfo = new FieldInfo(f, type);
        final String attrName = toLowerCase(fieldInfo.getAttributeName());
        if (fields.containsKey(attrName)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), fieldInfo.getAttributeName()));
        } else {
          fields.put(attrName, fieldInfo);
        }

        switch (fieldInfo.getFilterUsage()) {
          case REQUIRED:
            tmpRFilterFields.add(fieldInfo);
            break;
          case ALWAYS_ALLOWED:
            tmpAAFilterFields.add(fieldInfo);
            break;
          case CONDITIONALLY_ALLOWED:
            tmpCAFilterFields.add(fieldInfo);
            break;
          case EXCLUDED:
          default:
            break;
        }

        if (fieldInfo.includeInRDN()) {
          tmpRDNFields.add(fieldInfo);
        }
      }

      if (dnFieldAnnotation != null) {
        f.setAccessible(true);

        if (fieldAnnotation != null) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get(
                  type.getName(), "LDAPField", "LDAPDNField", f.getName()));
        }

        if (tmpDNField != null) {
          throw new LDAPPersistException(ERR_OBJECT_HANDLER_MULTIPLE_DN_FIELDS.get(type.getName()));
        }

        final int modifiers = f.getModifiers();
        if (Modifier.isFinal(modifiers)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_DN_FIELD_FINAL.get(f.getName(), type.getName()));
        } else if (Modifier.isStatic(modifiers)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_DN_FIELD_STATIC.get(f.getName(), type.getName()));
        }

        final Class<?> fieldType = f.getType();
        if (fieldType.equals(String.class)) {
          tmpDNField = f;
        } else {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_INVALID_DN_FIELD_TYPE.get(
                  type.getName(), f.getName(), fieldType.getName()));
        }
      }

      if (entryFieldAnnotation != null) {
        f.setAccessible(true);

        if (fieldAnnotation != null) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_CONFLICTING_FIELD_ANNOTATIONS.get(
                  type.getName(), "LDAPField", "LDAPEntryField", f.getName()));
        }

        if (tmpEntryField != null) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_MULTIPLE_ENTRY_FIELDS.get(type.getName()));
        }

        final int modifiers = f.getModifiers();
        if (Modifier.isFinal(modifiers)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ENTRY_FIELD_FINAL.get(f.getName(), type.getName()));
        } else if (Modifier.isStatic(modifiers)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ENTRY_FIELD_STATIC.get(f.getName(), type.getName()));
        }

        final Class<?> fieldType = f.getType();
        if (fieldType.equals(ReadOnlyEntry.class)) {
          tmpEntryField = f;
        } else {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_INVALID_ENTRY_FIELD_TYPE.get(
                  type.getName(), f.getName(), fieldType.getName()));
        }
      }
    }

    dnField = tmpDNField;
    entryField = tmpEntryField;
    requiredFilterFields = Collections.unmodifiableList(tmpRFilterFields);
    alwaysAllowedFilterFields = Collections.unmodifiableList(tmpAAFilterFields);
    conditionallyAllowedFilterFields = Collections.unmodifiableList(tmpCAFilterFields);
    rdnFields = Collections.unmodifiableList(tmpRDNFields);

    final LinkedList<GetterInfo> tmpRFilterGetters = new LinkedList<GetterInfo>();
    final LinkedList<GetterInfo> tmpAAFilterGetters = new LinkedList<GetterInfo>();
    final LinkedList<GetterInfo> tmpCAFilterGetters = new LinkedList<GetterInfo>();
    final LinkedList<GetterInfo> tmpRDNGetters = new LinkedList<GetterInfo>();
    for (final Method m : type.getDeclaredMethods()) {
      final LDAPGetter getter = m.getAnnotation(LDAPGetter.class);
      final LDAPSetter setter = m.getAnnotation(LDAPSetter.class);

      if (getter != null) {
        m.setAccessible(true);

        if (setter != null) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_CONFLICTING_METHOD_ANNOTATIONS.get(
                  type.getName(), "LDAPGetter", "LDAPSetter", m.getName()));
        }

        final GetterInfo methodInfo = new GetterInfo(m, type);
        final String attrName = toLowerCase(methodInfo.getAttributeName());
        if (fields.containsKey(attrName) || getters.containsKey(attrName)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName()));
        } else {
          getters.put(attrName, methodInfo);
        }

        switch (methodInfo.getFilterUsage()) {
          case REQUIRED:
            tmpRFilterGetters.add(methodInfo);
            break;
          case ALWAYS_ALLOWED:
            tmpAAFilterGetters.add(methodInfo);
            break;
          case CONDITIONALLY_ALLOWED:
            tmpCAFilterGetters.add(methodInfo);
            break;
          case EXCLUDED:
          default:
            // No action required.
            break;
        }

        if (methodInfo.includeInRDN()) {
          tmpRDNGetters.add(methodInfo);
        }
      }

      if (setter != null) {
        m.setAccessible(true);

        final SetterInfo methodInfo = new SetterInfo(m, type);
        final String attrName = toLowerCase(methodInfo.getAttributeName());
        if (fields.containsKey(attrName) || setters.containsKey(attrName)) {
          throw new LDAPPersistException(
              ERR_OBJECT_HANDLER_ATTR_CONFLICT.get(type.getName(), methodInfo.getAttributeName()));
        } else {
          setters.put(attrName, methodInfo);
        }
      }
    }

    requiredFilterGetters = Collections.unmodifiableList(tmpRFilterGetters);
    alwaysAllowedFilterGetters = Collections.unmodifiableList(tmpAAFilterGetters);
    conditionallyAllowedFilterGetters = Collections.unmodifiableList(tmpCAFilterGetters);

    rdnGetters = Collections.unmodifiableList(tmpRDNGetters);
    if (rdnFields.isEmpty() && rdnGetters.isEmpty()) {
      throw new LDAPPersistException(ERR_OBJECT_HANDLER_NO_RDN_DEFINED.get(type.getName()));
    }

    fieldMap = Collections.unmodifiableMap(fields);
    getterMap = Collections.unmodifiableMap(getters);
    setterMap = Collections.unmodifiableMap(setters);

    final TreeSet<String> attrSet = new TreeSet<String>();
    final TreeSet<String> lazySet = new TreeSet<String>();
    if (ldapObject.requestAllAttributes()) {
      attrSet.add("*");
      attrSet.add("+");
    } else {
      for (final FieldInfo i : fields.values()) {
        if (i.lazilyLoad()) {
          lazySet.add(i.getAttributeName());
        } else {
          attrSet.add(i.getAttributeName());
        }
      }

      for (final SetterInfo i : setters.values()) {
        attrSet.add(i.getAttributeName());
      }
    }
    attributesToRequest = new String[attrSet.size()];
    attrSet.toArray(attributesToRequest);

    lazilyLoadedAttributes = new String[lazySet.size()];
    lazySet.toArray(lazilyLoadedAttributes);
  }
예제 #28
0
  public Type navigateQualified(String name, Type[] qualifiers) throws OclTypeException {
    Type theQualifier = null;

    if (qualifiers != null) {
      if (qualifiers.length == 1) theQualifier = qualifiers[0];
      else throw new OclTypeException("ReflectionFacade can handle one qualifier only");
    }
    // System.out.println("ClassAny.navigateQualified:"+this+" "+name);
    Type ret = Basic.navigateAnyQualified(name, this, qualifiers);
    if (ret != null) return ret;
    String[] javaNames = rf.nameAdapter.getNames(name);
    Field f = null;
    for (int i = 0; i < javaNames.length && f == null; i++) {
      Class nextClass = c;
      while (nextClass != null && f == null) {
        try {
          f = nextClass.getDeclaredField(javaNames[i]);
        } catch (NoSuchFieldException nsf) {
          // try next class
        }
        nextClass = nextClass.getSuperclass();
      }
    }
    if (f == null) {
      throw new OclTypeException(c.getName() + " has no field " + name);
    }
    Class type = f.getType();
    Type modeltype = getTypeForClass(type);

    if (modeltype instanceof Collection) {
      Class elementtype = rf.getElementType(f);

      if (rf.reflAdapter.isMap(type)) {
        if (theQualifier == null) {
          if (elementtype != null)
            return new Collection(
                ((Collection) modeltype).getCollectionKind(), getTypeForClass(elementtype));
          else return modeltype;
        } else {
          Class keytype_class = rf.getKeyType(f);
          Type keytype = null;
          if (keytype_class != null) keytype = getTypeForClass(keytype_class);

          if (keytype != null) {
            if (!theQualifier.equals(keytype))
              throw new OclTypeException(
                  "feature "
                      + name
                      + " in classifier "
                      + c
                      + ": expected qualifier type "
                      + keytype
                      + " found "
                      + theQualifier
                      + ".");
            if (elementtype != null) return getTypeForClass(elementtype);
            else
              throw new OclTypeException(
                  "feature "
                      + name
                      + "["
                      + keytype
                      + "] in classifier "
                      + c
                      + " has no @element-type tag.");
          } else
            throw new OclTypeException(
                "feature "
                    + name
                    + " in classifier "
                    + c
                    + ": qualified with type "
                    + theQualifier
                    + ", but feature has no @keytype tag.");
        }
      } else {
        if (theQualifier != null)
          throw new OclTypeException(
              "feature " + name + " in classifier " + c + " cannot be qualified.");

        if (elementtype != null)
          return new Collection(
              ((Collection) modeltype).getCollectionKind(), getTypeForClass(elementtype));
        else return modeltype;
      }
    } else {
      if (theQualifier != null)
        throw new OclTypeException(
            "feature " + name + " in classifier " + c + " cannot be qualified.");
      return modeltype;
    }
  }
예제 #29
0
 private Object createObject(
     Node node, String name, String classPackage, String type, String value, boolean setProperty) {
   Bean parentBean = null;
   if (beansStack.size() > 0) parentBean = (Bean) beansStack.peek();
   Object object = null;
   // param is either an XSD type or a bean,
   // check if it can be converted to an XSD type
   XSDatatype dt = null;
   try {
     dt = DatatypeFactory.getTypeByName(type);
   } catch (DatatypeException dte) {
     // the type is not a valid XSD data type
   }
   // convert null value to default
   if ((dt != null) && (value == null)) {
     Class objType = dt.getJavaObjectType();
     if (objType == String.class) value = "";
     else if ((objType == java.math.BigInteger.class)
         || (objType == Long.class)
         || (objType == Integer.class)
         || (objType == Short.class)
         || (objType == Byte.class)) value = "0";
     else if ((objType == java.math.BigDecimal.class)
         || (objType == Double.class)
         || (objType == Float.class)) value = "0.0";
     else if (objType == Boolean.class) value = "false";
     else if (objType == java.util.Date.class) value = DateUtils.getCurrentDate();
     else if (objType == java.util.Calendar.class) value = DateUtils.getCurrentDateTime();
   }
   //  check whether the type was converted to an XSD datatype
   if ((dt != null) && dt.isValid(value, null)) {
     // create and return an XSD Java object (e.g. String, Integer, Boolean, etc)
     object = dt.createJavaObject(value, null);
     if (object instanceof java.util.Calendar) {
       // check that the object is truly a Calendar
       // because DatatypeFactory converts xsd:date
       // types to GregorianCalendar instead of Date.
       if (type.equals("date")) {
         java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd");
         try {
           object = df.parse(value);
         } catch (java.text.ParseException pe) {
           object = new java.util.Date();
         }
       }
     }
   } else {
     // Create a bean object
     if (topLevelBean == null) topLevelBean = parentBean;
     object = pushBeanOnStack(classPackage, type);
     // Check fields to see if this property is the 'value' for the object
     Field[] fields = object.getClass().getDeclaredFields();
     for (int i = 0; i < fields.length; i++) {
       if (fields[i].isAnnotationPresent(ObjectXmlAsValue.class)) {
         try {
           StringBuffer fieldName = new StringBuffer(fields[i].getName());
           char c = fieldName.charAt(0);
           if (c >= 'a' && c <= 'z') {
             c += 'A' - 'a';
           }
           fieldName.setCharAt(0, c);
           fieldName.insert(0, "set");
           Method method =
               object
                   .getClass()
                   .getMethod(fieldName.toString(), new Class[] {fields[i].getType()});
           method.invoke(object, value);
           break;
         } catch (Exception e) {
           System.err.println(e.getMessage());
         }
       }
     }
     NamedNodeMap nodeAttrs = node.getAttributes();
     // iterate attributes and set field values for property attributes
     for (int i = 0; i < nodeAttrs.getLength(); i++) {
       String nodePrefix = nodeAttrs.item(i).getPrefix();
       if (nodePrefix.equals(nsPrefix)) {
         String nodeName = nodeAttrs.item(i).getLocalName();
         String nodeValue = nodeAttrs.item(i).getNodeValue();
         try {
           Field field = object.getClass().getDeclaredField(nodeName);
           if (field.isAnnotationPresent(ObjectXmlAsAttribute.class)) {
             StringBuffer fieldName = new StringBuffer(field.getName());
             char c = fieldName.charAt(0);
             if (c >= 'a' && c <= 'z') {
               c += 'A' - 'a';
             }
             fieldName.setCharAt(0, c);
             fieldName.insert(0, "set");
             Method method =
                 object.getClass().getMethod(fieldName.toString(), new Class[] {field.getType()});
             if (field.getType() == String.class) method.invoke(object, nodeValue);
             else if (field.getType() == Boolean.TYPE)
               method.invoke(object, StringUtils.strToBool(nodeValue, "true"));
             else if (field.getType() == Byte.TYPE)
               method.invoke(object, Byte.valueOf(nodeValue).byteValue());
             else if (field.getType() == Character.TYPE)
               method.invoke(object, Character.valueOf(nodeValue.charAt(0)));
             else if (field.getType() == Double.TYPE)
               method.invoke(object, Double.valueOf(nodeValue).doubleValue());
             else if (field.getType() == Float.TYPE)
               method.invoke(object, Float.valueOf(nodeValue).floatValue());
             else if (field.getType() == Integer.TYPE)
               method.invoke(object, Integer.valueOf(nodeValue).intValue());
             else if (field.getType() == Long.TYPE)
               method.invoke(object, Long.valueOf(nodeValue).longValue());
             else if (field.getType() == Short.TYPE)
               method.invoke(object, Short.valueOf(nodeValue).shortValue());
           }
         } catch (Exception e) {
           System.err.println(e.getMessage());
         }
       }
     }
   }
   if ((parentBean != null) && (setProperty)) {
     parentBean.setProperty(name, object);
   }
   return object;
 }
  private Statement statementOrNull(Statement methodInvoker, Field field) {
    if (field.getType().isAssignableFrom(Statement.class))
      return getOriginalStatement(methodInvoker, field);

    return null;
  }