Example usage for javax.persistence Persistence createEntityManagerFactory

List of usage examples for javax.persistence Persistence createEntityManagerFactory

Introduction

In this page you can find the example usage for javax.persistence Persistence createEntityManagerFactory.

Prototype

public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName) 

Source Link

Document

Create and return an EntityManagerFactory for the named persistence unit.

Usage

From source file:edu.csueb.cs6320.utils.UserService.java

public boolean updatePassword(long userid, String newPassword) {
    EntityManager em = Persistence.createEntityManagerFactory("TestPU").createEntityManager();
    User u = em.find(User.class, userid);
    if (u == null) {
        return false;
    }/*from  w w  w  . java2 s.  c o m*/

    em.getTransaction().begin();

    // TODO: This block of code really belongs in User.setPassword()
    String salt = Auth.getSalt();
    u.setSalt(salt);
    try {
        u.setSaltedHashedPassword(Auth.hashPassword(newPassword, salt));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        em.getTransaction().rollback();
        return false;
    }
    em.getTransaction().commit();
    em.close();

    return true;
}

From source file:servlet.itemdescription.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w w  .j a  va 2  s  .co m*/
 *
 * @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:facades.PersonFacadeDB.java

@Override
public String getPerson(Integer id) throws NotFoundException {
    String result = "";
    //get person with this id from DB
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceFileName);
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();//from w  ww  . j  ava2  s.c o m
    try {
        Person p = em.find(Person.class, id);

        result = om.writeValueAsString(p);
        //            Query query = em.createNamedQuery("Person.findById").setParameter("id", id);
        //            List<Person> people = query.getResultList();

        //result = gson.toJson(people.get(0));
        //result = om.writeValueAsString(people.get(0));
    } catch (Exception e) {
        throw new NotFoundException("No person exists for the given id");
    } finally {
        em.close();
    }
    return result;
}

From source file:com.sun.socialsite.userapi.UserManagerImpl.java

private static EntityManagerFactory getEmf() {
    synchronized (UserManagerImpl.class) {
        if (emf == null) {
            String puName = Config.getProperty("usermanager.puname", "SocialSite_PU");
            emf = Persistence.createEntityManagerFactory(puName);
        }//from ww w.j av a2s. c o m
        return emf;
    }
}

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

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

    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:com.impetus.client.cassandra.config.CassandraPropertyReaderTest.java

/**
 * Test method for/*from w w w  .  ja  v  a 2  s . c o m*/
 * {@link com.impetus.client.cassandra.config.CassandraPropertyReader#readProperty()}
 * .
 * 
 * @throws IOException
 */
@Test
public void testReadProperty() throws IOException {
    log.info("running CassandraPropertyReaderTest");
    // reader = new CassandraPropertyReader();
    // reader.read("CassandraCounterTest");
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(pu);
    PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(pu);
    // metadata = CassandraPropertyReader.csmd;
    Properties properties = new Properties();
    InputStream inStream = ClassLoader
            .getSystemResourceAsStream(puMetadata.getProperty(PersistenceProperties.KUNDERA_CLIENT_PROPERTY));

    if (inStream != null) {
        properties.load(inStream);
        replication = properties.getProperty(Constants.REPLICATION_FACTOR);
        strategy = properties.getProperty(Constants.PLACEMENT_STRATEGY);
        String dataCenters = properties.getProperty(Constants.DATA_CENTERS);
        if (dataCenters != null) {
            StringTokenizer stk = new StringTokenizer(dataCenters, ",");
            while (stk.hasMoreTokens()) {
                StringTokenizer tokenizer = new StringTokenizer(stk.nextToken(), ":");
                if (tokenizer.countTokens() == 2) {
                    dataCenterToNode.put(tokenizer.nextToken(), tokenizer.nextToken());
                }
            }
        }

        String cf_defs = properties.getProperty(Constants.CF_DEFS);
        if (cf_defs != null) {
            StringTokenizer stk = new StringTokenizer(cf_defs, ",");
            while (stk.hasMoreTokens()) {
                CassandraColumnFamilyProperties familyProperties = new CassandraColumnFamilyProperties();
                StringTokenizer tokenizer = new StringTokenizer(stk.nextToken(), "|");
                if (tokenizer.countTokens() != 0 && tokenizer.countTokens() >= 2) {
                    String columnFamilyName = tokenizer.nextToken();
                    String defaultValidationClass = tokenizer.nextToken();
                    familyProperties.setDefault_validation_class(defaultValidationClass);

                    if (tokenizer.countTokens() != 0) {
                        String comparator = tokenizer.nextToken();

                        familyProperties.setComparator(comparator);

                    }
                    familyToProperties.put(columnFamilyName, familyProperties);
                }
            }
        }

        metadata = CassandraPropertyReader.csmd;
        if (replication != null) {
            Assert.assertNotNull(replication);
            Assert.assertNotNull(metadata.getReplication_factor());

        } else {
            Assert.assertNull(replication);
            Assert.assertNull(metadata.getReplication_factor());
        }
        Assert.assertEquals(replication, metadata.getReplication_factor());

        if (strategy != null) {
            Assert.assertNotNull(strategy);
            Assert.assertNotNull(metadata.getPlacement_strategy());

        } else {
            Assert.assertNull(strategy);
            Assert.assertNull(metadata.getPlacement_strategy());
        }
        Assert.assertEquals(strategy, metadata.getPlacement_strategy());

        if (!familyToProperties.isEmpty()) {
            Assert.assertNotNull(familyToProperties);
            Assert.assertNotNull(metadata.getColumnFamilyProperties());
            Assert.assertFalse(metadata.getColumnFamilyProperties().isEmpty());
        } else {
            Assert.assertTrue(metadata.getColumnFamilyProperties().isEmpty());
        }
        Assert.assertEquals(familyToProperties.size(), metadata.getColumnFamilyProperties().size());

        if (!dataCenterToNode.isEmpty()) {
            Assert.assertNotNull(dataCenterToNode);
            Assert.assertNotNull(metadata.getDataCenters());
            Assert.assertFalse(metadata.getDataCenters().isEmpty());
        } else {
            Assert.assertTrue(metadata.getDataCenters().isEmpty());
        }
        Assert.assertEquals(dataCenterToNode.size(), metadata.getDataCenters().size());
    } else {
        Assert.assertEquals("1", metadata.getReplication_factor());
        Assert.assertEquals(SimpleStrategy.class.getName(), metadata.getPlacement_strategy());
        Assert.assertEquals(0, metadata.getDataCenters().size());
        Assert.assertEquals(0, metadata.getColumnFamilyProperties().size());
    }
}

From source file:org.querybyexample.jpa.GenericRepository.java

/**
 * This constructor needs the real type of the generic type E so it can be
 * given to the {@link EntityManager}./*from w w w.j a  v a  2 s . c  om*/
 * @param type
 */
public GenericRepository(Class<E> type) {
    this.type = type;
    this.log = LoggerFactory.getLogger(getClass());
    this.cacheRegion = type.getCanonicalName();
    entityManager = Persistence.createEntityManagerFactory(PersistencyConfig.PERSISTANCE_UNIT_NAME)
            .createEntityManager();
    byExampleUtil = new ByExampleUtil();
    orderByUtil = new OrderByUtil();
}

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

/**
 * start up tmm - do initialization code here
 *///from   w w w.j ava2 s . c om
public void startUp() {
    // enhance if needed
    if (System.getProperty("tmmenhancer") != null) {
        // changed enhancer to be in sync with the build.xml
        com.objectdb.Enhancer.enhance("-s org.tinymediamanager.core.*");
        // com.objectdb.Enhancer.enhance("org.tinymediamanager.core.entities.*");
        // com.objectdb.Enhancer.enhance("org.tinymediamanager.core.movie.entities.*");
        // com.objectdb.Enhancer.enhance("org.tinymediamanager.core.tvshow.entities.*");
        // com.objectdb.Enhancer.enhance("org.tinymediamanager.scraper.MediaTrailer");
    }

    // get a connection to the database
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(TMM_DB);
    try {
        entityManager = entityManagerFactory.createEntityManager();
    } catch (PersistenceException e) {
        if (e.getCause().getMessage().contains("does not match db file")) {
            // happens when there's a recovery file which does not match (cannot be recovered) - just delete and try again
            FileUtils.deleteQuietly(new File(TMM_DB + "$"));
            entityManager = entityManagerFactory.createEntityManager();
        } else {
            // unknown
            throw (e);
        }
    }
}

From source file:test.automation.execution.TestExecutor.java

private void initializeHibernate() {
    entityManagerFactory = Persistence.createEntityManagerFactory(entityManagerName);

}

From source file:nl.b3p.kaartenbalie.core.server.persistence.MyEMFDatabase.java

public static void openEntityManagerFactory(String persistenceUnit) throws Exception {
    log.debug("ManagedPersistence.openEntityManagerFactory(" + persistenceUnit + ")");

    if (emf != null) {
        log.warn("EntityManagerFactory already initialized: " + emf.toString());
        return;/*w  w  w.j  a  v a  2  s .  c om*/
    }
    if (persistenceUnit == null || persistenceUnit.trim().length() == 0) {
        throw new Exception("PersistenceUnit cannot be left empty.");
    }
    try {
        emf = Persistence.createEntityManagerFactory(persistenceUnit);
    } catch (Throwable t) {
        log.fatal("Error initializing EntityManagerFactory: ", t);
    }
    if (emf == null) {
        log.fatal("Cannot initialize EntityManagerFactory");
        throw new Exception("Cannot initialize EntityManagerFactory");
    }
    log.debug("EntityManagerFactory initialized: " + emf.toString());
}