@Override public final Object load() { final Serializable entityId = resolveNaturalId( this.naturalIdParameters ); if ( entityId == null ) { return null; } try { return this.getIdentifierLoadAccess().load( entityId ); } catch (EntityNotFoundException enf) { // OK } catch (ObjectNotFoundException nf) { // OK } return null; }
@Override public Object load(Object naturalIdValue) { final Serializable entityId = resolveNaturalId( getNaturalIdParameters( naturalIdValue ) ); if ( entityId == null ) { return null; } try { return this.getIdentifierLoadAccess().load( entityId ); } catch (EntityNotFoundException enf) { // OK } catch (ObjectNotFoundException nf) { // OK } return null; }
public Assignment getAssignment(Class_ clazz) { Long solutionId = getSolutionId(clazz); if (solutionId==null) return super.getAssignment(clazz); Iterator i = null; try { i = clazz.getAssignments().iterator(); } catch (ObjectNotFoundException e) { new _RootDAO().getSession().refresh(clazz); i = clazz.getAssignments().iterator(); } while (i.hasNext()) { Assignment a = (Assignment)i.next(); if (solutionId.equals(a.getSolution().getUniqueId())) return a; } return null; }
@Test public void testLoadWithNotFound() throws HibernateException { ObjectNotFoundException onfex = new ObjectNotFoundException("id", TestBean.class.getName()); given(session.load(TestBean.class, "id")).willThrow(onfex); try { hibernateTemplate.load(TestBean.class, "id"); fail("Should have thrown HibernateObjectRetrievalFailureException"); } catch (HibernateObjectRetrievalFailureException ex) { // expected assertEquals(TestBean.class.getName(), ex.getPersistentClassName()); assertEquals("id", ex.getIdentifier()); assertEquals(onfex, ex.getCause()); } verify(session).close(); }
/** * Find or create message. * * @param aMessage * the a message * @param session * the session * @return the message */ private synchronized Message findOrCreateMessage(final Message aMessage, final Session session) { Message message = null; try { message = this.findMessage(aMessage, session); if (null == message) { session.saveOrUpdate(aMessage.getPoster()); message = aMessage; session.saveOrUpdate(aMessage); // messagesCache.put(key, message); } } catch (final ObjectNotFoundException e) { HibernateHelper.logger.warn(message.getPoster(), e); } return message; }
/** * @verifies should purge the provider * @see org.openmrs.web.controller.provider.ProviderFormController#onSubmit(javax.servlet.http.HttpServletRequest, * String, String, String, String, org.openmrs.Provider, * org.springframework.validation.BindingResult, org.springframework.ui.ModelMap) */ @Test(expected = ObjectNotFoundException.class) public void onSubmit_shouldPurgeTheProvider() throws Exception { executeDataSet(PROVIDERS_ATTRIBUTES_XML); executeDataSet(PROVIDERS_XML); Provider provider = Context.getProviderService().getProvider(2); ProviderAttributeType providerAttributeType = Context.getProviderService().getProviderAttributeType(1); MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); BindException errors = new BindException(provider, "provider"); ProviderFormController providerFormController = (ProviderFormController) applicationContext .getBean("providerFormController"); providerFormController.onSubmit(mockHttpServletRequest, null, null, null, "purge", provider, errors, createModelMap(providerAttributeType)); Context.flushSession(); Assert.assertNull(Context.getProviderService().getProvider(2)); }
public void removeTransientEntries(Map<Long, String> transientMap) { CalendarEntry entry; Transaction tx = _persister.getOrBeginTransaction(); for (Long entryID : transientMap.keySet()) { String status = transientMap.get(entryID); if (status.equals(TRANSIENT_FLAG)) { try { entry = (CalendarEntry) _persister.load(CalendarEntry.class, entryID); _persister.delete(entry, tx); } catch (ObjectNotFoundException onfe) { // nothing to remove if not found } } else { entry = (CalendarEntry) _persister.get(CalendarEntry.class, entryID); if (entry != null) { entry.setStatus(status); _persister.update(entry, tx); } } } }
private boolean canManipulateReport(PostReport report) { int[] forumIds = this.userSession.getRoleManager() .getRoleValues(SecurityConstants.FORUM); for (int forumId : forumIds) { // Make sure the user is removing a report from a forum he can // moderate try { if (forumId == report.getPost().getForum().getId()) { return true; } } catch (ObjectNotFoundException e) { return true; } } return false; }
private void handleLastPostDeleted(Post post) { boolean isLastPost = false; try { // FIXME: post.getTopic.getLastPost() may throw this exception, // because the post itself was deleted before this method, // and a call to post.getTopic().getLastPost() may issue // a query to load the last post of such topic, which // won't exist, of course. So, is this expected, or should // we handle this using another approach? isLastPost = post.getTopic().getLastPost().equals(post); } catch (ObjectNotFoundException e) { isLastPost = true; } if (isLastPost) { post.getTopic().setLastPost(this.topicRepository.getLastPost(post.getTopic())); } }
private boolean handleFirstPostDeleted(Post post) { boolean isFirstPost = false; try { isFirstPost = post.getTopic().getFirstPost().equals(post); } catch (ObjectNotFoundException e) { isFirstPost = true; } if (isFirstPost) { Post firstPost = this.topicRepository.getFirstPost(post.getTopic()); post.getTopic().setFirstPost(firstPost); post.getTopic().setUser(firstPost.getUser()); return true; } return false; }
/** * The actions are: * <ul> * <li> If last post, update forum.lastPost * </ul> */ @Override public void deleted(Post post) { boolean isLastPost = false; try { // FIXME: Check TopicPostEvent#handleLastPostDeleted isLastPost = post.equals(post.getForum().getLastPost()); } catch (ObjectNotFoundException e) { isLastPost = true; } if (isLastPost) { Post lastPost = this.repository.getLastPost(post.getForum()); post.getForum().setLastPost(lastPost); } }
/** * The actions are: * <ul> * <li> If topic.lastPost == forum.lastPost, update forum.lastPost * </ul> */ @Override public void deleted(Topic topic) { Forum forum = topic.getForum(); boolean topicMatches = false; try { // FIXME: Check TopiPostEvent#handleLastPostDeleted topicMatches = forum.getLastPost() == null ? true : forum.getLastPost().getTopic().equals(topic); } catch (ObjectNotFoundException e) { topicMatches = true; } if (topicMatches) { forum.setLastPost(this.repository.getLastPost(forum)); } }
public void removeItem(Item item) { try { if (item == null) { throw new IllegalArgumentException("item cannot be null"); } if (item instanceof HomeCollectionItem) { throw new IllegalArgumentException("cannot remove root item"); } removeItemInternal(item); getSession().flush(); } catch (ObjectNotFoundException onfe) { throw new ItemNotFoundException("item not found"); } catch (ObjectDeletedException ode) { throw new ItemNotFoundException("item not found"); } catch (UnresolvableObjectException uoe) { throw new ItemNotFoundException("item not found"); } catch (HibernateException e) { getSession().clear(); throw SessionFactoryUtils.convertHibernateAccessException(e); } }
public String getAuthor() { try { // try to handle as identity id final Identity identity = getBaseSecurity().loadIdentityByKey(Long.valueOf(author)); if (identity == null) { return author; } return identity.getName(); } catch (final NumberFormatException nEx) { return author; } catch (final ObjectNotFoundException oEx) { DBFactory.getInstanceForClosing().rollbackAndCloseSession(); return author; } catch (final Throwable th) { DBFactory.getInstanceForClosing().rollbackAndCloseSession(); return author; } }
/** * Lookup a ConfigFile by its channel's id and config file name's id * @param channel The file's config channel id * @param name The file's config file name id * @return the ConfigFile found or null if not found. */ public static ConfigFile lookupConfigFileByChannelAndName(Long channel, Long name) { Session session = HibernateFactory.getSession(); Query query = session.getNamedQuery("ConfigFile.findByChannelAndName") .setLong("channel_id", channel.longValue()) .setLong("name_id", name.longValue()) .setLong("state_id", ConfigFileState.normal(). getId().longValue()) //Retrieve from cache if there .setCacheable(true); try { return (ConfigFile) query.uniqueResult(); } catch (ObjectNotFoundException e) { return null; } }
/** * Gets an Action Chain by id. * @param requestor the user whose chain we're looking for * @param id the id * @return the Action Chain * @throws ObjectNotFoundException if there is no such id accessible to the requestor */ public static ActionChain getActionChain(User requestor, Long id) throws ObjectNotFoundException { log.debug("Looking up Action Chain with id " + id); if (id == null) { return null; } ActionChain ac = (ActionChain) getSession() .createCriteria(ActionChain.class) .add(Restrictions.eq("id", id)) .add(Restrictions.eq("user", requestor)) .uniqueResult(); if (ac == null) { throw new ObjectNotFoundException(ActionChain.class, "ActionChain Id " + id + " not found for User " + requestor.getLogin()); } return ac; }
/** * Gets an Action Chain Entry by id. * @param requestor the user whose entry we're looking for * @param id the action chain entry id * @return the Action Chain Entry * @throws ObjectNotFoundException if there is no such id accessible to the requestor */ public static ActionChainEntry getActionChainEntry(User requestor, Long id) throws ObjectNotFoundException { if (id == null) { return null; } ActionChainEntry ace = (ActionChainEntry) getSession() .load(ActionChainEntry.class, id); if (ace.getActionChain().getUser().getId().longValue() == requestor.getId().longValue()) { return ace; } throw new ObjectNotFoundException(ActionChainEntry.class, "ActionChainEntry Id " + id + " not found for User " + requestor.getLogin()); }
@Test public void testConsistencyIssuesWhenRemovingChildDirectly() { LOGGER.info("Removing Child causes inconsistencies"); doInTransaction(session -> { Commit commit = (Commit) session.get(Commit.class, 1L); session.delete(commit); }); try { doInTransaction(session -> { Repository repository = (Repository) session.get(Repository.class, 1L); assertEquals(1, repository.getCommits().size()); }); } catch (ObjectNotFoundException e) { LOGGER.warn("Object not found", e); } }
/** * Return a WSSecured object mapped from the given method and method arguments for validation. * This produced a secure object for validation from web-service method calls that only accept and return * ID's instead of WS objects that can be individually validated. * * @param method method to map * @param args method arguments * @return instance of WSSecured mapped from the given entity, null if entity could not be mapped. */ public static WSSecured getMappedSecuredWS(Method method, Object[] args) { if (method != null) { SecuredMethodSignature sig = SecuredMethodFactory.getSignature(method); if (sig != null && sig.getIdArgIndex() <= args.length) { try { return sig.getType().getMappedSecuredWS((Serializable) args[sig.getIdArgIndex()]); } catch (ObjectNotFoundException e) { // hibernate complains loudly... object does not exist, no reason to validate. return null; } } } return null; }
public void set(Integer entityId, Integer typeId) throws EmptyResultDataAccessException { LOG.debug("Looking for preference " + typeId + ", for entity " + entityId + " and table '" + Constants.TABLE_ENTITY + "'"); try { preference = preferenceDas.findByType_Row( typeId, entityId, Constants.TABLE_ENTITY); type = typeDas.find(typeId); // throw exception if there is no preference, or if the type does not have a // default value that can be returned. if (preference == null) { if (type == null || type.getDefaultValue() == null) { throw new EmptyResultDataAccessException("Could not find preference " + typeId, 1); } } } catch (ObjectNotFoundException e) { // do nothing throw new EmptyResultDataAccessException("Could not find preference " + typeId, 1); } }
/** * @param aClass * @return */ public boolean appliesTo(Class_ aClass) { if (this.getDistributionObjects()==null) return false; Iterator it = null; try { it = getDistributionObjects().iterator(); } catch (ObjectNotFoundException e) { Debug.error("Exception "+e.getMessage()+" seen for "+this); new _RootDAO().getSession().refresh(this); it = getDistributionObjects().iterator(); } while (it.hasNext()) { DistributionObject dObj = (DistributionObject) it.next(); //Class_ check //no checking whether dObj.getPrefGroup() is Class_ not needed since all PreferenceGroups have unique ids if (dObj.getPrefGroup().getUniqueId().equals(aClass.getUniqueId())) return true; //SchedulingSubpart check SchedulingSubpart ss = null; if (Hibernate.isInitialized(dObj.getPrefGroup())) { if (dObj.getPrefGroup() instanceof SchedulingSubpart) { ss = (SchedulingSubpart) dObj.getPrefGroup(); } } else { //dObj.getPrefGroup() is a proxy -> try to load it PreferenceGroup pg = (new PreferenceGroupDAO()).get(dObj.getPrefGroup().getUniqueId()); if (pg!=null && pg instanceof SchedulingSubpart) ss = (SchedulingSubpart)pg; } if (ss!=null && ss.getClasses()!=null && ss.getClasses().size()>0) { for (Iterator it2 = ss.getClasses().iterator();it2.hasNext();) if (((Class_)it2.next()).getUniqueId().equals(aClass.getUniqueId())) return true; } } return false; }
/** Ordered set of distribution objects */ public Set<DistributionObject> getOrderedSetOfDistributionObjects() { try { return new TreeSet<DistributionObject>(getDistributionObjects()); } catch (ObjectNotFoundException ex) { (new DistributionPrefDAO()).getSession().refresh(this); return new TreeSet<DistributionObject>(getDistributionObjects()); } }
public InstructionalOffering getNextInstructionalOffering(SessionContext context, Comparator cmp) { Long nextId = Navigation.getNext(context, Navigation.sInstructionalOfferingLevel, getUniqueId()); if (nextId!=null) { if (nextId.longValue()<0) return null; return (new InstructionalOfferingDAO()).get(nextId); } InstructionalOffering next = null; SubjectArea area = getControllingCourseOffering().getSubjectArea(); Iterator i = null; try { i = area.getCourseOfferings().iterator(); } catch (ObjectNotFoundException e) { new _RootDAO().getSession().refresh(area); i = area.getCourseOfferings().iterator(); } for (;i.hasNext();) { CourseOffering c = (CourseOffering)i.next(); if (!c.isIsControl().booleanValue()) continue; InstructionalOffering o = (InstructionalOffering)c.getInstructionalOffering(); if (!o.isNotOffered().equals(isNotOffered())) continue; if (cmp.compare(this, o)>=0) continue; if (next==null || cmp.compare(next,o)>0) next = o; } return next; }
public InstructionalOffering getPreviousInstructionalOffering(SessionContext context, Comparator cmp) { Long previousId = Navigation.getPrevious(context, Navigation.sInstructionalOfferingLevel, getUniqueId()); if (previousId!=null) { if (previousId.longValue()<0) return null; return (new InstructionalOfferingDAO()).get(previousId); } InstructionalOffering previous = null; SubjectArea area = getControllingCourseOffering().getSubjectArea(); Iterator i = null; try { i = area.getCourseOfferings().iterator(); } catch (ObjectNotFoundException e) { new _RootDAO().getSession().refresh(area); i = area.getCourseOfferings().iterator(); } for (;i.hasNext();) { CourseOffering c = (CourseOffering)i.next(); if (!c.isIsControl().booleanValue()) continue; InstructionalOffering o = (InstructionalOffering)c.getInstructionalOffering(); if (!o.isNotOffered().equals(isNotOffered())) continue; if (cmp.compare(this, o)<=0) continue; if (previous==null || cmp.compare(previous,o)<0) previous = o; } return previous; }
@Test public void testLoadWithNotFound() { ObjectNotFoundException onfex = new ObjectNotFoundException("id", TestBean.class.getName()); given(session.load(TestBean.class, "id")).willThrow(onfex); try { hibernateTemplate.load(TestBean.class, "id"); fail("Should have thrown HibernateObjectRetrievalFailureException"); } catch (HibernateObjectRetrievalFailureException ex) { // expected assertEquals(TestBean.class.getName(), ex.getPersistentClassName()); assertEquals("id", ex.getIdentifier()); assertEquals(onfex, ex.getCause()); } }
public IntakeNodeLabel getIntakeNodeLabel(Integer intakeNodeLabelId) { IntakeNodeLabel intakeNodeLabel = null; if (intakeNodeLabelId == null || intakeNodeLabelId < 1) { throw new IllegalArgumentException( "intakeNodeLabelId must be non-null and greater than 0"); } //in case the node with intakenodelabel id doesn't exist try { intakeNodeLabel = getHibernateTemplate().get( IntakeNodeLabel.class, intakeNodeLabelId); } catch (ObjectNotFoundException onfe) { LOG.warn("no node found for : " + intakeNodeLabelId); } return intakeNodeLabel; }
@Override public T loadObjectForDocument(SolrDocument solrDocument) { try { Class clazz = Class.forName((String)solrDocument.getFieldValue("base.class_s")); Long id = (Long) solrDocument.getFieldValue("base.id_l"); T t = (T) getSession().load(clazz, id); t.getIdentifier(); return t; } catch (ClassNotFoundException cnfe) { throw new RuntimeException("Could not instantiate search result", cnfe); } catch (ObjectNotFoundException onfe) { return null; } }
/** * load a single record with id and filter. * * @param entityClass class of query object * @param id id of the query object * @param filterExpression FilterExpression contains the predicates * @param scope Request scope associated with specific request */ @Override public Object loadObject(Class<?> entityClass, Serializable id, Optional<FilterExpression> filterExpression, RequestScope scope) { try { EntityDictionary dictionary = scope.getDictionary(); Class<?> idType = dictionary.getIdType(entityClass); String idField = dictionary.getIdFieldName(entityClass); //Construct a predicate that selects an individual element of the relationship's parent (Author.id = 3). FilterPredicate idExpression; Path.PathElement idPath = new Path.PathElement(entityClass, idType, idField); if (id != null) { idExpression = new FilterPredicate(idPath, Operator.IN, Collections.singletonList(id)); } else { idExpression = new FilterPredicate(idPath, Operator.FALSE, Collections.emptyList()); } FilterExpression joinedExpression = filterExpression .map(fe -> (FilterExpression) new AndFilterExpression(fe, idExpression)) .orElse(idExpression); QueryWrapper query = (QueryWrapper) new RootCollectionFetchQueryBuilder(entityClass, dictionary, sessionWrapper) .withPossibleFilterExpression(Optional.of(joinedExpression)) .build(); return query.getQuery().uniqueResult(); } catch (ObjectNotFoundException e) { return null; } }
@Test(expected = ObjectNotFoundException.class) public void testDelete() throws DatabaseUnitException, SQLException { IDataSet ds = createDateSet("t_user"); DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, ds); userDao.delete(1); User tu = userDao.load(1); System.out.println(tu.getUsername()); }
/** * Reads a document from the database * * @param id the id of the document to read * @return a YDocument wrapper for the document * @throws IOException if no document can be found with the id passed */ private YDocument getDocument(long id) throws IOException { try { return (YDocument) _db.load(YDocument.class, id); } catch (ObjectNotFoundException onfe) { throw new IOException("No stored document found with id: " + id); } }
/** * Removes a document from the database * * @param id the id of the document to remove * @return true if successful */ private boolean removeDocument(long id) { try { YDocument doc = (YDocument) _db.load(YDocument.class, id); return (doc != null) && _db.exec(doc, HibernateEngine.DB_DELETE, true); } catch (ObjectNotFoundException onfe) { return false; } }
private String addCaseID(long id, String caseID) throws IOException { try { YDocument doc = (YDocument) _db.load(YDocument.class, id); if (doc != null) { doc.setCaseId(caseID); if (_db.exec(doc, HibernateEngine.DB_UPDATE, true)) { return "Case ID successfully updated"; } } throw new IOException("No document found with id: " + id); } catch (ObjectNotFoundException onfe) { throw new IOException(onfe.getMessage()); } }