Example usage for javax.persistence EntityTransaction begin

List of usage examples for javax.persistence EntityTransaction begin

Introduction

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

Prototype

public void begin();

Source Link

Document

Start a resource transaction.

Usage

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void updateEventWithMetadata(long eventId, Properties caProperties)
        throws SchedulerServiceDatabaseException, NotFoundException {
    if (caProperties == null) {
        caProperties = new Properties();
    }/*from ww w. j  av  a 2s .  c  o m*/
    String caSerialized;
    try {
        caSerialized = serializeProperties(caProperties);
    } catch (IOException e) {
        logger.error("Could not serialize properties: {}", e);
        throw new SchedulerServiceDatabaseException(e);
    }
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        EventEntity entity = em.find(EventEntity.class, eventId);
        if (entity == null) {
            throw new NotFoundException("Event with ID: " + eventId + " does not exist");
        }
        entity.setCaptureAgentMetadata(caSerialized);
        em.merge(entity);
        tx.commit();
    } catch (NotFoundException e) {
        logger.error("Event with ID '{}' does not exist", eventId);
        throw e;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        logger.error("Could not store event metadata: {}", e.getMessage());
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            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;/*from www .ja  v  a 2 s .c o m*/
    EntityTransaction tx = null;
    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:org.opencastproject.themes.persistence.ThemesServiceDatabaseImpl.java

@Override
public Theme updateTheme(Theme theme) throws ThemesServiceDatabaseException {
    EntityManager em = null;/*from  ww  w. j  ava  2  s. com*/
    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();
        }
    }
}

From source file:de.randi2.testUtility.utility.Bootstrap.java

private void initRandBS(Trial trial, GregorianCalendar date, Random rand) {
    // long time1 = System.nanoTime();
    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();
    trial = entityManager.find(Trial.class, trial.getId());

    TrialSubject subject = new TrialSubject();
    SubjectProperty<Serializable> subprob = new SubjectProperty<Serializable>(trial.getCriteria().get(0));
    SubjectProperty<Serializable> subprob1 = new SubjectProperty<Serializable>(trial.getCriteria().get(1));
    SubjectProperty<Serializable> subprob2 = new SubjectProperty<Serializable>(trial.getCriteria().get(2));
    try {/* www  .ja v  a 2  s. com*/
        if (rand.nextInt(2) == 0) {
            subprob.setValue(DichotomousCriterion.class.cast(trial.getCriteria().get(0)).getOption1());
        } else {
            subprob.setValue(DichotomousCriterion.class.cast(trial.getCriteria().get(0)).getOption2());
        }

        if (rand.nextInt(2) == 0) {
            subprob1.setValue(DichotomousCriterion.class.cast(trial.getCriteria().get(1)).getOption1());
        } else {
            subprob1.setValue(DichotomousCriterion.class.cast(trial.getCriteria().get(1)).getOption2());
        }
        if (rand.nextInt(2) == 0) {
            subprob2.setValue(DichotomousCriterion.class.cast(trial.getCriteria().get(2)).getOption1());
        } else {
            subprob2.setValue(DichotomousCriterion.class.cast(trial.getCriteria().get(2)).getOption2());
        }

    } catch (ConstraintViolatedException e) {
        e.printStackTrace();
    }

    Set<SubjectProperty<?>> proberties = new HashSet<SubjectProperty<?>>();
    proberties.add(subprob);
    proberties.add(subprob1);
    proberties.add(subprob2);
    subject.setProperties(proberties);
    trialService.randomize(trial, subject);
    transaction.commit();
    transaction.begin();
    subject = entityManager.find(TrialSubject.class, subject.getId());
    subject.setCreatedAt(date);
    subject = entityManager.merge(subject);
    transaction.commit();
    // System.out.println("time random before: " +
    // (System.nanoTime()-time1)/1000000 + " ms");
}

From source file:org.opencastproject.adminui.usersettings.UserSettingsService.java

/**
 * Create a new user setting key value pair.
 *
 * @param key/*from   w w w.java2 s . c o m*/
 *          The key to use for the current user setting.
 * @param value
 *          The value of the user setting.
 * @return A new user setting object
 * @throws UserSettingsServiceException
 */
public UserSetting addUserSetting(String key, String value) throws UserSettingsServiceException {
    EntityManager em = null;
    EntityTransaction tx = null;
    String orgId = "";
    String username = "";
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        orgId = securityService.getOrganization().getId();
        username = securityService.getUser().getUsername();
        UserSettingDto userSettingDto = new UserSettingDto();
        userSettingDto.setKey(key);
        userSettingDto.setValue(value);
        userSettingDto.setUsername(username);
        userSettingDto.setOrganization(orgId);
        em.persist(userSettingDto);
        tx.commit();
        return userSettingDto.toUserSetting();
    } catch (Exception e) {
        logger.error("Could not update user setting username '%s' org:'%s' key:'%s' value:'%s':%s", username,
                orgId, key, value, ExceptionUtils.getStackTrace(e));
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new UserSettingsServiceException(e);
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

From source file:org.sigmah.server.schedule.export.AutoExportJob.java

public void execute(JobExecutionContext executionContext) throws JobExecutionException {
    final JobDataMap dataMap = executionContext.getJobDetail().getJobDataMap();
    final EntityManager em = (EntityManager) dataMap.get("em");
    final Log log = (Log) dataMap.get("log");
    final Injector injector = (Injector) dataMap.get("injector");
    EntityTransaction tx = null;

    try {/*from  w  ww. j  a  va 2 s  . co  m*/

        // Open transaction
        /*
         *  NOTE: it is impossible to use @Transactional for this method
         *  The reason is link{TransactionalInterceptor} gets EntityManager 
         *  from the injector which is out of scope 
         */
        tx = em.getTransaction();
        tx.begin();

        final GlobalExportDAO exportDAO = new GlobalExportHibernateDAO(em);
        final GlobalExportDataProvider dataProvider = injector.getInstance(GlobalExportDataProvider.class);

        final List<GlobalExportSettings> settings = exportDAO.getGlobalExportSettings();
        for (final GlobalExportSettings setting : settings) {

            /*
             * Check for auto export schedule 
             */

            //skip if no export schedule is specified
            if (setting.getAutoExportFrequency() == null || setting.getAutoExportFrequency() < 1)
                continue;

            final Calendar systemCalendar = Calendar.getInstance();

            boolean doExport = false;

            if ((setting.getAutoExportFrequency() >= 31) && (setting.getAutoExportFrequency() <= 58)) {
                //Case of Monthly Auto Export
                if ((setting.getAutoExportFrequency() - 30) == systemCalendar.get(Calendar.DAY_OF_MONTH)) {
                    doExport = true;
                }
            } else if ((setting.getAutoExportFrequency() >= 61) && (setting.getAutoExportFrequency() <= 67)) {
                //Case of Weekly Auto Export
                if ((setting.getAutoExportFrequency() - 60) == systemCalendar.get(Calendar.DAY_OF_WEEK)) {
                    doExport = true;
                }

            } else {
                //Regular Auto-Export every N-days

                final Calendar scheduledCalendar = Calendar.getInstance();
                Date lastExportDate = setting.getLastExportDate();
                if (lastExportDate == null) {
                    lastExportDate = systemCalendar.getTime();
                    setting.setLastExportDate(lastExportDate);
                    em.merge(setting);
                } else {
                    scheduledCalendar.setTime(lastExportDate);
                    // add scheduled days to the last exported date
                    scheduledCalendar.add(Calendar.DAY_OF_MONTH, setting.getAutoExportFrequency());
                }

                final Date systemDate = getZeroTimeDate(systemCalendar.getTime());
                final Date scheduledDate = getZeroTimeDate(scheduledCalendar.getTime());

                if (systemDate.compareTo(scheduledDate) >= 0) {
                    doExport = true;
                }
            }

            if (doExport) {
                /*
                 * Start auto export  
                 */

                // persist global export logger
                final GlobalExport globalExport = new GlobalExport();
                globalExport.setOrganization(setting.getOrganization());
                globalExport.setDate(systemCalendar.getTime());
                em.persist(globalExport);

                // generate export content
                final Map<String, List<String[]>> exportData = dataProvider
                        .generateGlobalExportData(setting.getOrganization().getId(), em, setting.getLocale());

                // persist export content
                dataProvider.persistGlobalExportDataAsCsv(globalExport, em, exportData);
            }

        }
        tx.commit();

        log.info("Scheduled EXPORT of global exports fired");

    } catch (Exception ex) {
        if (tx != null && tx.isActive())
            tx.rollback();
        log.error("Scheduled global export job failed : " + ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:org.opencastproject.series.impl.persistence.SeriesServiceDatabaseImpl.java

@Override
public boolean storeSeriesAccessControl(String seriesId, AccessControlList accessControl)
        throws NotFoundException, SeriesServiceDatabaseException {
    if (accessControl == null) {
        logger.error("Access control parameter is <null> for series '{}'", seriesId);
        throw new IllegalArgumentException("Argument for updating ACL for series " + seriesId + " is null");
    }//from  w w  w. j  a v a  2s  .  com

    String serializedAC;
    try {
        serializedAC = AccessControlParser.toXml(accessControl);
    } catch (Exception e) {
        logger.error("Could not serialize access control parameter: {}", e.getMessage());
        throw new SeriesServiceDatabaseException(e);
    }
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    boolean updated = false;
    try {
        tx.begin();
        SeriesEntity entity = getSeriesEntity(seriesId, em);
        if (entity == null) {
            throw new NotFoundException("Series with ID " + seriesId + " does not exist.");
        }
        if (entity.getAccessControl() != null) {
            // 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 ACLs on series " + seriesId);
                }
            }
            updated = true;
        }
        entity.setAccessControl(serializedAC);
        em.merge(entity);
        tx.commit();
        return updated;
    } catch (NotFoundException e) {
        throw e;
    } 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.opencastproject.adminui.usersettings.UserSettingsService.java

/**
 * Delete a user setting by using a unique id to find it.
 *
 * @param id/*ww w  .jav  a 2 s  . co  m*/
 *          The unique id for the user setting.
 * @throws UserSettingsServiceException
 */
public void deleteUserSetting(long id) throws UserSettingsServiceException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        UserSettingDto userSettingsDto = em.find(UserSettingDto.class, id);
        tx = em.getTransaction();
        tx.begin();
        em.remove(userSettingsDto);
        tx.commit();
    } catch (Exception e) {
        logger.error("Could not delete user setting '%d': %s", id, ExceptionUtils.getStackTrace(e));
        if (tx.isActive())
            tx.rollback();
        throw new UserSettingsServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

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");
    }//w ww  .  j a v  a  2s. com
    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.openjpa.persistence.event.TestBeforeCommit.java

public void testEmptyTransaction() {
    OpenJPAEntityManagerSPI em = (OpenJPAEntityManagerSPI) emf.createEntityManager();
    em.addTransactionListener(this);
    EntityTransaction tran = em.getTransaction();
    ae = doQuery(em);/*from w  w  w. j  ava 2  s.  com*/
    if (dict instanceof OracleDictionary) {
        assertNull(ae.getName());
    } else if (dict instanceof SybaseDictionary) {
        // Sybase converts "" to " "
        assertEquals(" ", ae.getName());
    } else {
        assertEquals("", ae.getName());
    }
    assertEquals(1, ae.getVersion());
    em.clear();

    tran.begin();
    tran.commit();

    // when BeforeCommit was fired AE was not managed. As a result its state is out of sync with the database.
    assertEquals("Ava", ae.getName());
    ae = doQuery(em);
    if (dict instanceof OracleDictionary) {
        assertNull(ae.getName());
    } else if (dict instanceof SybaseDictionary) {
        assertEquals(" ", ae.getName());
    } else {
        assertEquals("", ae.getName());
    }
    assertEquals(1, ae.getVersion());
    em.close();
}