Example usage for javax.persistence EntityTransaction commit

List of usage examples for javax.persistence EntityTransaction commit

Introduction

In this page you can find the example usage for javax.persistence EntityTransaction commit.

Prototype

public void commit();

Source Link

Document

Commit the current resource transaction, writing any unflushed changes to the database.

Usage

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Deletes a news article from the db//from   ww w  .java2 s .c om
 *
 * @param entity The article to delete
 */
public void delete(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        //         Query query = em.createQuery(new StringBuilder().append("SELECT x FROM Article x WHERE x.aid = ").append(entity.getUuid()).append(" AND x.language='").append(entity.getLanguage()).append("'").toString());
        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.aid = :fsid AND x.language=:language").toString());
        query.setParameter("fsid", Long.parseLong(entity.getUuid()));
        query.setParameter("language", entity.getLanguage());

        if (!query.getResultList().isEmpty()) {
            Article art = (Article) query.getSingleResult();
            em.remove(art);
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while deleting from the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

From source file:org.opencastproject.capture.admin.impl.CaptureAgentStateServiceImpl.java

/**
 * Removes an agent from the database./*  ww w .j a  v a  2 s  .  com*/
 * 
 * @param agentName
 *          The name of the agent you wish to remove.
 */
private void deleteAgentFromDatabase(String agentName) throws NotFoundException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String org = securityService.getOrganization().getId();
        Agent existing = getAgentEntity(agentName, org, em);
        if (existing == null)
            throw new NotFoundException();
        em.remove(existing);
        tx.commit();
        agentCache.remove(agentName.concat(DELIMITER).concat(org));
    } catch (RollbackException e) {
        logger.warn("Unable to commit to DB in deleteAgent.");
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.sakaiproject.kernel.authz.simple.AclListener.java

/**
 * {@inheritDoc}/*from  w w w  . j a  v a 2  s.co m*/
 *
 * @see org.sakaiproject.kernel.jcr.api.JcrContentListener#onEvent(int,
 *      java.lang.String, java.lang.String, java.lang.String)
 */
public void handleEvent(int type, String userID, String filePath) {
    try {
        if ((type == Event.PROPERTY_ADDED || type == Event.PROPERTY_CHANGED
                || type == Event.PROPERTY_REMOVED)) {

            ArrayList<AclIndexBean> toCreate = new ArrayList<AclIndexBean>();
            ArrayList<AclIndexBean> toUpdate = new ArrayList<AclIndexBean>();
            ArrayList<AclIndexBean> toDelete = new ArrayList<AclIndexBean>();

            Query query = entityManager.createNamedQuery(AclIndexBean.Queries.FINDBY_PATH);
            query.setParameter(AclIndexBean.QueryParams.FINDBY_PATH_PATH, filePath);
            List<?> currentIndex = query.getResultList();

            try {
                Node node = jcrNodeFactoryService.getNode(filePath);
                Property acl = node.getProperty(JCRConstants.MIX_ACL);
                for (Value val : acl.getValues()) {
                    AccessControlStatement acs = new JcrAccessControlStatementImpl(val.getString());

                    switch (type) {
                    case Event.PROPERTY_ADDED:
                        if (inList(acs, currentIndex) == null) {
                            toCreate.add(convert(acs));
                        }
                        break;
                    case Event.PROPERTY_CHANGED:
                        AclIndexBean indexBean = inList(acs, currentIndex);
                        if (indexBean != null) {
                            toUpdate.add(indexBean);
                        }
                        break;
                    case Event.PROPERTY_REMOVED:
                        if (inList(acs, currentIndex) == null) {
                            toDelete.add(convert(acs));
                        }
                        break;
                    }
                }

                EntityTransaction trans = entityManager.getTransaction();
                trans.begin();
                try {
                    if (!toCreate.isEmpty()) {
                        for (AclIndexBean bean : toCreate) {
                            entityManager.persist(bean);
                        }
                    } else if (!toUpdate.isEmpty()) {
                        for (AclIndexBean bean : toUpdate) {
                            entityManager.persist(bean);
                        }
                    } else if (!toDelete.isEmpty()) {
                        for (AclIndexBean bean : toDelete) {
                            entityManager.remove(bean);
                        }
                    }
                    trans.commit();
                } catch (Exception e) {
                    LOG.error("Transaction rolled back due to a problem when updating the ACL index: "
                            + e.getMessage(), e);
                    trans.rollback();
                }
            } catch (PathNotFoundException e) {
                // nothing to care about. this happens when there is no ACL
                // on the node
            } catch (RepositoryException e) {
                // nothing we can do
                LOG.error(e.getMessage(), e);
            } catch (JCRNodeFactoryServiceException e) {
                // nothing we can do
                LOG.error(e.getMessage(), e);
            }
        }
    } finally {
        try {
            cacheManagerService.unbind(CacheScope.REQUEST);
        } catch (Exception ex) {
            // not interested
        }
        try {
            cacheManagerService.unbind(CacheScope.THREAD);
        } catch (Exception ex) {
            // not interested
        }
    }
}

From source file:org.opencastproject.messages.MailService.java

public MessageTemplate updateMessageTemplate(MessageTemplate template) throws MailServiceException {
    EntityManager em = null;/* w  w w . j av  a2 s  .c o m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String orgId = securityService.getOrganization().getId();
        MessageTemplateDto msgTmpl = mergeMessageTemplate(template, orgId, em);
        tx.commit();
        return msgTmpl.toMessageTemplate(userDirectoryService);
    } catch (Exception e) {
        logger.error("Could not update message template '{}': {}", template, e.getMessage());
        if (tx.isActive())
            tx.rollback();
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.messages.MailService.java

public MessageSignature updateMessageSignature(MessageSignature signature) throws MailServiceException {
    EntityManager em = null;//from w  ww .ja  v  a 2  s .  co  m
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String orgId = securityService.getOrganization().getId();
        MessageSignatureDto msgSign = mergeMessageSignature(signature, orgId, em);
        tx.commit();
        return msgSign.toMessageSignature(userDirectoryService);
    } catch (Exception e) {
        logger.error("Could not update message signature '{}': {}", signature, e.getMessage());
        if (tx.isActive())
            tx.rollback();
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:info.dolezel.jarss.rest.v1.ws.UnreadNotificationEndpoint.java

@OnWebSocketMessage
public void onMessage(Session session, String text) {
    EntityManager em = null;/* w ww  .ja  v  a 2s . co  m*/
    EntityTransaction tx = null;
    try {
        JsonReader reader;
        JsonObject object;
        Token token;

        em = HibernateUtil.getEntityManager();
        tx = em.getTransaction();

        tx.begin();

        reader = Json.createReader(new StringReader(text));
        object = reader.readObject();

        token = Token.loadToken(em, object.getString("token"));
        if (token == null) {
            tx.rollback();

            Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.WARNING,
                    "Invalid token provided over WebSocket");
            session.close();
        } else {
            synchronized (sessions) {
                sessions.put(session, token.getUser());
            }
            synchronized (userSessions) {
                userSessions.put(token.getUser(), session);
            }
        }

        tx.commit();
    } catch (Exception ex) {
        if (tx != null)
            tx.rollback();

        Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.SEVERE,
                "Error processing incoming WebSocket message", ex);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.apache.juddi.subscription.SubscriptionNotifier.java

/**
 * Sends out the notifications./* w w  w  .  j a v a 2s  .  com*/
 * @param getSubscriptionResults
 * @param resultList 
 * @param notificationDate 
 */
protected void notify(GetSubscriptionResults getSubscriptionResults, SubscriptionResultsList resultList,
        Date notificationDate) {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        String subscriptionKey = resultList.getSubscription().getSubscriptionKey();
        org.apache.juddi.model.Subscription modelSubscription = em
                .find(org.apache.juddi.model.Subscription.class, subscriptionKey);
        Date lastNotifiedDate = modelSubscription.getLastNotified();
        //now log to the db that we are sending the notification.
        tx.begin();
        modelSubscription.setLastNotified(notificationDate);
        em.persist(modelSubscription);
        tx.commit();

        org.apache.juddi.model.BindingTemplate bindingTemplate = em
                .find(org.apache.juddi.model.BindingTemplate.class, modelSubscription.getBindingKey());
        NotifySubscriptionListener body = new NotifySubscriptionListener();
        //         if (resultList.getServiceList()!=null && resultList.getServiceList().getServiceInfos()!=null &&
        //               resultList.getServiceList().getServiceInfos().getServiceInfo().size() == 0) {
        //            resultList.getServiceList().setServiceInfos(null);
        //         }
        body.setSubscriptionResultsList(resultList);

        //TODO if the endpoint requires an auth token, look up the security endpoint of the remote registry
        //via ClientSubscriptionInfo

        if (sendToken) {
            String authorizedName = modelSubscription.getAuthorizedName();
            UDDISecurityImpl security = new UDDISecurityImpl();

            if (authorizedName != null) { // add a security token if needed
                try {
                    //obtain a token for this publisher
                    org.uddi.api_v3.AuthToken token = security.getAuthToken(authorizedName);
                    body.setAuthInfo(token.getAuthInfo());
                } catch (DispositionReportFaultMessage e) {
                    body.setAuthInfo("Failed to generate token, please contact UDDI admin");
                    log.error(e.getMessage(), e);
                }
            }
        }

        if (bindingTemplate != null) {
            if (AccessPointType.END_POINT.toString().equalsIgnoreCase(bindingTemplate.getAccessPointType())
                    || AccessPointType.WSDL_DEPLOYMENT.toString()
                            .equalsIgnoreCase(bindingTemplate.getAccessPointType())) {
                try {
                    Notifier notifier = new NotifierFactory().getNotifier(bindingTemplate);
                    if (notifier != null) {
                        log.info("Sending out notification to " + bindingTemplate.getAccessPointUrl());
                        notifier.notifySubscriptionListener(body);
                        //there maybe more chunks we have to send
                        String chunkToken = body.getSubscriptionResultsList().getChunkToken();
                        while (chunkToken != null) {
                            UddiEntityPublisher publisher = new UddiEntityPublisher();
                            publisher.setAuthorizedName(modelSubscription.getAuthorizedName());
                            log.debug("Sending out next chunk: " + chunkToken + " to "
                                    + bindingTemplate.getAccessPointUrl());
                            getSubscriptionResults.setChunkToken(chunkToken);
                            resultList = subscriptionImpl.getSubscriptionResults(getSubscriptionResults,
                                    publisher);
                            body.setSubscriptionResultsList(resultList);
                            notifier.notifySubscriptionListener(body);
                            chunkToken = body.getSubscriptionResultsList().getChunkToken();
                        }
                        //successful notification so remove from the badNotificationList
                        if (badNotifications.containsKey(resultList.getSubscription().getSubscriptionKey()))
                            badNotifications.remove(resultList.getSubscription().getSubscriptionKey());
                    }
                } catch (Exception e) {
                    if (e.getCause() instanceof IOException) {
                        addBadNotificationToList(subscriptionKey, bindingTemplate.getAccessPointUrl());
                        //we could not notify so compensate the transaction above
                        modelSubscription.setLastNotified(lastNotifiedDate);
                        tx.begin();
                        em.persist(modelSubscription);
                        tx.commit();
                        //} else {
                        //log.warn("Unexpected WebServiceException " + e.getMessage() + e.getCause());
                    }
                    log.error("Unexpected notification exception:" + e.getClass().getCanonicalName() + " "
                            + e.getMessage() + " " + e.getCause());
                    log.debug("Unexpected notification exception:" + e.getClass().getCanonicalName() + " "
                            + e.getMessage() + " " + e.getCause(), e);
                }
            } else {
                log.info("Binding " + bindingTemplate.getEntityKey() + " has an unsupported binding type of "
                        + bindingTemplate.getAccessPointType() + ". Only "
                        + AccessPointType.END_POINT.toString() + " and "
                        + AccessPointType.WSDL_DEPLOYMENT.toString() + " are supported.");
                addBadNotificationToList(subscriptionKey,
                        bindingTemplate.getAccessPointType() + " not supported");
            }
        } else {
            log.info("There is no valid binding template defined for this subscription: "
                    + modelSubscription.getBindingKey());
            addBadNotificationToList(subscriptionKey, modelSubscription.getBindingKey() + " not found");
        }

    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:com.eucalyptus.images.ImageManager.java

public ResetImageAttributeResponseType resetImageAttribute(ResetImageAttributeType request)
        throws EucalyptusCloudException {
    ResetImageAttributeResponseType reply = (ResetImageAttributeResponseType) request.getReply();
    reply.set_return(true);
    EntityTransaction tx = Entities.get(ImageInfo.class);
    try {//from  w  ww.  j  a  va  2  s  . co m
        ImageInfo imgInfo = Entities
                .uniqueResult(Images.exampleWithImageId(imageIdentifier(request.getImageId())));
        if (canModifyImage(imgInfo)) {
            imgInfo.resetPermission();
            tx.commit();
            return reply.markWinning();
        } else {
            tx.rollback();
            return reply.markFailed();
        }
    } catch (EucalyptusCloudException e) {
        LOG.error(e, e);
        tx.rollback();
        return reply.markFailed();
    } catch (TransactionException | NoSuchElementException ex) {
        tx.rollback();
        return reply.markFailed();
    }
}

From source file:org.opencastproject.messages.MailService.java

public EmailConfiguration updateEmailConfiguration(EmailConfiguration emailConfiguration)
        throws MailServiceException {
    EntityManager em = null;/*from w w  w. j a va  2 s  . c o  m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        String orgId = securityService.getOrganization().getId();
        EmailConfigurationDto emailConfig = mergeEmailConfiguration(emailConfiguration, orgId, em);
        tx.commit();
        EmailConfiguration updatedEmailConfiguration = emailConfig.toEmailConfiguration();
        updateSmtpConfiguration(updatedEmailConfiguration);
        return updatedEmailConfiguration;
    } catch (Exception e) {
        logger.error("Could not update email configuration '{}': {}", emailConfiguration, e.getMessage());
        if (tx.isActive())
            tx.rollback();
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.themes.persistence.ThemesServiceDatabaseImpl.java

@Override
public Theme updateTheme(Theme theme) throws ThemesServiceDatabaseException {
    EntityManager em = null;// w  ww  .java2 s .  c  o m
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        ThemeDto themeDto = null;
        if (theme.getId().isSome())
            themeDto = getThemeDto(theme.getId().get(), em);

        if (themeDto == null) {
            // no theme stored, create new entity
            themeDto = new ThemeDto();
            themeDto.setOrganization(securityService.getOrganization().getId());
            updateTheme(theme, themeDto);
            em.persist(themeDto);
        } else {
            updateTheme(theme, themeDto);
            em.merge(themeDto);
        }
        tx.commit();
        theme = themeDto.toTheme(userDirectoryService);
        messageSender.sendObjectMessage(ThemeItem.THEME_QUEUE, MessageSender.DestinationType.Queue,
                ThemeItem.update(toSerializableTheme(theme)));
        return theme;
    } catch (Exception e) {
        logger.error("Could not update theme {}: {}", theme, ExceptionUtils.getStackTrace(e));
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new ThemesServiceDatabaseException(e);
    } finally {
        if (em != null) {
            em.close();
        }
    }
}