Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

In this page you can find the example usage for javax.persistence EntityManager getTransaction.

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:de.iai.ilcd.model.dao.SourceDao.java

private boolean saveDigitalFiles(Source source, PrintWriter out) {
    EntityManager em = PersistenceUtil.getEntityManager();

    File directory = null;//  w  w  w.  jav a 2s.co m
    EntityTransaction t = em.getTransaction();
    try {

        // OK, now let's handle the files if any
        if ((source.getFiles().size() > 0) && (source.getId() > 0)) { // we have files and the source has a valid
            // id
            // first let's check if the source has already a file directory to save binary files
            String directoryPath = source.getFilesDirectory();
            directory = new File(directoryPath);

            if (!directory.exists()) {
                directory.mkdirs(); // OK, create the directory and all parents
            } // OK, now that we verified that we have a directory, let's copy the files to the directory
            for (DigitalFile digitalFile : source.getFiles()) {
                String sourcePath = digitalFile.getFileName();
                logger.info("have to save digital file {}", sourcePath);
                File file = new File(sourcePath);
                if (file.canRead()) {
                    // copy file only if we have a real file and not only a URL
                    File dest = new File(directory, file.getName());
                    if (!file.copyTo(dest)) {
                        if (out != null) {
                            out.println("cannot copy file " + file.getName() + " of source data set "
                                    + source.getName().getDefaultValue() + " to database file firectory");
                        }
                        logger.error("cannot copy digital file {} to source directory {}", file.getName(),
                                directoryPath);
                    }
                    // now, replace name in digitalFile with just the name of the file
                    digitalFile.setFileName(FilenameUtils.getName(sourcePath));
                } else {
                    if (!file.getName().startsWith("http:") || !file.getName().startsWith("https:")) {
                        // there are sometimes URL refs in source which don't have http:// prepended
                        if (!file.getName().matches(".+\\....") && file.getName().contains(".")) {
                            // looks like a URL with no http:// in front; try to fix that
                            digitalFile.setFileName("http://" + file.getName());
                        } else {
                            // we have a file which we cannot find
                            digitalFile.setFileName(FilenameUtils.getName(sourcePath));
                            out.println("warning: digital file " + FilenameUtils.getName(sourcePath)
                                    + " of source data set " + source.getName().getDefaultValue()
                                    + " cannot be found in external_docs directory");
                            logger.warn(
                                    "warning: digital file {} of source data set {} cannot be found in external_docs directory; will be ignored",
                                    file.getName(), source.getName().getDefaultValue());
                        }
                    }
                }
                t.begin();
                em.persist(digitalFile);
                t.commit();
            }
        }
    } catch (Exception e) {
        // OK, let's delete the digital files and rollback the whole transaction to remove database items
        logger.error("cannot save digital file", e);
        if (t.isActive()) {
            t.rollback();
        }
        this.deleteDigitalFiles(source);
        return false;
    }
    return true;
}

From source file:BO.UserHandler.java

public boolean respondFriendRequest(VUser user) {
    EntityManager em;

    EntityManagerFactory emf;/*  ww  w. ja  v a  2  s .  c o  m*/
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {
        em.getTransaction().begin();
        System.out.println("Receiving friend: " + user.getEmail());
        System.out.println("Sending friend: " + user.getFriendToAdd());

        Friendship f = (Friendship) em
                .createQuery("SELECT f from Friendship f WHERE f.receivingFriend.email LIKE :email1 "
                        + "AND f.sendingFriend.email LIKE :email2")
                .setParameter("email1", user.getEmail()).setParameter("email2", user.getFriendToAdd())
                .getSingleResult();
        f.setDidRespond(true);
        f.setDidAccept(user.isDidAccept());
        em.persist(f);
        em.flush();
        em.getTransaction().commit();
        return true;
    } catch (Exception e) {
        System.out.println(e);
        return false;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.CommandITCase.java

/**
 * Before test.//from   w w w  .  ja  v  a  2  s  . c  om
 *
 * @throws Exception the exception
 */
@Before
public void beforeTest() throws Exception {
    EntityManager em = emf.createEntityManager();
    try {
        EntityTransaction et = em.getTransaction();
        et.begin();
        Query query = em.createQuery(new StringBuilder().append("SELECT x FROM news x").toString());
        List<News> newsList = query.getResultList();
        for (News news : newsList) {
            em.remove(news);
        }

        query = em.createQuery(new StringBuilder().append("SELECT x FROM category x").toString());
        List<NewsCategory> catList = query.getResultList();
        for (NewsCategory temp : catList) {
            em.remove(temp);
        }

        query = em.createQuery(new StringBuilder().append("SELECT x FROM metaCategory x").toString());
        List<NewsMetaCategory> metaList = query.getResultList();
        for (NewsMetaCategory temp : metaList) {
            em.remove(temp);
        }
        et.commit();
    } finally {
        em.close();
    }

}

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

@PUT
@Path("{username}.json")
@RestQuery(name = "roleupdate", description = "Updates a user's roles", returnDescription = "No content", restParameters = @RestParameter(name = "roles", type = TEXT, isRequired = true, description = "The user roles as a json array"), pathParameters = @RestParameter(name = "username", type = STRING, isRequired = true, description = "The username"), reponses = {
        @RestResponse(responseCode = SC_NO_CONTENT, description = "The user roles have been updated.") })
public Response updateUserFromJson(@PathParam("username") String username, @FormParam("roles") String roles) {
    JSONArray rolesArray = (JSONArray) JSONValue.parse(roles);
    EntityManager em = null;
    EntityTransaction tx = null;//  w  w w . j a  va 2  s.  com
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        // Find the existing user
        Query q = em.createNamedQuery("user");
        q.setParameter("u", username);
        q.setParameter("o", securityService.getOrganization().getId());
        JpaUser jpaUser = null;
        try {
            jpaUser = (JpaUser) q.getSingleResult();
            jpaUser.roles.clear();
            for (Object role : rolesArray) {
                jpaUser.roles.add((String) role);
            }
            em.merge(jpaUser);
        } catch (NoResultException e) {
            return null; // this will be translated into a 404
        }
        tx.commit();
        return Response.noContent().build();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}

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

public User saveUser(User user, boolean savePassword) {
    EntityManager em = emf.createEntityManager();
    try {//from w  ww .  jav a 2 s  . c o  m
        user.password = Utils.hashPassword(user.password);
        em.getTransaction().begin();
        if (user.userId == null) {
            grantDefaultRoleToUser(em, user);
            em.persist(user);
        } else {
            user = em.merge(user);
            if (savePassword) {
                Query q = em.createNamedQuery("User.setPassword");
                q.setParameter("password", user.password);
                q.setParameter("userId", user.userId);
                q.executeUpdate();
            }
        }
        em.getTransaction().commit();
    } finally {
        em.clear();
        em.close();
    }
    return user;
}

From source file:com.gigglinggnus.controllers.ManageExamsController.java

/**
 *
 * @param request servlet request//from  www  . ja v  a2  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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    EntityManager em = (EntityManager) request.getSession().getAttribute("em");

    String examId = request.getParameter("examid");
    String status = request.getParameter("status");
    Clock clk = (Clock) (request.getSession().getAttribute("clock"));
    User user = (User) (request.getSession().getAttribute("user"));

    Exam exam = em.find(Exam.class, examId);

    try {
        em.getTransaction().begin();
    } catch (Exception e) {
    }

    try {
        if (status.equals("approved")) {
            user.changeExamStatus(exam, ExamStatus.APPROVED);
            em.persist(exam);
            em.getTransaction().commit();
            request.setAttribute("msg", "Exam APPROVED");
        } else if (status.equals("denied")) {
            user.changeExamStatus(exam, ExamStatus.DENIED);
            em.persist(exam);
            em.getTransaction().commit();
            request.setAttribute("msg", "Exam Denied");
        } else {
            request.setAttribute("msg", "Invalid status");
        }
    } catch (Exception e) {
        em.getTransaction().rollback();
        request.setAttribute("msg", e.toString());
        throw e;
    }

    RequestDispatcher rd = request.getRequestDispatcher("/home.jsp");
    rd.forward(request, response);
}

From source file:BO.UserHandler.java

public boolean addFriend(VUser u) {
    EntityManager em;
    EntityManagerFactory emf;/*  w w  w  .j a va 2s  .co m*/
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {
        em.getTransaction().begin();
        System.out.println(u.getEmail());
        System.out.println(u.getFriendToAdd());

        try {
            List<Friendship> f = (List<Friendship>) em
                    .createQuery("SELECT f from Friendship f WHERE f.receivingFriend.email LIKE :email1 "
                            + "AND f.sendingFriend.email LIKE :email2")
                    .setParameter("email1", u.getEmail()).setParameter("email2", u.getFriendToAdd())
                    .getResultList();
            if (!f.isEmpty()) {
                return false;
            }
        } catch (Exception e) {

        }

        try {

            List<Friendship> f = (List<Friendship>) em
                    .createQuery("SELECT f from Friendship f WHERE f.sendingFriend.email LIKE :email1 "
                            + "AND f.receivingFriend.email LIKE :email2")
                    .setParameter("email1", u.getEmail()).setParameter("email2", u.getFriendToAdd())
                    .getResultList();
            if (!f.isEmpty()) {
                return false;
            }
        } catch (Exception e) {

        }

        User sender = getUserByEmail(u.getEmail());
        User receiver = getUserByEmail(u.getFriendToAdd());

        Friendship friendship = new Friendship(sender, receiver);
        em.persist(friendship);
        em.flush();
        em.getTransaction().commit();
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }
}

From source file:BO.UserHandler.java

public int sendChallengeRequest(VUser user) {
    EntityManager em;

    EntityManagerFactory emf;//from  w  w w  .  j  av  a2s  .com
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {
        em.getTransaction().begin();
        System.out.println("Challenged by: " + user.getEmail());
        System.out.println("Challenged friend: " + user.getFriendToAdd());

        User friend = getUserByEmail(user.getFriendToAdd());

        GameServerCommunicator gameComm = new GameServerCommunicator();
        ArrayList<String> playerNames = new ArrayList<>();
        playerNames.add(user.getEmail());
        playerNames.add(user.getFriendToAdd());
        int gameId = gameComm.requestNewGame(playerNames);
        if (gameId == -1) {
            //if something went wrong
            return -1;
        }

        //Send cloud message to friend
        JSONObject notificationObj = new JSONObject();
        notificationObj.put("body", "CHALLENGE " + user.getEmail() + " " + GameInfo.getInstance().getIp() + " "
                + GameInfo.getInstance().getClientPort() + " " + gameId);
        notificationObj.put("title", "A Challenge");

        JSONObject messageObj = new JSONObject();
        messageObj.put("token", friend.getDeviceToken());
        messageObj.put("notification", notificationObj);

        JSONObject mainObject = new JSONObject();
        mainObject.put("message", messageObj);

        HttpPost url = getHttpURL();
        url.setEntity(new StringEntity(mainObject.toString()));

        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(url);
        System.out.println("Response:");
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseString);
        em.flush();
        em.getTransaction().commit();
        return gameId;
    } catch (Exception e) {
        System.out.println(e);
        return -1;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }
}

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

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

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

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