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.ge.apm.service.data.DataService.java

public Object postDirectData(String tablename, List<Map> list) {
    if (tablename == null)
        return "{\"code\":\"1\",\"msg\":\"please input table_name\"}";
    if (list == null || list.isEmpty())
        return "{\"code\":\"1\",\"msg\":\"no data post\"}";
    String tableName = tablename.toLowerCase();
    String talbeClassName = "com.ge.apm.domain." + tabelNameToClassName(tableName);
    Class<?> table = getDao(talbeClassName);
    Map<String, String> fields = getFields(table);

    EntityManagerFactory emf = WebUtil.getBean(EntityManagerFactory.class);
    EntityManager em = emf.createEntityManager();
    int fortimes = list.size() / 50 + 1;//
    for (int j = 0; j < fortimes; j++) {
        List<Map> subList = list.subList(j * 50, (j + 1) * 50 < list.size() ? (j + 1) * 50 : list.size());

        em.getTransaction().begin();//from w  w w . jav  a 2 s . c om
        Query query = null;
        for (int i = 0; i < subList.size(); i++) {
            Map<String, Object> map = subList.get(i);
            String outColumnStr = "insert into " + tableName + " (";
            String outValueStr = ") values(";
            String[] strs = insertColumn(fields, map);
            outColumnStr += strs[0];
            outValueStr += strs[1];
            String sql = outColumnStr + outValueStr + ")";
            query = em.createNativeQuery(sql);
            query.executeUpdate();
        }
        try {
            em.getTransaction().commit();
        } catch (Exception ex) {
            em.getTransaction().rollback();
            Logger.getLogger(DataGetAndPushController.class.getName()).log(Level.SEVERE, null, ex);
            em.close();
            return "{\"code\":\"1\",\"msg\":\"save failed\"}";//
        }
    }
    if (em != null) {
        em.close();
    }
    return "{\"code\":\"0\",\"msg\":\"save success\"}";//?
}

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

@Override
@RequestMapping(value = "/_{subspaceId}/_{sliceKindId}/_{sliceId}", method = RequestMethod.POST)
@Secured("ROLE_USER")
public ResponseEntity<Specifier<Void>> transformSlice(@PathVariable final String subspaceId,
        @PathVariable final String sliceKindId, @PathVariable final String sliceId,
        @RequestBody final Specifier<Void> newSliceKind, @RequestHeader("DN") final String dn) {
    GNDMSResponseHeader headers = setHeaders(subspaceId, sliceKindId, sliceId, dn);

    try {//from   ww w .j a v  a  2s . com
        Slice slice = findSliceOfKind(subspaceId, sliceKindId, sliceId);

        SliceKind newSliceK = sliceKindProvider.get(subspaceId, newSliceKind.getUrl());
        Subspace space = subspaceProvider.get(subspaceId);

        EntityManager em = emf.createEntityManager();
        TxFrame tx = new TxFrame(em);
        try {
            // TODO is this right? what is this uuid generator (last entry)?
            TransformSliceAction action = new TransformSliceAction(dn, slice.getTerminationTime(), newSliceK,
                    space, slice.getTotalStorageSize(), null);
            action.setOwnEntityManager(em);
            logger.info("Calling action for transforming sliceId " + sliceId + ".");
            action.call();
            tx.commit();
        } finally {
            tx.finish();
            if (em != null && em.isOpen()) {
                em.close();
            }
        }

        Specifier<Void> spec = new Specifier<Void>();

        HashMap<String, String> urimap = new HashMap<String, String>(2);
        urimap.put("service", "dspace");
        urimap.put(UriFactory.SUBSPACE, subspaceId);
        urimap.put(UriFactory.SLICE_KIND, sliceKindId);
        urimap.put(UriFactory.SLICE, sliceId);
        spec.setUriMap(new HashMap<String, String>(urimap));
        spec.setUrl(uriFactory.quoteUri(urimap));

        return new ResponseEntity<Specifier<Void>>(spec, headers, HttpStatus.OK);
    } catch (NoSuchElementException ne) {
        logger.warn(ne.getMessage());
        return new ResponseEntity<Specifier<Void>>(null, headers, HttpStatus.NOT_FOUND);
    }
}

From source file:com.edugility.substantia.substance.TestCasePerson.java

@Test
public void testingJPA() throws Exception {
    final EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
    assertNotNull(emf);/*from w  ww .  ja  v  a 2  s. c om*/

    final EntityManager em = emf.createEntityManager();
    assertNotNull(em);

    final EntityTransaction et = em.getTransaction();
    assertNotNull(et);
    et.begin();

    final Person p = new Person();
    em.persist(p);
    em.flush();
    assertFalse(p.isTransient());
    assertTrue(p.isVersioned());
    assertEquals(Long.valueOf(1L), p.getId());
    assertEquals(Integer.valueOf(1), p.getVersion());

    et.commit();
    et.begin();

    final Person p2 = em.find(Person.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
    assertNotNull(p2);
    assertFalse(p2.isTransient());
    assertTrue(p2.isVersioned());
    assertEquals(Long.valueOf(1L), p2.getId());
    assertEquals(Integer.valueOf(1), p2.getVersion());

    et.commit();
    et.begin();

    final Person p3 = em.getReference(Person.class, 1L);
    assertNotNull(p3);
    assertFalse(p3.isTransient());
    assertTrue(p3.isVersioned());
    assertEquals(Long.valueOf(1L), p3.getId());
    assertEquals(Integer.valueOf(2), p3.getVersion());

    et.commit();
    et.begin();

    assertTrue(em.contains(p));
    em.remove(p);

    et.commit();

    em.close();

    emf.close();
}

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

/**
 * Updates an entry./*from   ww  w .  j  av  a 2  s.  com*/
 * @param _groupId The id of the group containing the entry.
 * @param _entryUUID The uuid of the entry itself.
 * @param _entity Data for updating the entry.
 */
@PUT
@TokenSecured
@Path("{entryuuid}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response putEntry(@PathParam("groupid") int _groupId, @PathParam("entryuuid") String _entryUUID,
        EntryInfo _entity) throws Exception {
    if ((_entity.getUUID() != null && !_entity.getUUID().equals(_entryUUID))
            || (_entity.getDeleted() != null && _entity.getDeleted())
            || (_entity.getAmount() != null && _entity.getAmount() < 0.001f))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toUpdate;
    UUID productUUID = null;
    UUID listUUID = null;
    try {
        toUpdate = UUID.fromString(_entryUUID);
        if (_entity.getProductUUID() != null)
            productUUID = UUID.fromString(_entity.getProductUUID());
        if (_entity.getListUUID() != null)
            listUUID = UUID.fromString(_entity.getListUUID());
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }
    Instant updated;
    if (_entity.getLastChanged() != null) {
        updated = _entity.getLastChanged().toInstant();
        if (Instant.now().isBefore(updated))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    } else
        updated = Instant.now();

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IEntryController entryController = ControllerFactory.getEntryController(manager);
    try {
        entryController.update(_groupId, toUpdate, productUUID, listUUID, _entity.getAmount(),
                _entity.getPriority(), _entity.getStruck(), updated);
    } catch (NotFoundException _e) {
        return ResponseFactory.generateNotFound(new Error().withMessage("The entry was not " + "found."));
    } catch (GoneException _e) {
        return ResponseFactory.generateGone(new Error().withMessage("The entry has been " + "deleted."));
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The sent data would " + "conflict with saved list entry."));
    } catch (BadRequestException _e) {
        return ResponseFactory.generateBadRequest(
                new Error().withMessage("The referenced " + "product or list was not found."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}

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

/**
 * Updates an tagged product. This REST-Endpoint is currently not really useful as
 * TaggedProduct only contain links between Products and Tags and no additional information. It
 * was created as reservation for future use.
 * @param _groupId The id of the group containing the tagged product.
 * @param _taggedProductUUID The uuid of the tagged product itself.
 * @param _entity Data for updating the tagged product.
 *//* w  ww  .  j ava2  s  . c o  m*/
@PUT
@TokenSecured
@Path("{tpuuid}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response putTaggedProduct(@PathParam("groupid") int _groupId,
        @PathParam("tpuuid") String _taggedProductUUID, TaggedProductInfo _entity) throws Exception {
    if ((_entity.getUUID() != null && !_entity.getUUID().equals(_taggedProductUUID))
            || (_entity.getDeleted() != null && _entity.getDeleted()))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toUpdate;
    UUID productUUID = null;
    UUID tagUUID = null;
    try {
        toUpdate = UUID.fromString(_taggedProductUUID);
        if (_entity.getProductUUID() != null)
            productUUID = UUID.fromString(_entity.getProductUUID());
        if (_entity.getTagUUID() != null)
            tagUUID = UUID.fromString(_entity.getTagUUID());
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }
    Instant updated;
    if (_entity.getLastChanged() != null) {
        updated = _entity.getLastChanged().toInstant();
        if (Instant.now().isBefore(updated))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    } else
        updated = Instant.now();

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    ITaggedProductController taggedProductController = ControllerFactory.getTaggedProductController(manager);
    try {
        taggedProductController.update(_groupId, toUpdate, tagUUID, productUUID, updated);
    } catch (NotFoundException _e) {
        return ResponseFactory
                .generateNotFound(new Error().withMessage("The tagged product " + "was not found."));
    } catch (GoneException _e) {
        return ResponseFactory
                .generateGone(new Error().withMessage("The tagged product has " + "been deleted."));
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The sent data would " + "conflict with saved tagged product."));
    } catch (BadRequestException _e) {
        return ResponseFactory.generateBadRequest(
                new Error().withMessage("The referenced " + "product or tag was not found."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}

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

public void saveSpmBooking(SpmLabBooking spm) throws AppException {
    EntityManager em = emf.createEntityManager();
    try {//w ww.ja  va2  s.c  om
        em.getTransaction().begin();
        if (spm.spmId == null) {
            em.persist(spm);
            fixAnalysisModesAndResourceType(spm.booking, em, false);
        } else {
            // Validate status change, if any
            Query q = em.createNamedQuery("ResourceBooking.findById");
            ResourceBooking rb = (ResourceBooking) q.setParameter("bookingId", spm.booking.bookingId)
                    .getSingleResult();
            if (!statusChangeValid(rb.status, spm.booking.status)) {
                throw new AppException(String.format("Status cannot be changed from %s to %s.", rb.status,
                        spm.booking.status));
            }

            fixAnalysisModesAndResourceType(spm.booking, em, true);
            em.merge(spm);
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
}

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

public void saveXrdBooking(XrdLabBooking xrd) throws AppException {
    EntityManager em = emf.createEntityManager();
    try {/* w  w w  .  j  a  v a  2  s  .c om*/
        em.getTransaction().begin();
        if (xrd.xrdId == null) {
            em.persist(xrd);
            fixAnalysisModesAndResourceType(xrd.booking, em, false);
        } else {
            // Validate status change, if any
            Query q = em.createNamedQuery("ResourceBooking.findById");
            ResourceBooking rb = (ResourceBooking) q.setParameter("bookingId", xrd.booking.bookingId)
                    .getSingleResult();
            if (!statusChangeValid(rb.status, xrd.booking.status)) {
                throw new AppException(String.format("Status cannot be changed from %s to %s.", rb.status,
                        xrd.booking.status));
            }

            fixAnalysisModesAndResourceType(xrd.booking, em, true);
            em.merge(xrd);
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
}

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

/**
 * Updates the product./*www  .j av a2 s  .  c o m*/
 * @param _groupId The group containing the product to update.
 * @param _productUUID The uuid of the product to update.
 * @param _entity The data for changing the product.
 *      e.g. examples/product.example
 */
@PUT
@TokenSecured
@Path("{productuuid}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response putProduct(@PathParam("groupid") int _groupId, @PathParam("productuuid") String _productUUID,
        ProductInfo _entity) throws Exception {
    if ((_entity.getUUID() != null && !_entity.getUUID().equals(_productUUID))
            || (_entity.getName() != null && _entity.getName().length() == 0)
            || (_entity.getDeleted() != null && _entity.getDeleted())
            || (_entity.getDefaultAmount() != null && _entity.getDefaultAmount() < 0.001f)
            || (_entity.getStepAmount() != null && _entity.getStepAmount() < 0.001f))
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);

    UUID toUpdate;
    UUID unitUUID = null;
    boolean removeUnit = (_entity.getRemoveUnit() != null ? _entity.getRemoveUnit() : false);
    try {
        toUpdate = UUID.fromString(_productUUID);
        if (_entity.getUnitUUID() != null && !removeUnit)
            unitUUID = UUID.fromString(_entity.getUnitUUID());
    } catch (IllegalArgumentException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }
    Instant updated;
    if (_entity.getLastChanged() != null) {
        updated = _entity.getLastChanged().toInstant();
        if (Instant.now().isBefore(updated))
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    } else
        updated = Instant.now();

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    IProductController productController = ControllerFactory.getProductController(manager);
    try {
        productController.update(_groupId, toUpdate, _entity.getName(), _entity.getDefaultAmount(),
                _entity.getStepAmount(), unitUUID, removeUnit, updated);
    } catch (NotFoundException _e) {
        return ResponseFactory.generateNotFound(new Error().withMessage("The product was not " + "found."));
    } catch (GoneException _e) {
        return ResponseFactory.generateGone(new Error().withMessage("The product has been " + "deleted."));
    } catch (ConflictException _e) {
        return ResponseFactory.generateConflict(
                new Error().withMessage("The sent data would " + "conflict with saved product."));
    } catch (BadRequestException _e) {
        return ResponseFactory
                .generateBadRequest(new Error().withMessage("The referenced " + "unit was not found."));
    } finally {
        manager.close();
    }

    return ResponseFactory.generateOK(null);
}

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

/**
 * Uploads input files. The method store input files for the specified task.
 * Input files are provided as a <i>multipart form data</i> using the field
 * file. This can contains multiple file using the html input attribute
 * <i>multiple="multiple"</i> which allows to associate multiple files with
 * a single field.//from ww  w. jav  a  2  s  . c o m
 *
 * @param id The task id retrieved from the url path
 * @param lstFiles List of file in the POST body
 */
@Path("/input")
@POST
@Consumes({ MediaType.MULTIPART_FORM_DATA })
public final void setInputFile(@PathParam("id") final String id,
        @FormDataParam("file") final List<FormDataBodyPart> lstFiles) {
    if (lstFiles == null || lstFiles.isEmpty()) {
        throw new BadRequestException("Input not accessible!");
    }
    EntityManager em = getEntityManager();
    Task task = em.find(Task.class, id);
    task.addObserver(new TaskObserver(getEntityManagerFactory(), getSubmissionThreadPool()));
    if (task == null) {
        throw new NotFoundException("Task " + id + " does not exist");
    }
    for (FormDataBodyPart fdbp : lstFiles) {
        final String fName = fdbp.getFormDataContentDisposition().getFileName();
        try {
            Storage store = getStorage();
            store.storeFile(Storage.RESOURCE.TASKS, id, fdbp.getValueAs(InputStream.class), fName);
            EntityTransaction et = em.getTransaction();
            try {
                et.begin();
                task.updateInputFileStatus(fName, TaskFile.FILESTATUS.READY);
                et.commit();
            } catch (RuntimeException re) {
                if (et != null && et.isActive()) {
                    et.rollback();
                }
                log.error(re);
                log.error("Impossible to update the task");
                throw new InternalServerErrorException("Errore to update " + "the task");
            } finally {
                em.close();
            }
        } catch (IOException ex) {
            log.error(ex);
            throw new InternalServerErrorException("Errore to store input " + "files");
        }
    }
    em.close();
}

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

/**
 * gets the category for its fs_id.//from ww w.j  a  v  a 2  s  .co m
 *
 * @param fs_id    The fs_id
 * @param language the language
 * @param em       the em
 * @return the NewsCategory instance
 */
private NewsCategory getNewsCategory(Long fs_id, String language, EntityManager em) {

    boolean close = false;
    try {
        if (em == null) {
            em = emf.createEntityManager();
            close = true;
        }

        Query categoryQuery = em.createQuery(new StringBuilder()
                .append("SELECT x FROM category x WHERE x.fs_id = :fs_id AND x.language = :language")
                .toString()); // or fsidindex2?
        categoryQuery.setParameter("fs_id", fs_id);
        categoryQuery.setParameter("language", language);

        if (categoryQuery.getResultList().size() > 0) {
            return (NewsCategory) categoryQuery.getSingleResult();
        }

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