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.epam.training.taranovski.web.project.repository.implementation.VacancyRepositoryImplementation.java

@Override
public boolean create(Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    try {/*from  w  w w. j  ava  2s  .c  o  m*/
        em.getTransaction().begin();
        em.persist(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:org.SRV.testServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    double value1 = Double.parseDouble(request.getParameter("val1"));
    double value2 = Double.parseDouble(request.getParameter("val2"));

    UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String username = user.getUsername();
    //com.seostella_springsecuritybasics_war_1.0.0-BUILD-SNAPSHOTPU
    entityManagerFactory = Persistence.createEntityManagerFactory("org.SRV_war_1.0.0-BUILD-SNAPSHOTPU");

    double result = 0;
    switch (request.getParameter("operation").charAt(0)) {
    case '+':
        result = value1 + value2;//from   w  w  w. j ava  2s . c  o  m
        break;
    case '-':
        result = value1 - value2;
        break;
    case '*':
        result = value1 * value2;
        break;
    case '/':
        result = value1 / value2;
        break;
    default:
        break;
    }

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
    Date date = new Date();
    Essence essence = new Essence();
    essence.setLogin(username);
    essence.setDate(date);
    essence.setValue1(Double.toString(value1));
    essence.setValue2(Double.toString(value2));
    essence.setOperation(request.getParameter("operation"));
    essence.setResult(Double.toString(result));
    entityManager.persist(essence);
    entityManager.getTransaction().commit();
    entityManager.clear();
    entityManager.close();
    entityManagerFactory.close();
    JSONObject obj;
    obj = new JSONObject();
    obj.put("result", result);
    //response.getOutputStream().print(obj.toString());
    response.getWriter().write(obj.toString());
}

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

/**
 * Finds a single product.//from  ww  w.j  a v a 2s . com
 * @param _groupId The id of the group containing the searched product.
 * @param _productUUID The uuid of the needed product.
 */
@GET
@TokenSecured
@Path("{productuuid}")
@Produces({ "application/json" })
public Response getProduct(@PathParam("groupid") int _groupId, @PathParam("productuuid") String _productUUID)
        throws Exception {
    UUID toFind;
    try {
        toFind = UUID.fromString(_productUUID);
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);
    IProductController productController = ControllerFactory.getProductController(manager);

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

    ProductInfo rtn = new ProductInfo().withDeleted(false);
    rtn.setUUID(toFind);
    rtn.setName(foundProduct.getName());
    rtn.setDefaultAmount(foundProduct.getDefaultAmount());
    rtn.setStepAmount(foundProduct.getStepAmount());
    if (foundProduct.getUnit() != null)
        rtn.setUnitUUID(foundProduct.getUnit().getUUID());
    rtn.setLastChanged(Date.from(foundProduct.getUpdated()));

    return ResponseFactory.generateOK(rtn);
}

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

/**
 * A utility class to load the user directory.
 * /*from  w  w w  .  jav  a2 s  . c om*/
 * @param user
 *          the user object
 */
public void addUser(JpaUser user) {

    // Create a JPA user with an encoded password.
    String encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername());
    user = new JpaUser(user.getUsername(), encodedPassword, user.getOrganization(), user.getRoles());

    // Then save the user
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        em.persist(user);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}

From source file:in.bookmylab.jpa.JpaDAO.java

public UserProfile getProfile(User user) {
    EntityManager em = emf.createEntityManager();
    UserProfile p = null;/*from   w  w w .j av  a  2  s . c  o  m*/
    try {
        List<UserProfile> res = em.createNamedQuery("UserProfile.findByUser", UserProfile.class)
                .setParameter("user", user).getResultList();
        if (!res.isEmpty()) {
            p = res.get(0);
        }
    } finally {
        em.close();
    }
    return p;
}

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

/**
 * Creates the unit./*from  w  w w  . j a v  a 2s. co  m*/
 * @param _groupId The group-id the new Unit should belong to.
 * @param _entity Data of the new unit.
 */
@POST
@TokenSecured
@Consumes("application/json")
@Produces({ "application/json" })
public Response postUnit(@PathParam("groupid") int _groupId, UnitInfo _entity) throws Exception {
    if (_entity.getUUID() == null || (_entity.getDeleted() != null && _entity.getDeleted())
            || _entity.getName() == null || _entity.getName().length() == 0)
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toInsert;
    try {
        toInsert = UUID.fromString(_entity.getUUID());
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    Instant insertDate;
    if (_entity.getLastChanged() == null)
        insertDate = Instant.now();
    else {
        insertDate = _entity.getLastChanged().toInstant();
        if (Instant.now().isBefore(insertDate))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IUnitController unitController = ControllerFactory.getUnitController(manager);
    try {
        unitController.add(_groupId, toInsert, _entity.getName(), insertDate);
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The sent data would " + "lead to a conflict with saved unit."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateCreated(null);
}

From source file:org.fornax.cartridges.sculptor.framework.web.jpa.JpaFlowExecutionListener.java

public void sessionEnded(RequestContext context, FlowSession session, String outcome, AttributeMap output) {
    if (isPersistenceContext(session.getDefinition())) {
        final EntityManager em = (EntityManager) context.getConversationScope()
                .remove(session.getDefinition().getId() + "/" + PERSISTENCE_CONTEXT_ATTRIBUTE);
        Boolean commitStatus = session.getState().getAttributes().getBoolean("commit");
        if (Boolean.TRUE.equals(commitStatus)) {
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    em.joinTransaction();
                }/*from  www  .j  a va2  s .c om*/
            });
        }
        unbind(em);
        em.close();
    }
    if (!session.isRoot()) {
        FlowSession parent = session.getParent();
        if (isPersistenceContext(parent.getDefinition())) {
            bind(getEntityManager(context, parent.getDefinition().getId()));
        }
    }
}

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

/**
 * Returns a single ingredient.//from  w  w w. j a v  a  2  s.  c om
 * @param _groupId The id of the group containing the ingredient.
 * @param _entryUUID The uuid of the ingredient itself.
 */
@GET
@TokenSecured
@Path("{entryuuid}")
@Produces({ "application/json" })
public Response getIngredient(@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);
    IIngredientController ingredientController = ControllerFactory.getIngredientController(manager);

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

    IngredientInfo rtn = new IngredientInfo().withDeleted(false);
    rtn.setUUID(foundIngredient.getUUID());
    rtn.setProductUUID(foundIngredient.getProduct().getUUID());
    rtn.setRecipeUUID(foundIngredient.getRecipe().getUUID());
    rtn.setAmount(foundIngredient.getAmount());
    rtn.setLastChanged(Date.from(foundIngredient.getUpdated()));

    return ResponseFactory.generateOK(rtn);
}

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

/**
 * Creates a list in the group.//from w ww. jav a2 s.  c  o m
 * @param _groupId The id of the group containing the list.
 * @param _listInfo Information for changing the list. Not all information needs to be set.
 */
@POST
@TokenSecured
@Consumes("application/json")
@Produces({ "application/json" })
public Response postList(@PathParam("groupid") int _groupId, ListInfo _listInfo) throws Exception {
    if ((_listInfo.getDeleted() != null && _listInfo.getDeleted()) || _listInfo.getName() == null
            || _listInfo.getName().length() == 0 || _listInfo.getUUID() == null)
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID listUUID;
    UUID categoryUUID = null;
    try {
        listUUID = UUID.fromString(_listInfo.getUUID());
        if (_listInfo.getCategoryUUID() != null)
            categoryUUID = UUID.fromString(_listInfo.getCategoryUUID());
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }
    Instant created;
    if (_listInfo.getLastChanged() != null) {
        created = _listInfo.getLastChanged().toInstant();
        if (created.isAfter(Instant.now()))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    } else
        created = Instant.now();

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IListController listController = ControllerFactory.getListController(manager);
    try {
        listController.add(_groupId, listUUID, _listInfo.getName(), categoryUUID, created);
    } catch (ConflictException _e) {
        return ResponseFactory
                .generateConflict(new Error().withMessage("A list with this " + "uuid already exists."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateCreated(null);
}

From source file:com.sixsq.slipstream.persistence.Run.java

public static int viewListCount(User user, String moduleResourceUri, String cloudServiceName)
        throws ConfigurationException, ValidationException {
    int count = 0;
    EntityManager em = PersistenceUtil.createEntityManager();
    try {//from   w  w  w . j  a v  a2 s .c om
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Long> critQuery = builder.createQuery(Long.class);
        Root<Run> rootQuery = critQuery.from(Run.class);
        critQuery.select(builder.count(rootQuery));
        Predicate where = viewListCommonQueryOptions(builder, rootQuery, user, moduleResourceUri,
                cloudServiceName);
        if (where != null) {
            critQuery.where(where);
        }
        TypedQuery<Long> query = em.createQuery(critQuery);
        count = (int) (long) query.getSingleResult();
    } finally {
        em.close();
    }
    return count;
}