Example #1
0
  /**
   * Prints one Unicode property value per line, along with its aliases, if any, for the given
   * unicodeVersion.
   *
   * @param unicodeVersion The Unicode version to print property values and aliases for
   * @throws UnicodeProperties.UnsupportedUnicodeVersionException if unicodeVersion is not supported
   */
  private static void printUnicodePropertyValuesAndAliases(String unicodeVersion)
      throws UnicodeProperties.UnsupportedUnicodeVersionException {
    Pattern versionPattern = Pattern.compile("(\\d+)(?:\\.(\\d+))?(?:\\.\\d+)?");
    Matcher matcher = versionPattern.matcher(unicodeVersion);
    if (!matcher.matches()) {
      throw new UnicodeProperties.UnsupportedUnicodeVersionException();
    }
    String underscoreVersion =
        matcher.group(1) + (null == matcher.group(2) ? "_0" : "_" + matcher.group(2));

    String[] propertyValues;
    String[] propertyValueAliases;
    try {
      Class<?> clazz = Class.forName("jflex.unicode.data.Unicode_" + underscoreVersion);
      Field field = clazz.getField("propertyValues");
      propertyValues = (String[]) field.get(null);
      field = clazz.getField("propertyValueAliases");
      propertyValueAliases = (String[]) field.get(null);
    } catch (Exception e) {
      throw new UnicodeProperties.UnsupportedUnicodeVersionException();
    }
    SortedMap<String, SortedSet<String>> propertyValuesToAliases =
        new TreeMap<String, SortedSet<String>>();
    for (String value : propertyValues) {
      propertyValuesToAliases.put(value, new TreeSet<String>());
    }
    for (int i = 0; i < propertyValueAliases.length; i += 2) {
      String alias = propertyValueAliases[i];
      String value = propertyValueAliases[i + 1];
      SortedSet<String> aliases = propertyValuesToAliases.get(value);
      if (null == aliases) {
        aliases = new TreeSet<String>();
        propertyValuesToAliases.put(value, aliases);
      }
      aliases.add(alias);
    }
    for (Map.Entry<String, SortedSet<String>> entry : propertyValuesToAliases.entrySet()) {
      String value = entry.getKey();
      SortedSet<String> aliases = entry.getValue();
      Out.print(value);
      if (aliases.size() > 0) {
        for (String alias : aliases) {
          Out.print(", " + alias);
        }
      }
      Out.println("");
    }
  }
Example #2
0
    @CallerSensitive
    public <T> Prop<T> type() {

      Prop on = this;
      if (!isCannon()) {
        Prop<T> already = (Prop<T>) findCannon();
        if (already == null) {
          toCannon();
          on.setCannon();
        } else {
          on = already;
        }
      }

      Class c = sun.reflect.Reflection.getCallerClass(2);

      on.definedInClass = c;

      Field f = null;
      try {
        f = c.getField(name);
      } catch (NoSuchFieldException e) {

        try {
          f = c.getField("_" + name);
        } catch (NoSuchFieldException e3) {
          if (name.startsWith("_"))
            try {
              f = c.getField(name.substring(1));
            } catch (NoSuchFieldException e1) {
              if (name.startsWith("__"))
                try {
                  f = c.getField(name.substring(1));
                } catch (NoSuchFieldException e2) {
                }
            }
        }
      }
      if (f == null)
        throw new IllegalStateException(
            " cannot type a Dict.Prop<T> that we can't find. Name is :" + name + " class is :" + c);

      on.typeInformation = Conversions.linearize(f.getGenericType());

      on.typeInformation.remove(0);

      return (Prop<T>) on;
    }
Example #3
0
  public static void writeParam(String xNameFile) {
    //
    // write to file xpar all parameters.....
    //
    IOseq xFile;

    xFile = new IOseq(xNameFile);
    xFile.IOseqOpenW(false);

    try {

      Class c = Class.forName("jneat.Neat");
      Field[] fieldlist = c.getDeclaredFields();

      for (int i = 0; i < fieldlist.length; i++) {
        Field f1 = fieldlist[i];
        String x1 = f1.getName();

        if (x1.startsWith("p_")) {
          Field f2 = c.getField("d_" + Neat.normalizeName(x1));
          Object s1 = f1.get(c);
          Object s2 = f2.get(c);
          //	   String riga = s1 + "  " + s2;
          String riga = x1 + "  " + s1;
          xFile.IOseqWrite(riga);
        }
      }

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

    xFile.IOseqCloseW();
  }
Example #4
0
 /**
  * Returns a Field object that represents an attribute of a class
  *
  * @param type the class that holds the attribute
  * @param name the name of the attribute
  * @return a Field object that represents the attribute
  */
 public static Field getField(Class<?> type, String name) {
   try {
     return type.getField(name);
   } catch (NoSuchFieldException e) {
     throw ExceptionMapper.configurationException(e, type.getName() + '.' + name);
   }
 }
Example #5
0
 public static String getDescription(String xkey) {
   try {
     Class c = Class.forName("jneat.Neat");
     Field f = c.getField("d_" + xkey);
     return (String) f.get(c);
   } catch (Throwable e) {
     return null;
   }
 }
Example #6
0
 /**
  * Construct a JSONObject from an Object, using reflection to find the public members. The
  * resulting JSONObject's keys will be the strings from the names array, and the values will be
  * the field values associated with those keys in the object. If a key is not found or not
  * visible, then it will not be copied into the new JSONObject.
  *
  * @param object An object that has fields that should be used to make a JSONObject.
  * @param names An array of strings, the names of the fields to be obtained from the object.
  */
 public JSONObject(Object object, String names[]) {
   this();
   final Class c = object.getClass();
   for (final String name : names) {
     try {
       this.putOpt(name, c.getField(name).get(object));
     } catch (final Exception ignore) {
     }
   }
 }
Example #7
0
 // Use reflection to get version since early versions
 // of ImageJ do not have the IJ.getVersion() method.
 String version() {
   String version = "";
   try {
     Class ijClass = ImageJ.class;
     Field field = ijClass.getField("VERSION");
     version = (String) field.get(ijClass);
   } catch (Exception ex) {
   }
   return version;
 }
Example #8
0
  public static Object invoke_description(Class c) {
    try {
      Field f = c.getField("description_array");
      return f.get(null);
    } catch (NoSuchFieldException e) {
    } // eat the exception; apparently c is not a helper
    catch (Exception e) {
    } // HMM, SHOULD WE TRY HARDER TO FIGURE OUT WHAT'S GOING ON HERE ???

    return null;
  }
Example #9
0
 public static Object getFieldValue(Object target, String name, boolean strict) {
   Class<?> type = target.getClass();
   try {
     Field field = type.getField(name);
     return getFieldValue(field, target, strict);
   } catch (NoSuchFieldException e) {
     if (strict) throw ExceptionMapper.configurationException(e, type.getName() + '.' + name);
     else {
       escalator.escalate("Class '" + type + "' does not have a field '" + name + "'", type, name);
       return null;
     }
   }
 }
Example #10
0
 /**
  * Construct a JSONObject from an Object, using reflection to find the public members. The
  * resulting JSONObject's keys will be the strings from the names array, and the values will be
  * the field values associated with those keys in the object. If a key is not found or not
  * visible, then it will not be copied into the new JSONObject.
  *
  * @param object An object that has fields that should be used to make a JSONObject.
  * @param names An array of strings, the names of the fields to be obtained from the object.
  */
 public JSONObject(Object object, String names[]) {
   this();
   Class c = object.getClass();
   for (int i = 0; i < names.length; i += 1) {
     String name = names[i];
     try {
       Field field = c.getField(name);
       Object value = field.get(object);
       this.put(name, value);
     } catch (Exception e) {
       /* forget about it */
     }
   }
 }
Example #11
0
 public Y call(X value) {
   Class cls = value.getClass();
   try {
     Field f = cls.getField(fieldName);
     return (Y) f.get(value);
   } catch (SecurityException e) {
     e.printStackTrace();
     throw new IllegalStateException();
   } catch (NoSuchFieldException e) {
     e.printStackTrace();
     throw new IllegalStateException();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
     throw new IllegalStateException();
   }
 }
Example #12
0
  public static boolean registerEntity(String name, Class<? extends Entity> clazz, boolean force) {
    if (clazz == null) {
      return false;
    }
    try {
      int networkId = clazz.getField("NETWORK_ID").getInt(null);
      knownEntities.put(String.valueOf(networkId), clazz);
    } catch (Exception e) {
      if (!force) {
        return false;
      }
    }

    knownEntities.put(name, clazz);
    shortNames.put(clazz.getSimpleName(), name);
    return true;
  }
Example #13
0
 private void updateCursor(final String selection) {
   Cursor cursor = null;
   Class swtClass = SWT.class;
   if (selection != null) {
     try {
       Field field = swtClass.getField(selection);
       int cursorStyle = field.getInt(swtClass);
       cursor = Display.getCurrent().getSystemCursor(cursorStyle);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   Iterator iter = controls.iterator();
   while (iter.hasNext()) {
     Control control = (Control) iter.next();
     control.setCursor(cursor);
   }
 }
    public Option(
        @Nullable Class<? extends CustomCodeStyleSettings> clazz,
        @NotNull String fieldName,
        @NotNull String title,
        @Nullable String groupName,
        @Nullable OptionAnchor anchor,
        @Nullable String anchorFiledName) {
      super(fieldName, anchor, anchorFiledName);
      this.clazz = clazz;
      this.title = title;
      this.groupName = groupName;

      try {
        Class styleSettingsClass = clazz == null ? CommonCodeStyleSettings.class : clazz;
        this.field = styleSettingsClass.getField(fieldName);
      } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
      }
    }
Example #15
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));
    }
  }
Example #16
0
  // Needed by NativeJavaObject serializer
  public static void writeAdapterObject(Object javaObject, ObjectOutputStream out)
      throws IOException {
    Class<?> cl = javaObject.getClass();
    out.writeObject(cl.getSuperclass().getName());

    Class<?>[] interfaces = cl.getInterfaces();
    String[] interfaceNames = new String[interfaces.length];

    for (int i = 0; i < interfaces.length; i++) interfaceNames[i] = interfaces[i].getName();

    out.writeObject(interfaceNames);

    try {
      Object delegee = cl.getField("delegee").get(javaObject);
      out.writeObject(delegee);
      return;
    } catch (IllegalAccessException e) {
    } catch (NoSuchFieldException e) {
    }
    throw new IOException();
  }
Example #17
0
  public static void getParam(vectTableModel _model) {

    String xline;
    StringTokenizer st = null;
    String s1 = null;
    String s2 = null;
    Object m1 = null;
    Field fx = null;
    int j = 0;

    try {
      Class c = Class.forName("jneat.Neat");
      Field[] fieldlist = c.getDeclaredFields();

      int number_params = fieldlist.length / 2;

      j = 0;
      for (int i = 0; i < number_params; i++) {
        Field f1 = fieldlist[i];
        String nomeF = f1.getName();
        String nomeF1 = nomeF.substring(2);
        if (nomeF.substring(0, 2).equalsIgnoreCase("p_")) {
          Object o1 = nomeF1;
          fx = c.getField("p_" + nomeF1);
          Object o2 = fx.get(c);

          _model.setValueAt(o1, j, 0);
          _model.setValueAt(o2, j, 1);

          j++;
        }
      }

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

    _model.rows = j;
    return;
  }
 static {
   try {
     Class bootCls = Class.forName("bluej.Boot");
     Field field = bootCls.getField("GREENFOOT_API_VERSION");
     String versionStr = (String) field.get(null);
     VERSION = new Version(versionStr);
   } catch (ClassNotFoundException e) {
     VERSION = new Version("0");
     // It's fine - running in standalone.
   } catch (SecurityException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (NoSuchFieldException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IllegalArgumentException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Example #19
0
 static {
   // compute primitives/primitiveMap/primitiveToWrapper
   for (Class<?> c : primitiveWrappers) {
     try {
       Field f = c.getField("TYPE");
       Class<?> p = (Class<?>) f.get(null);
       primitives.add(p);
       primitiveMap.put(p.getName(), p);
       primitiveToWrapper.put(p.getName(), c);
     } catch (Exception e) {
       throw new AssertionError(e);
     }
   }
   // compute editableTypes
   for (Class<?> c : primitives) {
     editableTypes.add(c.getName());
   }
   for (Class<?> c : primitiveWrappers) {
     editableTypes.add(c.getName());
   }
   for (Class<?> c : extraEditableClasses) {
     editableTypes.add(c.getName());
   }
   // compute numericalTypes
   for (Class<?> c : primitives) {
     String name = c.getName();
     if (!name.equals(Boolean.TYPE.getName())) {
       numericalTypes.add(name);
     }
   }
   for (Class<?> c : primitiveWrappers) {
     String name = c.getName();
     if (!name.equals(Boolean.class.getName())) {
       numericalTypes.add(name);
     }
   }
 }
Example #20
0
  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);
      }
    }
  }
Example #21
0
  @SuppressWarnings("rawtypes")
  protected static final Map<String, Field> fillOptions(
      Class<?>[] classes, Map<String, String> options, boolean ensureAllOptions) {

    // --Get Fillable Options
    Map<String, Field> canFill = new HashMap<String, Field>();
    Map<String, Marker> required = new HashMap<String, Marker>();
    Map<String, String> interner = new HashMap<String, String>();
    for (Class c : classes) {
      Field[] fields = null;
      try {
        fields = c.getDeclaredFields();
      } catch (Throwable e) {
        log.debug(
            LOG_TAG,
            "Could not check fields for class: "
                + c.getName()
                + "  (caused by "
                + e.getClass()
                + ": "
                + e.getMessage()
                + ")");
        continue;
      }

      for (Field f : fields) {
        Option o = f.getAnnotation(Option.class);
        if (o != null) {
          // (check if field is static)
          if ((f.getModifiers() & Modifier.STATIC) == 0) {
            log.err(LOG_TAG, "Option can only be applied to static field: " + c + "." + f);
            System.exit(ExitCode.BAD_OPTION.code);
          }
          // (required marker)
          Marker mark = null;
          if (o.required()) {
            mark = new Marker();
            mark.unset();
          }
          // (add main name)
          String name = o.name().toLowerCase();
          if (name.equals("")) {
            name = f.getName().toLowerCase();
          }
          if (canFill.containsKey(name)) {
            String name1 =
                canFill.get(name).getDeclaringClass().getCanonicalName()
                    + "."
                    + canFill.get(name).getName();
            String name2 = f.getDeclaringClass().getCanonicalName() + "." + f.getName();
            if (!name1.equals(name2)) {
              log.err(
                  LOG_TAG,
                  "Multiple declarations of option " + name + ": " + name1 + " and " + name2);
              System.exit(ExitCode.BAD_OPTION.code);
            } else {
              log.err(
                  LOG_TAG,
                  "Class is in classpath multiple times: "
                      + canFill.get(name).getDeclaringClass().getCanonicalName());
            }
          }
          canFill.put(name, f);
          if (mark != null) required.put(name, mark);
          interner.put(name, name);
          // (add alternate names)
          if (!o.alt().equals("")) {
            for (String alt : o.alt().split(" *, *")) {
              alt = alt.toLowerCase();
              if (canFill.containsKey(alt) && !alt.equals(name))
                throw new IllegalArgumentException(
                    "Multiple declarations of option "
                        + alt
                        + ": "
                        + canFill.get(alt)
                        + " and "
                        + f);
              canFill.put(alt, f);
              if (mark != null) required.put(alt, mark);
              interner.put(alt, name);
            }
          }
        }
      }
    }

    // --Fill Options
    for (String key : options.keySet()) {
      String rawKey = key;
      key = key.toLowerCase();
      // (get values)
      String value = options.get(rawKey);
      Field target = canFill.get(key);
      // (mark required option as fulfilled)
      Marker mark = required.get(key);
      if (mark != null) {
        mark.set();
      }
      // (fill the field)
      if (target != null) {
        // (case: declared option)
        fillField(target, value);
      } else if (ensureAllOptions) {
        // (case: undeclared option)
        // split the key
        int lastDotIndex = rawKey.lastIndexOf('.');
        if (lastDotIndex < 0) {
          log.err(LOG_TAG, "Unrecognized option: " + key);
          System.exit(ExitCode.BAD_OPTION.code);
        }
        String className = rawKey.substring(0, lastDotIndex);
        String fieldName = rawKey.substring(lastDotIndex + 1);
        // get the class
        Class clazz = null;
        try {
          clazz = ClassLoader.getSystemClassLoader().loadClass(className);
        } catch (Exception e) {
          log.err(LOG_TAG, "Could not set option: " + rawKey + "; no such class: " + className);
          System.exit(ExitCode.BAD_OPTION.code);
        }
        // get the field
        try {
          target = clazz.getField(fieldName);
        } catch (Exception e) {
          log.err(
              LOG_TAG,
              "Could not set option: "
                  + rawKey
                  + "; no such field: "
                  + fieldName
                  + " in class: "
                  + className);
          System.exit(ExitCode.BAD_OPTION.code);
        }
        fillField(target, value);
      }
    }

    // --Ensure Required
    boolean good = true;
    for (String key : required.keySet()) {
      if (!required.get(key).isSet()) {
        log.err(
            LOG_TAG,
            "Missing required option: "
                + interner.get(key)
                + "   <in class: "
                + canFill.get(key).getDeclaringClass()
                + ">");
        required.get(key).set(); // don't duplicate error messages
        good = false;
      }
    }
    if (!good) {
      System.exit(ExitCode.BAD_OPTION.code);
    }

    return canFill;
  }
Example #22
0
  /**
   * Parse XML Attributes. Should only be called once and at the end of the base class constructor.
   * The first-pass attempts to locate styleable attributes and apply those first. After that,
   * configurator-style attributes are applied, overriding any styleable attrs that may have been
   * previously applied.
   *
   * @param attrs
   */
  private void loadAttrs(AttributeSet attrs, int defStyle) {

    if (attrs != null) {

      Field styleableFieldInR = null;
      TypedArray typedAttrs = null;

      final String appPkg = getContext().getPackageName();
      Class styleableClass = null;
      try {
        /**
         * Need to retrieve R$styleable.class dynamically to avoid exceptions in environments where
         * this class does not exist, such as .jar users that have not merged the library's
         * attrs.xml with their own.
         */
        styleableClass = Class.forName(appPkg + ".R$styleable");

      } catch (ClassNotFoundException e) {
        // when running as a preview in IntelliJ or AndroidStudio it seems that the package of R is
        // something else; this fixes that issue:
        if (isInEditMode()) {
          styleableClass = R.styleable.class;
        }
      }

      if (styleableClass != null) {
        String styleableName = getClass().getName().substring(BASE_PACKAGE.length());
        styleableName = styleableName.replace('.', '_');
        try {
          /**
           * Use reflection to safely check for the existence of styleable defs for Plot and it's
           * derivatives. This safety check is necessary to avoid runtime exceptions in apps that
           * don't include Androidplot as a .aar and won't have access to the resources defined in
           * the core library.
           */
          styleableFieldInR = styleableClass.getField(styleableName);
        } catch (NoSuchFieldException e) {
          Log.d(TAG, "Styleable definition not found for: " + styleableName);
        }
        if (styleableFieldInR != null) {
          try {
            int[] resIds = (int[]) styleableFieldInR.get(null);
            typedAttrs = getContext().obtainStyledAttributes(attrs, resIds, defStyle, 0);
          } catch (IllegalAccessException e) {
            // nothing to do
          } finally {
            if (typedAttrs != null) {
              // apply derived class' attrs:
              processAttrs(typedAttrs);
              typedAttrs.recycle();
            }
          }
        }

        try {
          styleableFieldInR = styleableClass.getField(Plot.class.getSimpleName());
          if (styleableFieldInR != null) {
            int[] resIds = (int[]) styleableFieldInR.get(null);
            typedAttrs = getContext().obtainStyledAttributes(attrs, resIds, defStyle, 0);
          }
        } catch (IllegalAccessException e) {
          // nothing to do
        } catch (NoSuchFieldException e) {
          Log.d(TAG, "Styleable definition not found for: " + Plot.class.getSimpleName());
        } finally {
          if (typedAttrs != null) {
            // apply base attrs:
            processBaseAttrs(typedAttrs);
            typedAttrs.recycle();
          }
        }
      }

      // apply "configurator" attrs: (overrides any previously applied styleable attrs)
      // filter out androidplot prefixed attrs:
      HashMap<String, String> attrHash = new HashMap<String, String>();
      for (int i = 0; i < attrs.getAttributeCount(); i++) {
        String attrName = attrs.getAttributeName(i);

        // case insensitive check to see if this attr begins with our prefix:
        if (attrName != null && attrName.toUpperCase().startsWith(XML_ATTR_PREFIX.toUpperCase())) {
          attrHash.put(
              attrName.substring(XML_ATTR_PREFIX.length() + 1), attrs.getAttributeValue(i));
        }
      }
      Configurator.configure(getContext(), this, attrHash);
    }
  }