Example usage for org.hibernate Hibernate isInitialized

List of usage examples for org.hibernate Hibernate isInitialized

Introduction

In this page you can find the example usage for org.hibernate Hibernate isInitialized.

Prototype

@SuppressWarnings("SimplifiableIfStatement")
public static boolean isInitialized(Object proxy) 

Source Link

Document

Check if the proxy or persistent collection is initialized.

Usage

From source file:ch.algotrader.cache.CacheTest.java

License:Open Source License

@Test
public void testRefresh() {

    LookupService lookupService = context.getBean(LookupService.class);

    // expect SecurityFamily with Exchange proxied
    SecurityFamily securityFamily = cache.get(SecurityFamilyImpl.class, securityFamilyId1);
    Assert.assertFalse(Hibernate.isInitialized(securityFamily.getExchange()));

    // expect Security / SecurityFamily / Exchange fully initialized
    Security security1 = lookupService.findUnique(SecurityImpl.class, "from SecurityImpl as s " + //
            "left join fetch s.underlying as ul " + //
            "join fetch s.securityFamily as f " + //
            "join fetch f.exchange as ex " + //
            "where s.id = :id", //
            QueryType.HQL, true, new NamedParam("id", securityId1));

    Assert.assertTrue(Hibernate.isInitialized(security1.getSecurityFamily()));
    Assert.assertTrue(Hibernate.isInitialized(security1.getSecurityFamily().getExchange()));
}

From source file:ch.flashcard.HibernateDetachUtility.java

License:Open Source License

private static void nullOutFieldsByAccessors(Object value, Map<Integer, Object> checkedObjects,
        Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType)
        throws Exception {
    // Null out any collections that aren't loaded
    BeanInfo bi = Introspector.getBeanInfo(value.getClass(), Object.class);

    PropertyDescriptor[] pds = bi.getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
        Object propertyValue = null;
        try {//from  w  w w .jav  a 2  s .  c o  m
            propertyValue = pd.getReadMethod().invoke(value);
        } catch (Throwable lie) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Couldn't load: " + pd.getName() + " off of " + value.getClass().getSimpleName(),
                        lie);
            }
        }

        if (!Hibernate.isInitialized(propertyValue)) {
            try {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Nulling out: " + pd.getName() + " off of " + value.getClass().getSimpleName());
                }

                Method writeMethod = pd.getWriteMethod();
                if ((writeMethod != null) && (writeMethod.getAnnotation(XmlTransient.class) == null)) {
                    pd.getWriteMethod().invoke(value, new Object[] { null });
                } else {
                    nullOutField(value, pd.getName());
                }
            } catch (Exception lie) {
                LOG.debug("Couldn't null out: " + pd.getName() + " off of " + value.getClass().getSimpleName()
                        + " trying field access", lie);
                nullOutField(value, pd.getName());
            }
        } else {
            if ((propertyValue instanceof Collection) || ((propertyValue != null)
                    && propertyValue.getClass().getName().startsWith("org.rhq.core.domain"))) {
                nullOutUninitializedFields(propertyValue, checkedObjects, checkedObjectCollisionMap, depth + 1,
                        serializationType);
            }
        }
    }
}

From source file:ch.systemsx.cisd.openbis.generic.shared.util.HibernateUtils.java

License:Apache License

/**
 * Extends {@link Hibernate#isInitialized(Object)} by checking for
 * {@link UnmodifiableCollectionDecorator}.
 *//*from w  ww  .  j  a va 2 s  .  c o  m*/
public final static boolean isInitialized(final Object proxy) {
    return Hibernate.isInitialized(getRealProxy(proxy));
}

From source file:ch.systemsx.cisd.openbis.generic.shared.util.HibernateUtils.java

License:Apache License

/**
 * @return Unproxied <var>proxy</var>.
 *//*from   w w  w. j  a  va2  s  . co  m*/
@SuppressWarnings({ "unchecked" })
public final static <T> T unproxy(final T proxy) {
    if (proxy instanceof HibernateProxy && Hibernate.isInitialized(proxy)) {
        LazyInitializer lazyInitializer = ((HibernateProxy) proxy).getHibernateLazyInitializer();
        SessionImplementor sessionImplementor = lazyInitializer.getSession();
        // check if the given bean still has a session instance attached
        if (sessionImplementor != null) {
            // use the unproxy method of the persistenceContext class
            return (T) sessionImplementor.getPersistenceContext().unproxy(proxy);
        } else {
            // return the wrapped bean instance if there's no active session instance available
            return (T) lazyInitializer.getImplementation();
        }
    } else {
        // not a proxy - nothing to do
        return proxy;
    }
}

From source file:com.abiquo.abiserver.business.hibernate.pojohb.LazyUtils.java

License:Open Source License

/**
 * Get the given object, taking care of initializing it if necessary.
 * /*from   w  w w .  j a  va2  s.  com*/
 * @param obj The object to get.
 * @return The object initialized.
 */
public static <T> T lazyGet(final T obj) {
    // Check wheter the object is a proxy or not
    if (obj != null && !Hibernate.isInitialized(obj)) {
        DAOFactory factory = HibernateDAOFactory.instance();
        boolean participate = factory.isTransactionActive();

        // If we have an open transaction don't open another one
        if (!participate) {
            factory.beginConnection();
        }

        // This method needs the Hibernate Session
        try {
            Hibernate.initialize(obj);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

        // Don't close the transaction if someone else opened it
        if (!participate) {
            factory.endConnection();
        }
    }

    return obj;
}

From source file:com.algoTrader.entity.security.SecurityImpl.java

License:Open Source License

public boolean isOnWatchlist() {

    return Hibernate.isInitialized(getWatchListItems()) && (getWatchListItems().size() != 0);
}

From source file:com.algoTrader.util.CustomToStringStyle.java

License:Open Source License

public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {

    if (value instanceof BaseObject) {
        return;//w w w .  j  a va 2s .c o  m
    } else if (Hibernate.isInitialized(value)) {
        super.append(buffer, fieldName, value, fullDetail);
    }
}

From source file:com.apress.progwt.server.gwt.HibernateFilter.java

License:Apache License

public static Object filter(Object instance) {
    if (instance == null) {
        return instance;
    }//  w ww  .  ja  v a2  s  .c o  m
    if (instance instanceof Date) {
        return new java.util.Date(((java.util.Date) instance).getTime());
    }

    if (instance instanceof PersistentSet) {
        HashSet<Object> hashSet = new HashSet<Object>();
        PersistentSet persSet = (PersistentSet) instance;
        if (persSet.wasInitialized()) {
            hashSet.addAll(persSet);
        }
        return hashSet;
    }
    if (instance instanceof PersistentList) {
        ArrayList<Object> arrayList = new ArrayList<Object>();
        PersistentList persList = (PersistentList) instance;
        if (persList.wasInitialized()) {
            arrayList.addAll(persList);
        }
        return arrayList;
    }
    if (instance instanceof PersistentBag) {
        ArrayList<Object> arrayList = new ArrayList<Object>();
        PersistentBag persBag = (PersistentBag) instance;
        if (persBag.wasInitialized()) {
            arrayList.addAll(persBag);
        }
        return arrayList;
    }
    if (instance instanceof PersistentMap) {
        HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
        PersistentMap persMap = (PersistentMap) instance;
        if (persMap.wasInitialized()) {
            hashMap.putAll(persMap);
        }
        return hashMap;
    }
    if (instance.getClass().getName().contains("CGLIB")) {

        if (Hibernate.isInitialized(instance)) {

            try {
                HibernateProxy hp = (HibernateProxy) instance;
                LazyInitializer li = hp.getHibernateLazyInitializer();
                log.warn("On The Fly initialization: " + li.getEntityName());
                return li.getImplementation();

            } catch (ClassCastException c) {
                log.error("error casting to HibernateProxy " + instance);
                return null;
            }

            // Hibernate.initialize(instance);
            //
            //               
            // log.warn("\nentity: " + cg.getEntityName()
            // + "\nidentifier" + cg.getIdentifier()
            // + "\nimplemenation " + cg.getImplementation());
            //
            // log.warn("On The Fly initialization: " + instance
            // + " now: " + instance.getClass().getName());
            //
            // if (instance instanceof ReallyCloneable) {
            // log.debug(instance.getClass().getName()
            // + " CGLIB Cloning " + instance);
            // return ((ReallyCloneable) instance).clone();
            // } else {
            // log
            // .warn("Initialized, but doesn't implement
            // ReallyCloneable"
            // + instance.getClass()
            // + " "
            // + instance.getClass().getName());
            // throw new CouldntFixCGLIBException(
            // instance.getClass()
            // + " must implement ReallyCloneable if we're to fix
            // it.");
            // }
        } else {
            log.debug("Uninitialized CGLIB");
            return null;
        }
    }

    return instance;
}

From source file:com.apress.progwt.server.web.controllers.ViewUserController.java

License:Apache License

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse arg1)
        throws Exception {

    log.debug("SERVLET PATH: " + req.getServletPath() + " " + req.getPathInfo() + " " + req.getQueryString());

    Map<String, Object> model = getDefaultModel(req);

    String path = req.getPathInfo();

    String[] pathParts = path.split("/");
    log.debug("!path parts " + Arrays.toString(pathParts));

    // "/user/jeff" splits to [,jeff]
    if (pathParts.length < 2) {
        return new ModelAndView(getNotFoundView());
    }//from   w ww .j  av a  2 s  .  co m

    String nickname = pathParts[1];

    User fetchedUser = userService.getUserByNicknameFullFetch(nickname);

    if (log.isDebugEnabled()) {
        log.debug("user u: " + fetchedUser);
        log.debug("isinit user " + Hibernate.isInitialized(fetchedUser));
        log.debug("isinit schools " + Hibernate.isInitialized(fetchedUser.getSchoolRankings()));
        for (Application sap : fetchedUser.getSchoolRankings()) {
            if (!Hibernate.isInitialized(sap)) {
                log.debug("Not initialized");
            }
        }
    }

    if (fetchedUser == null) {
        return new ModelAndView(getNotFoundView(), "message", "Couldn't find user with nickname: " + nickname);
    }
    model.put("viewUser", fetchedUser);

    ModelAndView mav = getMav();
    mav.addAllObjects(model);
    return mav;
}

From source file:com.dell.asm.asmcore.asmmanager.app.rest.DeploymentService.java

License:Open Source License

private Deployment entityToView(DeploymentEntity deploymentEntity, User thisUser) {
    logger.debug("entityToView " + deploymentEntity.getId() + " " + deploymentEntity.getJobId());
    Deployment deployment = new Deployment();
    deployment.setId(deploymentEntity.getId());
    deployment.setBrownfield(deploymentEntity.isBrownfield());
    deployment.setCreatedBy(deploymentEntity.getCreatedBy());
    deployment.setUpdateServerFirmware(deploymentEntity.isManageFirmware());
    deployment.setUseDefaultCatalog(deploymentEntity.isUseDefaultCatalog());

    if (Hibernate.isInitialized(deploymentEntity.getFirmwareRepositoryEntity())) {
        FirmwareRepositoryEntity repoEntity = deploymentEntity.getFirmwareRepositoryEntity();
        if (repoEntity != null) {
            deployment.setFirmwareRepositoryId(repoEntity.getId());
            deployment.setFirmwareRepository(repoEntity.getSimpleFirmwareRepository());
        }/*from   www . java  2 s. co m*/
    }

    deployment.setDeploymentName(deploymentEntity.getName());
    deployment.setDeploymentDescription(deploymentEntity.getDeploymentDesc());

    deployment.setCreatedDate(deploymentEntity.getCreatedDate());
    deployment.setCreatedBy(deploymentEntity.getCreatedBy());
    deployment.setUpdatedDate(deploymentEntity.getUpdatedDate());
    deployment.setUpdatedBy(deploymentEntity.getUpdatedBy());

    deployment.setDeploymentStartedDate(deploymentEntity.getDeploymentStartedDate());
    deployment.setDeploymentFinishedDate(deploymentEntity.getDeploymentFinishedDate());

    boolean powerUser = false;
    if (thisUser == null) {
        // Normally shouldn't be allowed to not have a valid user, but there is no harm in this
        // case as it just changes some of the return values and it makes testing easier.
        powerUser = false;
    } else {
        boolean isAdmin = thisUser.getRole().equals(AsmConstants.USERROLE_ADMINISTRATOR);
        boolean isOwner = thisUser.getUserName().equals(deploymentEntity.getCreatedBy());
        powerUser = isAdmin || isOwner;
    }
    deployment.setOwner(deploymentEntity.getCreatedBy());

    deployment.setCanCancel(powerUser);
    deployment.setCanDelete(powerUser);
    deployment.setCanEdit(powerUser);
    deployment.setCanRetry(powerUser);
    deployment.setCanDeleteResources(powerUser);

    deployment.setCanMigrate(false);
    deployment.setCanScaleupServer(powerUser);
    deployment.setCanScaleupStorage(powerUser);
    deployment.setCanScaleupVM(powerUser);
    deployment.setCanScaleupApplication(powerUser);
    deployment.setCanScaleupCluster(false);
    deployment.setCanScaleupNetwork(powerUser);

    deployment.setAllUsersAllowed(deploymentEntity.isAllUsersAllowed());
    deployment.setAssignedUsers(new HashSet<User>());

    deployment.setTemplateValid(deploymentEntity.isTemplateValid());
    deployment.setStatus(deploymentEntity.getStatus());
    deployment.setCompliant(deploymentEntity.isCompliant());

    if (deploymentEntity.getAssignedUserList() != null) {
        for (DeploymentUserRefEntity ref : deploymentEntity.getAssignedUserList()) {
            try {
                User user = getAdminProxy().getUser(ref.getUserId());
                deployment.getAssignedUsers().add(user);
            } catch (LocalizedWebApplicationException lwae) {
                logger.warn(
                        "Could not find User in the Users database for user sequence id: " + ref.getUserId(),
                        lwae);
            }
        }
    }

    if (deploymentEntity.getVmList() != null && deploymentEntity.getVmList().size() > 0) {
        deployment.setVms(new HashSet<VM>());
        for (VMRefEntity currDevice : deploymentEntity.getVmList()) {
            VM newVm = new VM();
            newVm.setCertificateName(currDevice.getVmId());
            newVm.setVmIpaddress(currDevice.getVmIpaddress());
            newVm.setVmManufacturer(currDevice.getVmManufacturer());
            newVm.setVmModel(currDevice.getVmModel());
            newVm.setVmServiceTag(currDevice.getVmServiceTag());
            deployment.getVms().add(newVm);
        }
    }

    ServiceTemplate template = MarshalUtil.unmarshal(ServiceTemplate.class,
            deploymentEntity.getMarshalledTemplateData());
    deployment.setServiceTemplate(template);

    // get the status of this job from Ruby service ( i.e. asm-deployer )
    List<AsmDeployerComponentStatus> asmDeployerComponentStatuses = null;

    // If status is pending, deployment has not yet been sent to asm-deployer
    if (DeploymentStatusType.PENDING != deployment.getStatus()) {
        try {
            AsmDeployerStatus dStatus = getAsmDeployerProxy().getDeploymentStatus(deploymentEntity.getId());
            // do not update DB record with this status, as it can be different because of components/firmware compliance
            asmDeployerComponentStatuses = dStatus.getComponents();
        } catch (WebApplicationException e) {
            logger.error("Failed to retrieve deployment " + deploymentEntity.getId() + " status", e);
        }
    }

    if (Hibernate.isInitialized(deploymentEntity.getDeployedDevices())) {

        //Check if any of the associated inventory is currently having its firmware updated
        if (deployment.getStatus() == DeploymentStatusType.COMPLETE) {
            for (DeviceInventoryEntity device : deploymentEntity.getDeployedDevices()) {
                if (device.getState() == DeviceState.UPDATING) {
                    deployment.setStatus(DeploymentStatusType.IN_PROGRESS);
                    break;
                }
            }
        }

        if (asmDeployerComponentStatuses != null) {
            deployment.setDeploymentDevice(new HashSet<DeploymentDevice>());
            deployment.setCompliant(deploymentEntity.isCompliant());

            for (AsmDeployerComponentStatus cs : asmDeployerComponentStatuses) {
                DeploymentDevice newDevice = new DeploymentDevice();
                newDevice.setRefId(cs.getAsmGuid());
                newDevice.setRefType(cs.getType().name());
                newDevice.setComponentId(cs.getId());
                newDevice.setStatus(cs.getStatus());
                newDevice.setStatusMessage(cs.getMessage());
                newDevice.setStatusStartTime(cs.getStartTime());
                newDevice.setStatusEndTime(cs.getEndTime());

                // need some data from inventory but don't want to make expensive call to DAO
                for (DeviceInventoryEntity device : deploymentEntity.getDeployedDevices()) {
                    if (device.getRefId().equals(cs.getAsmGuid())) {
                        newDevice.setIpAddress(device.getIpAddress());
                        newDevice.setServiceTag(device.getServiceTag());
                        newDevice.setDeviceType(device.getDeviceType());
                        newDevice.setDeviceHealth(device.getHealth());
                        newDevice.setHealthMessage(device.getHealthMessage());
                        newDevice.setCompliantState(this.getCompliantState(deploymentEntity, device));

                        if (!CompliantState.COMPLIANT.equals(newDevice.getCompliantState())) {
                            deployment.setCompliant(false);
                        }
                    }
                }

                ServiceTemplateComponent templateComponent = (template == null) ? null
                        : template.findComponentById(cs.getId());

                if (templateComponent != null) {
                    deployment.getDeploymentDevice().add(newDevice);

                    if (ServiceTemplateComponentType.SERVER.equals(cs.getType())) {
                        // Service can migrate if at least one device can migrate.
                        // Service can scale up servers in all cases, we now support scaleUp from scratch. Except Boot from SAN
                        // service can scale up storage if it is not HyperV swim lane and Not Boot from SAN
                        if (templateComponent.hasSanBoot()) {
                            deployment.setCanMigrate(powerUser);
                            deployment.setCanScaleupStorage(false);
                            deployment.setCanScaleupServer(false);
                        }
                        deployment.setVDS(ServiceDeploymentUtil.isVDSService(template, templateComponent));
                    }
                }
            }
        } else { // null possibly due to Pending status
            if (DeploymentStatusType.PENDING == deployment.getStatus()) {
                Set<DeviceInventoryEntity> deviceInventoryEntities = deploymentEntity.getDeployedDevices();
                ArrayList<AsmDeployerComponentStatus> fakeAsmDeployerComponentStatuses = new ArrayList<AsmDeployerComponentStatus>();

                for (DeviceInventoryEntity deviceInventoryEntity : deviceInventoryEntities) {
                    DeploymentDevice newDevice = new DeploymentDevice();
                    newDevice.setRefId(deviceInventoryEntity.getRefId());
                    newDevice.setStatus(DeploymentStatusType.PENDING); // Set to Pending since they are scheduled/pending
                    newDevice.setIpAddress(deviceInventoryEntity.getIpAddress());
                    newDevice.setServiceTag(deviceInventoryEntity.getServiceTag());
                    newDevice.setDeviceType(deviceInventoryEntity.getDeviceType());
                    newDevice.setDeviceHealth(deviceInventoryEntity.getHealth());
                    newDevice.setHealthMessage(deviceInventoryEntity.getHealthMessage());
                    newDevice.setCompliantState(CompliantState.fromValue(deviceInventoryEntity.getCompliant()));

                    ServiceTemplateComponent templateComponent = (template == null) ? null
                            : template.findComponentByGUID(deviceInventoryEntity.getRefId());

                    // newDevice.setStatusEndTime(statusEndTime);
                    // newDevice.setStatusMessage(statusMessage);
                    // newDevice.setStatusStartTime(statusStartTime);

                    if (templateComponent != null) {
                        newDevice.setComponentId(templateComponent.getId());
                        newDevice.setRefType(templateComponent.getType().name());
                        deployment.getDeploymentDevice().add(newDevice);

                        if (ServiceTemplateComponentType.SERVER.equals(templateComponent.getType())) {
                            // find corresponding device
                            // Service can migrate if at least one device can migrate.
                            // Service can scale up servers in all cases, we now support scaleUp from scratch. Except Boot from SAN
                            // service can scale up storage if it is not HyperV swim lane and Not Boot from SAN
                            if (templateComponent.hasSanBoot()) {
                                deployment.setCanMigrate(powerUser);
                                deployment.setCanScaleupStorage(false);
                                deployment.setCanScaleupServer(false);
                            }

                        }
                    }
                }
            }
        }
    }

    // get the detailed logs for this job from Ruby service ( i.e. asm-deployer )
    try {
        List<AsmDeployerLogEntry> dLogs = getAsmDeployerProxy().getDeploymentLogs(deploymentEntity.getId());
        deployment.setJobDetails(dLogs);
    } catch (Exception logErr) {
        logger.warn("asm-deployer log service returned exception", logErr);
    }

    deployment.setDeploymentHealthStatusType(this.calculateDeploymentHealthStatusType(deployment));

    return deployment;
}