Example #1
0
  /**
   * Convert {@code Object} value to a value of the specified class type.
   *
   * @param value {@code Object} value to convert.
   * @param type conversion type.
   * @param <T> converted value type.
   * @return value converted to the specified class type.
   */
  public static <T> T convertValue(Object value, Class<T> type) {
    if (!type.isInstance(value)) {
      // TODO: Move string value readers from server to common and utilize them here
      final Constructor constructor =
          AccessController.doPrivileged(ReflectionHelper.getStringConstructorPA(type));
      if (constructor != null) {
        try {
          return type.cast(constructor.newInstance(value));
        } catch (Exception e) {
          // calling the constructor wasn't successful - ignore and try valueOf()
        }
      }

      final Method valueOf =
          AccessController.doPrivileged(ReflectionHelper.getValueOfStringMethodPA(type));
      if (valueOf != null) {
        try {
          return type.cast(valueOf.invoke(null, value));
        } catch (Exception e) {
          // calling valueOf wasn't successful
        }
      }

      // at this point we don't know what to return -> return null
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.warning(
            LocalizationMessages.PROPERTIES_HELPER_GET_VALUE_NO_TRANSFORM(
                String.valueOf(value), value.getClass().getName(), type.getName()));
      }

      return null;
    }

    return type.cast(value);
  }
 @Override
 public void enrich(final SearchContext searchContext, Object target) {
   Collection<Field> fields =
       ReflectionHelper.getFieldsWithAnnotation(target.getClass(), JavaScript.class);
   for (Field field : fields) {
     GrapheneContext grapheneContext =
         searchContext == null
             ? null
             : ((GrapheneProxyInstance) searchContext).getGrapheneContext();
     if (grapheneContext == null) {
       grapheneContext =
           GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations()));
     }
     if (!field.isAccessible()) {
       field.setAccessible(true);
     }
     try {
       field.set(target, JSInterfaceFactory.create(grapheneContext, field.getType()));
     } catch (Exception e) {
       throw new IllegalStateException(
           "Can't inject value to the field '"
               + field.getName()
               + "' declared in class '"
               + field.getDeclaringClass().getName()
               + "'",
           e);
     }
   }
 }
 private static Activity verifyActivity(Context context, SharedXWalkExceptionHandler handler) {
   assert context instanceof Activity;
   assert context.getApplicationContext() instanceof XWalkApplication;
   ReflectionHelper.allowCrossPackage();
   ReflectionHelper.setExceptionHandler(handler);
   return (Activity) context;
 }
Example #4
0
 public static void setRenderDistance(World world, int distance) {
   try {
     ReflectionHelper.field("e")
         .in(ReflectionHelper.field("manager").in(((CraftWorld) world).getHandle()).get())
         .set(distance);
   } catch (Exception ignored) {
     ignored.printStackTrace();
   }
 }
Example #5
0
 /**
  * Controls minecraft's thunderstorm flag in world data.
  *
  * @param world Bukkit world object
  * @param flag whether to set it to thundering or not
  */
 public static void setThunderNoEvent(World world, boolean flag) {
   try {
     WorldData data = ((CraftWorld) world).getHandle().worldData;
     ReflectionHelper.field("isThundering").in(data).set(flag);
     ReflectionHelper.field("thunderTicks").in(data).set(flag ? Integer.MAX_VALUE : 0);
   } catch (Exception ex) {
     world.setStorm(true); // Can still set the storm
   }
 }
  /** See JERSEY-1598. */
  @Test
  public void getParameterizedClassArgumentsTest() {

    ReflectionHelper.DeclaringClassInterfacePair dcip =
        ReflectionHelper.getClass(TestNoInterface.class, I.class);
    Class[] arguments = ReflectionHelper.getParameterizedClassArguments(dcip);
    Class aClass = arguments[0];

    dcip = ReflectionHelper.getClass(TestInterface.class, I.class);
    arguments = ReflectionHelper.getParameterizedClassArguments(dcip);
    assertEquals(aClass, arguments[0]);
  }
 @Test
 public void annotationTest_ReadAnnotation() throws Exception {
   System.out.println(
       "public static <T extends Annotation> T  getMethodAnnotation(Class<?> clz, String methodName, Class<T> annotationClazz)");
   XmlElement xmlElementAnnotation =
       ReflectionHelper.getMethodAnnotation(SimplePojo.class, "getValueB", XmlElement.class);
   assertNotNull(xmlElementAnnotation);
   System.out.println(" xmlElementAnnotation: " + xmlElementAnnotation);
   Test testAnnotation =
       ReflectionHelper.getMethodAnnotation(
           ReflectionHelperTest.class, "annotationTest_ReadAnnotation", Test.class);
   assertNotNull(testAnnotation);
   System.out.println(" testAnnotation: " + testAnnotation);
 }
  /**
   * Test of 'public static <T> T newObject(String className, Class<?>[] paramTypes, Object...
   * parameters)' method, of class ReflectionHelper.
   */
  @Test
  public void shouldCreateNewObjects() {
    System.out.println(
        "public static <T> T newClass(String className, Class<?>[] paramTypes, Object... parameters)");
    String clazzName = "java.math.BigDecimal";
    Class<?>[] parameterTypes = new Class<?>[] {int.class};
    int expResult = 30;
    Object result = ReflectionHelper.newObject(clazzName, parameterTypes, 30);
    assertEquals(expResult, ((BigDecimal) result).intValue());
    System.out.println(" result = " + result);

    System.out.println("public static <T> T newClass(String className)");
    Object result2 = ReflectionHelper.newObject("java.util.Date");
    assertNotNull(result2);
    System.out.println(" result = " + result2);
  }
Example #9
0
  public static void reflectXmlRootNode(Object model, Node node)
      throws IllegalArgumentException, IllegalAccessException, InstantiationException {

    // Check if the root node is an array
    Class<?> modelClass = model.getClass();
    Field rootNodeField = null;

    try {
      rootNodeField = ReflectionHelper.getFieldInHierarchy(modelClass, node.name);

    } catch (NoSuchFieldException e) {
    }

    // The developer has declared a field to match the root node
    if (rootNodeField != null) {

      if (rootNodeField.getType() == List.class) {
        processListField(model, rootNodeField, node, null);
      } else {
        reflectXmlObject(model, node);
      }

    } else {
      // The developer has mapped the root node to the object itself
      reflectXmlObject(model, node);
    }
  }
Example #10
0
  private static void accessFieldAndProcess(
      Object model, Class<?> modelClass, Node node, Node parentNode) {

    try {
      Field field = ReflectionHelper.getFieldInHierarchy(modelClass, node.name);

      if (field.getType() == List.class) {
        processListField(model, field, node, parentNode);

      } else {
        processSingleField(model, field, node);
      }

    } catch (NoSuchFieldException e) {
      Log.w(XmlReflector.class.getName(), "Can not locate field named " + node.name);

    } catch (IllegalAccessException e) {
      Log.w(XmlReflector.class.getName(), "Can not access field named " + node.name);

    } catch (InstantiationException e) {
      Log.w(
          XmlReflector.class.getName(),
          "Can not create an instance of the type defined in the field named " + node.name);
    }
  }
Example #11
0
  public static void reflectJsonObject(Object model, JSONObject jsonObj) throws JSONException {
    Class<?> modelClass = model.getClass();
    JSONArray names = jsonObj.names();

    if (names != null) {
      for (int i = 0; i < names.length(); i++) {

        String name = names.getString(i);

        try {
          Field field = ReflectionHelper.getFieldInHierarchy(modelClass, name);

          if (field.getType() == List.class) {
            processListField(model, field, jsonObj.getJSONArray(name));

          } else {
            processSingleField(model, field, jsonObj, name);
          }

        } catch (NoSuchFieldException e) {
          Log.w(JsonReflector.class.getName(), "Can not locate field named " + name);

        } catch (IllegalAccessException e) {
          Log.w(JsonReflector.class.getName(), "Can not access field named " + name);

        } catch (InstantiationException e) {
          Log.w(
              JsonReflector.class.getName(),
              "Can not create an instance of the type defined in the field named " + name);
        }
      }
    }
  }
  @Test
  public void testFindFieldTransitive() throws Exception {
    List<SyntheticField> fields = new ArrayList<SyntheticField>();
    SyntheticField f1 = new SimpleSyntheticField(PersonDomain.class.getDeclaredField("name"));
    SyntheticField f2 = new SimpleSyntheticField(PersonDomain.class.getDeclaredField("address"));
    fields.add(f1);
    fields.add(f2);
    SyntheticField f3 = new SimpleSyntheticField(AddressDomain.class.getDeclaredField("id"));
    when(reflectionHelper.getSyntheticFields(any(Class.class)))
        .thenReturn(Collections.singletonList(f3));

    SyntheticField[] res;
    res =
        converterHelper.findField(
            fields, "id", new String[] {"address"}, PersonDomain.class, false);
    assertThat(res).hasSize(2);
    assertThat(res[0]).isEqualTo(f2);
    assertThat(res[1]).isEqualTo(f3);

    exception.expect(JTransfoException.class);
    exception.expectMessage(
        "Cannot find getter from [getBla, isBla, hasBla] on "
            + "class org.jtransfo.object.PersonDomain.");

    converterHelper.findField(fields, "id", new String[] {"bla"}, PersonDomain.class, false);
  }
 @Override
 public void startElement(String uri, String localName, String qName, Attributes attributes)
     throws SAXException {
   if (qName.equals(CLASS_ELEMENT))
     instance = ReflectionHelper.createInstance(attributes.getValue(0));
   element = qName;
 }
 @Test(expected = IllegalArgumentException.class)
 public void shouldThrowExceptionWhenCalledWithNullParameter_newObject_P3() {
   Object newObject =
       ReflectionHelper.newObject(
           "java.lang.Integer", new Class<?>[] {int.class}, (Object[]) null);
   fail("Integer " + newObject + " created!");
 }
  private void checkExisting(
      File targetFile, ClassLoader classLoader, Document doc, Set<String> entityClasses) {
    if (targetFile.exists()) {
      final Set<String> alreadyDefined = PersistenceXmlHelper.getClassesAlreadyDefined(doc);
      for (String className : alreadyDefined) {
        if (!ReflectionHelper.classExists(className, classLoader)) {
          getLog().warn("Class " + className + " defined in " + targetFile + " does not exist");
        }
      }

      if (!alreadyDefined.containsAll(entityClasses)) {
        final Set<String> undefined = new TreeSet<>();
        for (String className : entityClasses) {
          if (!alreadyDefined.contains(className)) {
            undefined.add(className);
          }
        }

        getLog()
            .warn(
                "The following classes was not defined in "
                    + targetFile
                    + " even "
                    + "though they are available on the class path: "
                    + Arrays.toString(undefined.toArray()));
      }

      // Don't add so we end up with duplicates
      entityClasses.removeAll(alreadyDefined);
    }
  }
 @Test
 public void shouldCreateANewExceptionUsingAnEmptyConstructor() throws Exception {
   System.out.println(
       "public static <T extends Exception> T newException(Class<T> clazz, Object... parameters)");
   IOException exception = ReflectionHelper.newException(IOException.class);
   assertThat("IOException is not null", exception, notNullValue());
   assertThat("MessageText is not null", exception.getMessage(), nullValue());
   System.out.println(exception);
 }
 /**
  * Test of 'public static <T> Class<T> loadClass(String className)' method, of class
  * ReflectionHelper.
  */
 @Test
 public void loadClass() {
   System.out.println("public static <T> Class<T> loadClass(String className)");
   String classname = "java.util.Date";
   Class expResult = Date.class;
   Class result = ReflectionHelper.loadClass(classname);
   assertEquals(expResult, result);
   System.out.println(" result = " + result);
 }
 @Test
 public void shouldCreateANewExceptionUsingAStringParameter() throws Exception {
   System.out.println(
       "public static <T extends Exception> T newException(Class<T> clazz, Object... parameters)");
   IOException exception =
       ReflectionHelper.newException(IOException.class, "AnyMessageForOurIOException");
   assertThat("IOException is not null", exception, notNullValue());
   assertThat("MessageText", exception.getMessage(), equalTo("AnyMessageForOurIOException"));
   System.out.println(exception);
 }
  @Test
  public void testGetDeclaredTypeConverterAsName() throws Exception {
    MappedBy mappedBy = mock(MappedBy.class);
    when(mappedBy.typeConverterClass()).thenReturn(MappedBy.DefaultTypeConverter.class);
    when(mappedBy.typeConverter()).thenReturn(NoConversionTypeConverter.class.getName());
    when(mappedBy.field()).thenReturn(MappedBy.DEFAULT_FIELD);
    when(reflectionHelper.newInstance(NoConversionTypeConverter.class.getName()))
        .thenReturn(new NoConversionTypeConverter());

    TypeConverter res = converterHelper.getDeclaredTypeConverter(mappedBy);

    assertThat(res).isInstanceOf(NoConversionTypeConverter.class);
  }
  /**
   * Test of 'public static Field getField(Class<?> clazz, String fieldname, Class<?> fieldtype)'
   * method, of class ReflectionHelper.
   */
  @Test
  public void shouldGetAField() throws Exception {
    System.out.println(
        "public static Field getField(Class<?> clazz, String fieldname, Class<?> fieldtype)");

    File cut = new File("pom.xml");
    Field pathField = ReflectionHelper.getField(File.class, "path", String.class);
    assertThat(pathField, notNullValue());
    assertThat(pathField.getName(), equalTo("path"));

    pathField.setAccessible(true);
    assertThat(pathField.get(cut), equalTo("pom.xml"));
  }
  @Test
  public void testGetDeclaredTypeConverterIae() throws Exception {
    MappedBy mappedBy = mock(MappedBy.class);
    when(mappedBy.typeConverterClass()).thenReturn(MappedBy.DefaultTypeConverter.class);
    when(mappedBy.typeConverter()).thenReturn(NoConversionTypeConverter.class.getName());
    when(mappedBy.field()).thenReturn(MappedBy.DEFAULT_FIELD);
    when(reflectionHelper.newInstance(NoConversionTypeConverter.class.getName()))
        .thenThrow(new IllegalAccessException());

    exception.expect(JTransfoException.class);
    exception.expectMessage(
        "Declared TypeConverter class org.jtransfo.NoConversionTypeConverter cannot be accessed.");
    converterHelper.getDeclaredTypeConverter(mappedBy);
  }
  @Test
  public void testGetDeclaredTypeConverter_withTypeConverter() throws Exception {
    MapOnly mapOnly = mock(MapOnly.class);
    when(reflectionHelper.newInstance(
            "org.jtransfo.internal.ConverterHelperTest$DefaultTypeConverter"))
        .thenReturn(new DefaultTypeConverter());
    when(mapOnly.typeConverterClass()).thenReturn(DefaultTypeConverter.class);
    when(mapOnly.typeConverter()).thenReturn(MappedBy.DEFAULT_TYPE_CONVERTER);
    TypeConverter tc = mock(TypeConverter.class);

    TypeConverter res = converterHelper.getDeclaredTypeConverter(mapOnly, tc);

    assertThat(res).isInstanceOf(DefaultTypeConverter.class);
  }
Example #23
0
  private static void reflectXmlObject(Object model, Node node) {

    Class<?> modelClass = model.getClass();

    // Treat attributes like fields
    if (node.attributes != null) {
      for (String key : node.attributes.keySet()) {

        String value = node.attributes.get(key);

        try {
          Field field = ReflectionHelper.getFieldInHierarchy(modelClass, key);

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

          if (type == String.class) {
            field.set(model, value);

          } else if (type == boolean.class || type == Boolean.class) {
            field.set(model, Boolean.valueOf(value));

          } else if (type == int.class || type == Integer.class) {
            field.set(model, Integer.valueOf(value));

          } else if (type == double.class || type == Double.class) {
            field.set(model, Double.valueOf(value));
          }
        } catch (NoSuchFieldException e) {
          Log.w(XmlReflector.class.getName(), "Can not locate field named " + key);

        } catch (IllegalAccessException e) {
          Log.w(XmlReflector.class.getName(), "Can not access field named " + key);
        }
      }
    }

    if (node.subnodes != null) {

      for (int i = 0; i < node.subnodes.size(); i++) {

        Node subnode = node.subnodes.get(i);
        accessFieldAndProcess(model, modelClass, subnode, node);
      }

    } else {
      // This node has no children (hope it has a wife).
      accessFieldAndProcess(model, modelClass, node, null);
    }
  }
  @Test
  public void shouldExtractAllClasses() {
    // given
    String one = "a string";
    Class two = Double.class;
    SimplePojo three = new SimplePojo();
    Object[] anything = new Object[] {one, two, three};

    // when
    Class[] extracted = ReflectionHelper.extractClasses(anything);

    // then
    assertEquals(extracted[0], String.class);
    assertEquals(extracted[1], Double.class);
    assertEquals(extracted[2], SimplePojo.class);
  }
Example #25
0
  /*
   ************************************************************************************************
   * Overriden Methods
   ************************************************************************************************
   */
  @Override
  public void onReceive(Context context, Intent intent) {

    // Get all the registered and loop through and start them
    String[] serviceList = PropertyHelper.getBootServices(context);

    if (serviceList != null) {
      for (int i = 0; i < serviceList.length; i++) {
        // Fix to https://github.com/Red-Folder/bgs-core/issues/18
        // Gets the class from string
        Class<?> serviceClass = ReflectionHelper.LoadClass(serviceList[i]);

        Intent serviceIntent = new Intent(context, serviceClass);
        context.startService(serviceIntent);
      }
    }
  }
  @Test
  public void testGetDeclaredTypeConverterAsClass() throws Exception {
    MappedBy mappedBy = mock(MappedBy.class);
    when(mappedBy.typeConverterClass()).thenReturn(NoConversionTypeConverter.class);
    when(mappedBy.typeConverter()).thenReturn(MappedBy.DEFAULT_TYPE_CONVERTER);
    when(mappedBy.field()).thenReturn(MappedBy.DEFAULT_FIELD);
    when(reflectionHelper.newInstance(NoConversionTypeConverter.class.getName()))
        .thenReturn(new NoConversionTypeConverter());

    TypeConverter res = converterHelper.getDeclaredTypeConverter(mappedBy);

    assertThat(res).isInstanceOf(NoConversionTypeConverter.class);

    TypeConverter res2 = converterHelper.getDeclaredTypeConverter(mappedBy);

    assertThat(res2 == res).isTrue(); // instance needs to be cached and reused
  }
Example #27
0
 /**
  * Deletes the reportCategoryBean satisfying a certain criteria together with the dependent
  * database entries
  *
  * @param crit
  * @throws TorqueException
  */
 public static void doDelete(Criteria crit) throws TorqueException {
   List list = null;
   try {
     list = doSelect(crit);
   } catch (TorqueException e) {
     LOGGER.error(
         "Getting the list of TReportCategoryBean to be deleted failed with " + e.getMessage());
     throw e;
   }
   if (list != null && !list.isEmpty()) {
     Iterator<TReportCategory> iter = list.iterator();
     TReportCategory filterCategory = null;
     while (iter.hasNext()) {
       filterCategory = iter.next();
       ReflectionHelper.delete(deletePeerClasses, deleteFields, filterCategory.getObjectID());
     }
   }
 }
  /**
   * Test of 'public static void setValue(Object instance, String setter, Object value)' method, of
   * class ReflectionHelper.
   */
  @Test
  public void setValueAndGetValue() throws Exception {
    System.out.println("public static void setValue(Object instance, String setter, Object value)");

    SimplePojo pojo = new SimplePojo();

    assertNull(pojo.getValueA());
    assertNull(pojo.getValueB());

    ReflectionHelper.setValue(pojo, "setValueA", "Alpha");

    assertEquals("Alpha", pojo.getValueA());

    ReflectionHelper.setValue(pojo, "setValueB", "Beta");

    assertEquals("Alpha", pojo.getValueA());

    System.out.println(" result = setValue works fine! ");

    String got = ReflectionHelper.getValue(pojo, "getValueA");
    assertEquals(got, pojo.getValueA());
    System.out.println(" result = getValue works also fine! ");

    long start = System.currentTimeMillis();

    for (int i = 1; i <= 100000; i++) {

      ReflectionHelper.setValue(pojo, "setValueA", "Alpha");
      ReflectionHelper.setValue(pojo, "setValueB", "Beta");
      ReflectionHelper.getValue(pojo, "getValueA");
      ReflectionHelper.getValue(pojo, "getValueB");
    }

    long end = System.currentTimeMillis();
    System.out.println(" time: " + (end - start) + " ms ");

    System.out.println(" " + ReflectionHelper.getCacheInfo());
  }
Example #29
0
  private static void reflectJsonArray(Object model, JSONArray jsonArray) throws JSONException {

    Class<?> modelClass = model.getClass();
    try {
      Field listField = ReflectionHelper.getFieldInHierarchy(modelClass, "list");

      processListField(model, listField, jsonArray);

    } catch (NoSuchFieldException e) {
      Log.w(JsonReflector.class.getName(), "Can not locate field named list");

    } catch (IllegalArgumentException e) {
      Log.w(JsonReflector.class.getName(), "Can not put a List in the field named list");

    } catch (IllegalAccessException e) {
      Log.w(JsonReflector.class.getName(), "Can not access field named list");

    } catch (InstantiationException e) {
      Log.w(
          JsonReflector.class.getName(),
          "Can not create an instance of the type defined in the field named list");
    }
  }
  @Override
  public void init(GenericTask task, Map<String, String> properties) {
    Field[] fields = ReflectionHelper.getDeclaredFields(this.getClass(), null);
    for (Field field : fields) {
      if (!field.isAnnotationPresent(VersionProviderParam.class)) {
        continue;
      }

      VersionProviderParam param = field.getAnnotation(VersionProviderParam.class);
      if (!properties.containsKey(param.value())) {
        continue;
      }

      // make private and protected fields also accessible
      field.setAccessible(true);

      try {
        field.set(this, properties.get(param.value()));
      } catch (IllegalAccessException e) {
        throw new BuildException(
            "Failed to set build version provider param '" + param.value() + "'", e);
      }
    }
  }