Example usage for java.lang.reflect Modifier isTransient

List of usage examples for java.lang.reflect Modifier isTransient

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isTransient.

Prototype

public static boolean isTransient(int mod) 

Source Link

Document

Return true if the integer argument includes the transient modifier, false otherwise.

Usage

From source file:stc.app.bean.lang.ReflectionToStringBuilder.java

/**
 * Returns whether or not to append the given <code>Field</code>.
 * <ul>//from ww w.  j  av a  2  s. c  o  m
 * <li>Transient fields are appended only if {@link #isAppendTransients()} returns
 * <code>true</code>.
 * <li>Static fields are appended only if {@link #isAppendStatics()} returns <code>true</code>.
 * <li>Inner class fields are not appened.</li>
 * </ul>
 * 
 * @param field The Field to test.
 * @return Whether or not to append the given <code>Field</code>.
 */
protected boolean accept(Field field) {
    if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
        // Reject field from inner class.
        return false;
    }
    if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) {
        // Reject transient fields.
        return false;
    }
    if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) {
        // Reject static fields.
        return false;
    }
    if (this.getExcludeFieldNames() != null
            && Arrays.binarySearch(this.getExcludeFieldNames(), field.getName()) >= 0) {
        // Reject fields from the getExcludeFieldNames list.
        return false;
    }
    return true;
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java

/**
 * Serializes and packages an intercepted change in object state.
 * <p>/*from w  w w. j  a va 2  s .c  om*/
 * IMPORTANT serialization notes:
 * <p>
 * Transient Properties. Transients are not serialized/journalled. Marking an object property as
 * transient is the supported way of designating it as something not to be recorded into the
 * journal.
 * <p/>
 * Hibernate Identity property. A property designated in Hibernate as identity (i.e. primary
 * key) *is* not serialized. This is because sync does not enforce global uniqueness of database
 * primary keys. Instead, custom uuid property is used. This allows us to continue to use native
 * types for 'traditional' entity relationships.
 *
 * @param entity The object changed.
 * @param currentState Array containing data for each field in the object as they will be saved.
 * @param propertyNames Array containing name for each field in the object, corresponding to
 *            currentState.
 * @param types Array containing Type of the field in the object, corresponding to currentState.
 * @param state SyncItemState, e.g. NEW, UPDATED, DELETED
 * @param id Value of the identifier for this entity
 */
protected void packageObject(OpenmrsObject entity, Object[] currentState, String[] propertyNames, Type[] types,
        Serializable id, SyncItemState state) throws SyncException {

    String objectUuid = null;
    String originalRecordUuid = null;
    Set<String> transientProps = null;
    String infoMsg = null;

    ClassMetadata data = null;
    String idPropertyName = null;
    org.hibernate.tuple.IdentifierProperty idPropertyObj = null;

    // The container of values to be serialized:
    // Holds tuples of <property-name> -> {<property-type-name>,
    // <property-value as string>}
    HashMap<String, PropertyClassValue> values = new HashMap<String, PropertyClassValue>();

    try {
        objectUuid = entity.getUuid();

        // pull-out sync-network wide change id for the sync *record* (not the entity itself),
        // if one was already assigned (i.e. this change is coming from some other server)
        originalRecordUuid = getSyncRecord().getOriginalUuid();

        if (log.isDebugEnabled()) {
            // build up a starting msg for all logging:
            StringBuilder sb = new StringBuilder();
            sb.append("In PackageObject, entity type:");
            sb.append(entity.getClass().getName());
            sb.append(", entity uuid:");
            sb.append(objectUuid);
            sb.append(", originalUuid uuid:");
            sb.append(originalRecordUuid);
            log.debug(sb.toString());
        }

        // Transient properties are not serialized.
        transientProps = new HashSet<String>();
        for (Field f : entity.getClass().getDeclaredFields()) {
            if (Modifier.isTransient(f.getModifiers())) {
                transientProps.add(f.getName());
                if (log.isDebugEnabled())
                    log.debug("The field " + f.getName() + " is transient - so we won't serialize it");
            }
        }

        /*
         * Retrieve metadata for this type; we need to determine what is the
         * PK field for this type. We need to know this since PK values are
         * *not* journalled; values of primary keys are assigned where
         * physical DB records are created. This is so to avoid issues with
         * id collisions.
         *
         * In case of <generator class="assigned" />, the Identifier
         * property is already assigned value and needs to be journalled.
         * Also, the prop will *not* be part of currentState,thus we need to
         * pull it out with reflection/metadata.
         */
        data = getSessionFactory().getClassMetadata(entity.getClass());
        if (data.hasIdentifierProperty()) {
            idPropertyName = data.getIdentifierPropertyName();
            idPropertyObj = ((org.hibernate.persister.entity.AbstractEntityPersister) data).getEntityMetamodel()
                    .getIdentifierProperty();

            if (id != null && idPropertyObj.getIdentifierGenerator() != null
                    && (idPropertyObj.getIdentifierGenerator() instanceof org.hibernate.id.Assigned
                    //   || idPropertyObj.getIdentifierGenerator() instanceof org.openmrs.api.db.hibernate.NativeIfNotAssignedIdentityGenerator
                    )) {
                // serialize value as string
                values.put(idPropertyName, new PropertyClassValue(id.getClass().getName(), id.toString()));
            }
        } else if (data.getIdentifierType() instanceof EmbeddedComponentType) {
            // if we have a component identifier type (like AlertRecipient),
            // make
            // sure we include those properties
            EmbeddedComponentType type = (EmbeddedComponentType) data.getIdentifierType();
            for (int i = 0; i < type.getPropertyNames().length; i++) {
                String propertyName = type.getPropertyNames()[i];
                Object propertyValue = type.getPropertyValue(entity, i, org.hibernate.EntityMode.POJO);
                addProperty(values, entity, type.getSubtypes()[i], propertyName, propertyValue, infoMsg);
            }
        }

        /*
         * Loop through all the properties/values and put in a hash for
         * duplicate removal
         */
        for (int i = 0; i < types.length; i++) {
            String typeName = types[i].getName();
            if (log.isDebugEnabled())
                log.debug("Processing, type: " + typeName + " Field: " + propertyNames[i]);

            if (propertyNames[i].equals(idPropertyName) && log.isInfoEnabled())
                log.debug(infoMsg + ", Id for this class: " + idPropertyName + " , value:" + currentState[i]);

            if (currentState[i] != null) {
                // is this the primary key or transient? if so, we don't
                // want to serialize
                if (propertyNames[i].equals(idPropertyName)
                        || ("personId".equals(idPropertyName) && "patientId".equals(propertyNames[i]))
                        //|| ("personId".equals(idPropertyName) && "userId".equals(propertyNames[i]))
                        || transientProps.contains(propertyNames[i])) {
                    // if (log.isInfoEnabled())
                    log.debug("Skipping property (" + propertyNames[i]
                            + ") because it's either the primary key or it's transient.");

                } else {

                    addProperty(values, entity, types[i], propertyNames[i], currentState[i], infoMsg);
                }
            } else {
                // current state null -- skip
                if (log.isDebugEnabled())
                    log.debug("Field Type: " + typeName + " Field Name: " + propertyNames[i]
                            + " is null, skipped");
            }
        }

        /*
         * Now serialize the data identified and put in the value-map
         */
        // Setup the serialization data structures to hold the state
        Package pkg = new Package();
        String className = entity.getClass().getName();
        Record xml = pkg.createRecordForWrite(className);
        Item entityItem = xml.getRootItem();

        // loop through the map of the properties that need to be serialized
        for (Map.Entry<String, PropertyClassValue> me : values.entrySet()) {
            String property = me.getKey();

            // if we are processing onDelete event all we need is uuid
            if ((state == SyncItemState.DELETED) && (!"uuid".equals(property))) {
                continue;
            }

            try {
                PropertyClassValue pcv = me.getValue();
                appendRecord(xml, entity, entityItem, property, pcv.getClazz(), pcv.getValue());
            } catch (Exception e) {
                String msg = "Could not append attribute. Error while processing property: " + property + " - "
                        + e.getMessage();
                throw (new SyncException(msg, e));
            }
        }

        values.clear(); // Be nice to GC

        if (objectUuid == null)
            throw new SyncException("uuid is null for: " + className + " with id: " + id);

        /*
         * Create SyncItem and store change in SyncRecord kept in
         * ThreadLocal.
         */
        SyncItem syncItem = new SyncItem();
        syncItem.setKey(new SyncItemKey<String>(objectUuid, String.class));
        syncItem.setState(state);
        syncItem.setContent(xml.toStringAsDocumentFragment());
        syncItem.setContainedType(entity.getClass());

        if (log.isDebugEnabled())
            log.debug("Adding SyncItem to SyncRecord");

        getSyncRecord().addItem(syncItem);
        getSyncRecord().addContainedClass(entity.getClass().getName());

        // set the originating uuid for the record: do this once per Tx;
        // else we may end up with empty string
        if (getSyncRecord().getOriginalUuid() == null || "".equals(getSyncRecord().getOriginalUuid())) {
            getSyncRecord().setOriginalUuid(originalRecordUuid);
        }
    } catch (SyncException ex) {
        log.error("Journal error\n", ex);
        throw (ex);
    } catch (Exception e) {
        log.error("Journal error\n", e);
        throw (new SyncException("Error in interceptor, see log messages and callstack.", e));
    }

    return;
}

From source file:com.sm.query.utils.QueryUtils.java

/**
 * @param field//  w ww  .j  av  a  2  s  .  com
 * @return true - for write able field
 */
public static boolean isSkipField(Field field) {
    int modifier = field.getModifiers();
    if (Modifier.isFinal(modifier) || Modifier.isStatic(modifier) || Modifier.isNative(modifier)
            || Modifier.isTransient(modifier))
        return true;
    else
        return false;
}

From source file:org.dcm4che3.conf.core.misc.DeepEquals.java

/**
 * Get all non static, non transient, fields of the passed in class.
 * The special this$ field is also not returned.  The result is cached
 * in a static ConcurrentHashMap to benefit execution performance.
 * @param c Class instance/*ww  w . j a  v a  2s.c  o m*/
 * @return Collection of only the fields in the passed in class
 * that would need further processing (reference fields).  This
 * makes field traversal on a class faster as it does not need to
 * continually process known fields like primitives.
 */
public static Collection<Field> getDeepDeclaredFields(Class c) {
    if (_reflectedFields.containsKey(c)) {
        return _reflectedFields.get(c);
    }
    Collection<Field> fields = new ArrayList<Field>();
    Class curr = c;

    while (curr != null) {
        try {
            Field[] local = curr.getDeclaredFields();

            for (Field field : local) {
                if (!field.isAccessible()) {
                    try {
                        field.setAccessible(true);
                    } catch (Exception ignored) {
                    }
                }

                int modifiers = field.getModifiers();
                if (!Modifier.isStatic(modifiers) && !field.getName().startsWith("this$")
                        && !Modifier.isTransient(modifiers)) { // speed up: do not count static fields, not go back up to enclosing object in nested case    
                    fields.add(field);
                }
            }
        } catch (ThreadDeath t) {
            throw t;
        } catch (Throwable ignored) {
        }

        curr = curr.getSuperclass();
    }
    _reflectedFields.put(c, fields);
    return fields;
}

From source file:org.projectforge.database.XmlDump.java

/**
 * @param field/*from  w w w  .  jav  a 2s . c o m*/
 * @return true, if the given field should be compared.
 */
protected boolean accept(final Field field) {
    if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
        // Reject field from inner class.
        return false;
    }
    if (field.getName().equals("handler") == true) {
        // Handler of Javassist proxy should be ignored.
        return false;
    }
    if (Modifier.isTransient(field.getModifiers()) == true) {
        // transients.
        return false;
    }
    if (Modifier.isStatic(field.getModifiers()) == true) {
        // transients.
        return false;
    }
    return true;
}

From source file:org.apache.openjpa.persistence.PersistenceMetaDataDefaults.java

protected boolean isDefaultPersistent(ClassMetaData meta, Member member, String name, boolean ignoreTransient) {
    int mods = member.getModifiers();
    if (Modifier.isTransient(mods))
        return false;
    int access = meta.getAccessType();

    if (member instanceof Field) {
        // If mixed or unknown, default property access, keep explicit 
        // field members
        if (AccessCode.isProperty(access)) {
            if (!isAnnotatedAccess(member, AccessType.FIELD))
                return false;
        }/*from  ww w.  j  a  va  2s  . c o  m*/
    } else if (member instanceof Method) {
        // If mixed or unknown, field default access, keep explicit property
        // members
        if (AccessCode.isField(access)) {
            if (!isAnnotatedAccess(member, AccessType.PROPERTY))
                return false;
        }
        try {
            // check for setters for methods
            Method setter = (Method) AccessController.doPrivileged(J2DoPrivHelper.getDeclaredMethodAction(
                    meta.getDescribedType(), "set" + StringUtils.capitalize(name),
                    new Class[] { ((Method) member).getReturnType() }));
            if (setter == null && !isAnnotatedTransient(member)) {
                logNoSetter(meta, name, null);
                return false;
            }
        } catch (Exception e) {
            // e.g., NoSuchMethodException
            if (!isAnnotatedTransient(member))
                logNoSetter(meta, name, e);
            return false;
        }
    }

    PersistenceStrategy strat = getPersistenceStrategy(null, member, ignoreTransient);
    if (strat == null) {
        warn(meta, _loc.get("no-pers-strat", name));
        return false;
    } else if (strat == PersistenceStrategy.TRANSIENT) {
        return false;
    } else {
        return true;
    }
}

From source file:org.projectforge.core.ConfigXml.java

/**
 * Returns whether or not to append the given <code>Field</code>.
 * <ul>//from  ww  w  .  j  av a  2  s  .c  o m
 * <li>Ignore transient fields
 * <li>Ignore static fields
 * <li>Ignore inner class fields</li>
 * </ul>
 * 
 * @param field The Field to test.
 * @return Whether or not to consider the given <code>Field</code>.
 */
protected static boolean accept(final Field field) {
    if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
        // Reject field from inner class.
        return false;
    }
    if (Modifier.isTransient(field.getModifiers()) == true) {
        // transients.
        return false;
    }
    if (Modifier.isStatic(field.getModifiers()) == true) {
        // transients.
        return false;
    }
    return true;
}

From source file:wwutil.jsoda.Jsoda.java

private void validateFields(Class modelClass, Field idField, Field rangeField) {
    if (idField == null)
        throw new ValidationException("Missing the annotated @Id field in the model class.");

    if (Modifier.isTransient(idField.getModifiers()) || ReflectUtil.hasAnnotation(idField, Transient.class))
        throw new ValidationException(
                "The @Key field cannot be transient or annotated with Transient in the model class.");

    if (rangeField != null && (Modifier.isTransient(idField.getModifiers())
            || Modifier.isTransient(rangeField.getModifiers())))
        throw new ValidationException("The @Key field cannot be transient in the model class.");

    if (ReflectUtil.hasAnnotation(idField, S3Field.class))
        throw new ValidationException("The @Key field cannot be @S3Field in the model class.");

    if (rangeField != null && ReflectUtil.hasAnnotation(rangeField, S3Field.class))
        throw new ValidationException("The @Key field cannot be @S3Field in the model class.");

    if (idField.getType() != String.class && idField.getType() != Integer.class
            && idField.getType() != int.class && idField.getType() != Long.class
            && idField.getType() != long.class)
        throw new ValidationException("The @Id field can only be String, Integer, or Long.");

}

From source file:de.javakaffee.web.msm.integration.TestUtils.java

public static void assertEqualDeclaredFields(final Class<? extends Object> clazz, final Object one,
        final Object another, final Map<Object, Object> alreadyChecked) {
    for (final Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);//from  w  ww  .  j a v  a  2 s .c  o m
        if (!Modifier.isTransient(field.getModifiers())) {
            try {
                assertDeepEquals(field.get(one), field.get(another), alreadyChecked);
            } catch (final IllegalArgumentException e) {
                throw new RuntimeException(e);
            } catch (final IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}