org.hibernate.ObjectNotFoundException Java Examples

The following examples show how to use org.hibernate.ObjectNotFoundException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CollectionCacheTest.java    From hibernate-master-class with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #2
Source File: ConfigurationFactory.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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)
                .setLong("name_id", name)
                .setLong("state_id", ConfigFileState.normal().
                        getId());
    try {
        return (ConfigFile) query.uniqueResult();
    }
    catch (ObjectNotFoundException e) {
        return null;
    }
}
 
Example #3
Source File: ActionChainFactory.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #4
Source File: ActionChainFactory.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #5
Source File: ActionChainFactory.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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) singleton.lookupObjectByNamedQuery(
        "ActionChain.getActionChain",
        new HashMap<String, Object>() { {
            put("user", requestor);
            put("id", id);
        } }
    );
    if (ac == null) {
        throw new ObjectNotFoundException(ActionChain.class,
                        "ActionChain Id " + id + " not found for User " +
                        requestor.getLogin());
    }
    return ac;
}
 
Example #6
Source File: ActionChainFactory.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #7
Source File: ConfigurationFactory.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #8
Source File: DialogElement.java    From olat with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example #9
Source File: DialogElement.java    From olat with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example #10
Source File: HibernateTemplateTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #11
Source File: SolutionClassAssignmentProxy.java    From unitime with Apache License 2.0 6 votes vote down vote up
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;
  }
 
Example #12
Source File: ResourceCalendar.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
            }
        }
    }
}
 
Example #13
Source File: DistributionPref.java    From unitime with Apache License 2.0 5 votes vote down vote up
/**
 * @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;
}
 
Example #14
Source File: ActionChainEditAction.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private ActionChain getActionChain(User user, Long actionChainId) {
    try {
        return ActionChainFactory.getActionChain(user, actionChainId);
    }
    catch (ObjectNotFoundException objectNotFoundException) {
        LocalizationService ls = LocalizationService.getInstance();
        LookupException e = new LookupException("Could not find action chain id: " +
                actionChainId);
        e.setLocalizedTitle(ls.getMessage("lookup.jsp.title.actionchain"));
        e.setLocalizedReason1(ls.getMessage("lookup.jsp.actionchain.reason1"));
        throw e;
    }
}
 
Example #15
Source File: DistributionPref.java    From unitime with Apache License 2.0 5 votes vote down vote up
/** 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());
	}
}
 
Example #16
Source File: InstructionalOffering.java    From unitime with Apache License 2.0 5 votes vote down vote up
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;
  }
 
Example #17
Source File: InstructionalOffering.java    From unitime with Apache License 2.0 5 votes vote down vote up
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;
  }
 
Example #18
Source File: ActionChainEditAction.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
private ActionChain getActionChain(User user, Long actionChainId) {
    try {
        return ActionChainFactory.getActionChain(user, actionChainId);
    }
    catch (ObjectNotFoundException notFoundException) {
        LocalizationService ls = LocalizationService.getInstance();
        LookupException e = new LookupException("Could not find action chain id: " +
                actionChainId);
        e.setLocalizedTitle(ls.getMessage("lookup.jsp.title.actionchain"));
        e.setLocalizedReason1(ls.getMessage("lookup.jsp.actionchain.reason1"));
        throw e;
    }
}
 
Example #19
Source File: ActionChainFactoryTest.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks that an Action Chain does not exist anymore.
 * @param actionChain the Action Chain to check
 */
public static void assertDeleted(ActionChain actionChain) {
    try {
        ActionChain ac = ActionChainFactory.getActionChain(actionChain.getUser(),
                        actionChain.getId());
        fail();
    }
    catch (ObjectNotFoundException e) {
        // correct
    }
}
 
Example #20
Source File: DocumentStore.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example #21
Source File: ActionChainFactoryTest.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks that an Action Chain does not exist anymore.
 * @param actionChain the Action Chain to check
 */
public static void assertDeleted(ActionChain actionChain) {
    try {
        ActionChainFactory.getActionChain(actionChain.getUser(),
                        actionChain.getId());
        fail();
    }
    catch (ObjectNotFoundException e) {
        // correct
    }
}
 
Example #22
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public final T load() {
	final Serializable entityId = resolveNaturalId( this.naturalIdParameters );
	if ( entityId == null ) {
		return null;
	}
	try {
		return (T) this.getIdentifierLoadAccess().load( entityId );
	}
	catch (EntityNotFoundException | ObjectNotFoundException enf) {
		// OK
	}
	return null;
}
 
Example #23
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public T load(Object naturalIdValue) {
	final Serializable entityId = resolveNaturalId( getNaturalIdParameters( naturalIdValue ) );
	if ( entityId == null ) {
		return null;
	}
	try {
		return (T) this.getIdentifierLoadAccess().load( entityId );
	}
	catch (EntityNotFoundException | ObjectNotFoundException e) {
		// OK
	}
	return null;
}
 
Example #24
Source File: HibernateTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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());
	}
}
 
Example #25
Source File: UserDaoTest.java    From wetech-cms with MIT License 5 votes vote down vote up
@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());
}
 
Example #26
Source File: TestUserDao.java    From SpringCloud with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #27
Source File: DocumentStore.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #28
Source File: DocumentStore.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
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());
    }
}
 
Example #29
Source File: StandardEntityNotFoundDelegate.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handleEntityNotFound(String entityName, Serializable id) {
	throw new ObjectNotFoundException( id, entityName );
}
 
Example #30
Source File: CoreModule.java    From onedev with MIT License 4 votes vote down vote up
private void configureWeb() {
	bind(WicketServlet.class).to(DefaultWicketServlet.class);
	bind(WicketFilter.class).to(DefaultWicketFilter.class);
	bind(WebSocketPolicy.class).toProvider(WebSocketPolicyProvider.class);
	bind(EditSupportRegistry.class).to(DefaultEditSupportRegistry.class);
	bind(WebSocketManager.class).to(DefaultWebSocketManager.class);

	bind(AttachmentUploadServlet.class);
	
	contributeFromPackage(EditSupport.class, EditSupport.class);
	
	bind(WebApplication.class).to(OneWebApplication.class);
	bind(Application.class).to(OneWebApplication.class);
	bind(AvatarManager.class).to(DefaultAvatarManager.class);
	bind(WebSocketManager.class).to(DefaultWebSocketManager.class);
	
	contributeFromPackage(EditSupport.class, EditSupportLocator.class);
	
	contribute(WebApplicationConfigurator.class, new WebApplicationConfigurator() {
		
		@Override
		public void configure(WebApplication application) {
			application.mount(new OnePageMapper("/test", TestPage.class));
		}
		
	});
	
	bind(CommitIndexedBroadcaster.class);
	
	contributeFromPackage(DiffRenderer.class, DiffRenderer.class);
	contributeFromPackage(BlobRendererContribution.class, BlobRendererContribution.class);

	contribute(Extension.class, new EmojiExtension());
	contribute(Extension.class, new SourcePositionTrackExtension());
	
	contributeFromPackage(MarkdownProcessor.class, MarkdownProcessor.class);

	contribute(ResourcePackScopeContribution.class, new ResourcePackScopeContribution() {
		
		@Override
		public Collection<Class<?>> getResourcePackScopes() {
			return Lists.newArrayList(OneWebApplication.class);
		}
		
	});
	contribute(ExpectedExceptionContribution.class, new ExpectedExceptionContribution() {
		
		@SuppressWarnings("unchecked")
		@Override
		public Collection<Class<? extends Exception>> getExpectedExceptionClasses() {
			return Sets.newHashSet(ConstraintViolationException.class, EntityNotFoundException.class, 
					ObjectNotFoundException.class, StaleStateException.class, UnauthorizedException.class, 
					OneException.class, PageExpiredException.class, StalePageException.class);
		}
		
	});

	bind(UrlManager.class).to(DefaultUrlManager.class);
	bind(CodeCommentEventBroadcaster.class);
	bind(PullRequestEventBroadcaster.class);
	bind(IssueEventBroadcaster.class);
	bind(BuildEventBroadcaster.class);
	
	bind(TaskButton.TaskFutureManager.class);
	
	bind(UICustomization.class).toInstance(new UICustomization() {
		
		@Override
		public Class<? extends BasePage> getHomePage() {
			return DashboardPage.class;
		}
		
		@Override
		public List<MainTab> getMainTabs() {
			return Lists.newArrayList(
					new ProjectListTab(), new IssueListTab(), 
					new PullRequestListTab(), new BuildListTab());
		}

	});
}