Example usage for java.lang.reflect Field getModifiers

List of usage examples for java.lang.reflect Field getModifiers

Introduction

In this page you can find the example usage for java.lang.reflect Field getModifiers.

Prototype

public int getModifiers() 

Source Link

Document

Returns the Java language modifiers for the field represented by this Field object, as an integer.

Usage

From source file:fr.certu.chouette.command.Command.java

private void executeInfoValidationParameters() throws Exception {
    try {/*  w w  w  .j a  v  a 2s . co m*/
        Class<?> c = validationParameters.getClass();
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals("test3_2_Polygon"))
                continue;
            int m = field.getModifiers();
            if (Modifier.isPrivate(m) && !Modifier.isStatic(m)) {
                printField(c, field, "");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

}

From source file:adalid.core.EntityAtlas.java

@SuppressWarnings("deprecation")
void initialiseFields(Class<?> clazz) {
    track("initialiseFields", _declaringArtifact, clazz.getSimpleName());
    Class<?> c;// ww w . jav a 2s. c  om
    int d, r;
    String name;
    String key;
    String pattern = "there are several fields for operation {0}";
    String message;
    Class<?> type;
    Class<?> decl;
    Class<?> operationClass;
    Field operationField;
    int modifiers;
    boolean restricted;
    Object o;
    int depth = _declaringArtifact.depth();
    int round = _declaringArtifact.round();
    Class<?>[] classes = new Class<?>[] { Property.class, Key.class, Tab.class, View.class, Instance.class,
            NamedValue.class, Expression.class, Transition.class, Operation.class, Trigger.class };
    Class<?> dac = _declaringArtifact.getClass();
    Class<?> top = Entity.class;
    int i = ArrayUtils.indexOf(classes, clazz);
    if (i != ArrayUtils.INDEX_NOT_FOUND) {
        c = classes[i];
        for (Field field : XS1.getFields(dac, top)) {
            field.setAccessible(true);
            logger.trace(field);
            name = field.getName();
            type = field.getType();
            decl = field.getDeclaringClass();
            if (!c.isAssignableFrom(type)) {
                continue;
            }
            if (c.equals(Expression.class) && Property.class.isAssignableFrom(type)) {
                continue;
            }
            // TODO: extension handling
            if (field.isAnnotationPresent(Extension.class) && Entity.class.isAssignableFrom(type)) {
                //                  if (!dac.equals(decl) || !dac.isAssignableFrom(type)) {
                //                      continue;
                //                  }
                continue;
            }
            modifiers = type.getModifiers();
            if (NamedValue.class.isAssignableFrom(type) || Expression.class.isAssignableFrom(type)) {
                restricted = false;
            } else {
                restricted = type.isInterface() || Modifier.isAbstract(modifiers);
            }
            restricted = restricted || !Modifier.isPublic(modifiers);
            if (restricted) {
                continue;
            }
            modifiers = field.getModifiers();
            restricted = Modifier.isPrivate(modifiers);
            if (restricted) {
                continue;
            }
            restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
            if (restricted) {
                continue;
            }
            if (Operation.class.isAssignableFrom(type)) {
                key = type.getSimpleName();
                operationClass = _operationClasses.get(key);
                if (operationClass != null) {
                    operationField = _operationFields.get(key);
                    if (operationField == null) {
                        _operationFields.put(key, field);
                    } else {
                        message = MessageFormat.format(pattern, operationClass.getName());
                        logger.warn(message);
                        TLC.getProject().getParser().increaseWarningCount();
                    }
                }
            }
            String errmsg = "failed to create a new instance of field \"" + field + "\" at "
                    + _declaringArtifact;
            try {
                o = field.get(_declaringArtifact);
                if (o == null) {
                    logger.debug(message(type, name, o, depth, round));
                    o = XS1.initialiseField(_declaringArtifact, field);
                    if (o == null) {
                        logger.debug(message(type, name, o, depth, round));
                        //                          throw new RuntimeException(message(type, name, o, depth, round));
                    } else {
                        logger.debug(message(type, name, o, depth, round));
                        field.set(_declaringArtifact, o);
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new InstantiationRuntimeException(errmsg, ex);
            }
        }
    }
}

From source file:solidstack.reflect.Dumper.java

public void dumpTo(Object o, DumpWriter out) {
    try {/* ww  w . ja v a2 s  . c o  m*/
        if (o == null) {
            out.append("<null>");
            return;
        }
        Class<?> cls = o.getClass();
        if (cls == String.class) {
            out.append("\"").append(((String) o).replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "\\r")
                    .replace("\t", "\\t").replace("\"", "\\\"")).append("\"");
            return;
        }
        if (o instanceof CharSequence) {
            out.append("(").append(o.getClass().getName()).append(")");
            dumpTo(o.toString(), out);
            return;
        }
        if (cls == char[].class) {
            out.append("(char[])");
            dumpTo(String.valueOf((char[]) o), out);
            return;
        }
        if (cls == byte[].class) {
            out.append("byte[").append(Integer.toString(((byte[]) o).length)).append("]");
            return;
        }
        if (cls == Class.class) {
            out.append(((Class<?>) o).getCanonicalName()).append(".class");
            return;
        }
        if (cls == File.class) {
            out.append("File( \"").append(((File) o).getPath()).append("\" )");
            return;
        }
        if (cls == AtomicInteger.class) {
            out.append("AtomicInteger( ").append(Integer.toString(((AtomicInteger) o).get())).append(" )");
            return;
        }
        if (cls == AtomicLong.class) {
            out.append("AtomicLong( ").append(Long.toString(((AtomicLong) o).get())).append(" )");
            return;
        }
        if (o instanceof ClassLoader) {
            out.append(o.getClass().getCanonicalName());
            return;
        }

        if (cls == java.lang.Short.class || cls == java.lang.Long.class || cls == java.lang.Integer.class
                || cls == java.lang.Float.class || cls == java.lang.Byte.class
                || cls == java.lang.Character.class || cls == java.lang.Double.class
                || cls == java.lang.Boolean.class || cls == BigInteger.class || cls == BigDecimal.class) {
            out.append("(").append(cls.getSimpleName()).append(")").append(o.toString());
            return;
        }

        String className = cls.getCanonicalName();
        if (className == null)
            className = cls.getName();
        out.append(className);

        if (this.skip.contains(className) || o instanceof java.lang.Thread) {
            out.append(" (skipped)");
            return;
        }

        Integer id = this.visited.get(o);
        if (id == null) {
            id = ++this.id;
            this.visited.put(o, id);
            if (!this.hideIds)
                out.append(" <id=" + id + ">");
        } else {
            out.append(" <refid=" + id + ">");
            return;
        }

        if (cls.isArray()) {
            if (Array.getLength(o) == 0)
                out.append(" []");
            else {
                out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
                int rowCount = Array.getLength(o);
                for (int i = 0; i < rowCount; i++) {
                    out.comma();
                    dumpTo(Array.get(o, i), out);
                }
                out.newlineOrSpace().unIndent().append("]");
            }
        } else if (o instanceof Collection && !this.overriddenCollection.contains(className)) {
            Collection<?> list = (Collection<?>) o;
            if (list.isEmpty())
                out.append(" []");
            else {
                out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
                for (Object value : list) {
                    out.comma();
                    dumpTo(value, out);
                }
                out.newlineOrSpace().unIndent().append("]");
            }
        } else if (o instanceof Properties && !this.overriddenCollection.contains(className)) // Properties is a Map, so it must come before the Map
        {
            Field def = cls.getDeclaredField("defaults");
            if (!def.isAccessible())
                def.setAccessible(true);
            Properties defaults = (Properties) def.get(o);
            Hashtable<?, ?> map = (Hashtable<?, ?>) o;
            out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                out.comma();
                dumpTo(entry.getKey(), out);
                out.append(": ");
                dumpTo(entry.getValue(), out);
            }
            if (defaults != null && !defaults.isEmpty()) {
                out.comma().append("defaults: ");
                dumpTo(defaults, out);
            }
            out.newlineOrSpace().unIndent().append("]");
        } else if (o instanceof Map && !this.overriddenCollection.contains(className)) {
            Map<?, ?> map = (Map<?, ?>) o;
            if (map.isEmpty())
                out.append(" []");
            else {
                out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    out.comma();
                    dumpTo(entry.getKey(), out);
                    out.append(": ");
                    dumpTo(entry.getValue(), out);
                }
                out.newlineOrSpace().unIndent().append("]");
            }
        } else if (o instanceof Method) {
            out.newlineOrSpace().append("{").newlineOrSpace().indent().setFirst();

            Field field = cls.getDeclaredField("clazz");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("clazz").append(": ");
            dumpTo(field.get(o), out);

            field = cls.getDeclaredField("name");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("name").append(": ");
            dumpTo(field.get(o), out);

            field = cls.getDeclaredField("parameterTypes");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("parameterTypes").append(": ");
            dumpTo(field.get(o), out);

            field = cls.getDeclaredField("returnType");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("returnType").append(": ");
            dumpTo(field.get(o), out);

            out.newlineOrSpace().unIndent().append("}");
        } else {
            ArrayList<Field> fields = new ArrayList<Field>();
            while (cls != Object.class) {
                Field[] fs = cls.getDeclaredFields();
                for (Field field : fs)
                    fields.add(field);
                cls = cls.getSuperclass();
            }

            Collections.sort(fields, new Comparator<Field>() {
                public int compare(Field left, Field right) {
                    return left.getName().compareTo(right.getName());
                }
            });

            if (fields.isEmpty())
                out.append(" {}");
            else {
                out.newlineOrSpace().append("{").newlineOrSpace().indent().setFirst();
                for (Field field : fields)
                    if ((field.getModifiers() & Modifier.STATIC) == 0)
                        if (!this.hideTransients || (field.getModifiers() & Modifier.TRANSIENT) == 0) {
                            out.comma().append(field.getName()).append(": ");

                            if (!field.isAccessible())
                                field.setAccessible(true);

                            if (field.getType().isPrimitive())
                                if (field.getType() == boolean.class) // TODO More?
                                    out.append(field.get(o).toString());
                                else
                                    out.append("(").append(field.getType().getName()).append(")")
                                            .append(field.get(o).toString());
                            else
                                dumpTo(field.get(o), out);
                        }
                out.newlineOrSpace().unIndent().append("}");
            }
        }
    } catch (IOException e) {
        throw new FatalIOException(e);
    } catch (Exception e) {
        dumpTo(e.toString(), out);
    }
}

From source file:org.apache.ambari.server.controller.AmbariManagementControllerImplTest.java

@Test
public void testgetAmbariServerURI() throws Exception {
    // create mocks
    Injector injector = createStrictMock(Injector.class);
    Capture<AmbariManagementController> controllerCapture = new Capture<AmbariManagementController>();

    // set expectations
    injector.injectMembers(capture(controllerCapture));
    expect(injector.getInstance(Gson.class)).andReturn(null);

    //replay// ww  w  .j a v a 2  s. com
    replay(injector);

    AmbariManagementControllerImpl controller = new AmbariManagementControllerImpl(null, null, injector);

    class AmbariConfigsSetter {
        public void setConfigs(AmbariManagementController controller, String masterProtocol,
                String masterHostname, Integer masterPort) throws Exception {
            // masterProtocol
            Class<?> c = controller.getClass();
            Field f = c.getDeclaredField("masterProtocol");
            f.setAccessible(true);

            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);

            f.set(controller, masterProtocol);

            // masterHostname
            f = c.getDeclaredField("masterHostname");
            f.setAccessible(true);

            modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);

            f.set(controller, masterHostname);

            // masterPort
            f = c.getDeclaredField("masterPort");
            f.setAccessible(true);

            modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);

            f.set(controller, masterPort);
        }
    }

    AmbariConfigsSetter ambariConfigsSetter = new AmbariConfigsSetter();

    ambariConfigsSetter.setConfigs(controller, "http", "hostname", 8080);
    assertEquals("http://hostname:8080/jdk_path", controller.getAmbariServerURI("/jdk_path"));

    ambariConfigsSetter.setConfigs(controller, "https", "somesecuredhost", 8443);
    assertEquals("https://somesecuredhost:8443/mysql_path", controller.getAmbariServerURI("/mysql_path"));

    ambariConfigsSetter.setConfigs(controller, "https", "othersecuredhost", 8443);
    assertEquals("https://othersecuredhost:8443/oracle/ojdbc/",
            controller.getAmbariServerURI("/oracle/ojdbc/"));

    verify(injector);
}

From source file:com.impetus.client.cassandra.CassandraClientBase.java

/**
 * On where clause.//ww  w.  ja  v a 2 s  .  com
 * 
 * @param metadata
 *            the metadata
 * @param key
 *            the compound key object
 * @param translator
 *            the translator
 * @param queryBuilder
 *            the query builder
 * @param metaModel
 *            the meta model
 * @param attribute
 *            the attribute
 */
protected void onWhereClause(EntityMetadata metadata, Object key, CQLTranslator translator,
        StringBuilder queryBuilder, MetamodelImpl metaModel, SingularAttribute attribute) {
    // SingularAttribute idAttribute = metadata.getIdAttribute();
    if (metaModel.isEmbeddable(attribute.getBindableJavaType())) {
        Field[] fields = attribute.getBindableJavaType().getDeclaredFields();
        EmbeddableType compoundKey = metaModel.embeddable(attribute.getBindableJavaType());

        for (Field field : fields) {
            if (field != null && !Modifier.isStatic(field.getModifiers())
                    && !Modifier.isTransient(field.getModifiers())
                    && !field.isAnnotationPresent(Transient.class)) {
                attribute = (SingularAttribute) compoundKey.getAttribute(field.getName());
                Object valueObject = PropertyAccessorHelper.getObject(key, field);
                if (metaModel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) {
                    onWhereClause(metadata, valueObject, translator, queryBuilder, metaModel, attribute);
                } else {
                    String columnName = ((AbstractAttribute) attribute).getJPAColumnName();
                    translator.buildWhereClause(queryBuilder, field.getType(), columnName, valueObject,
                            CQLTranslator.EQ_CLAUSE, false);
                }
            }
        }
    } else {
        translator.buildWhereClause(queryBuilder, ((AbstractAttribute) attribute).getBindableJavaType(),
                CassandraUtilities.getIdColumnName(kunderaMetadata, metadata, getExternalProperties(),
                        isCql3Enabled(metadata)),
                key, translator.EQ_CLAUSE, false);
    }
}

From source file:org.apache.bookkeeper.mledger.impl.ManagedLedgerTest.java

@Test
public void testBacklogCursor() throws Exception {
    ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("cache_backlog_ledger");

    final long maxMessageCacheRetentionTimeMillis = 100;
    Field field = ManagedLedgerImpl.class.getDeclaredField("maxMessageCacheRetentionTimeMillis");
    field.setAccessible(true);/*  w ww  .  j a  va 2 s  .  c om*/
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(ledger, maxMessageCacheRetentionTimeMillis);
    Field backlogThresholdField = ManagedLedgerImpl.class.getDeclaredField("maxActiveCursorBacklogEntries");
    backlogThresholdField.setAccessible(true);
    final long maxActiveCursorBacklogEntries = (long) backlogThresholdField.get(ledger);

    // Open Cursor also adds cursor into activeCursor-container
    ManagedCursor cursor1 = ledger.openCursor("c1");
    ManagedCursor cursor2 = ledger.openCursor("c2");

    final int totalBacklogSizeEntries = (int) maxActiveCursorBacklogEntries;
    CountDownLatch latch = new CountDownLatch(totalBacklogSizeEntries);
    for (int i = 0; i < totalBacklogSizeEntries + 1; i++) {
        String content = "entry"; // 5 bytes
        ByteBuf entry = getMessageWithMetadata(content.getBytes());
        ledger.asyncAddEntry(entry, new AddEntryCallback() {
            @Override
            public void addComplete(Position position, Object ctx) {
                latch.countDown();
                entry.release();
            }

            @Override
            public void addFailed(ManagedLedgerException exception, Object ctx) {
                latch.countDown();
                entry.release();
            }

        }, null);
    }
    latch.await();

    // Verify: cursors are active as :haven't started deactivateBacklogCursor scan
    assertTrue(cursor1.isActive());
    assertTrue(cursor2.isActive());

    // it allows message to be older enough to be considered in backlog
    Thread.sleep(maxMessageCacheRetentionTimeMillis * 2);

    // deactivate backlog cursors
    ledger.checkBackloggedCursors();
    Thread.sleep(100);

    // both cursors have to be inactive
    assertFalse(cursor1.isActive());
    assertFalse(cursor2.isActive());

    // read entries so, cursor1 reaches maxBacklog threshold again to be active again
    List<Entry> entries1 = cursor1.readEntries(50);
    for (Entry entry : entries1) {
        log.info("Read entry. Position={} Content='{}'", entry.getPosition(), new String(entry.getData()));
        entry.release();
    }

    // activate cursors which caught up maxbacklog threshold
    ledger.checkBackloggedCursors();

    // verify: cursor1 has consumed messages so, under maxBacklog threshold => active
    assertTrue(cursor1.isActive());

    // verify: cursor2 has not consumed messages so, above maxBacklog threshold => inactive
    assertFalse(cursor2.isActive());

    ledger.close();
}

From source file:org.cruk.genologics.api.impl.GenologicsAPIImpl.java

/**
 * Reflectively set all the attributes in {@code original} to the values given
 * by {@code updated}. This has the effect of making {@code original} the
 * same as {@code updated} but without requiring the client code to change the
 * object reference to {@code original}, which may be referenced in many places.
 *
 * <p>/*from w ww  .ja  v a  2  s .  c  o m*/
 * Where a field is a Collection, the existing collection is emptied and all the
 * objects from that field in {@code updated} are added in the same order to the
 * collection in {@code original}. Whether this order is maintained depends on
 * the type of collection in {@code original} (a list will maintain order, a set
 * typically won't).
 * </p>
 *
 * <p>
 * Fields that are static, transient or final are ignored, as are any fields annotated
 * with the {@code @XmlTransient} annotation.
 * </p>
 *
 * <p>
 * Note that fields within the original object that are objects themselves (as opposed to
 * primitives) are replaced with the new versions. References to sub objects are therefore
 * no longer valid.
 * </p>
 *
 * @param original The original object that was provided in the call and needs updating.
 * @param updated The version of the object returned from the LIMS with the current state.
 *
 * @throws IllegalArgumentException if either {@code original} or {@code updated}
 * are null, or are of different classes.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void reflectiveUpdate(Object original, Object updated) {
    if (original == null) {
        throw new IllegalArgumentException("original cannot be null");
    }
    if (updated == null) {
        throw new IllegalArgumentException("updated cannot be null");
    }

    if (!original.getClass().equals(updated.getClass())) {
        throw new IllegalArgumentException("original and updated are of different classes");
    }

    Class<?> clazz = original.getClass();

    do {
        Map<String, java.lang.reflect.Field> fieldMap = updaterFields.get(clazz);
        if (fieldMap == null) {
            fieldMap = Collections.synchronizedMap(new HashMap<String, java.lang.reflect.Field>());
            updaterFields.put(clazz, fieldMap);

            Class<?> currentClass = clazz;
            while (!Object.class.equals(currentClass)) {
                for (java.lang.reflect.Field field : currentClass.getDeclaredFields()) {
                    // Skip transient and XmlTransient fields.
                    if ((field.getModifiers() & REFLECTIVE_UPDATE_MODIFIER_MASK) == 0
                            && field.getAnnotation(XmlTransient.class) == null) {
                        field.setAccessible(true);
                        java.lang.reflect.Field clash = fieldMap.put(field.getName(), field);
                        if (clash != null) {
                            throw new AssertionError("There is more than one field with the name '"
                                    + field.getName() + " in the class hierarchy of " + clazz.getName() + " ("
                                    + getShortClassName(field.getDeclaringClass()) + " and "
                                    + getShortClassName(clash.getDeclaringClass()) + ")");
                        }
                    }
                }
                currentClass = currentClass.getSuperclass();
            }
        }

        for (java.lang.reflect.Field field : fieldMap.values()) {
            try {
                Object originalValue = field.get(original);
                Object updatedValue = field.get(updated);

                if (Collection.class.isAssignableFrom(field.getDeclaringClass())) {
                    Collection originalCollection = (Collection) originalValue;
                    Collection updatedCollection = (Collection) updatedValue;

                    if (originalCollection != null) {
                        originalCollection.clear();
                        if (updatedCollection != null) {
                            originalCollection.addAll(updatedCollection);
                        }
                    } else {
                        if (updatedCollection != null) {
                            // Getting as a property should create the collection object.
                            originalCollection = (Collection) PropertyUtils.getProperty(original,
                                    field.getName());
                            originalCollection.addAll(updatedCollection);
                        }
                    }
                } else if (Map.class.isAssignableFrom(field.getDeclaringClass())) {
                    throw new AssertionError("I didn't think we'd be dealing with maps: field "
                            + field.getName() + " on class " + field.getDeclaringClass().getName());
                } else {
                    field.set(original, updatedValue);
                }
            } catch (IllegalAccessException e) {
                logger.error("Cannot access the property {} on the class {}", field.getName(),
                        field.getDeclaringClass().getName());
                fieldMap.remove(field.getName());
            } catch (NoSuchMethodException e) {
                logger.error("There is no getter method for the property {} on the class {}", field.getName(),
                        field.getDeclaringClass().getName());
                fieldMap.remove(field.getName());
            } catch (InvocationTargetException e) {
                logger.error("Error while getting collection property {}", field.getName(),
                        e.getTargetException());
            } catch (ClassCastException e) {
                logger.error("Cannot cast a {} to a Collection.", e.getMessage());
            }
        }

        clazz = clazz.getSuperclass();
    } while (!Object.class.equals(clazz));
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private static final Set<PropertyDescriptor> initClassMapping(String className)
        throws ClassNotFoundException, IntrospectionException, PersistenceException {
    Set<PropertyDescriptor> ids = new HashSet<PropertyDescriptor>();
    Set<PropertyDescriptor> collections = new HashSet<PropertyDescriptor>();
    Set<PropertyDescriptor> lazys = new HashSet<PropertyDescriptor>();
    Set<PropertyDescriptor> eagers = new HashSet<PropertyDescriptor>();
    Set<LinkFileInfo> linkedFiles = new HashSet<LinkFileInfo>();
    idsByClassName.put(className, ids);//from  w w w .j av  a  2s  . c om
    collectionsByClassName.put(className, collections);
    lazysByClassName.put(className, lazys);
    eagerObjectsByClassName.put(className, eagers);
    linkedFilesByClassName.put(className, linkedFiles);
    List<String> idsAttributes = new ArrayList<String>();
    Class<?> c = Class.forName(className);
    Table tableAnn = c.getAnnotation(Table.class);
    if (tableAnn != null) {
        tableByClassName.put(className, tableAnn.name());
    } else {
        Entity entityAnn = c.getAnnotation(Entity.class);
        if (entityAnn.name() != null) {
            tableByClassName.put(className, entityAnn.name());
        } else {
            tableByClassName.put(className, className.substring(className.lastIndexOf(".") + 1));
        }
    }
    BeanInfo beanInfo = Introspector.getBeanInfo(c);
    PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
    propertyDescriptorsByClassName.put(className, pds);
    IdClass idClass = c.getAnnotation(IdClass.class);

    for (Field f : c.getDeclaredFields()) {
        Id id = f.getAnnotation(Id.class);
        if (id != null) {
            idsAttributes.add(f.getName());
            if (f.isAnnotationPresent(GeneratedValue.class)) {
                generatedIdClasses.add(className);
            }
        }
    }
    if (!idsAttributes.isEmpty()) {
        for (Field f : c.getDeclaredFields()) {
            if (!Modifier.isStatic(f.getModifiers())) {
                PropertyDescriptor pd = getPropertyDescriptor(pds, f);
                processField(className, pd, ids, collections, lazys, eagers, f);
            }
        }
        if (idClass != null) {
            Class clazz = idClass.value();
            for (Field f : clazz.getDeclaredFields()) {
                if (!Modifier.isStatic(f.getModifiers())) {
                    PropertyDescriptor pd = getPropertyDescriptor(pds, f);
                    processField(clazz.getName(), pd, ids, collections, lazys, eagers, f);
                }
            }
        }
        /*for(PropertyDescriptor pd : pds) {
           processLinkedFiles(pds, linkedFiles, pd);
        }*/
    } else {
        for (PropertyDescriptor pd : pds) {
            processMethod(className, pds, ids, collections, lazys, eagers, linkedFiles, pd);
        }
        if (idClass != null) {
            Class clazz = idClass.value();
            for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
                processMethod(clazz.getName(), pds, ids, collections, lazys, eagers, linkedFiles, pd);
            }
        }
    }
    return ids;

}

From source file:com.fluidops.iwb.api.ReadDataManagerImpl.java

/**
 * RDF string to Java Object// w  w w.j  ava  2s .c  o m
 */
@SuppressWarnings({ "unchecked" })
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "REC_CATCH_EXCEPTION", justification = "Exception caught for robustness.")
private <T> T convert(Value s, Class<T> t, Map<Value, Object> resourceStack) {
    if (s == null)
        return null;

    // avoid endless recursion
    if (resourceStack != null) {
        Object alreadySeen = resourceStack.get(s);
        if (alreadySeen != null) {
            if (alreadySeen.getClass().isAssignableFrom(t))
                return (T) alreadySeen;
            else
                // TODO: theoretically, a subject could be accessed as Type
                // T1 and later
                // as Type T2. So really, the stack should be Map<String,
                // Map<Class, Object>>
                // but this seems like a bit of overkill, so we just return
                // null if the type
                // seen for this resource before in the stack does not match
                return null;
        }
    }

    try {
        if (t == short.class || t == Short.class)
            return (T) new Short(s.stringValue());
        if (t == byte.class || t == Byte.class)
            return (T) new Byte(s.stringValue());
        if (t == boolean.class || t == Boolean.class)
            return (T) Boolean.valueOf(s.stringValue());
        if (t == long.class || t == Long.class)
            return (T) new Long(s.stringValue());
        if (t == float.class || t == Float.class)
            return (T) new Float(s.stringValue());
        if (t == double.class || t == Double.class)
            return (T) new Double(s.stringValue());
        if (t == int.class || t == Integer.class)
            return (T) new Integer(s.stringValue());
        if (t == String.class)
            return (T) s.stringValue();
        if (t == Date.class)
            return (T) literal2HumanDate(s.stringValue());
        if (t == Calendar.class) {
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(literal2HumanDate(s.stringValue()));
            return (T) cal;
        }
        if (t == URL.class)
            return (T) new URL(s.stringValue());
        if (t == java.net.URI.class)
            return (T) new java.net.URI(s.stringValue());
        if (t == org.openrdf.model.URI.class)
            return (T) s;
        /*
         * todo // interface - use dynamic proxy if ( t.isInterface() ||
         * Proxy.class.isAssignableFrom( t ) ) return (T)Proxy.newInstance(
         * s, this, t );
         */

        T instance = t.newInstance();

        // create object only if it is necessary
        if (resourceStack == null)
            resourceStack = new HashMap<Value, Object>();
        resourceStack.put(s, instance);

        for (Field f : t.getFields()) {
            if (Modifier.isStatic(f.getModifiers()))
                continue;
            if (Modifier.isFinal(f.getModifiers()))
                continue;

            if (List.class.isAssignableFrom(f.getType())) {
                @SuppressWarnings("rawtypes")
                Class listTypeValue = String.class;
                if (f.getGenericType() instanceof ParameterizedType)
                    listTypeValue = (Class<?>) ((ParameterizedType) f.getGenericType())
                            .getActualTypeArguments()[0];

                if (f.getAnnotation(RDFMapping.class) == null ? false
                        : f.getAnnotation(RDFMapping.class).inverse()) {
                    List<String> x = getInverseProps(s, RDFMappingUtil.uri(f), listTypeValue, false);
                    f.set(instance, x);
                } else {
                    List<T> x = new ArrayList<T>();
                    for (Value v : getProps((Resource) s, RDFMappingUtil.uri(f)))
                        x.add((T) convert(v, listTypeValue, resourceStack));
                    f.set(instance, x);
                }
            } else {
                if (f.getName().equals("__resource"))
                    f.set(instance, s);
                else if (f.getAnnotation(RDFMapping.class) == null ? false
                        : f.getAnnotation(RDFMapping.class).inverse()) {
                    Object x = getInversePropInternal(s, RDFMappingUtil.uri(f), f.getType(), resourceStack);
                    f.set(instance, x);
                } else if (s instanceof Resource) {
                    // for Resources, traverse deeper, for Literals, there
                    // is no substructure
                    Object x = getPropInternal(getProp((Resource) s, RDFMappingUtil.uri(f)), f.getType(),
                            resourceStack);
                    f.set(instance, x);
                }
            }
        }
        return instance;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}