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:org.opencastproject.series.impl.persistence.SeriesServiceDatabaseImpl.java

@Override
public DublinCoreCatalog storeSeries(DublinCoreCatalog dc)
        throws SeriesServiceDatabaseException, UnauthorizedException {
    if (dc == null) {
        throw new SeriesServiceDatabaseException("Invalid value for Dublin core catalog: null");
    }/*ww  w.  j a  v  a 2  s  .  c  o  m*/
    String seriesId = dc.getFirst(DublinCore.PROPERTY_IDENTIFIER);
    String seriesXML;
    try {
        seriesXML = serializeDublinCore(dc);
    } catch (Exception e1) {
        logger.error("Could not serialize Dublin Core: {}", e1);
        throw new SeriesServiceDatabaseException(e1);
    }
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    DublinCoreCatalog newSeries = null;
    try {
        tx.begin();
        SeriesEntity entity = getSeriesEntity(seriesId, em);
        if (entity == null) {
            // no series stored, create new entity
            entity = new SeriesEntity();
            entity.setOrganization(securityService.getOrganization().getId());
            entity.setSeriesId(seriesId);
            entity.setSeries(seriesXML);
            em.persist(entity);
            newSeries = dc;
        } else {
            // Ensure this user is allowed to update this series
            String accessControlXml = entity.getAccessControl();
            if (accessControlXml != null) {
                AccessControlList acl = AccessControlParser.parseAcl(accessControlXml);
                User currentUser = securityService.getUser();
                Organization currentOrg = securityService.getOrganization();
                if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, EDIT_SERIES_PERMISSION)) {
                    throw new UnauthorizedException(
                            currentUser + " is not authorized to update series " + seriesId);
                }
            }
            entity.setSeries(seriesXML);
            em.merge(entity);
        }
        tx.commit();
        return newSeries;
    } catch (Exception e) {
        logger.error("Could not update series: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SeriesServiceDatabaseException(e);
    } finally {
        em.close();
    }

}

From source file:org.apache.juddi.api.impl.UDDISubscriptionImpl.java

@SuppressWarnings("unchecked")
public List<Subscription> getSubscriptions(String authInfo) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from w w  w . j a v  a2 s .c o  m*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);

        List<Subscription> result = new ArrayList<Subscription>(0);

        List<org.apache.juddi.model.Subscription> modelSubscriptionList = (List<org.apache.juddi.model.Subscription>) FindSubscriptionByPublisherQuery
                .select(em, publisher.getAuthorizedName());
        if (modelSubscriptionList != null && modelSubscriptionList.size() > 0) {
            for (org.apache.juddi.model.Subscription modelSubscription : modelSubscriptionList) {

                Subscription apiSubscription = new Subscription();

                MappingModelToApi.mapSubscription(modelSubscription, apiSubscription);

                result.add(apiSubscription);
            }
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(SubscriptionQuery.GET_SUBSCRIPTIONS, QueryStatus.SUCCESS, procTime);

        return result;
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(SubscriptionQuery.GET_SUBSCRIPTIONS, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java

public List<PublisherAssertion> getPublisherAssertions(String authInfo) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//www  .  ja  va  2  s .  c  o  m
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo);

        List<org.uddi.api_v3.PublisherAssertion> result = new ArrayList<org.uddi.api_v3.PublisherAssertion>(0);

        List<?> businessKeysFound = null;
        businessKeysFound = FindBusinessByPublisherQuery.select(em, null, publisher, businessKeysFound);

        List<org.apache.juddi.model.PublisherAssertion> pubAssertionList = FindPublisherAssertionByBusinessQuery
                .select(em, businessKeysFound, null);
        if (pubAssertionList != null)
            for (org.apache.juddi.model.PublisherAssertion modelPubAssertion : pubAssertionList) {
                org.uddi.api_v3.PublisherAssertion apiPubAssertion = new org.uddi.api_v3.PublisherAssertion();

                MappingModelToApi.mapPublisherAssertion(modelPubAssertion, apiPubAssertion);

                result.add(apiPubAssertion);
            }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.GET_PUBLISHERASSERTIONS, QueryStatus.SUCCESS, procTime);
        return result;
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.GET_PUBLISHERASSERTIONS, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.apache.juddi.v3.auth.HTTPContainerAuthenticator.java

@Override
public UddiEntityPublisher identify(String authInfoNotused, String authorizedNameNotused, WebServiceContext ctx)
        throws AuthenticationException, FatalErrorException {
    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    try {//from ww  w  . ja va  2  s  .co m
        MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE,
                -1);
        MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS,
                -1);
        MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1);
        MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1);
    } catch (Exception ex) {
        MaxBindingsPerService = -1;
        MaxServicesPerBusiness = -1;
        MaxTmodels = -1;
        MaxBusinesses = -1;
        log.error("config exception! ", ex);
    }
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        String user = null;
        if (ctx == null)
            throw new UnknownUserException(
                    new ErrorMessage("errors.auth.NoPublisher", "no web service context!"));
        if (ctx.getUserPrincipal() != null) {
            user = ctx.getUserPrincipal().getName();
        }
        if (user == null) {
            MessageContext mc = ctx.getMessageContext();
            HttpServletRequest req = null;
            if (mc != null) {
                req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
            }
            if (req != null && req.getUserPrincipal() != null) {
                user = req.getUserPrincipal().getName();
            }
        }
        if (user == null || user.length() == 0) {
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher"));
        }
        tx.begin();
        Publisher publisher = em.find(Publisher.class, user);
        if (publisher == null) {
            log.warn("Publisher \"" + user
                    + "\" was not found in the database, adding the publisher in on the fly.");
            publisher = new Publisher();
            publisher.setAuthorizedName(user);
            publisher.setIsAdmin("false");
            publisher.setIsEnabled("true");
            publisher.setMaxBindingsPerService(MaxBindingsPerService);
            publisher.setMaxBusinesses(MaxBusinesses);
            publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness);
            publisher.setMaxTmodels(MaxTmodels);
            publisher.setPublisherName("Unknown");
            em.persist(publisher);
            tx.commit();
        }

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

From source file:org.apache.juddi.api.impl.UDDICustodyTransferImpl.java

public void transferEntities(TransferEntities body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from  w ww  .  j  a v a2  s  .co m*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateCustodyTransfer(publisher).validateTransferEntities(em, body);

        // Once validated, the ownership transfer is as simple as switching the publisher
        KeyBag keyBag = body.getKeyBag();
        List<String> keyList = keyBag.getKey();
        for (String key : keyList) {
            UddiEntity uddiEntity = em.find(UddiEntity.class, key);
            uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

            if (uddiEntity instanceof BusinessEntity) {
                BusinessEntity be = (BusinessEntity) uddiEntity;

                List<BusinessService> bsList = be.getBusinessServices();
                for (BusinessService bs : bsList) {
                    bs.setAuthorizedName(publisher.getAuthorizedName());

                    List<BindingTemplate> btList = bs.getBindingTemplates();
                    for (BindingTemplate bt : btList)
                        bt.setAuthorizedName(publisher.getAuthorizedName());
                }
            }
        }

        // After transfer is finished, the token can be removed
        org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken();
        String transferTokenId = new String(apiTransferToken.getOpaqueToken());
        org.apache.juddi.model.TransferToken modelTransferToken = em
                .find(org.apache.juddi.model.TransferToken.class, transferTokenId);
        em.remove(modelTransferToken);

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(CustodyTransferQuery.TRANSFER_ENTITIES, QueryStatus.SUCCESS, procTime);

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

}

From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java

public BusinessDetail saveBusiness(SaveBusiness body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    if (!body.getBusinessEntity().isEmpty()) {
        log.debug("Inbound save business request for key " + body.getBusinessEntity().get(0).getBusinessKey());
    }//from  w  ww  . j a  v  a2s  .c  om
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        ValidatePublish validator = new ValidatePublish(publisher);
        validator.validateSaveBusiness(em, body, null);

        BusinessDetail result = new BusinessDetail();

        List<org.uddi.api_v3.BusinessEntity> apiBusinessEntityList = body.getBusinessEntity();
        for (org.uddi.api_v3.BusinessEntity apiBusinessEntity : apiBusinessEntityList) {

            org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity();

            MappingApiToModel.mapBusinessEntity(apiBusinessEntity, modelBusinessEntity);

            setOperationalInfo(em, modelBusinessEntity, publisher);

            em.persist(modelBusinessEntity);

            result.getBusinessEntity().add(apiBusinessEntity);
        }

        //check how many business this publisher owns.
        validator.validateSaveBusinessMax(em);

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.SAVE_BUSINESS, QueryStatus.SUCCESS, procTime);

        return result;
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.SAVE_BUSINESS, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:nl.b3p.kaartenbalie.service.SecurityRealm.java

/** Checks wether an user, given his username and password, is allowed to use the system.
 *
 * @param username String representing the username.
 * @param password String representing the password.
 *
 * @return a principal object containing the user if he has been found as a registered user. Otherwise this object wil be empty (null).
 *//*  ww w . ja  v  a2s. c  o m*/
@Override
public Principal authenticate(String username, String password) {

    String encpw = null;
    try {
        encpw = KBCrypter.encryptText(password);
    } catch (Exception ex) {
        log.error("error encrypting password: ", ex);
    }
    Object identity = null;
    EntityTransaction tx = null;
    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.REALM_EM);
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.REALM_EM);
        tx = em.getTransaction();
        tx.begin();
        try {
            User user = (User) em
                    .createQuery("from User u where " + "u.timeout > :nu "
                            + "and lower(u.username) = lower(:username) " + "and u.password = :password")
                    .setParameter("nu", new Date()).setParameter("username", username)
                    .setParameter("password", encpw).getSingleResult();
            // if we get a result, this means successful login
            // set lastloginstatus to null to indicate success
            user.setLastLoginStatus(null);

            return user;
        } catch (NoResultException nre) {
            log.debug("No results using encrypted password");
        }
        // if login not succesful, set userstate to LOGIN_STATE_WRONG_PASSW
        User wrong_password_user = (User) em
                .createQuery(
                        "from User u where " + "u.timeout > :nu " + "and lower(u.username) = lower(:username) ")
                .setParameter("nu", new Date()).setParameter("username", username).getSingleResult();
        wrong_password_user.setLastLoginStatus(User.LOGIN_STATE_WRONG_PASSW_OR_ACCOUNT_EXPIRED);
        em.flush();
        log.warn("Login failure for username " + username);
    } catch (Exception e) {
        log.error("Exception checking user credentails", e);
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
    } finally {
        if (tx != null && tx.isActive() && !tx.getRollbackOnly()) {
            tx.commit();
        }
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.REALM_EM);
    }

    return null;
}

From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Retrieves clientSubscriptionKey(s) from the persistence layer. This
 * method is specific to jUDDI. Used for server to server subscriptions
 * Administrative privilege required./*w  ww  .  j av  a 2s .  c  om*/
 * @param body
 * @return ClientSubscriptionInfoDetail
 * @throws DispositionReportFaultMessage 
 */
public ClientSubscriptionInfoDetail getClientSubscriptionInfoDetail(GetClientSubscriptionInfoDetail body)
        throws DispositionReportFaultMessage {

    new ValidateClientSubscriptionInfo(null).validateGetClientSubscriptionInfoDetail(body);

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        this.getEntityPublisher(em, body.getAuthInfo());

        ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail();

        List<String> subscriptionKeyList = body.getClientSubscriptionKey();
        for (String subscriptionKey : subscriptionKeyList) {

            org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null;
            try {
                modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class,
                        subscriptionKey);
            } catch (ClassCastException e) {
            }
            if (modelClientSubscriptionInfo == null) {
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey));
            }

            org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo();

            MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo);

            result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo);
        }

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

}

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

/**
 * Generic persist method for data set objects.
 * /*  w  w w.  j  av  a2s  .co m*/
 * @param dataSet
 *            data set to persist
 * @param pType
 *            which type of persistence operation, new, update (i.e. overwrite existing data set), ...
 * @param out
 *            PrintWriter to log error messages which can be presented to the end user
 * @return true if persist is successful, false otherwise
 * @see #preCheckAndPersist(DataSet)
 */
public boolean checkAndPersist(T dataSet, PersistType pType, PrintWriter out) {
    // TODO: check if version shall be excluded for some types

    if (dataSet.getRootDataStock() == null) {
        out.println("Error: root data stock must not be null!");
        return false;
    }

    // perform pre-persist actions
    this.preCheckAndPersist(dataSet);

    EntityManager em = PersistenceUtil.getEntityManager();

    // locate existing method by UUID
    T existingDataSet = this.getByUuidAndVersion(dataSet.getUuidAsString(), dataSet.getVersion());

    // if existing found ...
    if (existingDataSet != null) {
        // ... and mode is set to only new ...
        if (PersistType.ONLYNEW.equals(pType)) {
            if (out != null) {
                out.println("Warning: " + this.getAccessedClass().getSimpleName() + " data set with uuid "
                        + dataSet.getUuidAsString() + " and version " + dataSet.getVersion().getVersionString()
                        + " already exists in database; will ignore this data set.");
            }
            // ... just ignore it
            return false;
        }
    }

    EntityTransaction t = em.getTransaction();
    // now the DB interaction
    try {
        t.begin();
        // delete existing for merge operation
        if (existingDataSet != null && PersistType.MERGE.equals(pType)) {
            if (out != null) {
                out.println("Notice: " + this.getAccessedClass().getSimpleName() + " method data set with uuid "
                        + existingDataSet.getUuidAsString() + " and version "
                        + existingDataSet.getVersion().getVersionString()
                        + " already exists in database; will replace it with this data set");
            }
            em.remove(existingDataSet);
        }
        // persist the new method
        em.persist(dataSet);

        // actual write to DB
        t.commit();

        // set the most recent version flags correctly
        if (!this.setMostRecentVersionFlags(dataSet.getUuidAsString())) {
            return false;
        }

        // and return with success :)
        return true;
    } catch (Exception e) {
        DataSetDao.LOGGER.error(
                "Cannot persist " + this.getAccessedClass().getSimpleName() + " data set with uuid {}",
                dataSet.getUuidAsString());
        DataSetDao.LOGGER.error("Exception is: ", e);
        if (out != null) {
            out.println("Error: " + this.getAccessedClass().getSimpleName() + " data set with uuid "
                    + dataSet.getUuidAsString() + " and version " + dataSet.getVersion().getVersionString()
                    + " could not be saved into database; unknown database error; Exception message: "
                    + e.getMessage());
        }
        t.rollback();
    }

    return false;
}

From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Adds client subscription information. This effectively links a server to
 * serverr subscription to clerk/*from  www  .  j  ava  2 s. c  om*/
 * Administrative privilege required.
 * @param body
 * @return ClientSubscriptionInfoDetail
 * @throws DispositionReportFaultMessage
 * @throws RemoteException 
 */
public ClientSubscriptionInfoDetail saveClientSubscriptionInfo(SaveClientSubscriptionInfo body)
        throws DispositionReportFaultMessage, RemoteException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateClientSubscriptionInfo(publisher).validateSaveClientSubscriptionInfo(em, body);

        ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail();

        List<org.apache.juddi.api_v3.ClientSubscriptionInfo> apiClientSubscriptionInfoList = body
                .getClientSubscriptionInfo();
        for (org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo : apiClientSubscriptionInfoList) {

            org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = new org.apache.juddi.model.ClientSubscriptionInfo();

            MappingApiToModel.mapClientSubscriptionInfo(apiClientSubscriptionInfo, modelClientSubscriptionInfo);

            Object existingUddiEntity = em.find(modelClientSubscriptionInfo.getClass(),
                    modelClientSubscriptionInfo.getSubscriptionKey());
            if (existingUddiEntity != null) {
                em.remove(existingUddiEntity);
            }

            em.persist(modelClientSubscriptionInfo);

            result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo);
        }

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