Example usage for javax.persistence EntityManagerFactory close

List of usage examples for javax.persistence EntityManagerFactory close

Introduction

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

Prototype

public void close();

Source Link

Document

Close the factory, releasing any resources that it holds.

Usage

From source file:org.rhq.server.metrics.migrator.DataSourceTest.java

public static void main2(String[] args) throws Exception {
    BasicConfigurator.configure();/*from  ww  w.  j  a v a2 s.  c om*/
    Logger.getRootLogger().setLevel(Level.INFO);
    Logger.getLogger("org.rhq").setLevel(Level.DEBUG);
    EntityManagerFactory entityManagerFactory = null;
    EntityManager entityManager = null;
    ExistingDataBulkExportSource source = null;
    try {
        entityManagerFactory = createEntityManager();
        entityManager = entityManagerFactory.createEntityManager();
        source = new ExistingPostgresDataBulkExportSource(entityManager,
                "SELECT  schedule_id, time_stamp, value, minvalue, maxvalue FROM RHQ_MEASUREMENT_DATA_NUM_1D");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        source.initialize();
        int rowIndex = 0;
        int maxResults = 30000;
        for (;;) {
            List<Object[]> existingData = source.getData(rowIndex, maxResults);
            if (existingData.size() < maxResults) {
                break;
            } else {
                rowIndex += maxResults;
            }
        }
        stopWatch.stop();
        System.out.println("Execution: " + stopWatch);
    } finally {
        if (source != null) {
            source.close();
        }
        if (entityManager != null) {
            entityManager.close();
        }
        if (entityManagerFactory != null) {
            entityManagerFactory.close();
        }
    }
}

From source file:org.tinymediamanager.core.TmmModuleManager.java

/**
 * shutdown tmm - forces all registered modules to shut down
 *///from w  w w  . j a  v  a 2  s. c o  m
public void shutDown() {
    for (ITmmModule module : modules) {
        if (module.isEnabled()) {
            try {
                module.shutDown();
            } catch (Exception e) {
                LOGGER.error("problem shutting down " + module.getModuleTitle() + ": " + e.getMessage());
            }
        }
    }

    try {
        EntityManagerFactory emf = entityManager.getEntityManagerFactory();
        entityManager.close();
        emf.close();
    } catch (Exception e) {
    }
}

From source file:servlet.itemdescription.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  ww.java 2  s  .  c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // location to store file uploaded
    final String UPLOAD_DIRECTORY = "upload";
    // upload settings
    final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
    final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
    //----------------------------------------------------------------------
    //response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    EntityManagerFactory emf = null;
    EntityManager em = null;
    try {

        emf = Persistence.createEntityManagerFactory(cons.entityName);
        em = emf.createEntityManager();
        ItemDescriptionJpaController controller = new ItemDescriptionJpaController(emf);

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            String id = "";
            String code = "";
            String description = "";
            String itemType = "";
            String fileName = "";
            String unitId = "";
            String generId = "";
            String operation = "";

            //-------------------------------------------------------------------------------------------------------------------------------------
            // File upload
            try {
                // Create a factory for disk-based file items
                DiskFileItemFactory factory = new DiskFileItemFactory();
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setFileSizeMax(MAX_FILE_SIZE);

                // sets maximum size of request (include file + form data)
                upload.setSizeMax(MAX_REQUEST_SIZE);

                // constructs the directory path to store upload file
                // this path is relative to application's directory
                //                    String uploadPath = getServletContext().getRealPath("")
                //                            + File.separator + UPLOAD_DIRECTORY;
                String uploadPath = "E:\\insiderUploads";
                // creates the directory if it does not exist
                File uploadDir = new File(uploadPath);
                if (!uploadDir.exists()) {
                    uploadDir.mkdir();
                }
                // Parse the request
                List<FileItem> items = upload.parseRequest(request);
                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = iter.next();
                    if (item.isFormField()) { //These are form fields
                        String fieldName = item.getFieldName();
                        String fieldValue = item.getString();
                        if (fieldName.equalsIgnoreCase("honga")) {
                            operation = request.getParameter("honga");
                            System.out.println("operation: " + operation);
                        } else if (fieldName.equalsIgnoreCase("operation")) {
                            operation = request.getParameter("operation");
                            System.out.println("operation: " + operation);
                        } //----------------- Check Add Fields -------------------------
                        else if (fieldName.equalsIgnoreCase("id")) {
                            id = request.getParameter("id");
                            System.out.println("id " + id);
                        } else if (fieldName.equalsIgnoreCase("code")) {
                            code = fieldValue;
                            System.out.println("code " + code);
                        } else if (fieldName.equalsIgnoreCase("description")) {
                            description = fieldValue;
                            System.out.println("description: " + description);
                        } else if (fieldName.equalsIgnoreCase("item_type")) {
                            itemType = fieldValue;
                            System.out.println("item_type: " + itemType);
                        } else if (fieldName.equalsIgnoreCase("unit_id")) {
                            unitId = fieldValue;
                            System.out.println("unit_id: " + itemType);
                        }
                        if (fieldName.equalsIgnoreCase("gener_id")) {
                            generId = fieldValue;
                            System.out.println("Genre: " + generId);
                        } //----------------- Check Edit Fields ------------------------
                        else if (fieldName.equalsIgnoreCase("editItemDescriptionId")) {
                            id = request.getParameter("editItemDescriptionId");
                            System.out.println("editItemDescriptionId: " + id);
                        } else if (fieldName.equalsIgnoreCase("editItemCode")) {
                            code = fieldValue;
                            System.out.println("editItemCode " + code);
                        } else if (fieldName.equalsIgnoreCase("editDescription")) {
                            description = fieldValue;
                            System.out.println("editDescription: " + description);
                        } else if (fieldName.equalsIgnoreCase("editItemType")) {
                            itemType = fieldValue;
                            System.out.println("editItemType: " + itemType);
                        } else if (fieldName.equalsIgnoreCase("editUnitId")) {
                            unitId = fieldValue;
                            System.out.println("editUnitId: " + itemType);
                        }
                        if (fieldName.equalsIgnoreCase("generId")) {
                            generId = fieldValue;
                            System.out.println("generId: " + generId);
                        }
                    } else // This is a file
                    {
                        fileName = item.getName();
                        System.out.println("FILE NAME: " + fileName);
                        if (fileName != null && !fileName.isEmpty()) {
                            String filePath = uploadPath + File.separator + fileName;
                            File storeFile = new File(filePath);

                            // saves the file on disk
                            item.write(storeFile);
                            request.setAttribute("message", "Upload has been done successfully!");
                            out.println("File Name: " + fileName);
                        } else {
                            continue;
                        }
                    }

                }
                // add the item to the database
                //                    if (operation.equalsIgnoreCase("add")) {
                em.getTransaction().begin();
                ItemDescription itemDescription = new ItemDescription();
                if (code != null) {
                    itemDescription.setItemCode(new Integer(code));
                }

                itemDescription.setItemDesc(description);
                itemDescription.setItemTypeId(new Integer(itemType));
                itemDescription.setUnitId(new Integer(unitId));
                itemDescription.setGenerId(new Integer(generId));
                //                    itemDescription.setUpload(request.getParameter("file").getBytes());
                itemDescription.setUploadFileName(fileName);
                controller.create(itemDescription);
                em.getTransaction().commit();
                //                    } else if (operation.equalsIgnoreCase("edit")) {
                //                        em.getTransaction().begin();
                //                        ItemDescription itemDescription = new ItemDescription();
                //                        if (code != null) {
                //                            itemDescription.setItemCode(new Integer(code));
                //                        }
                //
                //                        itemDescription.setItemDesc(description);
                //                        itemDescription.setItemTypeId(new Integer(itemType));
                //                        itemDescription.setUnitId(new Integer(unitId));
                //                        itemDescription.setGenerId(new Integer(generId));
                ////                    itemDescription.setUpload(request.getParameter("file").getBytes());
                //                        controller.edit(itemDescription);
                //                        em.getTransaction().commit();
                //                    }

                response.sendRedirect("itemdesc.jsp");

            } catch (FileUploadException ex) {
                Logger.getLogger(itemdescription.class.getName()).log(Level.SEVERE, null, ex);
            }
            //-------------------------------------------------------------------------------------------------------------------------------------

        } else if (request.getParameter("operation") != null && !request.getParameter("operation").isEmpty()) {
            String id = "";
            String code = "";
            String description = "";
            String itemType = "";
            String fileName = "";
            String unitId = "";
            String generId = "";
            String operation = request.getParameter("operation");
            String operationId = request.getParameter("operationId");
            response.setContentType("application/json");
            if (operation.equalsIgnoreCase("edit")) { //This is update operation
                System.out.println("UPDATE OPERATION");
                operationId = request.getParameter("editItemDescriptionId");
                code = request.getParameter("editItemCode");
                description = request.getParameter("editDescription");
                itemType = request.getParameter("editItemType");
                unitId = request.getParameter("editUnitId");
                generId = request.getParameter("generId");

                System.out.println("Item ID: " + operationId + "Item Code: " + code + " | Desc: " + description
                        + " | Item type: " + itemType + " | UnitId: " + unitId + " | Genre Id: " + generId);
                ItemDescription itemDescription = controller.findItemDescription(new Integer(operationId));
                if (code != null) {
                    itemDescription.setItemCode(new Integer(code));
                }

                em.getTransaction().begin();
                itemDescription.setItemDesc(description);
                itemDescription.setItemTypeId(new Integer(itemType));
                itemDescription.setUnitId(new Integer(unitId));
                itemDescription.setGenerId(new Integer(generId));
                //                    itemDescription.setUpload(request.getParameter("file").getBytes());
                controller.edit(itemDescription);
                em.getTransaction().commit();
                response.sendRedirect("itemdesc.jsp");

            } else if (operation.equalsIgnoreCase("delete")) {//This is delete operation
                System.out.println("DELETE OPERATION");

                controller.destroy(new Integer(operationId));

                ItemDescription item = controller.findItemDescription(new Integer(operationId));
                if (item == null) {//Item is deleted from the database
                    System.out.println("RECORD has been deleted");
                    out.print(convertMessageIntoJSON(
                            new CustomMessage(100, "Record has been deleted successfully")));
                } else {//couldn't delete item
                    System.out.println("COULDN'T DELETE RECORD");
                    out.print(convertMessageIntoJSON(new CustomMessage(0, "Error, couldn't delete record")));

                }
            } else if (operation.equalsIgnoreCase("showItemDescriptionDetails")) {
                int itemDescriptionId = Integer.parseInt(request.getParameter("operationId"));
                ItemDescription itemDescription = controller.findItemDescription(itemDescriptionId);
                if (itemDescription == null) {//Record not found
                    out.print(JSONUtils
                            .convertMessageIntoJSON(new dto.CustomMessage(404, "Error, No Such record!")));
                } else {//Record found 
                    out.print(JSONUtils.convertItemDescriptionIntoJSON(ItemDescriptionWrapper
                            .getItemDescriptionWrapper(100, "Record found successfully", itemDescription)));
                }
            }
        } else if (request.getParameter("save") != null) {
            em.getTransaction().begin();
            ItemDescription id = new ItemDescription();

            id.setItemCode(new Integer(request.getParameter("item_code")));
            id.setItemDesc(request.getParameter("item_desc"));
            id.setItemTypeId(new Integer(request.getParameter("item_type_id")));
            id.setUnitId(new Integer(request.getParameter("unit_id")));
            id.setGenerId(new Integer(request.getParameter("gener_id")));
            id.setUpload(request.getParameter("file").getBytes());

            controller.create(id);
            em.getTransaction().commit();
            response.sendRedirect("itemdesc.jsp");
        } else if (request.getParameter("update") != null) {
            em.getTransaction().begin();
            ItemDescription id = new ItemDescription();
            id = controller.findItemDescription(new Integer(request.getParameter("edit_material_id").trim()));

            id.setItemCode(new Integer(request.getParameter("item_code")));
            id.setItemDesc(request.getParameter("item_desc"));
            id.setItemTypeId(new Integer(request.getParameter("item_type_id")));
            id.setUnitId(new Integer(request.getParameter("unit_id")));
            id.setGenerId(new Integer(request.getParameter("gener_id")));
            id.setUpload(request.getParameter("file").getBytes());

            controller.edit(id);
            em.getTransaction().commit();
            response.sendRedirect("itemdesc.jsp");
        } else if (request.getParameter("del_item") != null) {
            if (request.getParameter("id_value_del").trim() != null) {
                em.getTransaction().begin();
                controller.destroy(new Integer(request.getParameter("id_value_del").trim()));
                em.getTransaction().commit();
                response.sendRedirect("itemdesc.jsp");
            }
        }

        //            request.setAttribute("generlist",findGenerEntities);
        //            request.getRequestDispatcher("/gener.jsp").forward(request, response);
    } catch (Exception ex) {
        Logger.getLogger(itemdescription.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
        em.close();
        emf.close();

    }
}

From source file:servlet.MatrialRequest.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*www.  j a  v a  2 s  . c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String requestType = request.getParameter("requestType");
    EntityManagerFactory emf = null;
    Gson gson = new Gson();
    emf = Persistence.createEntityManagerFactory(cons.entityName);
    EntityManager em = emf.createEntityManager();
    if (requestType.equalsIgnoreCase("load")) {

        MaterialRequestJpaController controller = new MaterialRequestJpaController(emf);
        MaterialTypeJpaController materialTypeJpaController = new MaterialTypeJpaController(emf);
        response.setContentType("application/json");
        em.getTransaction().begin();
        int nextId = controller.getNextId();
        List<MaterialType> allMaterials = materialTypeJpaController.getMaterialsByItemTypeDesc();
        em.getTransaction().commit();

        JsonObject jsonObject = new JsonObject();

        jsonObject.addProperty("nextId", nextId);

        jsonObject.addProperty("allTypes", gson.toJson(allMaterials));
        PrintWriter writer = response.getWriter();
        writer.write(gson.toJson(jsonObject));
        writer.close();
        em.close();
        emf.close();
    } else if (requestType.equalsIgnoreCase("getItemDescs")) {
        Integer mrid = Integer.valueOf(request.getParameter("mrid"));
        ItemDescriptionTypeJpaController itemDescriptionTypeJpaController = new ItemDescriptionTypeJpaController(
                emf);
        em.getTransaction().begin();
        List<ItemDescriptionType> idts = itemDescriptionTypeJpaController.findItemDescriptionTypeByMRId(mrid);
        List<Integer> ids = new ArrayList<>();
        for (ItemDescriptionType descriptionType : idts) {
            ids.add(descriptionType.getItemTypeId());
        }
        ItemDescriptionJpaController descriptionJpaController = new ItemDescriptionJpaController(emf);
        List<ItemDescription> descriptions = descriptionJpaController.findItemsDescriptionsByItemTypeIds(ids);
        em.getTransaction().commit();
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("allDescs", gson.toJson(descriptions));
        PrintWriter writer = response.getWriter();
        writer.write(gson.toJson(jsonObject));
        writer.close();
        em.close();
        emf.close();

    } else if (requestType.equalsIgnoreCase("getItemFileds")) {
        Integer itemId = Integer.valueOf(request.getParameter("itemid"));

        ItemDescriptionTypeJpaController itemDescriptionTypeJpaController = new ItemDescriptionTypeJpaController(
                emf);
        em.getTransaction().begin();
        ItemDescriptionJpaController descriptionJpaController = new ItemDescriptionJpaController(emf);
        ItemDescription itemDescription = descriptionJpaController.findItemDescription(itemId);
        JsonObject jsonObject = new JsonObject();
        UnitsJpaController unitsJpaController = new UnitsJpaController(emf);
        Units findUnits = unitsJpaController.findUnits(itemDescription.getUnitId());
        jsonObject.addProperty("unitId", findUnits.getUnitId());
        jsonObject.addProperty("unitDesc", findUnits.getUnitDesc());
        String image = "";
        try {
            String extension = FilenameUtils.getExtension(itemDescription.getUploadFileName());
            BufferedImage img = ImageIO.read(new File(PICS_DIRECTORY + itemDescription.getUploadFileName()));
            image = encodeToString(img, extension);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.addProperty("thumb", image);
        PrintWriter writer = response.getWriter();
        writer.write(gson.toJson(jsonObject));

        writer.close();
        em.close();
        emf.close();
    }

}

From source file:utilities.PopulateDatabase.java

public static void main(String[] args) throws Throwable {
    ApplicationContext applicationContext;
    EntityManagerFactory entityManagerFactory;
    EntityManager entityManager;/*  w  ww  .  j  a v  a  2s.c om*/
    EntityTransaction entityTransaction;

    applicationContext = new ClassPathXmlApplicationContext("classpath:PopulateDatabase.xml");

    entityManagerFactory = Persistence.createEntityManagerFactory(PersistenceUnit);
    entityManager = entityManagerFactory.createEntityManager();
    entityTransaction = entityManager.getTransaction();

    initialise(entityManagerFactory, entityManager);

    entityTransaction.begin();
    try {
        for (Entry<String, Object> entry : applicationContext.getBeansWithAnnotation(Entity.class).entrySet()) {
            String beanName;
            DomainEntity entity;

            beanName = entry.getKey();
            entity = (DomainEntity) entry.getValue();
            entityManager.persist(entity);
            System.out.println(String.format("Persisting (%s, %s, %d)", beanName, entity.getClass().getName(),
                    entity.getId()));
        }
        entityTransaction.commit();
    } catch (Exception oops) {
        oops.printStackTrace();
        entityTransaction.rollback();
    } finally {
        if (entityManager.isOpen())
            entityManager.close();
        if (entityManagerFactory.isOpen())
            entityManagerFactory.close();
    }
}