public void test_immutable() throws Exception {
   Class<CopticChronology> cls = CopticChronology.class;
   assertTrue(Modifier.isPublic(cls.getModifiers()));
   assertTrue(Modifier.isFinal(cls.getModifiers()));
   Field[] fields = cls.getDeclaredFields();
   for (Field field : fields) {
     if (Modifier.isStatic(field.getModifiers()) == false) {
       assertTrue(Modifier.isPrivate(field.getModifiers()));
       assertTrue(Modifier.isFinal(field.getModifiers()));
     }
   }
 }
Example #2
1
 public void testImmutable() {
   Class<Fastq> cls = Fastq.class;
   assertTrue(Modifier.isPublic(cls.getModifiers()));
   assertTrue(Modifier.isFinal(cls.getModifiers()));
   Field[] fields = cls.getDeclaredFields();
   for (Field field : fields) {
     assertTrue(Modifier.isPrivate(field.getModifiers()));
     assertTrue(
         Modifier.isFinal(field.getModifiers())
             || (Modifier.isVolatile(field.getModifiers())
                 && Modifier.isTransient(field.getModifiers())));
   }
 }
  static void assertMeetsHashCodeContract(Class<?> classUnderTest) {
    try {
      Field[] fields = classUnderTest.getDeclaredFields();
      for (int i = 0; i < fields.length; i++) {
        Object o1 = classUnderTest.newInstance();
        int initialHashCode = o1.hashCode();

        Field field = fields[i];
        if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
          continue;
        }
        toggleField(field, o1, true);
        int updatedHashCode = o1.hashCode();
        assertFalse(
            "The field "
                + field.getName()
                + " was not taken into account for the hashCode contract ",
            initialHashCode == updatedHashCode);
      }
    } catch (InstantiationException e) {
      e.printStackTrace();
      throw new AssertionError("Unable to construct an instance of the class under test");
    } catch (IllegalAccessException e) {
      e.printStackTrace();
      throw new AssertionError("Unable to construct an instance of the class under test");
    }
  }
  /**
   * Applications which override this can do custom serialization.
   *
   * @param object the object to write.
   */
  public void writeObjectImpl(Object obj) throws IOException {
    Class cl = obj.getClass();

    try {
      Method method = cl.getMethod("writeReplace", new Class[0]);
      Object repl = method.invoke(obj, new Object[0]);

      writeObject(repl);
      return;
    } catch (Exception e) {
    }

    try {
      writeMapBegin(cl.getName());
      for (; cl != null; cl = cl.getSuperclass()) {
        Field[] fields = cl.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
          Field field = fields[i];

          if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers()))
            continue;

          // XXX: could parameterize the handler to only deal with public
          field.setAccessible(true);

          writeString(field.getName());
          writeObject(field.get(obj));
        }
      }
      writeMapEnd();
    } catch (IllegalAccessException e) {
      throw new IOExceptionWrapper(e);
    }
  }
Example #5
0
  /**
   * Appends the fields and values defined by the given object of the given Class.
   *
   * @param lhs the left hand object
   * @param rhs the right hand object
   * @param clazz the class to append details of
   * @param builder the builder to append to
   * @param useTransients whether to test transient fields
   * @param excludeFields array of field names to exclude from testing
   */
  private static void reflectionAppend(
      Object lhs,
      Object rhs,
      Class<?> clazz,
      EqualsBuilder builder,
      boolean useTransients,
      String[] excludeFields) {

    if (isRegistered(lhs, rhs)) {
      return;
    }

    try {
      register(lhs, rhs);
      Field[] fields = clazz.getDeclaredFields();
      AccessibleObject.setAccessible(fields, true);
      for (int i = 0; i < fields.length && builder.isEquals; i++) {
        Field f = fields[i];
        if (!Arrays.contains(excludeFields, f.getName())
            && (f.getName().indexOf('$') == -1)
            && (useTransients || !Modifier.isTransient(f.getModifiers()))
            && (!Modifier.isStatic(f.getModifiers()))) {
          try {
            builder.append(f.get(lhs), f.get(rhs));
          } catch (IllegalAccessException e) {
            // this can't happen. Would get a Security exception instead
            // throw a runtime exception in case the impossible happens.
            throw new InternalError("Unexpected IllegalAccessException");
          }
        }
      }
    } finally {
      unregister(lhs, rhs);
    }
  }
  static void assertToString(Class<?> classUnderTest) {
    Object o;
    try {
      o = classUnderTest.newInstance();
      String str = o.toString();

      assertNotNull(str);
      assertTrue(
          "The toString() method for class "
              + classUnderTest.getName()
              + " did not begin with the class name",
          str.startsWith(classUnderTest.getSimpleName()));

      Field[] fields = classUnderTest.getDeclaredFields();
      for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
          continue;
        }

        assertTrue(
            "The field " + field.getName() + " did not appear in toString()",
            str.contains(field.getName()));
      }

    } catch (InstantiationException e) {
      e.printStackTrace();
      throw new AssertionError(
          "Unable to construct an instance of the class under test:" + classUnderTest.getName());
    } catch (IllegalAccessException e) {
      e.printStackTrace();
      throw new AssertionError(
          "Unable to construct an instance of the class under test:" + classUnderTest.getName());
    }
  }
 public FieldDefinition(Field field) {
   this.name = field.getName();
   this.type = field.getType().getName();
   this.isStatic = Modifier.isStatic(field.getModifiers());
   this.isPublic =
       !Modifier.isPrivate(field.getModifiers()) && !Modifier.isProtected(field.getModifiers());
 }
Example #8
0
 public void makeValid() {
   if (getIssuetype() != null) {
     Class<?> klass = getClass();
     while (klass != HashMap.class) {
       for (Field field : klass.getDeclaredFields()) {
         if (!getIssuetype().getFields().containsKey(field.getName())) {
           if (Modifier.isFinal(field.getModifiers())
               || Modifier.isStatic(field.getModifiers())
               || Modifier.isTransient(field.getModifiers())) {
             continue;
           }
           field.setAccessible(true);
           try {
             field.set(this, null);
           } catch (IllegalArgumentException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
           } catch (IllegalAccessException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
           }
         }
       }
       klass = klass.getSuperclass();
     }
     for (Map.Entry<String, Object> e : new HashMap<String, Object>(this).entrySet()) {
       if (!getIssuetype().getFields().containsKey(e.getKey())) {
         this.remove(e.getKey());
       }
     }
   }
 }
  /** {@inheritDoc} */
  @Override
  public String createFullLevelDefinition(Class objectClass) {
    Map<String, String> map = getLevelMapForClass(objectClass);
    if (map == null) {
      map = new HashMap<String, String>();
      getLevelMap().put(objectClass, map);
    }

    String levelDefinition = "";
    while (objectClass != null && objectClass != Object.class) {
      final Field[] fieldList = objectClass.getDeclaredFields();
      for (final Field field : fieldList) {
        if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) {
          levelDefinition = levelDefinition + field.getName() + ",";
        }
      }
      objectClass = objectClass.getSuperclass();
    }

    if (!levelDefinition.isEmpty()) {
      levelDefinition = levelDefinition.substring(0, levelDefinition.length() - 1);
    }
    map.put(FULL_LEVEL, levelDefinition);
    return levelDefinition;
  }
Example #10
0
 private static void reflectionAppend(
     Object obj,
     Object obj1,
     Class class1,
     CompareToBuilder comparetobuilder,
     boolean flag,
     String as[]) {
   Field afield[] = class1.getDeclaredFields();
   AccessibleObject.setAccessible(afield, true);
   int i = 0;
   do {
     if (i >= afield.length || comparetobuilder.comparison != 0) {
       return;
     }
     Field field = afield[i];
     if (!ArrayUtils.contains(as, field.getName())
         && field.getName().indexOf('$') == -1
         && (flag || !Modifier.isTransient(field.getModifiers()))
         && !Modifier.isStatic(field.getModifiers())) {
       try {
         comparetobuilder.append(field.get(obj), field.get(obj1));
       } catch (IllegalAccessException illegalaccessexception) {
         throw new InternalError("Unexpected IllegalAccessException");
       }
     }
     i++;
   } while (true);
 }
  private static HashMap<String, Object> inspectObject(Object o) throws IntrospectionException {
    if (inspections.containsKey(o.getClass())) {
      return inspections.get(o.getClass());
    }

    PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors();
    HashMap<String, Object> values = new HashMap<String, Object>();

    for (PropertyDescriptor pd : pds) {
      if (pd.getName().equals("class")
          || (pd.getReadMethod() == null)
          || (pd.getWriteMethod() == null)
          || ((pd.getReadMethod().getModifiers() & Modifier.PUBLIC) == 0)
          || ((pd.getWriteMethod().getModifiers() & Modifier.PUBLIC) == 0)) {
        continue;
      }

      values.put(pd.getName(), pd);
    }

    for (Field field : o.getClass().getFields()) {
      if (((field.getModifiers() & Modifier.PUBLIC) != 0)
          && ((field.getModifiers() & Modifier.FINAL) == 0)
          && ((field.getModifiers() & Modifier.STATIC) == 0)
          && (values.get(field.getName()) == null)) {
        values.put(field.getName(), field);
      }
    }

    inspections.put(o.getClass(), values);

    return values;
  }
 public SysField(java.lang.reflect.Field field) {
   this(
       Modifier.isStatic(field.getModifiers()),
       field.getType().getName(),
       field.getName(),
       SysAnalysis.getVisibility(field.getModifiers()));
 }
Example #13
0
  public void setAtributos(Entidade entidade) {
    try {
      Class classe = this.getClass();

      for (Field atributo : classe.getDeclaredFields()) {
        atributo.setAccessible(true);
        if (!Modifier.isFinal(atributo.getModifiers())
            && !Modifier.isStatic(atributo.getModifiers())) {
          Object valor = atributo.get(entidade);
          if (valor != null && !(valor instanceof Collection)) {
            StringBuilder nomeMetodo = new StringBuilder("set");
            nomeMetodo.append(atributo.getName().substring(0, 1).toUpperCase());
            nomeMetodo.append(atributo.getName().substring(1));

            Method metodo = classe.getDeclaredMethod(nomeMetodo.toString(), atributo.getType());
            metodo.setAccessible(true);
            metodo.invoke(this, valor);
          }
        }
      }
    } catch (SecurityException
        | IllegalArgumentException
        | IllegalAccessException
        | NoSuchMethodException
        | InvocationTargetException ex) {
      throw new ExcecaoSistema(ex);
    }
  }
Example #14
0
  private Object createChatPacket(String json)
      throws IllegalArgumentException, IllegalAccessException, InstantiationException,
          InvocationTargetException {
    if (nmsChatSerializerGsonInstance == null) {
      // Find the field and its value, completely bypassing obfuscation
      for (Field declaredField : Reflection.getNMSClass("ChatSerializer").getDeclaredFields()) {
        if (Modifier.isFinal(declaredField.getModifiers())
            && Modifier.isStatic(declaredField.getModifiers())
            && declaredField.getType() == com.google.gson.Gson.class) {
          // We've found our field
          declaredField.setAccessible(true);
          nmsChatSerializerGsonInstance = (com.google.gson.Gson) declaredField.get(null);
          break;
        }
      }
    }

    // Since the method is so simple, and all the obfuscated methods have the same name, it's easier
    // to reimplement 'IChatBaseComponent a(String)' than to reflectively call it
    // Of course, the implementation may change, but fuzzy matches might break with signature
    // changes
    Object serializedChatComponent =
        nmsChatSerializerGsonInstance.fromJson(json, Reflection.getNMSClass("IChatBaseComponent"));

    return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent);
  }
 public List<Model.Property> listProperties() {
   List<Model.Property> properties = new ArrayList<Model.Property>();
   Set<Field> fields = new HashSet<Field>();
   Class<?> tclazz = clazz;
   while (!tclazz.equals(Object.class)) {
     Collections.addAll(fields, tclazz.getDeclaredFields());
     tclazz = tclazz.getSuperclass();
   }
   for (Field f : fields) {
     if (Modifier.isTransient(f.getModifiers())) {
       continue;
     }
     if (Modifier.isStatic(f.getModifiers())) {
       continue;
     }
     if (f.isAnnotationPresent(Transient.class) && !f.getType().equals(Blob.class)) {
       continue;
     }
     Model.Property mp = buildProperty(f);
     if (mp != null) {
       properties.add(mp);
     }
   }
   return properties;
 }
Example #16
0
    @SuppressWarnings("rawtypes")
    @Override
    public final E map(R record) {
      try {
        E result = instance != null ? instance : constructor.newInstance();

        for (int i = 0; i < fields.length; i++) {
          for (java.lang.reflect.Field member : members[i]) {

            // [#935] Avoid setting final fields
            if ((member.getModifiers() & Modifier.FINAL) == 0) {
              map(record, result, member, i);
            }
          }

          for (java.lang.reflect.Method method : methods[i]) {
            Class<?> mType = method.getParameterTypes()[0];
            Object value = record.getValue(i, mType);

            // [#3082] Map nested collection types
            if (value instanceof Collection && List.class.isAssignableFrom(mType)) {
              Class componentType =
                  (Class)
                      ((ParameterizedType) method.getGenericParameterTypes()[0])
                          .getActualTypeArguments()[0];
              method.invoke(result, Convert.convert((Collection) value, componentType));
            }

            // Default reference types (including arrays)
            else {
              method.invoke(result, record.getValue(i, mType));
            }
          }
        }

        for (Entry<String, List<RecordMapper<R, Object>>> entry : nested.entrySet()) {
          String prefix = entry.getKey();

          for (RecordMapper<R, Object> mapper : entry.getValue()) {
            Object value = mapper.map(record);

            for (java.lang.reflect.Field member : getMatchingMembers(configuration, type, prefix)) {

              // [#935] Avoid setting final fields
              if ((member.getModifiers() & Modifier.FINAL) == 0) {
                map(value, result, member);
              }
            }

            for (Method method : getMatchingSetters(configuration, type, prefix)) {
              method.invoke(result, value);
            }
          }
        }

        return result;
      } catch (Exception e) {
        throw new MappingException("An error ocurred when mapping record to " + type, e);
      }
    }
Example #17
0
  public static void main(String[] args) throws Exception {
    int port = 7070;
    if (args.length >= 1) {
      port = Integer.parseInt(args[0]);
    }

    // test_case_data/sandbox/ contains HDP 2.2 site xmls which is dev sandbox
    ClasspathUtil.addClasspath(new File("../examples/test_case_data/sandbox").getAbsolutePath());
    System.setProperty(KylinConfig.KYLIN_CONF, "../examples/test_case_data/sandbox");
    System.setProperty("hdp.version", "2.2.0.0-2041"); // mapred-site.xml ref this

    // workaround for job submission from win to linux --
    // https://issues.apache.org/jira/browse/MAPREDUCE-4052
    if (Shell.WINDOWS) {
      {
        Field field = Shell.class.getDeclaredField("WINDOWS");
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, false);
      }
      {
        Field field = java.io.File.class.getDeclaredField("pathSeparator");
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, ":");
      }
    }

    System.setProperty("spring.profiles.active", "testing");
    String webBase = new File("../webapp/app").getAbsolutePath();
    if (new File(webBase, "WEB-INF").exists() == false) {
      throw new RuntimeException(
          "In order to launch Kylin web app from IDE, please make a symblink from webapp/app/WEB-INF to server/src/main/webapp/WEB-INF");
    }

    Tomcat tomcat = new Tomcat();
    tomcat.setPort(port);
    tomcat.setBaseDir(".");

    // Add AprLifecycleListener
    StandardServer server = (StandardServer) tomcat.getServer();
    AprLifecycleListener listener = new AprLifecycleListener();
    server.addLifecycleListener(listener);

    Context webContext = tomcat.addWebapp("/kylin", webBase);
    ErrorPage notFound = new ErrorPage();
    notFound.setErrorCode(404);
    notFound.setLocation("/index.html");
    webContext.addErrorPage(notFound);
    webContext.addWelcomeFile("index.html");

    // tomcat start
    tomcat.start();
    tomcat.getServer().await();
  }
 @Override
 public Veto getVeto(Field _field) {
   if (Modifier.isFinal(_field.getModifiers()) || Modifier.isStatic(_field.getModifiers())) {
     log.info("Not creating data for field [" + _field.getName() + "] because it is final/static");
     return Veto.DENY_ALL_HANDLERS;
   }
   return Veto.NO_VETO;
 }
Example #19
0
 /** 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。 */
 public static void makeAccessible(Field field) {
   if ((!Modifier.isPublic(field.getModifiers())
           || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
           || Modifier.isFinal(field.getModifiers()))
       && !field.isAccessible()) {
     field.setAccessible(true);
   }
 }
Example #20
0
 /**
  * Retrieve the names of all the public static fields in the clazz
  *
  * @param clazz the object to inspect
  * @return list of all the names of public statics
  */
 public String[] getPublicStaticFieldNames(Class<?> clazz) {
   Field[] fields = clazz.getFields();
   Set<String> fieldNames = new HashSet<String>();
   for (Field field : fields) {
     if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) {
       fieldNames.add(field.getName());
     }
   }
   return (String[]) fieldNames.toArray(new String[fieldNames.size()]);
 }
Example #21
0
  private static void insertGetString(
      ClassWriter cw, String classNameInternal, ArrayList<Field> fields) {
    int maxStack = 6;
    MethodVisitor mv =
        cw.visitMethod(
            ACC_PUBLIC, "getString", "(Ljava/lang/Object;I)Ljava/lang/String;", null, null);
    mv.visitCode();
    mv.visitVarInsn(ILOAD, 2);

    if (!fields.isEmpty()) {
      maxStack--;
      Label[] labels = new Label[fields.size()];
      Label labelForInvalidTypes = new Label();
      boolean hasAnyBadTypeLabel = false;
      for (int i = 0, n = labels.length; i < n; i++) {
        if (fields.get(i).getType().equals(String.class)) labels[i] = new Label();
        else {
          labels[i] = labelForInvalidTypes;
          hasAnyBadTypeLabel = true;
        }
      }
      Label defaultLabel = new Label();
      mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels);

      for (int i = 0, n = labels.length; i < n; i++) {
        if (!labels[i].equals(labelForInvalidTypes)) {
          Field field = fields.get(i);
          mv.visitLabel(labels[i]);
          mv.visitFrame(F_SAME, 0, null, 0, null);
          if (!Modifier.isStatic(field.getModifiers())) {
            mv.visitVarInsn(ALOAD, 1);
            mv.visitTypeInsn(CHECKCAST, classNameInternal);
          }
          mv.visitFieldInsn(
              Modifier.isStatic(field.getModifiers()) ? GETSTATIC : GETFIELD,
              classNameInternal,
              field.getName(),
              "Ljava/lang/String;");
          mv.visitInsn(ARETURN);
        }
      }
      // Rest of fields: different type
      if (hasAnyBadTypeLabel) {
        mv.visitLabel(labelForInvalidTypes);
        mv.visitFrame(F_SAME, 0, null, 0, null);
        insertThrowExceptionForFieldType(mv, "String");
      }
      // Default: field not found
      mv.visitLabel(defaultLabel);
      mv.visitFrame(F_SAME, 0, null, 0, null);
    }
    insertThrowExceptionForFieldNotFound(mv);
    mv.visitMaxs(maxStack, 3);
    mv.visitEnd();
  }
 /** Gets all declared fields and all inherited fields. */
 protected Set<Field> getFields(Class<?> c) {
   Set<Field> fields = new HashSet<Field>(Arrays.asList(c.getDeclaredFields()));
   while ((c = c.getSuperclass()) != null) {
     for (Field f : c.getDeclaredFields()) {
       if (!Modifier.isStatic(f.getModifiers()) && !Modifier.isPrivate(f.getModifiers())) {
         fields.add(f);
       }
     }
   }
   return fields;
 }
Example #23
0
 @Test
 public void checkThatSingletonContainsStaticPrivateInstanceField() {
   Field field = findSingletonStaticPrivateInstanceField();
   assertNotNull("No static private instance field found.", field);
   assertTrue(
       "Field pointing to the Earth instance should be static",
       Modifier.isStatic(field.getModifiers()));
   assertTrue(
       "Field pointing to the Earth instance should be private",
       Modifier.isPrivate(field.getModifiers()));
 }
Example #24
0
 /**
  * Copy fields belonging to 'cFrom' from 'from' to 'to'. Will only iterate on non-private field.
  * Private fields in 'cFrom' won't be set in 'to'.
  *
  * @param <T> check type given as argument is equals or under this type.
  * @param klass the klass in which to find the fields
  * @param from the T object in which to get the value
  * @param to the T object in which to set the value
  */
 private static <T> void autoCopyfields(Class<T> klass, T from, T to)
     throws IllegalArgumentException, IllegalAccessException {
   for (Field f : klass.getDeclaredFields()) {
     if (!Modifier.isPrivate(f.getModifiers()) && !Modifier.isStatic(f.getModifiers())) {
       f.setAccessible(true);
       Object newValue = f.get(from);
       if (newValue != null || f.get(to) == null) {
         f.set(to, newValue);
       }
     }
   }
 }
Example #25
0
  /** Creates a map of the classes fields. */
  protected HashMap getFieldMap(Class cl) {
    HashMap fieldMap = new HashMap();

    for (; cl != null; cl = cl.getSuperclass()) {
      Field[] fields = cl.getDeclaredFields();
      for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];

        if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers()))
          continue;
        else if (fieldMap.get(field.getName()) != null) continue;

        // XXX: could parameterize the handler to only deal with public
        try {
          field.setAccessible(true);
        } catch (Throwable e) {
          e.printStackTrace();
        }

        Class type = field.getType();
        FieldDeserializer deser;

        if (String.class.equals(type)) deser = new StringFieldDeserializer(field);
        else if (byte.class.equals(type)) {
          deser = new ByteFieldDeserializer(field);
        } else if (short.class.equals(type)) {
          deser = new ShortFieldDeserializer(field);
        } else if (int.class.equals(type)) {
          deser = new IntFieldDeserializer(field);
        } else if (long.class.equals(type)) {
          deser = new LongFieldDeserializer(field);
        } else if (float.class.equals(type)) {
          deser = new FloatFieldDeserializer(field);
        } else if (double.class.equals(type)) {
          deser = new DoubleFieldDeserializer(field);
        } else if (boolean.class.equals(type)) {
          deser = new BooleanFieldDeserializer(field);
        } else if (java.sql.Date.class.equals(type)) {
          deser = new SqlDateFieldDeserializer(field);
        } else if (java.sql.Timestamp.class.equals(type)) {
          deser = new SqlTimestampFieldDeserializer(field);
        } else if (java.sql.Time.class.equals(type)) {
          deser = new SqlTimeFieldDeserializer(field);
        } else {
          deser = new ObjectFieldDeserializer(field);
        }

        fieldMap.put(field.getName(), deser);
      }
    }

    return fieldMap;
  }
Example #26
0
  // Look through all mappings to find a match entry for this field
  private static void installField(
      ThreadContext context,
      Map<String, String> fieldMap,
      Field field,
      RubyModule module,
      boolean asReader,
      boolean asWriter) {
    boolean isFinal = Modifier.isFinal(field.getModifiers());

    for (Iterator<Map.Entry<String, String>> iter = fieldMap.entrySet().iterator();
        iter.hasNext(); ) {
      Map.Entry<String, String> entry = iter.next();
      String key = entry.getKey();
      if (key.equals(field.getName())) {
        if (Ruby.isSecurityRestricted() && !Modifier.isPublic(field.getModifiers())) {
          throw context
              .getRuntime()
              .newSecurityError(
                  "Cannot change accessibility on fields in a restricted mode: field '"
                      + field.getName()
                      + "'");
        }

        String asName = entry.getValue();

        if (Modifier.isStatic(field.getModifiers())) {
          if (asReader)
            module.getSingletonClass().addMethod(asName, new StaticFieldGetter(key, module, field));
          if (asWriter) {
            if (isFinal)
              throw context
                  .getRuntime()
                  .newSecurityError("Cannot change final field '" + field.getName() + "'");
            module
                .getSingletonClass()
                .addMethod(asName + "=", new StaticFieldSetter(key, module, field));
          }
        } else {
          if (asReader) module.addMethod(asName, new InstanceFieldGetter(key, module, field));
          if (asWriter) {
            if (isFinal)
              throw context
                  .getRuntime()
                  .newSecurityError("Cannot change final field '" + field.getName() + "'");
            module.addMethod(asName + "=", new InstanceFieldSetter(key, module, field));
          }
        }

        iter.remove();
        break;
      }
    }
  }
 protected final void init()
     throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException {
   Class declaringClass = Class.forName(this.className);
   Field[] fields = declaringClass.getFields();
   for (Field field : fields) {
     if (Modifier.isPublic(field.getModifiers())
         && Modifier.isStatic(field.getModifiers())
         && Modifier.isFinal(field.getModifiers())) {
       put(field.getName(), field.get(null));
     }
   }
 }
Example #28
0
  /**
   * Parse the string and convert it to a {@link java.awt.Color}. See class description for details
   * on the supported color formats.
   *
   * @param colorString the color string encoded.
   */
  public static Color toColor(final String colorString) {
    String trimmedString = colorString.trim();
    Color color = null;
    if (trimmedString.startsWith("#")) {
      final int shortHexCode = 4;
      if (trimmedString.length() == shortHexCode) {
        StringBuilder builder = new StringBuilder("#");
        for (int i = 1; i < trimmedString.length(); i++) {
          builder.append(trimmedString.charAt(i));
          builder.append(trimmedString.charAt(i));
        }
        color = SLD.toColor(builder.toString());
      } else {
        color = SLD.toColor(trimmedString);
      }
    }

    if (color == null) {
      color = parseRgbColor(trimmedString);
    }

    if (color == null) {
      color = parseRgbaColor(trimmedString);
    }

    if (color == null) {
      color = parseHslColor(trimmedString);
    }

    if (color == null) {
      color = parseHslaColor(trimmedString);
    }

    if (color == null) {
      final Field[] fields = Color.class.getFields();
      for (Field field : fields) {
        if (field.getType() == Color.class
            && Modifier.isFinal(field.getModifiers())
            && Modifier.isStatic(field.getModifiers())
            && field.getName().equalsIgnoreCase(trimmedString)) {
          try {
            return (Color) field.get(null);
          } catch (IllegalAccessException e) {
            throw new Error(e);
          }
        }
      }
      color = Color.decode(trimmedString);
    }

    return color;
  }
Example #29
0
 static {
   values = new HashMap<>();
   Field[] fields = EnumPutFunction.class.getDeclaredFields();
   for (Field f : fields) {
     if (Modifier.isStatic(f.getModifiers()) && Modifier.isFinal(f.getModifiers())) {
       try {
         values.put(f.getName(), f.getInt(EnumPutFunction.class));
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
   }
 }
 private void injectSessionFactory(
     Object test, Iterable<Field> fields, SessionFactory sessionFactory) {
   for (Field field : fields) {
     try {
       if ((test == null && Modifier.isStatic(field.getModifiers()))
           || (test != null && !Modifier.isStatic(field.getModifiers()))) {
         field.set(test, sessionFactory);
       }
     } catch (Exception e) {
       throw new RuntimeException("Can't inject session factory into field " + field);
     }
   }
 }