Example usage for org.springframework.beans PropertyAccessorFactory forDirectFieldAccess

List of usage examples for org.springframework.beans PropertyAccessorFactory forDirectFieldAccess

Introduction

In this page you can find the example usage for org.springframework.beans PropertyAccessorFactory forDirectFieldAccess.

Prototype

public static ConfigurablePropertyAccessor forDirectFieldAccess(Object target) 

Source Link

Document

Obtain a PropertyAccessor for the given target object, accessing properties in direct field style.

Usage

From source file:org.jdal.dao.jpa.JpaUtils.java

/**
 * Initialize collection//from   w w w  . j  a  va 2  s  .  c  om
 * @param em
 * @param entity
 * @param a
 * @param i
 */
@SuppressWarnings("rawtypes")
private static void intializeCollection(EntityManager em, Object entity, Object attached, Attribute a,
        int depth) {
    PropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(attached);
    Collection c = (Collection) accessor.getPropertyValue(a.getName());

    for (Object o : c)
        initialize(em, o, depth - 1);

    PropertyAccessorFactory.forDirectFieldAccess(entity).setPropertyValue(a.getName(), c);
}

From source file:org.web4thejob.orm.PropertyMetadataImpl.java

@Override
@SuppressWarnings("unchecked")
public <T, E extends Entity> T getValue(E entity) {
    if (isOneToManyType()) {
        throw new RuntimeException("cannot call getValue for a Collection property");
    }//from w  ww.  j a  v  a2s  . c om

    if (entity instanceof HibernateProxy) {
        entity = ContextUtil.getMRS().deproxyEntity(entity);
    }

    T value;
    if (!isIdentifier()) {
        value = (T) entityMetadata.getClassMetadata().getPropertyValue(entity, getName());
    } else {
        value = (T) PropertyAccessorFactory.forDirectFieldAccess(entity).getPropertyValue(getName());
    }

    if (value != null && value instanceof HibernateProxy) {
        value = (T) ContextUtil.getMRS().deproxyEntity((Entity) value);
    }

    return value;
}

From source file:org.jdal.dao.jpa.JpaDao.java

/**
 * Null References on one to many and one to one associations.
 * Will only work if association has annotated with a mappedBy attribute.
 * //from   w w  w .  jav  a  2s  .c o  m
 * @param entity entity
 */
private void nullReferences(T entity) {
    EntityType<T> type = em.getMetamodel().entity(getEntityClass());

    if (log.isDebugEnabled())
        log.debug("Null references on entity " + type.getName());

    for (Attribute<?, ?> a : type.getAttributes()) {
        if (PersistentAttributeType.ONE_TO_MANY == a.getPersistentAttributeType()
                || PersistentAttributeType.ONE_TO_ONE == a.getPersistentAttributeType()) {
            Object association = PropertyAccessorFactory.forDirectFieldAccess(entity)
                    .getPropertyValue(a.getName());
            if (association != null) {
                EntityType<?> associationType = null;
                if (a.isCollection()) {
                    associationType = em.getMetamodel()
                            .entity(((PluralAttribute<?, ?, ?>) a).getBindableJavaType());
                } else {
                    associationType = em.getMetamodel().entity(a.getJavaType());

                }

                String mappedBy = JpaUtils.getMappedBy(a);
                if (mappedBy != null) {
                    Attribute<?, ?> aa = associationType.getAttribute(mappedBy);
                    if (PersistentAttributeType.MANY_TO_ONE == aa.getPersistentAttributeType()) {
                        if (log.isDebugEnabled()) {
                            log.debug("Null ManyToOne reference on " + associationType.getName() + "."
                                    + aa.getName());
                        }
                        for (Object o : (Collection<?>) association) {
                            PropertyAccessorFactory.forDirectFieldAccess(o).setPropertyValue(aa.getName(),
                                    null);
                        }
                    } else if (PersistentAttributeType.ONE_TO_ONE == aa.getPersistentAttributeType()) {
                        if (log.isDebugEnabled()) {
                            log.debug("Null OneToOne reference on " + associationType.getName() + "."
                                    + aa.getName());
                        }
                        PropertyAccessorFactory.forDirectFieldAccess(association).setPropertyValue(aa.getName(),
                                null);
                    }
                }
            }
        }
    }
}

From source file:org.jdal.dao.jpa.JpaDao.java

/**
 * Test if entity is New//from   ww  w  .j a va  2  s. co  m
 * @param entity
 * @return true if entity is new, ie not detached
 */
@SuppressWarnings("unchecked")
protected boolean isNew(T entity) {
    SingularAttribute<?, ?> id = getIdAttribute(entity.getClass());
    // try field
    PropertyAccessor pa = PropertyAccessorFactory.forDirectFieldAccess(entity);
    PK key = (PK) pa.getPropertyValue(id.getName());
    if (key == null)
        key = (PK) PropertyAccessorFactory.forBeanPropertyAccess(entity).getPropertyValue(id.getName());

    return key == null || !exists(key, entity.getClass());
}

From source file:org.web4thejob.orm.PropertyMetadataImpl.java

@Override
public <E extends Entity> void setValue(E entity, Object value) {
    if (!identifier) {
        entityMetadata.getClassMetadata().setPropertyValue(entity, getName(), value);
    } else {//w ww. ja va  2 s .  c  o  m
        PropertyAccessorFactory.forDirectFieldAccess(entity).setPropertyValue(getName(), value);
    }
}

From source file:com.nestedbird.modules.formparser.FormParse.java

/**
 * Write the value to the existingEntity field with the name of key
 *
 * @param <T>            Type of the entity
 * @param existingEntity The entity we are changing
 * @param key            The key we are changing
 * @param value          The new value//from w ww  .  j av a 2  s  .co m
 */
private <T extends BaseEntity> void writeToEntity(T existingEntity, String key, Object value) {
    final PropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(existingEntity);

    if (accessor.getPropertyType(key) != null) {
        try {
            if (value.getClass().equals(JSONObject.class) && ((JSONObject) value).has("_isMap")
                    && ((JSONObject) value).get("_isMap").equals(true)) {
                writeArrayMapToEntity(accessor, key, (JSONObject) value);
            } else if (value.getClass().equals(JSONObject.class)) {
                writeObjectToEntity(accessor, key, (JSONObject) value);
            } else if (value.getClass().equals(JSONArray.class)) {
                writeArrayToEntity(accessor, key, (JSONArray) value);
            } else if (isFieldValid(accessor, key, existingEntity.getClass())) {
                writeValueToEntity(accessor, key, value);
            }
        } catch (JSONException e) {
            logger.info("[FormParse] [writeToEntity] Unable To Process JSON", e);
        }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.maltparser.MaltParser.java

@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);

    logger = getContext().getLogger();/*from w w w .  j  a v  a2  s. c  o m*/

    try {
        workingDir = File.createTempFile("maltparser", ".tmp");
        workingDir.delete();
        workingDir.mkdirs();
        workingDir.deleteOnExit();
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }

    modelProvider = new ModelProviderBase<MaltParserService>() {
        private MaltParserService parser;

        {
            setContextObject(MaltParser.this);

            setDefault(ARTIFACT_ID, "${groupId}.maltparser-model-parser-${language}-${variant}");
            setDefault(VARIANT, "linear");

            setDefault(LOCATION, "classpath:/${package}/lib/parser-${language}-${variant}.mco");

            setOverride(LOCATION, modelLocation);
            setOverride(LANGUAGE, language);
            setOverride(VARIANT, variant);
        }

        @Override
        protected MaltParserService produceResource(URL aUrl) throws IOException {
            if (parser != null) {
                // Terminates the parser model
                try {
                    parser.terminateParserModel();
                    parser = null;
                } catch (MaltChainedException e) {
                    logger.log(Level.SEVERE,
                            "MaltParser exception while terminating parser model: " + e.getMessage());
                }
            }

            try {
                // However, Maltparser is not happy at all if the model file does not have the right
                // name, so we are forced to create a temporary directory and place the file there.
                File modelFile = new File(workingDir, getRealName(aUrl));
                if (!modelFile.exists()) {
                    InputStream is = null;
                    OutputStream os = null;
                    try {
                        is = aUrl.openStream();
                        os = new FileOutputStream(modelFile);
                        IOUtils.copy(is, os);
                        modelFile.deleteOnExit();
                    } finally {
                        IOUtils.closeQuietly(is);
                        IOUtils.closeQuietly(os);
                    }
                }

                // Maltparser has a very odd way of finding out which command line options it supports.
                // By manually initializing the OptionManager before Maltparser tries it, we can work
                // around Maltparsers' own broken code.
                if (OptionManager.instance().getOptionContainerIndices().size() == 0) {
                    OptionManager.instance().loadOptionDescriptionFile(
                            MaltParserService.class.getResource("/appdata/options.xml"));
                    OptionManager.instance().generateMaps();
                }

                // Ok, now we can finally initialize the parser
                parser = new MaltParserService();
                parser.initializeParserModel("-w " + workingDir + " -c " + modelFile.getName() + " -m parse");
                // parser.initializeParserModel("-u " + modelUrl.toString() + " -m parse");

                Properties metadata = getResourceMetaData();

                PropertyAccessor paDirect = PropertyAccessorFactory.forDirectFieldAccess(parser);
                SingleMalt singleMalt = (SingleMalt) paDirect.getPropertyValue("singleMalt");

                SingletonTagset posTags = new SingletonTagset(POS.class, metadata.getProperty("pos.tagset"));
                SymbolTable posTagTable = singleMalt.getSymbolTables().getSymbolTable("POSTAG");
                for (int i : posTagTable.getCodes()) {
                    posTags.add(posTagTable.getSymbolCodeToString(i));
                }
                addTagset(posTags);

                SingletonTagset depTags = new SingletonTagset(Dependency.class,
                        metadata.getProperty("dependency.tagset"));
                SymbolTable depRelTable = singleMalt.getSymbolTables().getSymbolTable("DEPREL");
                for (int i : depRelTable.getCodes()) {
                    depTags.add(depRelTable.getSymbolCodeToString(i));
                }
                addTagset(depTags);

                if (printTagSet) {
                    getContext().getLogger().log(INFO, getTagset().toString());
                }

                return parser;
            } catch (MaltChainedException e) {
                logger.log(Level.SEVERE,
                        "MaltParser exception while initializing parser model: " + e.getMessage());
                throw new IOException(e);
            }
        }
    };
}