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:com.headissue.pigeon.admin.AdminSurveyHandler.java

public boolean disableSurvey(int _surveyId) {
    if (_surveyId <= 0) {
        return false;
    }//from   w  w w  .j  a  v  a2 s  . co m
    EntityManager _manager = factory.createEntityManager();
    try {
        Survey s = _manager.find(Survey.class, _surveyId);
        if (s == null) {
            return false;
        }
        _manager.getTransaction().begin();
        s.setStatus(SurveyStatus.DISABLED);
        _manager.getTransaction().commit();
        return true;
    } catch (Exception e) {
        LogUtils.warn(log, "set survey '%s' to disabled failed", _surveyId);
        _manager.getTransaction().rollback();
        return false;
    } finally {
        _manager.close();
    }
}

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

/**
 * Removes the task. Task is deleted and all the associated activities and
 * or files removed./* w w w. j  av  a2s  . co  m*/
 *
 * @param id Id of the task to remove
 */
@DELETE
public final void deleteTask(@PathParam("id") final String id) {
    Task task;
    EntityManager em = getEntityManager();
    try {
        task = em.find(Task.class, id);
        if (task == null) {
            throw new NotFoundException();
        }
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            em.remove(task);
            et.commit();
        } catch (RuntimeException re) {
            if (et != null && et.isActive()) {
                et.rollback();
            }
            log.error(re);
            log.error("Impossible to remove the task");
            em.close();
            throw new InternalServerErrorException("Errore to remove " + "the task " + id);
        }
        try {
            Storage store = getStorage();
            store.removeAllFiles(Storage.RESOURCE.TASKS, id);
        } catch (IOException ex) {
            log.error("Impossible to remove the directory associated with " + "the task " + id);
        }
    } catch (IllegalArgumentException re) {
        log.error("Impossible to retrieve the task list");
        log.error(re);
        throw new BadRequestException("Task '" + id + "' has a problem!");
    } finally {
        em.close();
    }
}

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

@Override
public boolean update(Employee employee) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    try {/*from w w w .  ja va 2s  . c  om*/
        em.getTransaction().begin();

        em.merge(employee);
        em.flush();

        em.getTransaction().commit();
        success = true;
    } catch (RuntimeException e) {
        Logger.getLogger(EmployeeRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
            success = false;
        }
        em.close();
    }

    return success;
}

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

@Override
public void resume() {
    EntityManager em = Helpers.getNewEm();
    em.getTransaction().begin();//from  w w w.java 2 s  .  c om
    em.createQuery("UPDATE Node n SET n.enabled = true WHERE n.id = :id").setParameter("id", node.getId())
            .executeUpdate();
    em.getTransaction().commit();
    em.close();
    refreshConfiguration();
}

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

/**
 * Creates the recipe.//from  w  ww. j ava2 s.c  o m
 * @param _groupId The id of the group that should contain the new recipe.
 * @param _entity Data to change.
 */
@POST
@TokenSecured
@Consumes("application/json")
@Produces({ "application/json" })
public Response postRecipe(@PathParam("groupid") int _groupId, RecipeInfo _entity) throws Exception {
    try {

        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();
        IRecipeController recipeController = ControllerFactory.getRecipeController(manager);
        try {
            recipeController.add(_groupId, toCreate, _entity.getName(), created);
        } catch (ConflictException _e) {
            return ResponseFactory.generateConflict(
                    new Error().withMessage("The sent data would " + "conflict with saved recipe."));
        } finally {
            manager.close();
        }

        return ResponseFactory.generateCreated(null);
    } catch (Exception _e) {
        _e.printStackTrace();
        throw _e;
    }
}

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

@Override
public void pause() {
    EntityManager em = Helpers.getNewEm();
    em.getTransaction().begin();/*  w ww. java  2  s  . co  m*/
    em.createQuery("UPDATE Node n SET n.enabled = false WHERE n.id = :id").setParameter("id", node.getId())
            .executeUpdate();
    em.getTransaction().commit();
    em.close();
    refreshConfiguration();
}

From source file:com.github.jinahya.persistence.ShadowTest.java

@Test(enabled = false, invocationCount = 1)
public void testPersist() {
    final EntityManager manager = LocalPU.createEntityManager();
    try {//from   w  w  w  . ja v a2  s . co m
        final EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        try {
            final Shadow shadow = persistInstance(manager, null, null);
            transaction.commit();
        } catch (Exception e) {
            LocalPU.printConstraintViolation(e);
            transaction.rollback();
            e.printStackTrace(System.err);
            Assert.fail(e.getMessage());
        }
    } finally {
        manager.close();
    }
}

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

/**
 * Creates a new EntityManager using <tt>emf</tt>.
 *
 * <p>Calls {@link #loadConfigletStates(javax.persistence.EntityManager)} and
 * {@link #createOrUpdateConfiglets(de.zib.gndms.model.common.ConfigletState[])} to load all configlets managed by
 * this EntityManager and update the {@link #configlets} map.
 * Old Configlets will be removed and shutted down using {@link #shutdownConfiglets()} 
 *
 * @param emf the factory the EntityManager will be created of
 *///from w w  w.ja  v  a  2 s  .co  m
public synchronized void reloadConfiglets(final EntityManagerFactory emf) {
    ConfigletState[] states;
    EntityManager em = emf.createEntityManager();
    try {
        states = loadConfigletStates(em);
        createOrUpdateConfiglets(states);
        shutdownOldConfiglets(em);
    } finally {
        if (em.isOpen())
            em.close();
    }
}

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

/**
 * Returns a single ingredient.// w ww  . ja v  a 2s .c o  m
 * @param _groupId The id of the group containing the tagged product.
 * @param _taggedProductUUID The uuid of the tagged product itself.
 */
@GET
@TokenSecured
@Path("{tpuuid}")
@Produces({ "application/json" })
public Response getTaggedProduct(@PathParam("groupid") int _groupId,
        @PathParam("tpuuid") String _taggedProductUUID) throws Exception {
    UUID toFind;
    try {
        toFind = UUID.fromString(_taggedProductUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);
    ITaggedProductController taggedProductController = ControllerFactory.getTaggedProductController(manager);

    TaggedProduct foundTaggedProduct = taggedProductController.findByGroupAndUUID(group, toFind);
    if (foundTaggedProduct == null) {
        if (taggedProductController.findDeletedByGroupAndUUID(group, toFind) != null) {
            manager.close();
            return ResponseFactory.generateGone(
                    new Error().withMessage("The requested " + "tagged product has been deleted."));
        }
        manager.close();
        return ResponseFactory
                .generateNotFound(new Error().withMessage("The requested " + "tagged product was not found."));
    }
    manager.close();

    TaggedProductInfo rtn = new TaggedProductInfo().withDeleted(false);
    rtn.setUUID(foundTaggedProduct.getUUID());
    rtn.setProductUUID(foundTaggedProduct.getProduct().getUUID());
    rtn.setTagUUID(foundTaggedProduct.getTag().getUUID());
    rtn.setLastChanged(Date.from(foundTaggedProduct.getUpdated()));

    return ResponseFactory.generateOK(rtn);
}

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

/**
 * Deletes the tag and linked tagged products (but not the products themselves).
 * @param _groupId The id of the group still containing the tag.
 * @param _tagUUID the uuid of the tag to delete.
 *///from w w w .j  a  v  a2  s  . c om
@DELETE
@TokenSecured
@Path("{taguuid}")
@Produces({ "application/json" })
public Response deleteTag(@PathParam("groupid") int _groupId, @PathParam("taguuid") String _tagUUID)
        throws Exception {
    UUID toDelete;
    try {
        toDelete = UUID.fromString(_tagUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    ITagController tagController = ControllerFactory.getTagController(manager);
    try {
        tagController.delete(_groupId, toDelete);
    } catch (NotFoundException _e) {
        return ResponseFactory.generateNotFound(new Error().withMessage("The tag was not " + "found."));
    } catch (GoneException _e) {
        return ResponseFactory.generateGone(new Error().withMessage("The tag has been " + "deleted."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}