Example usage for java.beans PropertyDescriptor PropertyDescriptor

List of usage examples for java.beans PropertyDescriptor PropertyDescriptor

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor PropertyDescriptor.

Prototype

PropertyDescriptor(PropertyDescriptor x, PropertyDescriptor y) 

Source Link

Document

Package-private constructor.

Usage

From source file:com.googlecode.jsonschema2pojo.integration.PropertiesIT.java

@Test
@SuppressWarnings("rawtypes")
public void wordDelimitersCausesCamelCase() throws ClassNotFoundException, IntrospectionException,
        InstantiationException, IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/properties/propertiesWithWordDelimiters.json",
            "com.example", config("usePrimitives", true, "propertyWordDelimiters", "_ -"));

    Class generatedType = resultsClassLoader.loadClass("com.example.WordDelimit");

    Object instance = generatedType.newInstance();

    new PropertyDescriptor("propertyWithUnderscores", generatedType).getWriteMethod().invoke(instance, "a_b_c");
    new PropertyDescriptor("propertyWithHyphens", generatedType).getWriteMethod().invoke(instance, "a-b-c");
    new PropertyDescriptor("propertyWithMixedDelimiters", generatedType).getWriteMethod().invoke(instance,
            "a b_c-d");

    JsonNode jsonified = mapper.valueToTree(instance);

    assertThat(jsonified.has("property_with_underscores"), is(true));
    assertThat(jsonified.has("property-with-hyphens"), is(true));
    assertThat(jsonified.has("property_with mixed-delimiters"), is(true));
}

From source file:com.sparkplatform.api.core.PropertyAsserter.java

/**
 * See {@link #assertBasicGetterSetterBehavior(Object,String)} method. Only difference is that here we accept an
 * explicit argument for the setter method.
 *
 * @param target   the object on which to invoke the getter and setter
 * @param property the property name, e.g. "firstName"
 * @param argument the property value, i.e. the value the setter will be invoked with
 *//*from w  w  w  .ja  v  a  2s .  co m*/
public static void assertBasicGetterSetterBehavior(Object target, String property, Object argument) {
    try {
        PropertyDescriptor descriptor = new PropertyDescriptor(property, target.getClass());
        Object arg = argument;
        Class type = descriptor.getPropertyType();
        if (arg == null) {
            if (type.isArray()) {
                arg = Array.newInstance(type.getComponentType(), new int[] { TEST_ARRAY_SIZE });
            } else if (type.isEnum()) {
                arg = type.getEnumConstants()[0];
            } else if (TYPE_ARGUMENTS.containsKey(type)) {
                arg = TYPE_ARGUMENTS.get(type);
            } else {
                arg = invokeDefaultConstructorEvenIfPrivate(type);
            }
        }

        Method writeMethod = descriptor.getWriteMethod();
        Method readMethod = descriptor.getReadMethod();

        writeMethod.invoke(target, arg);
        Object propertyValue = readMethod.invoke(target);
        if (type.isPrimitive()) {
            assertEquals(property + " getter/setter failed test", arg, propertyValue);
        } else {
            assertSame(property + " getter/setter failed test", arg, propertyValue);
        }
    } catch (IntrospectionException e) {
        String msg = "Error creating PropertyDescriptor for property [" + property
                + "]. Do you have a getter and a setter?";
        log.error(msg, e);
        fail(msg);
    } catch (IllegalAccessException e) {
        String msg = "Error accessing property. Are the getter and setter both accessible?";
        log.error(msg, e);
        fail(msg);
    } catch (InvocationTargetException e) {
        String msg = "Error invoking method on target";
        log.error(msg, e);
        fail(msg);
    }
}

From source file:org.jsonschema2pojo.integration.PropertiesIT.java

@Test
@SuppressWarnings("rawtypes")
public void wordDelimitersCausesCamelCase() throws ClassNotFoundException, IntrospectionException,
        InstantiationException, IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/properties/propertiesWithWordDelimiters.json", "com.example",
            config("usePrimitives", true, "propertyWordDelimiters", "_ -"));

    Class generatedType = resultsClassLoader.loadClass("com.example.WordDelimit");

    Object instance = generatedType.newInstance();

    new PropertyDescriptor("propertyWithUnderscores", generatedType).getWriteMethod().invoke(instance, "a_b_c");
    new PropertyDescriptor("propertyWithHyphens", generatedType).getWriteMethod().invoke(instance, "a-b-c");
    new PropertyDescriptor("propertyWithMixedDelimiters", generatedType).getWriteMethod().invoke(instance,
            "a b_c-d");

    JsonNode jsonified = mapper.valueToTree(instance);

    assertThat(jsonified.has("property_with_underscores"), is(true));
    assertThat(jsonified.has("property-with-hyphens"), is(true));
    assertThat(jsonified.has("property_with mixed-delimiters"), is(true));
}

From source file:org.jsonschema2pojo.integration.CustomDateTimeFormatIT.java

/**
 * This tests the class generated when formatDateTimes config option is set to TRUE
 * The field should have @JsonFormat annotation with iso8601 date time pattern and UTC timezone
 * It also tests the serialization and deserialization process
 * /*w  ww  .j  ava2 s . com*/
 * @throws Exception
 */
@Test
public void testDefaultWhenFormatDateTimesConfigIsTrue() throws Exception {
    Field field = classWhenConfigIsTrue.getDeclaredField("defaultFormat");
    JsonFormat annotation = field.getAnnotation(JsonFormat.class);

    assertThat(annotation, notNullValue());
    // Assert that the patterns match
    assertEquals("yyyy-MM-dd'T'HH:mm:ss.SSS", annotation.pattern());
    // Assert that the timezones match
    assertEquals("UTC", annotation.timezone());

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setTimeZone(TimeZone.getTimeZone("UTC"));

    ObjectNode node = objectMapper.createObjectNode();
    node.put("defaultFormat", "2016-11-06T00:00:00.000");

    Object pojo = objectMapper.treeToValue(node, classWhenConfigIsTrue);

    Method getter = new PropertyDescriptor("defaultFormat", classWhenConfigIsTrue).getReadMethod();

    // Assert that the Date object in the deserialized class is as expected
    assertEquals(dateTimeMilliSecFormatter.parse("2016-11-06T00:00:00.000").toString(),
            getter.invoke(pojo).toString());

    JsonNode jsonVersion = objectMapper.valueToTree(pojo);

    // Assert that when the class is serialized, the date object is serialized as expected 
    assertEquals("2016-11-06T00:00:00.000", jsonVersion.get("defaultFormat").asText());
}

From source file:ch.silviowangler.dox.AutomaticTranslatorAdvice.java

private void translate(Translatable translatable) {

    logger.debug("Detected translatable in class {}", translatable.getClass().getName());

    final String messageKey = translatable.retrieveMessageKey();
    final Locale locale = LocaleContextHolder.getLocale();
    try {//from ww w.j  av a  2s . c om
        String translation = translationService.findTranslation(messageKey, locale);
        translatable.setTranslation(translation);
    } catch (NoTranslationFoundException e) {
        String message = getTranslation(messageKey, locale);
        translatable.setTranslation(message);
    }

    final Field[] declaredFields = translatable.getClass().getDeclaredFields();

    for (Field field : declaredFields) {
        if (isTranslatable(field.getType())) {
            try {
                Translatable objectToTranslate = (Translatable) new PropertyDescriptor(field.getName(),
                        translatable.getClass()).getReadMethod().invoke(translatable);
                if (objectToTranslate != null) {
                    translate(objectToTranslate);
                }
            } catch (IllegalAccessException | IntrospectionException | InvocationTargetException e) {
                logger.error("Unable to translate", e);
            }
        }
    }
}

From source file:org.gerzog.jstataggr.core.manager.impl.StatisticsManagerImpl.java

protected MethodHandle findGetter(final Class<?> statisticsClass, final Field field) {
    return propogate(() -> {
        final Method readMethod = new PropertyDescriptor(field.getName(), statisticsClass).getReadMethod();

        return MethodHandles.lookup().unreflect(readMethod);
    }, (e) -> new IllegalStateException("There is no public getter for field <" + field + ">", e));
}

From source file:info.magnolia.freemarker.FreemarkerServletContextWrapper.java

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Set getResourcePaths(String path) {
    if (StringUtils.equals(path, "/WEB-INF/lib")) {
        log.debug("returning resources from classpath");
        // Just when asking libraries, pass the classpath ones.
        final Set<String> resources = new HashSet<String>();
        final ClassLoader cl = Thread.currentThread().getContextClassLoader();
        // if the classloader is an URLClassloader we have a better method for discovering resources
        // whis will also fetch files from jars outside WEB-INF/lib, useful during development
        if (cl instanceof URLClassLoader) {
            final URLClassLoader urlClassLoader = (URLClassLoader) cl;
            final URL[] urls = urlClassLoader.getURLs();
            for (int j = 0; j < urls.length; j++) {
                final File tofile = sanitizeToFile(urls[j]);
                if (tofile.isDirectory()) {
                    for (File file : ((List<File>) FileUtils.listFiles(tofile, null, true))) {
                        resources.add(file.getAbsolutePath());
                    }// w  ww  .  j  av a 2s  . c  o  m
                } else {
                    resources.add(tofile.getAbsolutePath());
                }
            }

            return resources;
        }
        try {
            // be friendly to WAS developers too...
            // in development mode under RAD 7.5 here we have an instance of com.ibm.ws.classloader.WsClassLoader
            // and jars are NOT deployed to WEB-INF/lib by default, so they can't be found without this explicit
            // check
            //
            // but since we don't want to depend on WAS stuff we just check if the cl exposes a "classPath" property
            PropertyDescriptor pd = new PropertyDescriptor("classPath", cl.getClass());
            if (pd != null && pd.getReadMethod() != null) {
                String classpath = (String) pd.getReadMethod().invoke(cl, new Object[] {});
                if (StringUtils.isNotBlank(classpath)) {
                    String[] paths = StringUtils.split(classpath, File.pathSeparator);
                    for (int j = 0; j < paths.length; j++) {
                        final File tofile = new File(paths[j]);
                        // there can be several missing (optional?) paths here...
                        if (tofile.exists()) {
                            if (tofile.isDirectory()) {
                                for (File file : ((List<File>) FileUtils.listFiles(tofile, null, true))) {
                                    resources.add(file.getAbsolutePath());
                                }
                            } else {
                                resources.add(tofile.getAbsolutePath());
                            }
                        }
                    }
                    return resources;
                }
            }
        } catch (Throwable e) {
            // no, it's not a classloader we can handle in a special way
        }
        // no way, we have to assume a standard war structure and look in the WEB-INF/lib and WEB-INF/classes dirs
        // read the jars in the lib dir
    }
    return parentContext.getResourcePaths(path);
}

From source file:com.webpagebytes.cms.engine.JSONToFromObjectConverter.java

public org.json.JSONObject JSONFromObject(Object object) {
    org.json.JSONObject json = new org.json.JSONObject();
    if (null == object)
        return json;
    Class<? extends Object> objClass = object.getClass();
    Field[] fields = objClass.getDeclaredFields();
    for (Field field : fields) {
        Object storeAdn = field.getAnnotation(WPBAdminFieldStore.class);
        if (storeAdn == null) {
            storeAdn = field.getAnnotation(WPBAdminFieldKey.class);
            if (storeAdn == null) {
                storeAdn = field.getAnnotation(WPBAdminFieldTextStore.class);
                if (storeAdn == null) {
                    storeAdn = field.getAnnotation(WPBAdminField.class);
                }/*from www . j a  v  a2 s.  c  o m*/
            }
        }

        if (storeAdn != null) {
            String fieldName = field.getName();
            try {
                PropertyDescriptor pd = new PropertyDescriptor(fieldName, objClass);
                Object value = pd.getReadMethod().invoke(object);
                String fieldValue = JSONStringFromField(value, field.getType());
                if (fieldValue != null) {
                    json.put(fieldName, fieldValue);
                }
            } catch (Exception e) {
                // do nothing, there is no write method for our field
            }
        }
    }
    return json;
}

From source file:com.webpagebytes.cms.local.WPBLocalDataStoreDao.java

private <T> T copyResultSetToObject(ResultSet resultSet, Class<T> kind)
        throws SQLException, WPBSerializerException {
    try {//w  w w  .j  av a 2 s  .c o  m
        T result = kind.newInstance();
        Field[] fields = kind.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            boolean storeField = (field.getAnnotation(WPBAdminFieldKey.class) != null)
                    || (field.getAnnotation(WPBAdminFieldStore.class) != null)
                    || (field.getAnnotation(WPBAdminFieldTextStore.class) != null);
            if (storeField) {
                String fieldName = field.getName();
                String fieldNameUpperCase = field.getName().toUpperCase();
                PropertyDescriptor pd = new PropertyDescriptor(fieldName, kind);
                // get the field type
                if (field.getType() == Long.class) {
                    Long value = resultSet.getLong(fieldNameUpperCase);
                    pd.getWriteMethod().invoke(result, value);
                } else if (field.getType() == String.class) {
                    String value = resultSet.getString(fieldNameUpperCase);
                    pd.getWriteMethod().invoke(result, value);
                } else if (field.getType() == Integer.class) {
                    Integer value = resultSet.getInt(fieldNameUpperCase);
                    pd.getWriteMethod().invoke(result, value);
                } else if (field.getType() == Date.class) {
                    Timestamp ts = resultSet.getTimestamp(fieldNameUpperCase);
                    Date value = new Date(ts.getTime());
                    pd.getWriteMethod().invoke(result, value);

                }
            }
        }
        return result;
    } catch (Exception e) {
        throw new WPBSerializerException("Cannot deserialize from Result Set", e);
    }
}