Example usage for org.hibernate.proxy HibernateProxy getHibernateLazyInitializer

List of usage examples for org.hibernate.proxy HibernateProxy getHibernateLazyInitializer

Introduction

In this page you can find the example usage for org.hibernate.proxy HibernateProxy getHibernateLazyInitializer.

Prototype

public LazyInitializer getHibernateLazyInitializer();

Source Link

Document

Get the underlying lazy initialization handler.

Usage

From source file:org.openvpms.component.business.dao.hibernate.im.common.HibernateHelper.java

License:Open Source License

/**
 * Determines if a (possibly) persistent object is uninitialised.
 *
 * @param object the object/*from  w w  w  .  jav  a 2  s . co  m*/
 * @return <tt>true</tt> if the object is uninitialised,
 *         otherwise <tt>false</tt>
 */
public static boolean isUnintialised(Object object) {
    if (object instanceof HibernateProxy) {
        HibernateProxy proxy = (HibernateProxy) object;
        LazyInitializer init = proxy.getHibernateLazyInitializer();
        return init.isUninitialized();
    }
    return false;
}

From source file:org.springframework.flex.core.io.HibernateProxyConverter.java

License:Apache License

/**
 * /*w  w  w  . j a v a  2  s  . co m*/
 * {@inheritDoc}
 */
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
    Assert.isInstanceOf(HibernateProxy.class, source, "Expected an instance of HibernateProxy to convert");
    Assert.isAssignable(HibernateProxy.class, sourceType.getType(),
            "Expected a subclass of HibernateProxy for the source type");
    HibernateProxy proxy = (HibernateProxy) source;
    if (targetType instanceof PropertyTypeDescriptor || targetType.getField() != null) {
        if (!Hibernate.isInitialized(proxy)) {
            return null;
        }
    }
    return proxy.getHibernateLazyInitializer().getImplementation();
}

From source file:org.springframework.flex.hibernate3.HibernateProxyConverter.java

License:Apache License

/**
 * //  w ww .j  av  a  2s  .  c  o  m
 * {@inheritDoc}
 */
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
    Assert.isInstanceOf(HibernateProxy.class, source, "Expected an instance of HibernateProxy to convert");
    Assert.isAssignable(HibernateProxy.class, sourceType.getType(),
            "Expected a subclass of HibernateProxy for the source type");
    HibernateProxy proxy = (HibernateProxy) source;
    boolean isField = targetType.getSource() instanceof Field;
    boolean isProperty = targetType.getSource() instanceof MethodParameter
            && BeanUtils.findPropertyForMethod(((MethodParameter) targetType.getSource()).getMethod()) != null;

    if (isField || isProperty) {
        if (!Hibernate.isInitialized(proxy)) {
            return null;
        }
    }
    return proxy.getHibernateLazyInitializer().getImplementation();
}

From source file:play.modules.yml.YmlExtractorUtil.java

License:Open Source License

/**
 * Method to convert an object to YmlObject.
 * /*ww w.  ja  v  a2 s.  c om*/
 * @param jpaSupport
 * @return
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws ParseException
 * @throws NoSuchMethodException
 * @throws SecurityException
 * @throws InvocationTargetException
 */
public static YmlObject object2YmlObject(JPABase jpaBase)
        throws IllegalArgumentException, IllegalAccessException, ParseException, SecurityException,
        NoSuchMethodException, InvocationTargetException {
    // Init YAML
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    options.setCanonical(false);
    Yaml yaml = new Yaml(options);

    // Initialization of YmlObject
    YmlObject ymlObject = new YmlObject();
    ymlObject.setId(getObjectId(jpaBase));

    // String value for the object
    String stringObject = "\n" + getObjectClassName(jpaBase) + "(" + getObjectId(jpaBase) + "):\n";
    Logger.info("Generate YML for class id :" + getObjectId(jpaBase) + "("
            + jpaBase.getClass().getFields().length + "fields)");

    // if class is a javassist class
    if (jpaBase.getClass().getCanonicalName().contains("_$$_")) {
        Hibernate.initialize(jpaBase);
        HibernateProxy proxy = (HibernateProxy) jpaBase;
        jpaBase = (JPABase) proxy.getHibernateLazyInitializer().getImplementation();
    }

    for (java.lang.reflect.Field field : jpaBase.getClass().getFields()) {
        Map<String, Object> data = new HashMap<String, Object>();

        String name = field.getName();

        if (!name.equals("id") && !name.equals("willBeSaved") && !isFieldHasMappedByInAnnotation(field)) {

            Boolean valueIsSet = Boolean.FALSE;
            Logger.debug("Generated field " + name);

            if (field.get(jpaBase) != null) {

                // if field is a List
                if (List.class.isInstance(field.get(jpaBase))) {
                    Logger.debug("Field " + name + " type is List");
                    List myList = (List) field.get(jpaBase);
                    if (!myList.isEmpty() && myList.size() > 0) {
                        String[] tmpValues = new String[myList.size()];
                        for (int i = 0; i < myList.size(); i++) {
                            tmpValues[i] = getObjectId(myList.get(i));
                            // if myObj is an entity, we add it to children
                            if (GenericModel.class.isInstance(myList.get(i))
                                    && !field.isAnnotationPresent(OneToMany.class)) {
                                ymlObject.getChildren().add(getObjectId(myList.get(i)));
                            }
                        }
                        data.put(name, tmpValues);
                    }
                    valueIsSet = Boolean.TRUE;
                }

                // if field is a Map
                if (Map.class.isInstance(field.get(jpaBase))) {
                    Logger.debug("Field " + name + " type is Map");
                    Map myMap = (Map) field.get(jpaBase);
                    if (myMap != null && myMap.size() > 0) {
                        String[] tmpValues = new String[myMap.size()];
                        Iterator it = myMap.entrySet().iterator();
                        int i = 0;
                        while (it.hasNext()) {
                            Object myObj = it.next();
                            tmpValues[i] = getObjectId(myObj);
                            // if myObj is an entity, we add it to children
                            if (myObj != null && GenericModel.class.isInstance(myObj)
                                    && !field.isAnnotationPresent(OneToMany.class)) {
                                if (getObjectId(myObj) != null) {
                                    ymlObject.getChildren().add(getObjectId(myObj));
                                }
                            }
                            i++;
                        }
                        data.put(name, tmpValues);
                    }
                    valueIsSet = Boolean.TRUE;
                }

                // if field is a Set
                if (Set.class.isInstance(field.get(jpaBase))) {
                    Logger.debug("Field " + name + " type is Set");
                    Set mySet = (Set) field.get(jpaBase);
                    if (mySet != null && mySet.size() > 0) {
                        String[] tmpValues = new String[mySet.size()];
                        Iterator it = mySet.iterator();
                        int i = 0;
                        while (it.hasNext()) {
                            Object myObj = it.next();
                            tmpValues[i] = getObjectId(myObj);
                            // if myObj is an entity, we add it to children
                            if (myObj != null && GenericModel.class.isInstance(myObj)
                                    && !field.isAnnotationPresent(OneToMany.class)) {
                                if (getObjectId(myObj) != null) {
                                    ymlObject.getChildren().add(getObjectId(myObj));
                                }
                            }
                            i++;
                        }
                        data.put(name, tmpValues);
                    }
                    valueIsSet = Boolean.TRUE;
                }

                // if Lob annotation, then bigtext
                if (field.isAnnotationPresent(Lob.class)) {
                    Logger.debug("Field " + name + " type is a Lob");
                    if (field.get(jpaBase) != null) {
                        data.put(name, field.get(jpaBase).toString());
                    }
                    valueIsSet = Boolean.TRUE;
                }

                // if field is an object that extend Model
                if (jpaBase != null && GenericModel.class.isInstance(field.get(jpaBase))) {
                    Logger.debug("Field " + name + " type is a Model");
                    ymlObject.getChildren().add(getObjectId(field.get(jpaBase)));
                    data.put(name, getObjectId(field.get(jpaBase)));
                    valueIsSet = Boolean.TRUE;
                }

                // if field is a date
                if (Date.class.isInstance(field.get(jpaBase))) {
                    Logger.debug("Field " + name + " type is Date");
                    // In case of temporal JPA annotation
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if (field.getAnnotation(Temporal.class) != null) {
                        Temporal temporal = field.getAnnotation(Temporal.class);
                        switch (temporal.value()) {
                        case DATE:
                            sdf = new SimpleDateFormat("yyyy-MM-dd");
                            break;
                        case TIME:
                            sdf = new SimpleDateFormat("hh:mm:ss");
                            break;
                        case TIMESTAMP:
                            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            break;
                        }
                    }

                    Date myDate = (Date) sdf.parse(field.get(jpaBase).toString());
                    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                    data.put(name, sd.format(myDate));
                    valueIsSet = Boolean.TRUE;
                }

                // if field is a calendar
                if (Calendar.class.isInstance(field.get(jpaBase))) {
                    Logger.debug("Field " + name + " type is Calendar");
                    Calendar cal = (Calendar) field.get(jpaBase);
                    Date date = cal.getTime();
                    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                    data.put(name, sd.format(date));
                    valueIsSet = Boolean.TRUE;
                }

                // if field is an Embedded
                if (field.isAnnotationPresent(Embedded.class)) {
                    Logger.debug("Field " + name + " is an embedded");
                    data.put(field.getName(), field.get(jpaBase));
                    valueIsSet = Boolean.TRUE;
                }

                // otherwise ...
                if (!valueIsSet) {
                    Logger.debug("Field " + name + " type is Basic");
                    String tmpValue = "" + field.get(jpaBase);
                    data.put(name, tmpValue);
                    valueIsSet = Boolean.TRUE;
                }

                if (valueIsSet && !data.isEmpty()) {
                    // yml indentation
                    String value = yaml.dump(data).replaceAll("^", TAB);
                    // a little hack for scalar ... I have to find a
                    // better solution
                    value = value.replaceAll("- ", TAB + "- ");
                    // a little hack for tab String empty
                    stringObject += value;
                }
            }
        }
    }
    ymlObject.setYmlValue(stringObject);

    return ymlObject;
}

From source file:stroom.entity.server.util.BaseEntityDeProxyProcessor.java

License:Apache License

/**
 * Do the work of processing the object and it's children.
 *///w w  w. j a  v a 2 s  .  com
private Object doProcess(final Object source) throws IntrospectionException, InvocationTargetException,
        InstantiationException, IllegalAccessException {
    Object target = source;

    // Walk unless we say otherwise
    boolean walk = true;

    // Convert all collections to standard collection types.
    if (source instanceof Collection || source instanceof Map) {
        target = replaceCollectionType(source);
    }

    // Are we dealing with a proxy?
    if (target instanceof HibernateProxy) {
        if (!(target instanceof BaseEntity)) {
            throw new RuntimeException("We are expecting all lazy objects to be BaseEntities");
        }
        // Return back our own proxy for the hibernate one that just returns
        // the id. We create a real base entity with just the ID set. The
        // client an then choose to load this up using the loadXYZ API's on
        // the service layer
        BaseEntity replacement = null;
        try {
            final HibernateProxy hibernateProxy = (HibernateProxy) target;
            final LazyInitializer lazyInitializer = hibernateProxy.getHibernateLazyInitializer();
            if (lazyInitializer != null) {
                if (lazyInitializer instanceof AbstractLazyInitializer) {
                    final AbstractLazyInitializer abstractLazyInitializer = (AbstractLazyInitializer) lazyInitializer;
                    if (!abstractLazyInitializer.isUninitialized()) {
                        replacement = (BaseEntity) abstractLazyInitializer.getImplementation();
                    }
                }

                if (replacement == null) {
                    final String entityName = lazyInitializer.getEntityName();
                    final Class<?> clazz = Class.forName(entityName);
                    replacement = (BaseEntity) clazz.newInstance();
                    final long lazyId = ((BaseEntity) source).getId();
                    replacement.setStub(lazyId);

                    // No Point in walking the child objects.
                    walk = false;
                }
            }
        } catch (final ClassNotFoundException e) {
            LOGGER.error(e, e);
        }

        target = replacement;
    }

    if (target instanceof HasEntity<?>) {
        final HasEntity<?> entityRow = (HasEntity<?>) target;

        if (entityRow.getEntity() != null) {
            doProcess(entityRow.getEntity());
        }
    } else {
        // Only walk children of base entities
        if (walk) {
            if (target instanceof BaseEntity) {
                final BaseEntity child = (BaseEntity) target;
                final BaseEntity objectDone = objectsDone.get(child);

                // Here is check if we are on a node that we have already
                // processed (but it was not a JPA PROXY thus a STUB)
                if (objectDone != null && !objectDone.isStub()) {
                    // Already done this one and it was not a stub
                    target = objectsDone.get(child);

                } else {
                    // If is was a stub replace with the real thing
                    objectsDone.put(child, child);

                    // One last check that we don't walk our dummy entities
                    // We know this as they will have the id set but not the
                    // version
                    if (!child.isStub()) {
                        // Now Walk the fields of the class.
                        walkChildren(child);
                    }
                }
            } else if (target instanceof SharedObject) {
                // Now Walk the fields of the class.... some kind of front
                // end holder
                walkChildren(target);
            }
        }
    }

    if (target instanceof HasPassword) {
        final HasPassword hasPassword = (HasPassword) target;
        if (hasPassword.isPassword()) {
            if (incoming) {
                // Password not changed!
                if (PASSWORD_MASK.equals(hasPassword.getValue())) {
                    throw new EntityServiceException("Password not set");
                }
            } else {
                // Outgoing
                hasPassword.setValue(PASSWORD_MASK);
            }
        }
    }

    return target;
}

From source file:to.etc.domui.hibernate.model.HibernateModelCopier.java

License:Open Source License

/**
 * Determine the object state using internal Hibernate data structures. Code was mostly stolen from {@link org.hibernate.event.internal.DefaultFlushEntityEventListener#dirtyCheck(FlushEntityEvent)} ()}
 *///from  ww w  . jav a 2 s.  com
@Override
protected QPersistentObjectState getObjectState(QDataContext dc, Object instance) throws Exception {
    if (!(dc instanceof BuggyHibernateBaseContext))
        throw new IllegalArgumentException("The QDataContext type is not a Hibernate context");
    SessionImpl ses = (SessionImpl) ((BuggyHibernateBaseContext) dc).getSession();

    PersistenceContext pc = ses.getPersistenceContext(); // The root of all hibernate persistent data
    EntityEntry ee = pc.getEntry(instance);
    if (ee == null) {
        /*
         * Incredible but true: proxies are not stored as entries in the hibernate session - the backing objects
         * of the proxies are. This means that a prime invariant does NOT hold for proxies: the SAME database object
         * in the SAME object, where one is retrieved using a lazy association and the other through Session.load,
         * ARE NOT == (the same reference): the first one points to the proxy, the second one to the instance itself.
         * This is another huge design blunder and again a pitfall: you cannot use == EVEN WHEN IN A SINGLE SESSION!
         * This problem is most probably caused by the enormous design blunder that separates the proxy instance from
         * the actual instance.
         *
         * In here it means we need to check if the object is indeed a proxy, and retry with the original object.
         */
        if (instance instanceof HibernateProxy) { // Ohh Horror of horrors.
            HibernateProxy hp = (HibernateProxy) instance;
            Object ainstance = hp.getHibernateLazyInitializer().getImplementation();
            ee = pc.getEntry(ainstance);

            String clz = instance.getClass().getName();
            if (clz.contains("Relation"))
                System.out.println("DEBUG 2nd try for " + MetaManager.identify(instance));

            if (ee == null) {
                //-- DEBUG
                //               if(clz.contains("Relation")) {
                //                  //-- The failing relation record.
                //                  System.out.println("DEBUG Examining " + MetaManager.identify(instance));
                //
                //                  Object pk = MetaManager.getPrimaryKey(instance);
                //                  Map<Object, Object> eemap = pc.getEntityEntries();
                //                  for(Iterator<Object> it = ((IdentityMap) eemap).keyIterator(); it.hasNext();) {
                //                     Object ent = it.next();
                //                     if(ent.getClass().getName().contains("Relation")) {
                //                        //-- Probable match. Get PK's and compare
                //                        Object epk = MetaManager.getPrimaryKey(ent);
                //                        if(epk.equals(pk)) {
                //                           System.out.println("Primary key matches " + ent);
                //                           ee = pc.getEntry(ent);
                //                           System.out.println("EntityEntry: " + ee);
                //                        }
                //                     }
                //                  }
                //               }

                System.out.println("    state for " + MetaManager.identify(instance) + ": null in session");
                //-- ENDDEBUG

                return QPersistentObjectState.UNKNOWN;
            }
        }
    }
    if (null == ee)
        throw new IllegalStateException("current EntityEntry is null- that cannot happen?");

    System.out.println("    state for " + MetaManager.identify(instance) + ": exists=" + ee.isExistsInDatabase()
            + ", state=" + ee.getStatus());

    if (ee.getStatus() == Status.DELETED)
        return QPersistentObjectState.DELETED;
    if (!ee.isExistsInDatabase())
        return QPersistentObjectState.NEW;

    //-- Let's do a check.
    Object[] snapshot = ee.getLoadedState(); // Get snapshot @ load time
    if (snapshot == null)
        return QPersistentObjectState.NEW;
    Object[] values = ee.getPersister().getPropertyValues(instance); // Load current instance's values.

    //-- Delegate to any interceptor.
    int[] dirtyProperties = ses.getInterceptor().findDirty(instance, ee.getId(), values, snapshot,
            ee.getPersister().getPropertyNames(), ee.getPersister().getPropertyTypes());
    if (dirtyProperties == null) {
        //-- Do it ourselves.
        dirtyProperties = ee.getPersister().findDirty(values, snapshot, instance, ses);
    }
    return dirtyProperties == null || dirtyProperties.length == 0 ? QPersistentObjectState.PERSISTED
            : QPersistentObjectState.DIRTY;
}

From source file:tools.xor.util.ClassUtil.java

License:Apache License

public static Object getTargetObject(Object object) {
    Object result = object;//w w w.j av a  2 s .  co m

    // Hibernate based implementation, safe to initialize the proxy since we need its data
    // Allow user to override this behavior
    if (object instanceof HibernateProxy) {
        while (object instanceof HibernateProxy) {
            HibernateProxy proxy = (HibernateProxy) object;
            LazyInitializer li = proxy.getHibernateLazyInitializer();
            object = li.getImplementation();
        }
        return object;
    } else if (AopUtils.isJdkDynamicProxy(object)) {
        try {
            return ((Advised) object).getTargetSource().getTarget();
        } catch (Exception e) {
            throw wrapRun(e);
        }
    }

    return result;
}

From source file:ubic.gemma.persistence.util.EntityUtils.java

License:Apache License

/**
 * Expert only. Must be called within a session? Not sure why this is necessary. Obtain the implementation for a
 * proxy. If target is not an instanceof HibernateProxy, target is returned.
 *
 * @param target The object to be un-proxied.
 * @return the underlying implementation.
 *///  ww  w . j  a v a2 s  .co m
public static Object getImplementationForProxy(Object target) {
    if (EntityUtils.isProxy(target)) {
        HibernateProxy proxy = (HibernateProxy) target;
        return proxy.getHibernateLazyInitializer().getImplementation();
    }
    return target;
}

From source file:uk.ac.bbsrc.tgac.miso.core.util.LimsUtils.java

License:Open Source License

@SuppressWarnings("unchecked")
public static <T> T deproxify(T from) {
    if (from instanceof HibernateProxy) {
        HibernateProxy proxy = (HibernateProxy) from;
        from = (T) proxy.getHibernateLazyInitializer().getImplementation();
    }/*from w  ww  .  j a  va 2s.  co m*/
    return from;
}

From source file:woko.hibernate.HibernateStore.java

License:Apache License

@SuppressWarnings("unchecked")
protected <T> T deproxyInstance(T maybeProxy) {
    if (maybeProxy instanceof HibernateProxy) {
        HibernateProxy proxy = (HibernateProxy) maybeProxy;
        LazyInitializer i = proxy.getHibernateLazyInitializer();
        return (T) i.getImplementation();
    }//from   w  w w .  j  a va2 s .  co  m
    return maybeProxy;
}