Example usage for javax.persistence EntityManager close

List of usage examples for javax.persistence EntityManager close

Introduction

In this page you can find the example usage for javax.persistence EntityManager close.

Prototype

public void close();

Source Link

Document

Close an application-managed entity manager.

Usage

From source file:de.zib.gndms.infra.system.GNDMSystem.java

/**
 * Checks if a commit can be done on the database
 *
 * @throws RuntimeException if an error occured while commiting on the database
 *///from   w w w  .  ja  v a2s .co m
private void tryTxExecution() throws RuntimeException {
    final EntityManager em = emf.createEntityManager();
    try {
        em.getTransaction().begin();
        em.getTransaction().commit();
    } catch (RuntimeException re) {
        em.getTransaction().rollback();
        em.close();
        throw re;
    } finally {
        em.close();
    }
}

From source file:it.infn.ct.futuregateway.apiserver.v1.ApplicationCollectionService.java

/**
 * Register a new application.//from  w  w  w.  j  a va 2s.  co m
 *
 * @param application The application to register
 * @return The registered application
 */
@POST
@Status(Response.Status.CREATED)
@Consumes({ MediaType.APPLICATION_JSON, Constants.INDIGOMIMETYPE })
@Produces(Constants.INDIGOMIMETYPE)
public final Application createApplication(final Application application) {
    if (application.getInfrastructureIds() == null || application.getInfrastructureIds().isEmpty()) {
        throw new BadRequestException();
    }
    Date now = new Date();
    application.setDateCreated(now);
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        List<Infrastructure> lstInfra = new LinkedList<>();
        for (String infraId : application.getInfrastructureIds()) {
            Infrastructure infra = em.find(Infrastructure.class, infraId);
            if (infra == null) {
                throw new BadRequestException();
            }
            lstInfra.add(infra);
        }
        application.setInfrastructures(lstInfra);
        em.persist(application);
        et.commit();
        log.debug("New application registered: " + application.getId());
    } catch (BadRequestException re) {
        throw re;
    } catch (RuntimeException re) {
        log.error("Impossible to create the application");
        log.error(re);
        throw re;
    } finally {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        em.close();
    }
    return application;
}

From source file:BO.UserHandler.java

public List<VUser> getPendingFriends(VUser user) {

    EntityManager em;

    EntityManagerFactory emf;//w  ww  .  ja v  a  2 s .c  om
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {
        List<Friendship> list = (List<Friendship>) em
                .createQuery("SELECT f FROM Friendship f WHERE f.receivingFriend.email LIKE :email "
                        + "AND f.didRespond LIKE :didrespond")
                .setParameter("email", user.getEmail()).setParameter("didrespond", false).getResultList();

        List<VUser> senders = new ArrayList<>();

        for (Friendship f : list) {
            senders.add(new VUser(f.getSendingFriend().getEmail(), "", "", "", false));
        }
        return senders;
    } catch (Exception e) {
        return null;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * selects a newsdrilldown by the FirstSpirit-ID.
 *
 * @param fs_id    the FirstSpirit ID//w w w  .  jav  a  2  s. c om
 * @param language the language
 * @return the newsdrilldown or null
 * @throws Exception the exception
 */
private News getNews(Long fs_id, String language) throws Exception {

    EntityManager em = null;
    try {
        em = emf.createEntityManager();

        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM news x WHERE x.fs_id = :fs_id AND x.language = :language").toString());
        query.setParameter("fs_id", fs_id);
        query.setParameter("language", language);

        if (query.getResultList().size() > 0) {
            return (News) query.getSingleResult();
        }

        return null;
    } finally {

        if (em != null) {
            em.close();
        }
    }
}

From source file:mil.navy.med.dzreg.dao.RegistriesManagerDAO.java

/**
 * Check registry for requested person, return a DzPatients object.
 * @param p/*from  ww w . j  a  va  2  s.c om*/
 * @return  DzType registry type object
 */
private DzPatients validPerson(PersonType p) throws Exception, NoResultException {
    EntityManager em = null;
    PersistentServiceFactory psf = null;
    DzPatients registeredPatient = null;

    try {
        psf = PersistentServiceFactory.getInstance(REGISTRY_MANAGER_PU);
        em = psf.getEntityManager();

        Query query = em.createNamedQuery("DzPatients.findByPatid");
        query.setParameter("patid", p.getId());
        registeredPatient = (DzPatients) query.getSingleResult();
    } catch (NoResultException nre) {
        throw nre;
    } catch (Exception ex) {
        throw new Exception("Person " + p.getId() + " not found;");
    } finally {
        em.close();
    }

    return registeredPatient;
}

From source file:org.noorganization.instalist.server.api.ListResource.java

/**
 * Updates a existing list./*from  w  w  w  . j  ava 2 s.  com*/
 * @param _groupId The id of the group containing the list.
 * @param _listUUID The uuid of the list to update.
 * @param _listInfo Information for changing the list. Not all information needs to be set.
 */
@PUT
@TokenSecured
@Path("{listuuid}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response putList(@PathParam("groupid") int _groupId, @PathParam("listuuid") String _listUUID,
        ListInfo _listInfo) throws Exception {
    if ((_listInfo.getDeleted() != null && _listInfo.getDeleted())
            || (_listInfo.getName() != null && _listInfo.getName().length() == 0)
            || (_listInfo.getUUID() != null && !_listInfo.getUUID().equals(_listUUID)))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID listUUID;
    UUID categoryUUID = null;
    boolean removeCategory = false;
    try {
        listUUID = UUID.fromString(_listUUID);
        if (_listInfo.getCategoryUUID() != null)
            categoryUUID = UUID.fromString(_listInfo.getCategoryUUID());
        else if (_listInfo.getRemoveCategory() != null && _listInfo.getRemoveCategory())
            removeCategory = true;
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }
    Instant updated;
    Instant now = Instant.now();
    if (_listInfo.getLastChanged() != null) {
        updated = _listInfo.getLastChanged().toInstant();
        if (now.isBefore(updated))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    } else
        updated = now;

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IListController listController = ControllerFactory.getListController(manager);
    try {
        listController.update(_groupId, listUUID, _listInfo.getName(), categoryUUID, removeCategory, updated);
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The new data is in " + "conflict with a saved list."));
    } catch (NotFoundException _e) {
        return ResponseFactory.generateNotFound(new Error().withMessage("The list was not " + "found."));
    } catch (GoneException _e) {
        return ResponseFactory.generateGone(new Error().withMessage("The list was " + "deleted already."));
    } catch (BadRequestException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);
    } finally {
        manager.close();
    }
    return ResponseFactory.generateOK(null);
}

From source file:mil.navy.med.dzreg.dao.RegistriesManagerDAO.java

/**
 * Returns a list of available registry types.
 * @return  List<RegistryType>/*from w  w w .ja  v a2s .  c  o  m*/
 */
public List<RegistryType> getRegistryTypes() {
    EntityManager em = null;
    List<RegistryType> types = new ArrayList<RegistryType>();
    PersistentServiceFactory psf = null;

    try {
        psf = PersistentServiceFactory.getInstance(REGISTRY_MANAGER_PU);
        em = psf.getEntityManager();

        Query query = em.createNamedQuery("DzType.findAll");
        Collection<DzType> results = query.getResultList();

        for (DzType d : results) {
            log.debug(d.toString());
            types.add(new RegistryType(d.getDztypeId(), d.getDescr()));
        }
    } catch (javax.persistence.NoResultException nr) {
        log.error(nr);
    } finally {
        em.close();
    }

    return types;
}

From source file:com.enioka.jqm.tools.JobManagerHandler.java

private Integer addDeliverable(String path, String fileLabel) throws IOException {
    Deliverable d = null;//  www  .  ja v  a  2s .com
    EntityManager em = Helpers.getNewEm();
    try {
        this.ji = em.find(JobInstance.class, ji.getId());

        String outputRoot = this.ji.getNode().getDlRepo();
        String ext = FilenameUtils.getExtension(path);
        String relDestPath = "" + ji.getJd().getApplicationName() + "/" + ji.getId() + "/" + UUID.randomUUID()
                + "." + ext;
        String absDestPath = FilenameUtils.concat(outputRoot, relDestPath);
        String fileName = FilenameUtils.getName(path);
        FileUtils.moveFile(new File(path), new File(absDestPath));
        jqmlogger.debug("A deliverable is added. Stored as " + absDestPath + ". Initial name: " + fileName);

        em.getTransaction().begin();
        d = Helpers.createDeliverable(relDestPath, fileName, fileLabel, this.ji.getId(), em);
        em.getTransaction().commit();
    } finally {
        em.close();
    }
    return d.getId();
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@GET
@Path("{id}/icon")
@Produces("image/png")
@PermitAll/*from ww w  .j av  a  2s  . c o  m*/
public Response getFeedIcon(@Context ServletContext ctx, @PathParam("id") int feedId,
        @QueryParam("token") String tokenString) throws IOException {
    EntityManager em = HibernateUtil.getEntityManager();
    Token token;
    Feed feed;
    byte[] data;

    try {
        token = Token.loadToken(em, tokenString);

        feed = em.find(Feed.class, feedId);
        if (feed == null) {
            return Response.status(Response.Status.NOT_FOUND).entity(emptyGif(ctx)).build();
        }
        if (!feed.getUser().equals(token.getUser())) {
            return Response.status(Response.Status.FORBIDDEN).entity(emptyGif(ctx)).build();
        }

        data = feed.getData().getIconData();
        if (data == null)
            data = emptyGif(ctx);

        return Response.ok(data).build();
    } finally {
        em.close();
    }
}

From source file:de.zib.gndms.dspace.service.SubspaceServiceImpl.java

@Override
@RequestMapping(value = "/_{subspaceId}", method = RequestMethod.DELETE)
@Secured("ROLE_ADMIN")
public ResponseEntity<Specifier<Facets>> deleteSubspace(@PathVariable final String subspaceId,
        @RequestHeader("DN") final String dn) {
    GNDMSResponseHeader headers = getSubspaceHeaders(subspaceId, dn);

    if (!subspaceProvider.exists(subspaceId)) {
        logger.warn("Subspace " + subspaceId + " not found");
        return new ResponseEntity<Specifier<Facets>>(null, headers, HttpStatus.NOT_FOUND);
    }/*  w ww.  ja  v a  2s .  c o  m*/

    final EntityManager em = emf.createEntityManager();
    TxFrame tx = new TxFrame(em);
    try {
        final Taskling taskling = subspaceProvider.delete(subspaceId);

        final TaskClient client = new TaskClient(localBaseUrl);
        client.setRestTemplate(restTemplate);
        final Specifier<Facets> spec = TaskClient.TaskServiceAux.getTaskSpecifier(client, taskling.getId(),
                uriFactory, null, dn);
        return new ResponseEntity<Specifier<Facets>>(spec, headers, HttpStatus.OK);
    } catch (NoSuchElementException e) {
        return new ResponseEntity<Specifier<Facets>>(null, headers, HttpStatus.NOT_FOUND);
    } finally {
        tx.finish();
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}