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:org.noorganization.instalist.server.api.TagResource.java

/**
 * Creates the tag.//from w  ww  .j a v  a 2s .  co m
 * @param _groupId The id of the group that should contain the new tag.
 * @param _entity Data needed for creation.
 */
@POST
@TokenSecured
@Consumes("application/json")
@Produces({ "application/json" })
public Response postTag(@PathParam("groupid") int _groupId, TagInfo _entity) throws Exception {
    if (_entity.getUUID() == null || (_entity.getName() != null && _entity.getName().length() == 0)
            || (_entity.getDeleted() != null && _entity.getDeleted()))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toCreate;
    try {
        toCreate = UUID.fromString(_entity.getUUID());
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }
    Instant created;
    if (_entity.getLastChanged() != null) {
        created = _entity.getLastChanged().toInstant();
        if (Instant.now().isBefore(created))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    } else
        created = Instant.now();

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    ITagController tagController = ControllerFactory.getTagController(manager);
    try {
        tagController.add(_groupId, toCreate, _entity.getName(), created);
    } catch (ConflictException _e) {
        return ResponseFactory
                .generateConflict(new Error().withMessage("The sent data would " + "conflict with saved tag."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateCreated(null);
}

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

/**
 * {@inheritDoc}/*from   w  w w. ja va 2s  . c o m*/
 * 
 * @see org.opencastproject.security.api.RoleDirectoryService#getRoles()
 */
@Override
public String[] getRoles() {
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("roles");
        @SuppressWarnings("unchecked")
        List<String> results = q.getResultList();
        return results.toArray(new String[results.size()]);
    } finally {
        if (em != null)
            em.close();
    }
}

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

/**
 * Get a single list.//from  w w  w .j av  a  2 s . c  o  m
 * @param _groupId The id of the group, containing the list.
 *     
 */
@GET
@TokenSecured
@Path("{listuuid}")
@Produces({ "application/json" })
public Response getList(@PathParam("groupid") int _groupId, @PathParam("listuuid") String _listUUID)
        throws Exception {
    UUID listUUID;
    try {
        listUUID = UUID.fromString(_listUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);
    IListController listController = ControllerFactory.getListController(manager);

    ShoppingList foundList = listController.findByGroupAndUUID(group, listUUID);
    if (foundList == null) {
        if (listController.findDeletedByGroupAndUUID(group, listUUID) == null) {
            manager.close();
            return ResponseFactory
                    .generateNotFound(new Error().withMessage("The requested " + "list was not found."));
        }
        manager.close();
        return ResponseFactory.generateGone(new Error().withMessage("The requested list was " + "deleted."));
    }

    ListInfo rtn = new ListInfo();
    rtn.setUUID(foundList.getUUID());
    rtn.setName(foundList.getName());
    if (foundList.getCategory() != null)
        rtn.setCategoryUUID(foundList.getCategory().getUUID());
    rtn.setLastChanged(Date.from(foundList.getUpdated()));
    rtn.setDeleted(false);

    return ResponseFactory.generateOK(rtn);
}

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

/**
 * Returns the unit.//  w ww .j  a v  a2s  .c om
 * @param _groupId The croup containing the requested unit.
 * @param _unitUUID The uuid of the requested unit.
 */
@GET
@TokenSecured
@Path("{unituuid}")
@Produces({ "application/json" })
public Response getUnit(@PathParam("groupid") int _groupId, @PathParam("unituuid") String _unitUUID)
        throws Exception {
    try {

        UUID toFind;
        try {
            toFind = UUID.fromString(_unitUUID);
        } catch (IllegalArgumentException _e) {
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
        }

        EntityManager manager = DatabaseHelper.getInstance().getManager();
        IUnitController unitController = ControllerFactory.getUnitController(manager);
        DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

        Unit resultUnit = unitController.findByGroupAndUUID(group, toFind);
        if (resultUnit == null) {
            if (unitController.findDeletedByGroupAndUUID(group, toFind) == null) {
                manager.close();
                return ResponseFactory
                        .generateNotFound(new Error().withMessage("The requested " + "unit was not found."));
            }
            manager.close();
            return ResponseFactory
                    .generateGone(new Error().withMessage("The requested unit has " + "been deleted."));
        }
        manager.close();

        UnitInfo rtn = new UnitInfo().withDeleted(false);
        rtn.setName(resultUnit.getName());
        rtn.setUUID(resultUnit.getUUID());
        rtn.setLastChanged(Date.from(resultUnit.getUpdated()));

        return ResponseFactory.generateOK(rtn);
    } catch (Exception _e) {
        _e.printStackTrace();
        throw _e;
    }
}

From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java

public void destroy(Long id) throws Exception {
    EntityManager em = null;
    try {/*  ww  w.  jav  a2s .  c o  m*/
        em = getEntityManager();
        em.getTransaction().begin();
        em.remove(id);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

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

/**
 * Returns a single list-entry./*  w  w w . j  a  v a  2s.c  om*/
 * @param _groupId The id of the group containing the entry.
 * @param _entryUUID The uuid of the entry itself.
 */
@GET
@TokenSecured
@Path("{entryuuid}")
@Produces({ "application/json" })
public Response getEntry(@PathParam("groupid") int _groupId, @PathParam("entryuuid") String _entryUUID)
        throws Exception {
    UUID toFind;
    try {
        toFind = UUID.fromString(_entryUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);
    IEntryController entryController = ControllerFactory.getEntryController(manager);

    ListEntry foundEntry = entryController.findByGroupAndUUID(group, toFind);
    if (foundEntry == null) {
        if (entryController.findDeletedByGroupAndUUID(group, toFind) != null) {
            manager.close();
            return ResponseFactory
                    .generateGone(new Error().withMessage("The requested " + "listentry has been deleted."));
        }
        manager.close();
        return ResponseFactory
                .generateNotFound(new Error().withMessage("The requested " + "listentry was not found."));
    }
    manager.close();

    EntryInfo rtn = new EntryInfo().withDeleted(false);
    rtn.setUUID(foundEntry.getUUID());
    rtn.setProductUUID(foundEntry.getProduct().getUUID());
    rtn.setListUUID(foundEntry.getList().getUUID());
    rtn.setAmount(foundEntry.getAmount());
    rtn.setPriority(foundEntry.getPriority());
    rtn.setStruck(foundEntry.getStruck());
    rtn.setLastChanged(Date.from(foundEntry.getUpdated()));

    return ResponseFactory.generateOK(rtn);
}

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

/**
 * Retrieve the application list./*  ww  w . ja va2  s  .  c  o  m*/
 * The fields not requested for the list are cleaned.
 * @return The list of applications
 */
private List<Infrastructure> retrieveInfrastructureList() {
    List<Infrastructure> lstInfras;
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        lstInfras = em.createNamedQuery("infrastructures.all", Infrastructure.class).getResultList();
        et.commit();
    } catch (RuntimeException re) {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        log.error("Impossible to retrieve the infrastructure list");
        log.error(re);
        throw new RuntimeException("Impossible to access the " + "infrastructures list");
    } finally {
        em.close();
    }
    if (lstInfras != null) {
        for (Infrastructure in : lstInfras) {
            in.setDescription(null);
            in.setParameters(null);
        }
    }
    return lstInfras;
}

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

/**
 * Retrieve the application list./*from  w ww. j  av  a 2 s  .c  o  m*/
 * The fields not requested for the list are cleaned.
 * @return The list of applications
 */
private List<Application> retrieveApplicationList() {
    List<Application> lstApps;
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        lstApps = em.createNamedQuery("applications.all", Application.class).getResultList();
        et.commit();
    } catch (RuntimeException re) {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        log.error("Impossible to retrieve the Application list");
        log.error(re);
        throw new RuntimeException("Impossible to access the " + "application list");
    } finally {
        em.close();
    }
    if (lstApps != null) {
        for (Application ap : lstApps) {
            ap.setDescription(null);
            ap.setParameters(null);
        }
    }
    return lstApps;
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.VacancyRepositoryImplementation.java

@Override
public boolean update(Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    try {// w  w  w.j  a  v a 2 s .  c o  m
        em.getTransaction().begin();
        em.merge(vacancy);
        em.getTransaction().commit();
        success = true;
    } catch (RuntimeException e) {
        Logger.getLogger(VacancyRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
            success = false;
        }
        em.close();
    }

    return success;
}

From source file:com.soen.ebanking.dao.ObjectDao.java

public void updateObject(Object entity, long id, Class<T> ClassName) {
    EntityManager em = this.getEMF().createEntityManager();
    try {/*ww w.  j a  va  2 s . c om*/
        em.getTransaction().begin();
        this.t = (T) em.find(ClassName, id);
        Object orig = entity;
        Object dest = this.t;
        BeanUtils.copyProperties(dest, orig);
        entity = t;
        t = null;
        em.getTransaction().commit();
    } catch (IllegalAccessException ex) {
        Logger.getLogger(ObjectDao.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
        Logger.getLogger(ObjectDao.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        em.close();
    }
}