Search in sources :

Example 6 with HibernateTemplate

use of org.springframework.orm.hibernate3.HibernateTemplate in project gocd by gocd.

the class MaterialRepositoryIntegrationTest method findModificationsSince_shouldCacheResults.

@Test
public void findModificationsSince_shouldCacheResults() {
    SvnMaterial material = MaterialsMother.svnMaterial();
    MaterialRevision zero = saveOneScmModification(material, "user1", "file1");
    MaterialRevision first = saveOneScmModification(material, "user1", "file1");
    MaterialRevision second = saveOneScmModification(material, "user2", "file2");
    MaterialRevision third = saveOneScmModification(material, "user2", "file2");
    repo.findModificationsSince(material, first);
    HibernateTemplate mockTemplate = mock(HibernateTemplate.class);
    repo.setHibernateTemplate(mockTemplate);
    List<Modification> modifications = repo.findModificationsSince(material, first);
    assertThat(modifications.size(), is(2));
    assertEquals(third.getLatestModification(), modifications.get(0));
    assertEquals(second.getLatestModification(), modifications.get(1));
    verifyNoMoreInteractions(mockTemplate);
}
Also used : SvnMaterial(com.thoughtworks.go.config.materials.svn.SvnMaterial) HibernateTemplate(org.springframework.orm.hibernate3.HibernateTemplate) Test(org.junit.Test)

Example 7 with HibernateTemplate

use of org.springframework.orm.hibernate3.HibernateTemplate in project gocd by gocd.

the class MaterialRepositoryIntegrationTest method findOrCreateFrom_shouldEnsureOnlyOneThreadCanCreateAtATime.

@Test
public void findOrCreateFrom_shouldEnsureOnlyOneThreadCanCreateAtATime() throws Exception {
    final Material svn = MaterialsMother.svnMaterial("url", null, "username", "password", false, null);
    HibernateTemplate mockTemplate = mock(HibernateTemplate.class);
    repo = new MaterialRepository(repo.getSessionFactory(), goCache, 200, transactionSynchronizationManager, materialConfigConverter, materialExpansionService, databaseStrategy) {

        @Override
        public MaterialInstance findMaterialInstance(Material material) {
            MaterialInstance result = super.findMaterialInstance(material);
            // force multiple threads to try to create the material
            TestUtils.sleepQuietly(20);
            return result;
        }

        @Override
        public void saveOrUpdate(MaterialInstance material) {
            material.setId(10);
            super.saveOrUpdate(material);
        }
    };
    repo.setHibernateTemplate(mockTemplate);
    List<Thread> threads = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        Thread thread = new Thread(new Runnable() {

            public void run() {
                repo.findOrCreateFrom(svn);
            }
        }, "thread-" + i);
        threads.add(thread);
        thread.start();
    }
    for (Thread thread : threads) {
        thread.join();
    }
    verify(mockTemplate, times(1)).saveOrUpdate(Mockito.<MaterialInstance>any());
}
Also used : HibernateTemplate(org.springframework.orm.hibernate3.HibernateTemplate) PackageMaterial(com.thoughtworks.go.config.materials.PackageMaterial) GitMaterial(com.thoughtworks.go.config.materials.git.GitMaterial) SvnMaterial(com.thoughtworks.go.config.materials.svn.SvnMaterial) PluggableSCMMaterial(com.thoughtworks.go.config.materials.PluggableSCMMaterial) HgMaterial(com.thoughtworks.go.config.materials.mercurial.HgMaterial) ScmMaterial(com.thoughtworks.go.config.materials.ScmMaterial) P4Material(com.thoughtworks.go.config.materials.perforce.P4Material) DependencyMaterial(com.thoughtworks.go.config.materials.dependency.DependencyMaterial) PackageMaterialInstance(com.thoughtworks.go.domain.materials.packagematerial.PackageMaterialInstance) PluggableSCMMaterialInstance(com.thoughtworks.go.domain.materials.scm.PluggableSCMMaterialInstance) SvnMaterialInstance(com.thoughtworks.go.domain.materials.svn.SvnMaterialInstance) Test(org.junit.Test)

Example 8 with HibernateTemplate

use of org.springframework.orm.hibernate3.HibernateTemplate in project opennms by OpenNMS.

the class AbstractDaoRestServiceWithDTO method getPropertyValues.

@GET
@Path("properties/{propertyId}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getPropertyValues(@PathParam("propertyId") final String propertyId, @QueryParam("q") final String query, @QueryParam("limit") final Integer limit) {
    Set<SearchProperty> props = getQueryProperties();
    // Find the property with the matching ID
    Optional<SearchProperty> prop = props.stream().filter(p -> p.getId().equals(propertyId)).findAny();
    if (prop.isPresent()) {
        SearchProperty property = prop.get();
        if (property.values != null && property.values.size() > 0) {
            final Set<String> validValues;
            if (query != null && query.length() > 0) {
                validValues = property.values.keySet().stream().filter(v -> v.contains(query)).collect(Collectors.toSet());
            } else {
                validValues = property.values.keySet();
            }
            switch(property.type) {
                case FLOAT:
                    return Response.ok(new FloatCollection(validValues.stream().map(Float::parseFloat).collect(Collectors.toList()))).build();
                case INTEGER:
                    return Response.ok(new IntegerCollection(validValues.stream().map(Integer::parseInt).collect(Collectors.toList()))).build();
                case LONG:
                    return Response.ok(new LongCollection(validValues.stream().map(Long::parseLong).collect(Collectors.toList()))).build();
                case IP_ADDRESS:
                case STRING:
                    return Response.ok(new StringCollection(validValues)).build();
                case TIMESTAMP:
                    return Response.ok(new DateCollection(validValues.stream().map(v -> {
                        try {
                            return ISO8601DateEditor.stringToDate(v);
                        } catch (IllegalArgumentException | UnsupportedOperationException e) {
                            LOG.error("Invalid date in value list: " + v, e);
                            return null;
                        }
                    }).filter(Objects::nonNull).collect(Collectors.toList()))).build();
                default:
                    return Response.noContent().build();
            }
        }
        switch(property.type) {
            case FLOAT:
                List<Float> floats = new HibernateTemplate(m_sessionFactory).execute(new HibernateListCallback<Float>(property, query, limit));
                return Response.ok(new FloatCollection(floats)).build();
            case INTEGER:
                List<Integer> ints = new HibernateTemplate(m_sessionFactory).execute(new HibernateListCallback<Integer>(property, query, limit));
                return Response.ok(new IntegerCollection(ints)).build();
            case LONG:
                List<Long> longs = new HibernateTemplate(m_sessionFactory).execute(new HibernateListCallback<Long>(property, query, limit));
                return Response.ok(new LongCollection(longs)).build();
            case IP_ADDRESS:
                List<InetAddress> addresses = new HibernateTemplate(m_sessionFactory).execute(new HibernateListCallback<InetAddress>(property, query, limit));
                return Response.ok(new StringCollection(addresses.stream().map(InetAddressUtils::str).collect(Collectors.toList()))).build();
            case STRING:
                List<String> strings = new HibernateTemplate(m_sessionFactory).execute(new HibernateListCallback<String>(property, query, limit));
                return Response.ok(new StringCollection(strings)).build();
            case TIMESTAMP:
                List<Date> dates = new HibernateTemplate(m_sessionFactory).execute(new HibernateListCallback<Date>(property, query, limit));
                return Response.ok(new DateCollection(dates)).build();
            default:
                return Response.noContent().build();
        }
    } else {
        // 404
        return Response.status(Status.NOT_FOUND).build();
    }
}
Also used : QueryParameters(org.opennms.web.utils.QueryParameters) Produces(javax.ws.rs.Produces) Date(java.util.Date) SearchPropertyCollection(org.opennms.web.rest.support.SearchPropertyCollection) Path(javax.ws.rs.Path) SecurityContext(javax.ws.rs.core.SecurityContext) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) CriteriaBuilderSearchVisitor(org.opennms.web.rest.support.CriteriaBuilderSearchVisitor) JaxbListWrapper(org.opennms.core.config.api.JaxbListWrapper) SearchConditionVisitor(org.apache.cxf.jaxrs.ext.search.SearchConditionVisitor) InetAddress(java.net.InetAddress) ReentrantReadWriteUpdateLock(com.googlecode.concurentlocks.ReentrantReadWriteUpdateLock) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) Event(org.opennms.netmgt.xml.event.Event) Map(java.util.Map) ReadWriteUpdateLock(com.googlecode.concurentlocks.ReadWriteUpdateLock) Query(org.hibernate.Query) FloatCollection(org.opennms.web.rest.support.FloatCollection) HibernateCallback(org.springframework.orm.hibernate3.HibernateCallback) QueryParametersBuilder(org.opennms.web.utils.QueryParametersBuilder) DELETE(javax.ws.rs.DELETE) PropertyNotFoundException(org.apache.cxf.jaxrs.ext.search.PropertyNotFoundException) MessageFormatter(org.slf4j.helpers.MessageFormatter) MultivaluedMapImpl(org.opennms.web.rest.support.MultivaluedMapImpl) Context(javax.ws.rs.core.Context) InetAddressUtils(org.opennms.core.utils.InetAddressUtils) Collection(java.util.Collection) SessionFactory(org.hibernate.SessionFactory) Set(java.util.Set) Collectors(java.util.stream.Collectors) Criteria(org.opennms.core.criteria.Criteria) Serializable(java.io.Serializable) CriteriaBehavior(org.opennms.web.rest.support.CriteriaBehavior) Objects(java.util.Objects) List(java.util.List) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) UriInfo(javax.ws.rs.core.UriInfo) CriteriaBuilder(org.opennms.core.criteria.CriteriaBuilder) EventProxyException(org.opennms.netmgt.events.api.EventProxyException) HibernateException(org.hibernate.HibernateException) PathParam(javax.ws.rs.PathParam) GET(javax.ws.rs.GET) HibernateTemplate(org.springframework.orm.hibernate3.HibernateTemplate) SearchContext(org.apache.cxf.jaxrs.ext.search.SearchContext) Session(org.hibernate.Session) OnmsDao(org.opennms.netmgt.dao.api.OnmsDao) ISO8601DateEditor(org.opennms.web.api.ISO8601DateEditor) ArrayList(java.util.ArrayList) SQLException(java.sql.SQLException) IntegerCollection(org.opennms.web.rest.support.IntegerCollection) Qualifier(org.springframework.beans.factory.annotation.Qualifier) SearchBean(org.apache.cxf.jaxrs.ext.search.SearchBean) Status(javax.ws.rs.core.Response.Status) Order(org.opennms.core.criteria.Order) SearchProperty(org.opennms.web.rest.support.SearchProperty) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) StringCollection(org.opennms.web.rest.support.StringCollection) RestUtils(org.opennms.web.api.RestUtils) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) LongCollection(org.opennms.web.rest.support.LongCollection) Lock(java.util.concurrent.locks.Lock) PUT(javax.ws.rs.PUT) SearchCondition(org.apache.cxf.jaxrs.ext.search.SearchCondition) Collections(java.util.Collections) EventProxy(org.opennms.netmgt.events.api.EventProxy) DateCollection(org.opennms.web.rest.support.DateCollection) CriteriaBuilderUtils(org.opennms.web.utils.CriteriaBuilderUtils) Transactional(org.springframework.transaction.annotation.Transactional) HibernateTemplate(org.springframework.orm.hibernate3.HibernateTemplate) InetAddressUtils(org.opennms.core.utils.InetAddressUtils) LongCollection(org.opennms.web.rest.support.LongCollection) DateCollection(org.opennms.web.rest.support.DateCollection) SearchProperty(org.opennms.web.rest.support.SearchProperty) FloatCollection(org.opennms.web.rest.support.FloatCollection) IntegerCollection(org.opennms.web.rest.support.IntegerCollection) Date(java.util.Date) StringCollection(org.opennms.web.rest.support.StringCollection) Objects(java.util.Objects) InetAddress(java.net.InetAddress) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 9 with HibernateTemplate

use of org.springframework.orm.hibernate3.HibernateTemplate in project simple-java by angryziber.

the class HibernatePhotoSpotRepositoryIntegrationTest method setUp.

@Before
public void setUp() throws Exception {
    dataSource = new DriverManagerDataSource("jdbc:h2:mem:hibernate;DB_CLOSE_DELAY=-1", "sa", "sa");
    System.setProperty("hibernate.dialect", H2Dialect.class.getName());
    System.setProperty("hibernate.hbm2ddl.auto", "create-drop");
    AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
    sessionFactory.setDataSource(dataSource);
    sessionFactory.setAnnotatedClasses(new Class[] { PhotoSpot.class });
    sessionFactory.afterPropertiesSet();
    repo.hibernate = new HibernateTemplate(sessionFactory.getObject());
}
Also used : H2Dialect(org.hibernate.dialect.H2Dialect) AnnotationSessionFactoryBean(org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean) DriverManagerDataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) HibernateTemplate(org.springframework.orm.hibernate3.HibernateTemplate) Before(org.junit.Before)

Example 10 with HibernateTemplate

use of org.springframework.orm.hibernate3.HibernateTemplate in project opennms by OpenNMS.

the class AnnotationIT method assertLoadAll.

private <T> void assertLoadAll(Class<T> annotatedClass, Checker<T> checker) {
    HibernateTemplate template = new HibernateTemplate(m_sessionFactory);
    Collection<T> results = template.loadAll(annotatedClass);
    assertNotNull(results);
    checker.checkCollection(results);
    for (T t : results) {
        checker.check(t);
    }
}
Also used : HibernateTemplate(org.springframework.orm.hibernate3.HibernateTemplate)

Aggregations

HibernateTemplate (org.springframework.orm.hibernate3.HibernateTemplate)13 Test (org.junit.Test)10 SvnMaterial (com.thoughtworks.go.config.materials.svn.SvnMaterial)6 PackageMaterialInstance (com.thoughtworks.go.domain.materials.packagematerial.PackageMaterialInstance)5 PluggableSCMMaterialInstance (com.thoughtworks.go.domain.materials.scm.PluggableSCMMaterialInstance)5 SvnMaterialInstance (com.thoughtworks.go.domain.materials.svn.SvnMaterialInstance)5 HibernateCallback (org.springframework.orm.hibernate3.HibernateCallback)4 PackageMaterial (com.thoughtworks.go.config.materials.PackageMaterial)3 PluggableSCMMaterial (com.thoughtworks.go.config.materials.PluggableSCMMaterial)3 ScmMaterial (com.thoughtworks.go.config.materials.ScmMaterial)3 DependencyMaterial (com.thoughtworks.go.config.materials.dependency.DependencyMaterial)3 GitMaterial (com.thoughtworks.go.config.materials.git.GitMaterial)3 HgMaterial (com.thoughtworks.go.config.materials.mercurial.HgMaterial)3 P4Material (com.thoughtworks.go.config.materials.perforce.P4Material)3 SQLException (java.sql.SQLException)3 HibernateException (org.hibernate.HibernateException)2 Session (org.hibernate.Session)2 ReadWriteUpdateLock (com.googlecode.concurentlocks.ReadWriteUpdateLock)1 ReentrantReadWriteUpdateLock (com.googlecode.concurentlocks.ReentrantReadWriteUpdateLock)1 AgentIdentifier (com.thoughtworks.go.remote.AgentIdentifier)1