Example usage for javax.ejb TransactionAttributeType REQUIRED

List of usage examples for javax.ejb TransactionAttributeType REQUIRED

Introduction

In this page you can find the example usage for javax.ejb TransactionAttributeType REQUIRED.

Prototype

TransactionAttributeType REQUIRED

To view the source code for javax.ejb TransactionAttributeType REQUIRED.

Click Source Link

Document

If a client invokes the enterprise bean's method while the client is associated with a transaction context, the container invokes the enterprise bean's method in the client's transaction context.

Usage

From source file:com.flexive.ejb.beans.workflow.WorkflowEngineBean.java

/**
 * {@inheritDoc}/*from   www.  ja  v  a  2s  .  c  o  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long create(Workflow workflow) throws FxApplicationException {
    UserTicket ticket = FxContext.getUserTicket();
    // Permission checks
    FxPermissionUtils.checkRole(ticket, Role.WorkflowManagement);

    // Do work ..
    Connection con = null;
    PreparedStatement stmt = null;
    String sCurSql = null;
    boolean success = false;
    long id = -1;
    try {
        // Sanity checks
        checkIfValid(workflow);

        // Obtain a database connection
        con = Database.getDbConnection();

        // Create the new workflow instance
        sCurSql = "INSERT INTO " + TBL_WORKFLOW + " (ID,NAME,DESCRIPTION) VALUES (?,?,?)";
        stmt = con.prepareStatement(sCurSql);
        id = seq.getId(FxSystemSequencer.WORKFLOW);
        stmt.setLong(1, id);
        stmt.setString(2, workflow.getName());
        stmt.setString(3, StringUtils.defaultString(workflow.getDescription()));
        stmt.executeUpdate();

        // create step(s)
        final Map<Long, Step> createdSteps = new HashMap<Long, Step>();
        for (Step step : workflow.getSteps()) {
            final Step wfstep = new Step(-1, step.getStepDefinitionId(), id, step.getAclId());
            final long newStepId = stepEngine.createStep(wfstep);
            createdSteps.put(step.getId(), new Step(newStepId, wfstep));
        }

        // create route(s)
        for (Route route : workflow.getRoutes()) {
            routeEngine.create(resolveTemporaryStep(createdSteps, route.getFromStepId()),
                    resolveTemporaryStep(createdSteps, route.getToStepId()), route.getGroupId());
        }
        success = true;
    } catch (Exception exc) {
        if (StorageManager.isUniqueConstraintViolation(exc)) {
            throw new FxEntryExistsException("ex.workflow.exists", workflow.getName());
        } else {
            throw new FxCreateException(LOG, "ex.workflow.create", exc, exc.getMessage());
        }
    } finally {
        Database.closeObjects(WorkflowEngineBean.class, con, stmt);
        if (!success) {
            EJBUtils.rollback(ctx);
        } else {
            StructureLoader.reloadWorkflows(FxContext.get().getDivisionId());
        }
    }
    return id;
}

From source file:ch.puzzle.itc.mobiliar.business.template.boundary.TemplateEditor.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
Object getSingleObjectOrNull(Query q) {
    try {/*w w  w  .  j  av  a 2  s  .c o  m*/
        return q.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:com.flexive.ejb.beans.BriefcaseEngineBean.java

/**
 * {@inheritDoc}// w w  w  .j ava  2  s .  com
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void removeItems(long id, Collection<FxPK> contents) throws FxApplicationException {
    if (contents == null || contents.isEmpty()) {
        return;
    }
    Connection con = null;
    PreparedStatement stmt = null;
    final Briefcase br = load(id);
    checkEditBriefcase(br);
    try {
        con = Database.getDbConnection();
        stmt = con.prepareStatement("DELETE FROM " + TBL_BRIEFCASE_DATA_ITEM + " WHERE briefcase_id=?"
                + " AND id IN (" + StringUtils.join(FxPK.getIds(contents), ',') + ")");
        stmt.setLong(1, id);
        stmt.executeUpdate();
        stmt.close();
        stmt = con.prepareStatement("DELETE FROM " + TBL_BRIEFCASE_DATA + " WHERE briefcase_id=?"
                + " AND id IN (" + StringUtils.join(FxPK.getIds(contents), ',') + ")");
        stmt.setLong(1, id);
        stmt.executeUpdate();
    } catch (Exception e) {
        EJBUtils.rollback(ctx);
        throw new FxRemoveException(LOG, e, "ex.briefcase.removeItems", br.getName(), e);
    } finally {
        closeObjects(BriefcaseEngineBean.class, con, stmt);
    }
}

From source file:com.flexive.ejb.beans.PhraseEngineBean.java

/**
 * {@inheritDoc}/*from  w ww  .j av  a  2s  . c  o  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long savePhrase(int category, String phraseKey, FxString value, FxPhraseSearchValueConverter converter,
        Object tag, long mandator) throws FxNoAccessException {
    Connection con = null;
    PreparedStatement ps = null;
    final UserTicket userTicket = FxContext.getUserTicket();
    checkMandatorAccess(mandator, userTicket);
    checkPhraseKey(phraseKey);
    try {
        // Obtain a database connection
        con = Database.getDbConnection();

        long phraseId;
        ps = con.prepareStatement("SELECT ID FROM " + TBL_PHRASE + " WHERE PKEY=? AND MANDATOR=? AND CAT=?");
        ps.setString(1, phraseKey);
        ps.setLong(2, mandator);
        ps.setInt(3, category);
        ResultSet rs = ps.executeQuery();
        if (rs != null && rs.next()) {
            phraseId = rs.getLong(1);
            rs.close();
            ps.close();
            ps = con.prepareStatement("DELETE FROM " + TBL_PHRASE_VALUES + " WHERE ID=? AND MANDATOR=?");
            ps.setLong(1, phraseId);
            ps.setLong(2, mandator);
            ps.executeUpdate();
        } else {
            try {
                phraseId = fetchNextPhraseId(mandator);
            } catch (FxApplicationException e) {
                EJBUtils.rollback(ctx);
                throw e.asRuntimeException();
            }
            ps.close();
            ps = con.prepareStatement(
                    "INSERT INTO " + TBL_PHRASE + "(ID,PKEY,MANDATOR,HID,CAT)VALUES(?,?,?,?,?)");
            ps.setLong(1, phraseId);
            ps.setString(2, phraseKey);
            ps.setLong(3, mandator);
            ps.setBoolean(4, false);
            ps.setInt(5, category);
            ps.executeUpdate();
        }
        if (!value.isEmpty()) {
            ps.close();
            ps = con.prepareStatement(
                    "INSERT INTO " + TBL_PHRASE_VALUES + "(ID,MANDATOR,LANG,PVAL,SVAL,TAG)VALUES(?,?,?,?,?,?)");
            ps.setLong(1, phraseId);
            ps.setLong(2, mandator);
            FxString fxTag = tag instanceof FxString ? (FxString) tag : null;
            for (long lang : value.getTranslatedLanguages()) {
                ps.setLong(3, lang);
                final String translation = value.getTranslation(lang);
                if (StringUtils.isBlank(translation))
                    continue;
                ps.setString(4, translation);
                if (converter != null)
                    ps.setString(5, converter.convert(translation, lang));
                else
                    ps.setString(5, translation.trim().toUpperCase());
                if (fxTag != null) {
                    if (!fxTag.isMultiLanguage() || fxTag.translationExists(lang))
                        ps.setString(6, fxTag.getTranslation(lang));
                    else
                        ps.setNull(6, Types.VARCHAR);
                } else {
                    if (tag != null && !StringUtils.isBlank(String.valueOf(tag)))
                        ps.setString(6, String.valueOf(tag));
                    else
                        ps.setNull(6, Types.VARCHAR);
                }
                ps.addBatch();
            }
            ps.executeBatch();
        }
        return phraseId;
    } catch (SQLException exc) {
        EJBUtils.rollback(ctx);
        throw new FxDbException(LOG, exc, "ex.db.sqlError", exc.getMessage()).asRuntimeException();
    } finally {
        Database.closeObjects(PhraseEngineBean.class, con, ps);
    }
}

From source file:com.flexive.ejb.beans.workflow.StepEngineBean.java

/**
 * {@inheritDoc}//  www  . j a  va2s  . c  o  m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void updateStep(long stepId, long aclId, int position) throws FxApplicationException {
    UserTicket ticket = FxContext.getUserTicket();
    // Security checks
    FxPermissionUtils.checkRole(ticket, Role.WorkflowManagement);

    // Load the step
    try {
        CacheAdmin.getEnvironment().getStep(stepId);
    } catch (Exception exc) {
        throw new FxUpdateException(exc);
    }

    // Do work ..
    Statement stmt = null;
    String sql;
    Connection con = null;
    boolean success = false;
    try {

        // Obtain a database connection
        con = Database.getDbConnection();

        // Update the step
        stmt = con.createStatement();
        sql = "UPDATE " + TBL_WORKFLOW_STEP + " SET ACL=" + aclId + ", POS=" + position + " WHERE ID=" + stepId;
        int ucount = stmt.executeUpdate(sql);

        // Is the step defined at all?
        if (ucount == 0) {
            throw new FxNotFoundException("ex.step.notFound.id", stepId);
        }

        // Update the active UserTickets
        // Refresh all tickets having the new acl (workflow access might be added) and refreshHavingUser all that
        // have the affected workflow (workflow access may be removed)
        // TODO
        //UserTicketImpl.refreshHavingACL(aclId);
        //UserTicketImpl.refreshHavingWorkflow(stp.getWorkflowId());
        success = true;

    } catch (SQLException exc) {
        throw new FxUpdateException(LOG, "ex.step.update", exc, exc.getMessage());
    } finally {
        Database.closeObjects(StepEngineBean.class, con, stmt);
        if (!success) {
            EJBUtils.rollback(ctx);
        } else {
            StructureLoader.reloadWorkflows(FxContext.get().getDivisionId());
        }
    }
}

From source file:com.flexive.ejb.beans.configuration.GlobalConfigurationEngineBean.java

/**
 * {@inheritDoc}/*from   w  w  w .  java  2  s. c om*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public DivisionData getDivisionData(int division) throws FxApplicationException {
    try {
        DivisionData data = (DivisionData) getCache(getBeanPath(CACHE_DIVISIONS), "" + division);
        if (data != null) {
            return data;
        }
    } catch (FxCacheException e) {
        LOG.error("Cache failure (ignored): " + e.getMessage(), e);
    }
    // get datasource
    String dataSource = get(SystemParameters.GLOBAL_DATASOURCES, "" + division);
    String domainRegEx = get(SystemParameters.GLOBAL_DIVISIONS_DOMAINS, "" + division);
    DivisionData data = createDivisionData(division, dataSource, domainRegEx);
    // put in cache
    putCache(getBeanPath(CACHE_DIVISIONS), "" + division, data, false);
    return data;
}

From source file:com.flexive.ejb.beans.structure.TypeEngineBean.java

/**
 * {@inheritDoc}//w ww  .  ja  va2 s . c om
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void flatten(long typeId) throws FxApplicationException {
    flatten(typeId, null);
}

From source file:com.flexive.ejb.beans.configuration.GenericConfigurationImpl.java

/**
 * {@inheritDoc}//from  w w  w. j av a 2 s  .c o  m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public <T extends Serializable> T get(Parameter<T> parameter) throws FxApplicationException {
    return get(parameter, parameter.getData().getKey());
}

From source file:gov.nih.nci.caarray.application.project.ProjectManagementServiceBean.java

/**
 * {@inheritDoc}//  w  w  w . j  a v a2 s . c  o  m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public AccessProfile addGroupProfile(Project project, CollaboratorGroup group)
        throws ProposalWorkflowException {
    LogUtil.logSubsystemEntry(LOG, project, group);
    if (!project.canModifyPermissions(CaArrayUsernameHolder.getCsmUser())) {
        LogUtil.logSubsystemExit(LOG);
        throw new PermissionDeniedException(project, SecurityUtils.PERMISSIONS_PRIVILEGE,
                CaArrayUsernameHolder.getUser());
    }
    final AccessProfile profile = project.addGroupProfile(group);
    this.projectDao.save(project);
    LogUtil.logSubsystemExit(LOG);
    return profile;
}

From source file:io.hops.hopsworks.api.pythonDeps.PythonDepsService.java

@POST
@Produces(MediaType.APPLICATION_JSON)//from   www .  j  av  a  2  s .  c om
@Path("/installOneHost/{hostId}")
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST })
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Response installOneHost(@PathParam("hostId") String hostId, PythonDepJson library)
        throws ServiceException {
    pythonDepsFacade.blockingCondaOp(Integer.parseInt(hostId), PythonDepsFacade.CondaOp.INSTALL,
            PythonDepsFacade.CondaInstallType.valueOf(library.getInstallType()),
            PythonDepsFacade.MachineType.valueOf(library.getMachineType()), project, library.getChannelUrl(),
            library.getLib(), library.getVersion());
    return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).build();
}