HibernateCORSCacheLoader extends CacheLoader<URI, Boolean> { @Override public Boolean load(final URI origin) throws Exception { Session s = factory.openSession(); try { Transaction t = s.beginTransaction(); Criteria c = s.createCriteria(ClientReferrer.class) .add(Restrictions.eq("uri", origin)) .setProjection(Projections.rowCount()); Long total = Long.valueOf(c.uniqueResult().toString()); t.commit(); return total > 0; } catch (HibernateException e) { return false; } finally { s.close(); } } @Inject  HibernateCORSCacheLoader(final SessionFactory factory); @Override Boolean load(final URI origin);  }
@Test public void loadValid() throws Exception { TEST_DATA_RESOURCE.getAdminApplication() .getBuilder() .referrer("https: .build(); URI valid = new URI("https: HibernateCORSCacheLoader loader = new HibernateCORSCacheLoader(getSessionFactory()); Boolean result = loader.load(valid); assertTrue(result); }
@Test public void loadInvalid() throws Exception { URI invalid = new URI("https: HibernateCORSCacheLoader loader = new HibernateCORSCacheLoader(getSessionFactory()); Boolean result = loader.load(invalid); assertFalse(result); }
@Test public void loadWithHibernateException() throws Exception { SessionFactory mockFactory = Mockito.mock(SessionFactory.class); Session mockSession = Mockito.mock(Session.class); Mockito.doReturn(mockSession).when(mockFactory).openSession(); Mockito.doThrow(HibernateException.class).when(mockSession) .beginTransaction(); URI invalid = new URI("https: HibernateCORSCacheLoader loader = new HibernateCORSCacheLoader(mockFactory); Boolean result = loader.load(invalid); assertFalse(result); }
@Test(expected = Exception.class) public void loadWithGenericException() throws Exception { SessionFactory mockFactory = Mockito.mock(SessionFactory.class); Session mockSession = Mockito.mock(Session.class); Mockito.doReturn(mockSession).when(mockFactory).openSession(); Mockito.doThrow(Exception.class).when(mockSession) .beginTransaction(); URI invalid = new URI("https: HibernateCORSCacheLoader loader = new HibernateCORSCacheLoader(mockFactory); Boolean result = loader.load(invalid); assertFalse(result); }