Example usage for org.hibernate StatelessSession close

List of usage examples for org.hibernate StatelessSession close

Introduction

In this page you can find the example usage for org.hibernate StatelessSession close.

Prototype

void close();

Source Link

Document

Close the stateless session and release the JDBC connection.

Usage

From source file:monasca.api.infrastructure.persistence.hibernate.AlarmHibernateUtils.java

License:Apache License

public List<String> findAlarmIds(String tenantId, Map<String, String> dimensions) {
    logger.trace(BaseSqlRepo.ORM_LOG_MARKER, "findAlarmIds(...) entering");
    List<String> alarmIdList = null;

    StatelessSession session = null;
    try {//from w  ww. ja v a  2  s  . c o  m
        session = sessionFactory.openStatelessSession();

        final String sql = this.findAlarmQueryString(dimensions);
        final Query query = session.createSQLQuery(sql).setString("tenantId", tenantId);

        this.bindDimensionsToQuery(query, dimensions);

        @SuppressWarnings("unchecked")
        List<Object[]> rows = query.list();
        alarmIdList = Lists.newArrayListWithCapacity(rows.size());
        for (Object[] row : rows) {
            String id = (String) row[0];
            alarmIdList.add(id);
        }

    } finally {
        if (session != null) {
            session.close();
        }
    }

    // no need to check if alarmIdList != null, because in case of exception method
    // will leave immediately, otherwise list wont be null.
    return alarmIdList;
}

From source file:monasca.thresh.infrastructure.persistence.hibernate.AlarmSqlImpl.java

License:Apache License

@SuppressWarnings("unchecked")
private List<Alarm> findAlarms(@Nonnull final LookupHelper lookupHelper) {
    StatelessSession session = null;

    try {//from   w  ww.ja  v a 2 s. c om
        session = sessionFactory.openStatelessSession();
        final Criteria criteria = lookupHelper.apply(session.createCriteria(AlarmDb.class, "a")
                .createAlias("a.subAlarms", "sa").createAlias("a.alarmDefinition", "ad")
                .add(Restrictions.isNull("ad.deletedAt")).addOrder(Order.asc("a.id"))
                .setProjection(Projections.projectionList().add(Projections.property("a.id"))
                        .add(Projections.property("a.alarmDefinition.id")).add(Projections.property("a.state"))
                        .add(Projections.alias(Projections.property("sa.id"), "sub_alarm_id"))
                        .add(Projections.property("sa.expression"))
                        .add(Projections.property("sa.subExpression.id"))
                        .add(Projections.property("ad.tenantId")))
                .setReadOnly(true));
        assert criteria != null;
        return this.createAlarms(session, (List<Object[]>) criteria.list(), lookupHelper);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:org.babyfish.hibernate.dialect.OracleDistinctLimits.java

License:Open Source License

public static void install(SessionFactoryImplementor sfi) {
    if (!SettingsFactory.isDistinctRankCreateable(sfi.getProperties())) {
        return;/*  w ww .  j a  v a  2 s  .c o m*/
    }
    LOGGER.info(LOGGER_RESOURCE.tryToCreateAnalyticFunction(SettingsFactory.CREATE_ORACLE_DISTINCT_RANK, "true",
            DISTINCT_RANK));
    StatelessSession sls = sfi.openStatelessSession();
    try {
        Connection con = ((SessionImplementor) sls).connection();
        installPLSQLWrapper(con);
    } catch (SQLException ex) {
        throw new QueryException(ex);
    } catch (IOException ex) {
        throw new HibernateException("Can not install the installable dialect", ex);
    } finally {
        sls.close();
    }
}

From source file:org.dcm4chee.arc.retrieve.impl.RetrieveServiceImpl.java

License:LGPL

@Override
public boolean calculateMatches(RetrieveContext ctx) throws DicomServiceException {
    StatelessSession session = openStatelessSession();
    Collection<InstanceLocations> matches = ctx.getMatches();
    matches.clear();// w  ww. j  av a 2 s  . com
    try {
        HashMap<Long, InstanceLocations> instMap = new HashMap<>();
        HashMap<Long, Attributes> seriesAttrsMap = new HashMap<>();
        HashMap<Long, StudyInfo> studyInfoMap = new HashMap<>();
        Series.MetadataUpdate metadataUpdate = ctx.getSeriesMetadataUpdate();
        if (metadataUpdate != null && metadataUpdate.instancePurgeState == Series.InstancePurgeState.PURGED) {
            SeriesAttributes seriesAttributes = getSeriesAttributes(session, metadataUpdate.seriesPk);
            studyInfoMap.put(seriesAttributes.studyInfo.getStudyPk(), seriesAttributes.studyInfo);
            ctx.getSeriesInfos().add(seriesAttributes.seriesInfo);
            addLocationsFromMetadata(ctx, metadataUpdate.storageID, metadataUpdate.storagePath,
                    seriesAttributes.attrs);
        } else {
            for (Tuple tuple : createQuery(ctx, session).fetch()) {
                Long instPk = tuple.get(QInstance.instance.pk);
                InstanceLocations match = instMap.get(instPk);
                if (match == null) {
                    Long seriesPk = tuple.get(QSeries.series.pk);
                    Attributes seriesAttrs = seriesAttrsMap.get(seriesPk);
                    if (seriesAttrs == null) {
                        SeriesAttributes seriesAttributes = getSeriesAttributes(session, seriesPk);
                        studyInfoMap.put(seriesAttributes.studyInfo.getStudyPk(), seriesAttributes.studyInfo);
                        ctx.getSeriesInfos().add(seriesAttributes.seriesInfo);
                        ctx.setPatientUpdatedTime(seriesAttributes.patientUpdatedTime);
                        seriesAttrsMap.put(seriesPk, seriesAttrs = seriesAttributes.attrs);
                    }
                    Attributes instAttrs = AttributesBlob.decodeAttributes(
                            tuple.get(QueryBuilder.instanceAttributesBlob.encodedAttributes), null);
                    Attributes.unifyCharacterSets(seriesAttrs, instAttrs);
                    instAttrs.addAll(seriesAttrs);
                    match = instanceLocationsFromDB(tuple, instAttrs);
                    matches.add(match);
                    instMap.put(instPk, match);
                }
                addLocation(match, tuple);
            }
            if (ctx.isConsiderPurgedInstances()) {
                for (Tuple tuple : queryMetadataStoragePath(ctx, session).fetch()) {
                    Long seriesPk = tuple.get(QSeries.series.pk);
                    SeriesAttributes seriesAttributes = getSeriesAttributes(session, seriesPk);
                    studyInfoMap.put(seriesAttributes.studyInfo.getStudyPk(), seriesAttributes.studyInfo);
                    ctx.getSeriesInfos().add(seriesAttributes.seriesInfo);
                    ctx.setPatientUpdatedTime(seriesAttributes.patientUpdatedTime);
                    addLocationsFromMetadata(ctx, tuple.get(QMetadata.metadata.storageID),
                            tuple.get(QMetadata.metadata.storagePath), seriesAttributes.attrs);
                }
            }
        }
        ctx.setNumberOfMatches(matches.size());
        ctx.getStudyInfos().addAll(studyInfoMap.values());
        updateStudyAccessTime(ctx);
        return !matches.isEmpty();
    } catch (IOException e) {
        throw new DicomServiceException(Status.UnableToCalculateNumberOfMatches, e);
    } finally {
        session.close();
    }
}

From source file:org.dcm4chee.archive.ejb.query.CompositeQueryBean.java

License:LGPL

@Override
@Remove//from w w  w  .j av a 2  s .c  om
public void close() {
    StatelessSession s = session;
    Connection c = connection;
    connection = null;
    session = null;
    query = null;
    s.close();
    try {
        c.close();
    } catch (SQLException e) {
        throw new EJBException(e);
    }
}

From source file:org.dcm4chee.archive.ejb.query.ModalityWorklistQueryBean.java

License:LGPL

@Override
@Remove/*from  w ww .j  a v  a2 s  . c om*/
public void close() {
    StatelessSession s = session;
    Connection c = connection;
    connection = null;
    session = null;
    results = null;
    s.close();
    try {
        c.close();
    } catch (SQLException e) {
        throw new EJBException(e);
    }
}

From source file:org.dcm4chee.archive.mwl.dao.MWLQueryService.java

License:LGPL

@Remove
public void close() {
    StatelessSession s = session;
    Connection c = connection;//  w  w w. j  a v  a 2s  .c om
    connection = null;
    session = null;
    results = null;
    s.close();
    try {
        c.close();
    } catch (SQLException e) {
        throw new EJBException(e);
    }
}

From source file:org.dcm4chee.archive.query.dao.QueryService.java

License:LGPL

@Remove
public void close() {
    StatelessSession s = session;
    Connection c = connection;//from w ww  .  j a  va2s .  c o m
    connection = null;
    session = null;
    query = null;
    results = null;
    s.close();
    try {
        c.close();
    } catch (Exception e) {
        //TODO
    }
}

From source file:org.geolatte.demo1.services.RiverService.java

License:Open Source License

@Path("/cities")
@GET/*from  ww w . ja  va  2  s .  c o m*/
@Produces(MediaType.APPLICATION_JSON)
public List<PlaceTo> getEndangeredCities(@QueryParam("x") final float x, @QueryParam("y") final float y) {

    StatelessSession session = HibernateUtil.getSessionFactory().openStatelessSession();
    try {
        // Begin unit of work
        session.beginTransaction();

        SimpleTransformerSink<PlaceTo> sink = new SimpleTransformerSink<PlaceTo>();

        ClosedTransformerChain chain = TransformerChainFactory.<Geometry, PlaceTo>newChain()
                .add(new RiverSegmentSource(x, y, session)) // <Geometry>
                .add(new Buffer()) // <Geometry> -> <Geometry>
                .add(new GetCitiesWithinBounds(session)) // <Geometry> -> [<Place>]
                .addFilter(new FilterDuplicates<Place>()) // <Place>    -> <Place>
                .add(new PlaceToTransferObject()) // <Place>    -> <PlaceTo>
                .last(sink); // collect

        chain.addTransformerEventListener(new TransformerEventListener() {
            @Override
            public void ErrorOccurred(TransformerErrorEvent event) {
                // Log errors here
            }
        });

        chain.run();

        List<PlaceTo> endangeredPlaces = sink.getCollectedOutput();

        session.getTransaction().commit();

        return endangeredPlaces;
    } catch (Exception ex) {
        HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
    } finally {
        session.close();
    }

    return Collections.emptyList();
}

From source file:org.jahia.modules.external.id.ExternalProviderInitializerServiceImpl.java

License:Open Source License

@Override
public void delete(List<String> externalIds, String providerKey, boolean includeDescendants)
        throws RepositoryException {
    if (externalIds.isEmpty()) {
        return;//from   ww w.  jav  a2  s.c  o  m
    }
    StatelessSession session = null;
    try {
        List<Integer> hashes = new LinkedList<Integer>();
        for (String externalId : externalIds) {
            int hash = externalId.hashCode();
            hashes.add(hash);
        }
        session = hibernateSessionFactory.openStatelessSession();
        session.beginTransaction();

        // delete all
        session.createQuery(
                "delete from UuidMapping where providerKey=:providerKey and externalIdHash in (:externalIds)")
                .setString("providerKey", providerKey).setParameterList("externalIds", hashes).executeUpdate();

        if (includeDescendants) {
            // delete descendants
            Query selectStmt = session
                    .createQuery(
                            "from UuidMapping where providerKey=:providerKey and externalId like :externalId")
                    .setString("providerKey", providerKey);
            for (String externalId : externalIds) {
                selectStmt.setString("externalId", externalId + "/%");
                List<?> descendants = selectStmt.list();

                for (Object mapping : descendants) {
                    UuidMapping m = (UuidMapping) mapping;
                    session.delete(m);
                    invalidateCache(m.getExternalIdHash(), providerKey);
                }
            }
        }

        session.getTransaction().commit();

        for (String externalId : externalIds) {
            int hash = externalId.hashCode();
            invalidateCache(hash, providerKey);
        }
    } catch (Exception e) {
        if (session != null) {
            session.getTransaction().rollback();
        }
        throw new RepositoryException(e);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}