List of usage examples for org.hibernate Session evict
void evict(Object object);
From source file:no.abmu.organisationregister.domain.HistoricObject.java
License:Open Source License
public boolean onUpdate(Session session) { HistoricObject fromDb = null;/* w w w . j a v a 2s. c o m*/ HistoricObject newFromDb = null; Serializable newDbId = null; try { fromDb = (HistoricObject) session.load(this.getClass(), getId()); if (!this.equals(fromDb)) { newFromDb = (HistoricObject) this.getClass().newInstance(); BeanUtils.copyProperties(newFromDb, fromDb); newFromDb.setWasReplacedBy(this); newFromDb.setEndDate(new Date()); newFromDb.setStartDate(fromDb.getStartDate()); session.evict(fromDb); newDbId = session.save(newFromDb); } if (newDbId != null) { newFromDb = (StreetAddress) session.load(getClass(), newDbId); this.setReplaced(newFromDb); } this.setStartDate(new Date()); } catch (HibernateException e) { logger.error("Problem when creating historic object for id " + getId(), e); throw new CallbackException("Problem when creating historic object for id " + getId(), e); } catch (IllegalAccessException e) { logger.error("could not access the default constructor for " + getClass().getName(), e); throw new CallbackException("could not access the default constructor for " + getClass().getName(), e); } catch (InstantiationException e) { logger.error("could not call the default constructor for " + getClass().getName(), e); throw new CallbackException("could not call the default constructor for " + getClass().getName(), e); } catch (InvocationTargetException e) { logger.error(e.getMessage(), e); throw new CallbackException("problem copying properties for " + getClass().getName(), e); } return false; }
From source file:onl.netfishers.netshot.TaskManager.java
License:Open Source License
/** * Adds a task to the scheduler.//from w ww. j a v a 2 s.c om * * @param task the task * @throws SchedulerException the scheduler exception * @throws HibernateException the hibernate exception */ static public void addTask(Task task) throws SchedulerException, HibernateException { logger.debug("Adding task."); Session session = Database.getSession(); try { session.beginTransaction(); task.onSchedule(); task.setScheduled(); session.saveOrUpdate(task); session.getTransaction().commit(); session.evict(task); logger.trace("Task successfully added to the database."); } catch (Exception e) { session.getTransaction().rollback(); logger.error("Error while saving the new task.", e); throw e; } finally { session.close(); } JobDetail job = JobBuilder.newJob(TaskJob.class).withIdentity(TaskManager.getTaskIdentity(task)).build(); job.getJobDataMap().put(TaskJob.NETSHOT_TASK, new Long(task.getId())); Date when = task.getNextExecutionDate(); Trigger trigger; if (when == null) { trigger = TriggerBuilder.newTrigger().startNow().build(); } else { trigger = TriggerBuilder.newTrigger().startAt(when).build(); } scheduler.scheduleJob(job, trigger); logger.trace("Task successfully added to the scheduler."); }
From source file:onl.netfishers.netshot.work.tasks.CheckComplianceTask.java
License:Open Source License
@Override public void run() { logger.debug("Starting check compliance task for device {}.", device.getId()); this.logIt(String.format("Check compliance task for device %s (%s).", device.getName(), device.getMgmtAddress().getIp()), 5); Session session = Database.getSession(); try {//from w ww .j av a 2 s. c om session.beginTransaction(); session.createQuery("delete from CheckResult c where c.key.device.id = :id") .setLong("id", this.device.getId()).executeUpdate(); session.evict(this.device); Device device = (Device) session.createQuery("from Device d join fetch d.lastConfig where d.id = :id") .setLong("id", this.device.getId()).uniqueResult(); if (device == null) { logger.info( "Unable to fetch the device with its last config... has it been captured at least once?"); throw new Exception("No last config for this device. Has it been captured at least once?"); } @SuppressWarnings("unchecked") List<Policy> policies = session .createQuery( "select p from Policy p join p.targetGroup g join g.cachedDevices d where d.id = :id") .setLong("id", this.device.getId()).list(); for (Policy policy : policies) { policy.check(device, session); session.merge(policy); } @SuppressWarnings("unchecked") List<SoftwareRule> softwareRules = session.createCriteria(SoftwareRule.class) .addOrder(Property.forName("priority").asc()).list(); device.setSoftwareLevel(ConformanceLevel.UNKNOWN); for (SoftwareRule rule : softwareRules) { rule.check(device); if (device.getSoftwareLevel() != ConformanceLevel.UNKNOWN) { break; } } @SuppressWarnings("unchecked") List<HardwareRule> hardwareRules = session.createCriteria(HardwareRule.class).list(); device.resetEoX(); for (HardwareRule rule : hardwareRules) { rule.check(device); } session.merge(device); session.getTransaction().commit(); this.status = Status.SUCCESS; } catch (Exception e) { session.getTransaction().rollback(); logger.error("Error while checking compliance.", e); this.logIt("Error while checking compliance: " + e.getMessage(), 2); this.status = Status.FAILURE; return; } finally { session.close(); } }
From source file:onl.netfishers.netshot.work.tasks.CheckGroupComplianceTask.java
License:Open Source License
@Override public void run() { logger.debug("Starting check compliance task for group {}.", deviceGroup.getId()); this.logIt(String.format("Check compliance task for group %s.", deviceGroup.getName()), 5); Session session = Database.getSession(); try {//from w w w . ja v a2s. c o m @SuppressWarnings("unchecked") List<Policy> policies = session.createCriteria(Policy.class).list(); session.beginTransaction(); session.createQuery( "delete from CheckResult c where c.key.device.id in (select d.id as id from DeviceGroup g1 join g1.cachedDevices d where g1.id = :id)") .setLong("id", deviceGroup.getId()).executeUpdate(); for (Policy policy : policies) { ScrollableResults devices = session.createQuery( "from Device d join fetch d.lastConfig where d.id in (select d.id as id from DeviceGroup g1 join g1.cachedDevices d join d.ownerGroups g2 join g2.appliedPolicies p where g1.id = :id and p.id = :pid)") .setLong("id", deviceGroup.getId()).setLong("pid", policy.getId()) .setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY); while (devices.next()) { Device device = (Device) devices.get(0); policy.check(device, session); session.flush(); session.evict(device); } } session.getTransaction().commit(); this.status = Status.SUCCESS; } catch (Exception e) { try { session.getTransaction().rollback(); } catch (Exception e1) { } logger.error("Error while checking compliance.", e); this.logIt("Error while checking compliance: " + e.getMessage(), 2); this.status = Status.FAILURE; return; } finally { session.close(); } }
From source file:onl.netfishers.netshot.work.tasks.CheckGroupSoftwareTask.java
License:Open Source License
@Override public void run() { logger.debug("Starting check software compliance and hardware support status task for group {}.", deviceGroup.getId());//from w w w .ja va2 s . co m this.logIt(String.format("Check software compliance task for group %s.", deviceGroup.getName()), 5); Session session = Database.getSession(); try { logger.debug("Retrieving the software rules"); @SuppressWarnings("unchecked") List<SoftwareRule> softwareRules = session.createCriteria(SoftwareRule.class) .addOrder(Property.forName("priority").asc()).list(); logger.debug("Retrieving the hardware rules"); @SuppressWarnings("unchecked") List<HardwareRule> hardwareRules = session.createCriteria(HardwareRule.class).list(); session.beginTransaction(); ScrollableResults devices = session .createQuery("select d from DeviceGroup g join g.cachedDevices d where g.id = :id") .setLong("id", deviceGroup.getId()).setCacheMode(CacheMode.IGNORE) .scroll(ScrollMode.FORWARD_ONLY); while (devices.next()) { Device device = (Device) devices.get(0); device.setSoftwareLevel(ConformanceLevel.UNKNOWN); for (SoftwareRule rule : softwareRules) { rule.check(device); if (device.getSoftwareLevel() != ConformanceLevel.UNKNOWN) { break; } } device.resetEoX(); for (HardwareRule rule : hardwareRules) { rule.check(device); } session.save(device); session.flush(); session.evict(device); } session.getTransaction().commit(); this.status = Status.SUCCESS; } catch (Exception e) { try { session.getTransaction().rollback(); } catch (Exception e1) { } logger.error("Error while checking compliance.", e); this.logIt("Error while checking compliance: " + e.getMessage(), 2); this.status = Status.FAILURE; return; } finally { session.close(); } }
From source file:org.apereo.portal.events.handlers.db.JpaPortalEventStore.java
License:Apache License
@Override public void getPortalEvents(DateTime startTime, DateTime endTime, int maxEvents, FunctionWithoutResult<PortalEvent> handler) { final Session session = this.getEntityManager().unwrap(Session.class); final org.hibernate.Query query = session.createQuery(this.selectQuery); query.setParameter(this.startTimeParameter.getName(), startTime); query.setParameter(this.endTimeParameter.getName(), endTime); if (maxEvents > 0) { query.setMaxResults(maxEvents);/*from w w w . j a v a2s . co m*/ } for (final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY); results.next();) { final PersistentPortalEvent persistentPortalEvent = (PersistentPortalEvent) results.get(0); final PortalEvent portalEvent = this.toPortalEvent(persistentPortalEvent.getEventData(), persistentPortalEvent.getEventType()); handler.apply(portalEvent); persistentPortalEvent.setAggregated(true); session.evict(persistentPortalEvent); } }
From source file:org.dt.bsa.util.HibernateUtil.java
License:Open Source License
public static void save(Object object) throws BSAException { Session session = getSessionFactory().openSession(); Transaction transaction = null;// ww w.j a va2 s . c om try { transaction = session.beginTransaction(); session.saveOrUpdate(object); transaction.commit(); session.evict(object); } catch (Exception e) { if (transaction != null) transaction.rollback(); log.error("HibernateUtil:save:exception:" + e.getMessage()); throw new BSAException(e.getMessage()); } finally { session.close(); } }
From source file:org.dt.bsa.util.HibernateUtil.java
License:Open Source License
public static void refresh(Object object) throws BSAException { Session session = getSessionFactory().openSession(); Transaction transaction = null;//from w w w .j a va2 s . c om try { transaction = session.beginTransaction(); session.refresh(object); transaction.commit(); session.evict(object); } catch (Exception e) { if (transaction != null) transaction.rollback(); log.error("HibernateUtil:refresh:exception:" + e.getMessage()); throw new BSAException(e.getMessage()); } finally { session.close(); } }
From source file:org.dt.bsa.util.HibernateUtil.java
License:Open Source License
public static void load(Object object, int id) throws BSAException { Session session = getSessionFactory().openSession(); try {// w w w .j av a 2 s. c o m session.load(object, new Integer(id)); session.evict(object); } catch (Exception e) { log.error("HibernateUtil:load:exception for id=" + id + ":" + e.getMessage()); throw new BSAException(e.getMessage()); } finally { session.close(); } }
From source file:org.etudes.component.app.melete.SectionDB.java
License:Apache License
public void editSection(Section section, MeleteResource melResource) throws Exception { try {//from ww w . j a v a 2 s. co m SectionResource secResource = getSectionResourcebyId(section.getSectionId().toString()); Session session = hibernateUtil.currentSession(); Transaction tx = null; try { hibernateUtil.ensureSectionHasNonNull(section); // set default values for not-null fields // SectionResource secResource = (SectionResource)section.getSectionResource(); if (secResource == null) secResource = new SectionResource(); secResource.setSection(section); secResource.setResource(melResource); section.setModificationDate(new java.util.Date()); section.setSectionResource(secResource); // save object if (!session.isOpen()) session = hibernateUtil.currentSession(); session.evict(section); tx = session.beginTransaction(); if (melResource != null) { String queryString = "from MeleteResource meleteresource where meleteresource.resourceId=:resourceId"; Query query = session.createQuery(queryString); query.setParameter("resourceId", melResource.getResourceId()); List result_list = query.list(); if (result_list != null && result_list.size() != 0) { MeleteResource newMelResource = (MeleteResource) result_list.get(0); newMelResource.setLicenseCode(melResource.getLicenseCode()); newMelResource.setCcLicenseUrl(melResource.getCcLicenseUrl()); newMelResource.setReqAttr(melResource.isReqAttr()); newMelResource.setAllowCmrcl(melResource.isAllowCmrcl()); newMelResource.setAllowMod(melResource.getAllowMod()); newMelResource.setCopyrightYear(melResource.getCopyrightYear()); newMelResource.setCopyrightOwner(melResource.getCopyrightOwner()); session.saveOrUpdate(newMelResource); } } session.saveOrUpdate(secResource); session.saveOrUpdate(section); session.flush(); tx.commit(); if (logger.isDebugEnabled()) logger.debug("commit transaction and edit section :" + section.getModuleId() + "," + section.getTitle()); // updateExisitingResource(secResource); return; } catch (StaleObjectStateException sose) { if (tx != null) tx.rollback(); logger.error("edit section stale object exception" + sose.toString()); throw new MeleteException("edit_section_multiple_users"); } catch (ConstraintViolationException cve) { if (tx != null) tx.rollback(); logger.error("constraint voilation exception" + cve.getConstraintName()); throw new MeleteException("add_section_fail"); } catch (HibernateException he) { if (tx != null) tx.rollback(); logger.error("edit section HE exception" + he.toString()); he.printStackTrace(); throw new MeleteException("add_section_fail"); } finally { hibernateUtil.closeSession(); } } catch (Exception ex) { // Throw application specific error throw ex; } }