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:org.traccar.web.server.model.DataServiceImpl.java

@Override
public User addUser(User user) {
    User currentUser = getSessionUser();
    if (user.getLogin().isEmpty() || user.getPassword().isEmpty()) {
        throw new IllegalArgumentException();
    }//from  w ww  . j av  a 2 s  .c o m
    if (currentUser.getAdmin()) {
        EntityManager entityManager = getSessionEntityManager();
        synchronized (entityManager) {
            entityManager.getTransaction().begin();
            try {
                entityManager.persist(user);
                entityManager.getTransaction().commit();
                return user;
            } catch (RuntimeException e) {
                entityManager.getTransaction().rollback();
                throw e;
            }
        }
    } else {
        throw new SecurityException();
    }
}

From source file:org.traccar.web.server.model.DataServiceImpl.java

@Override
public User updateUser(User user) {
    User currentUser = getSessionUser();
    if (user.getLogin().isEmpty() || user.getPassword().isEmpty()) {
        throw new IllegalArgumentException();
    }/*from   w  w w .  ja v a  2 s  .c  om*/
    if (currentUser.getAdmin() || (currentUser.getId() == user.getId() && !user.getAdmin())) {
        EntityManager entityManager = getSessionEntityManager();
        synchronized (entityManager) {
            entityManager.getTransaction().begin();
            try {
                // TODO: better solution?
                if (currentUser.getId() == user.getId()) {
                    currentUser.setLogin(user.getLogin());
                    currentUser.setPassword(user.getPassword());
                    currentUser.setUserSettings(user.getUserSettings());
                    currentUser.setAdmin(user.getAdmin());
                    entityManager.merge(currentUser);
                    user = currentUser;
                } else {
                    // TODO: handle other users
                }

                entityManager.getTransaction().commit();
                setSessionUser(user);
                return user;
            } catch (RuntimeException e) {
                entityManager.getTransaction().rollback();
                throw e;
            }
        }
    } else {
        throw new SecurityException();
    }
}

From source file:nl.b3p.datastorelinker.gui.stripes.ConvertLargeObjectsAction.java

public void convertLOBS() throws SQLException, NoSuchFieldException, IllegalArgumentException,
        IllegalAccessException, IOException {

    statusArray.put("Opening connection..");
    EntityManager em = JpaUtilServlet.getThreadEntityManager();
    Session session = (Session) em.getDelegate();
    Connection conn = session.connection();
    conn.setAutoCommit(false);//from w w  w . j a  v  a2 s .  c o m
    DatabaseMetaData metadata = conn.getMetaData();
    statusArray.put("Digging deep to retrieve implementation");

    Field f = metadata.getClass().getDeclaredField("inner");

    f.setAccessible(true);
    Object pgconnMetadata = f.get(metadata);
    statusArray.put("Retrieving postgres connection..");
    org.postgresql.PGConnection connection = (org.postgresql.PGConnection) ((org.postgresql.jdbc4.Jdbc4DatabaseMetaData) pgconnMetadata)
            .getConnection();
    statusArray.put("Connection established");
    lom = connection.getLargeObjectAPI();
    statusArray.put("Create LargeObjectManager");
    em.getTransaction().begin();
    statusArray.put("Begin converting LOBs");
    processProcesses(em);
    processProcessesStatusses(em);

    statusArray.put("Converting finished");
    em.getTransaction().commit();
    statusArray.put("Changes saved");
}

From source file:org.traccar.web.server.model.DataServiceImpl.java

@Override
public Device addDevice(Device device) {
    EntityManager entityManager = getSessionEntityManager();
    synchronized (entityManager) {
        User user = getSessionUser();/*from  w w w .  jav  a  2 s  .c  o  m*/
        entityManager.getTransaction().begin();
        try {
            entityManager.persist(device);
            user.getDevices().add(device);
            entityManager.getTransaction().commit();
            return device;
        } catch (RuntimeException e) {
            entityManager.getTransaction().rollback();
            throw e;
        }
    }
}

From source file:org.traccar.web.server.model.DataServiceImpl.java

@Override
public Device removeDevice(Device device) {
    EntityManager entityManager = getSessionEntityManager();
    synchronized (entityManager) {
        User user = getSessionUser();/*from   ww  w  .j  a v  a  2  s  .co m*/
        entityManager.getTransaction().begin();
        try {
            device = entityManager.merge(device);
            user.getDevices().remove(device);
            device.setLatestPosition(null);
            entityManager.flush();
            Query query = entityManager.createQuery("DELETE FROM Position x WHERE x.device = :device");
            query.setParameter("device", device);
            query.executeUpdate();
            entityManager.remove(device);
            entityManager.getTransaction().commit();
            return device;
        } catch (RuntimeException e) {
            entityManager.getTransaction().rollback();
            throw e;
        }
    }
}

From source file:de.zib.gndms.infra.system.GNDMSystem.java

/**
 * Checks if a commit can be done on the database
 *
 * @throws RuntimeException if an error occured while commiting on the database
 *///w  ww .  j a v  a  2 s.  c  om
private void tryTxExecution() throws RuntimeException {
    final EntityManager em = emf.createEntityManager();
    try {
        em.getTransaction().begin();
        em.getTransaction().commit();
    } catch (RuntimeException re) {
        em.getTransaction().rollback();
        em.close();
        throw re;
    } finally {
        em.close();
    }
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@POST
@Consumes(MediaType.APPLICATION_JSON)/*from  w  w  w.  ja va  2s.c o m*/
public Response subscribeFeed(@Context SecurityContext context, FeedSubscriptionData data) {
    FeedCategory fc = null;
    EntityManager em;
    EntityTransaction tx;
    User user;
    FeedData feedData;
    Feed f;
    boolean createdNewFD = false;

    if (data.getUrl() == null) {
        return Response.status(Response.Status.BAD_REQUEST).entity(new ErrorDescription("Feed URL missing"))
                .build();
    }

    user = (User) context.getUserPrincipal();
    em = HibernateUtil.getEntityManager();
    tx = em.getTransaction();
    tx.begin();

    try {
        if (data.getCategoryId() != 0) {
            try {
                fc = (FeedCategory) em
                        .createQuery("select fc from FeedCategory fc where fc.id = :id", FeedCategory.class)
                        .setParameter("id", data.getCategoryId()).getSingleResult();
            } catch (NoResultException e) {
                return Response.status(Response.Status.NOT_FOUND)
                        .entity(new ErrorDescription("Feed category not found")).build();
            }

            if (!fc.getUser().equals(user)) {
                return Response.status(Response.Status.FORBIDDEN)
                        .entity(new ErrorDescription("Feed category not owned by user")).build();
            }
        }

        // Try to look up existing FeedData
        try {
            feedData = (FeedData) em.createNamedQuery("FeedData.getByUrl").setParameter("url", data.getUrl())
                    .getSingleResult();
        } catch (NoResultException e) {
            feedData = new FeedData();
            feedData.setUrl(data.getUrl());

            try {
                loadFeedDetails(feedData);
            } catch (Exception ex) {
                e.printStackTrace();
                return Response.status(Response.Status.BAD_GATEWAY)
                        .entity(new ErrorDescription("Cannot fetch the feed")).build();
            }

            em.persist(feedData);
            createdNewFD = true;
        }

        f = new Feed();
        f.setUser(user);
        f.setFeedCategory(fc);
        f.setData(feedData);
        f.setName(feedData.getTitle());

        em.persist(f);

        tx.commit();

        if (createdNewFD)
            FeedsEngine.getInstance().submitFeedRefresh(feedData);

        return Response.noContent().build();
    } finally {
        if (tx.isActive())
            tx.rollback();
        em.close();
    }
}

From source file:de.zib.gndms.logic.model.TaskAction.java

/**
 * Initializes a TaskAction by denoting an EntityManager and primary key
 *
 * Retrieves the model (an AbstractTask), managed by the EntityManager, sets it as the model of {@code this} and
 * makes a backup of it./*  w  ww . ja va  2  s. c om*/
 *
 * The AbstractTask is select by the primary key {@code pk}. The EntityManager {@code em}
 * will be set as EntityManager for {@code this}, using {@link #setOwnEntityManager(javax.persistence.EntityManager)}.
 *
 * @param em an EntityManager, storing AbstractTasks
 * @param pk the primary key a of specific AbstractTask, which is managed by the EntityManager
 */
public void initFromPk(final EntityManager em, final String pk) {
    boolean wasActive = em.getTransaction().isActive();
    if (!wasActive)
        em.getTransaction().begin();
    try {
        final AbstractTask model = em.find(getTaskClass(), pk);
        if (model == null)
            throw new IllegalArgumentException("Model not found for pk: " + pk);
        if (!wasActive)
            em.getTransaction().commit();
        setOwnEntityManager(em);
        setModelAndBackup(model);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
    }
}

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

/**
 *
 * @param request servlet request/*from ww  w  .  j  av  a2 s.  co 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 {
    String msg = request.getParameter("msg");
    EntityManager em = (EntityManager) request.getSession().getAttribute("em");
    Clock clk = (Clock) (request.getSession().getAttribute("clock"));
    Term term = Term.getTermforInstant(em, Instant.now(clk));
    if (msg.equals("get_appointments")) {
        String userId = request.getParameter("username");
        User user = em.find(User.class, userId);

        JSONArray json = getAppointments(user, term, clk);
        response.getWriter().write(json.toString());
    } else if (msg.equals("do_checkin")) {
        String userId = request.getParameter("username");
        String examId = request.getParameter("examid");
        User admin = (User) (request.getSession().getAttribute("user"));
        User student = em.find(User.class, userId);
        Exam exam = em.find(Exam.class, examId);

        Appointment appt = student.getAppointmentByExam(exam);
        em.getTransaction().begin();
        admin.checkInStudent(appt);
        em.persist(appt);
        em.persist(student);
        em.getTransaction().commit();

        JSONArray json = getAppointments(student, term, clk);
        response.getWriter().write(json.toString());
    } else {
        JSONObject json = new JSONObject();
        json.put("error", msg);
        response.getWriter().write(json.toString());
    }
}

From source file:nl.b3p.viewer.admin.stripes.GeoServiceRegistryActionBean.java

public Resolution addSubcategory() throws JSONException {
    EntityManager em = Stripersist.getEntityManager();

    JSONObject json = new JSONObject();

    json.put("success", Boolean.FALSE);

    String error = checkCategoryAndNameError();

    if (error == null) {
        for (Category child : category.getChildren()) {
            if (name.equals(child.getName())) {
                error = "Categorie met dezelfde naam bestaat al";
            }//from   w  w  w. jav  a  2s.co m
        }
    }

    if (error == null) {
        try {
            Category c = new Category();
            c.setName(name);
            c.setParent(category);
            category.getChildren().add(c);

            em.persist(c);
            em.getTransaction().commit();

            JSONObject node = new JSONObject();
            node.put("id", "c" + c.getId());
            node.put("name", c.getName());
            node.put("type", "category");
            node.put("isLeaf", true);
            node.put("parentid", nodeId);
            json.put("node", node);

            json.put("success", Boolean.TRUE);
        } catch (Exception e) {
            log.error("Fout bij toevoegen categorie", e);
            error = "Kan categorie niet toevoegen: " + e;
            Throwable t = e;
            while (t.getCause() != null) {
                t = t.getCause();
                error += "; " + t;
            }
        }
    }

    if (error != null) {
        json.put("error", error);
    }
    return new StreamingResolution("application/json", new StringReader(json.toString()));
}