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:gov.medicaid.screening.dao.impl.PodiatricMedicineLicenseDAOBean.java

/**
 * Searches for Podiatric Medicine Licenses by license number.
 *
 * @param criteria the search criteria/*from w  w w  . j  av a  2 s.c  om*/
 * @return the matched results
 * @throws ParsingException if any parsing errors are encountered
 * @throws IllegalArgumentException If criteria is null
 * @throws IllegalArgumentException If criteria.pageNumber < 0
 * @throws IllegalArgumentException If criteria.pageSize < 1 unless criteria.pageNumber <= 0
 * @throws IllegalArgumentException if no license criteria is provider
 * @throws ServiceException for any other exceptions encountered
 */
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public SearchResult<License> searchByLicenseNumber(
        PodiatricMedicineLicenseSearchByLicenseNumberCriteria criteria)
        throws ParsingException, ServiceException {
    String signature = "PodiatricMedicineLicenseDAOBean#searchByLicenseNumber";
    LogUtil.traceEntry(getLog(), signature, new String[] { "criteria" }, new Object[] { criteria });

    if (criteria == null) {
        throw new IllegalArgumentException(ErrorCode.MITA10005.getDesc());
    }

    if (criteria.getPageNumber() < 0 || (criteria.getPageNumber() > 0 && criteria.getPageSize() < 0)) {
        throw new IllegalArgumentException(ErrorCode.MITA10027.getDesc());
    }

    if (criteria.getLicenseNumber() <= 0) {
        throw new IllegalArgumentException(ErrorCode.MITA10004.getDesc());
    }

    return LogUtil.traceExit(getLog(), signature,
            doSearch(criteria, Long.toString(criteria.getLicenseNumber())));
}

From source file:org.ejbca.core.ejb.ca.store.CertificateStoreSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override/*  w w  w.  j  a  v  a  2s .  c om*/
public boolean storeCertificate(Admin admin, Certificate incert, String username, String cafp, int status,
        int type, int certificateProfileId, String tag, long updateTime) throws CreateException {
    if (log.isTraceEnabled()) {
        log.trace(">storeCertificate(" + username + ", " + cafp + ", " + status + ", " + type + ")");
    }
    // Strip dangerous chars
    username = StringTools.strip(username);

    // We need special handling here of CVC certificate with EC keys, because they lack EC parameters in all certs except the Root certificate (CVCA)
    PublicKey pubk = incert.getPublicKey();
    if ((pubk instanceof PublicKeyEC)) {
        PublicKeyEC pkec = (PublicKeyEC) pubk;
        // The public key of IS and DV certificate (CVC) do not have any parameters so we have to do some magic to get a complete EC public key
        ECParameterSpec spec = pkec.getParams();
        if (spec == null) {
            // We need to enrich this public key with parameters
            try {
                if (cafp != null) {
                    String cafingerp = cafp;
                    CertificateData cacert = CertificateData.findByFingerprint(entityManager, cafp);
                    if (cacert == null) {
                        throw new FinderException();
                    }
                    String nextcafp = cacert.getCaFingerprint();
                    int bar = 0; // never go more than 5 rounds, who knows what strange things can exist in the CAFingerprint column, make sure we never get stuck here
                    while ((!StringUtils.equals(cafingerp, nextcafp)) && (bar++ < 5)) {
                        cacert = CertificateData.findByFingerprint(entityManager, cafp);
                        if (cacert == null) {
                            throw new FinderException();
                        }
                        cafingerp = nextcafp;
                        nextcafp = cacert.getCaFingerprint();
                    }
                    // We found a root CA certificate, hopefully ?
                    PublicKey pkwithparams = cacert.getCertificate().getPublicKey();
                    pubk = KeyTools.getECPublicKeyWithParams(pubk, pkwithparams);
                }
            } catch (FinderException e) {
                log.info("Can not find CA certificate with fingerprint: " + cafp);
            } catch (Exception e) {
                // This catches NoSuchAlgorithmException, NoSuchProviderException and InvalidKeySpecException and possibly something else (NPE?)
                // because we want to continue anyway
                if (log.isDebugEnabled()) {
                    log.debug("Can not enrich EC public key with missing parameters: ", e);
                }
            }
        }
    } // finished with ECC key special handling

    // Create the certificate in one go with all parameters at once. This used to be important in EJB2.1 so the persistence layer only creates *one* single
    // insert statement. If we do a home.create and the some setXX, it will create one insert and one update statement to the database.
    // Probably not important in EJB3 anymore
    final CertificateData data1 = new CertificateData(incert, pubk, username, cafp, status, type,
            certificateProfileId, tag, updateTime);
    final String issuerDN = data1.getIssuerDN();
    try {
        entityManager.persist(data1);
    } catch (Exception e) {
        // For backward compatibility. We should drop the throw entirely and rely on the return value.
        CreateException ce = new CreateException();
        ce.setStackTrace(e.getStackTrace());
        throw ce;
    }
    final String msg = intres.getLocalizedMessage("store.storecert");
    logSession.log(admin, issuerDN.hashCode(), LogConstants.MODULE_CA, new Date(), username, incert,
            LogConstants.EVENT_INFO_STORECERTIFICATE, msg);
    log.trace("<storeCertificate()");
    return true;
}

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

/**
 * {@inheritDoc}//w w  w  . j  a v a2 s  .  c  o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long create(String name, String description, Long aclId, LifeCycleInfo forcedLifeCycleInfo)
        throws FxApplicationException {
    final UserTicket ticket = FxContext.getUserTicket();

    if (description == null) {
        description = "";
    }
    if (name == null || name.trim().length() == 0) {
        throw new FxInvalidParameterException("ex.briefcase.nameMissing", "name");
    }
    if (aclId != null && aclId != -1) {
        ACL acl;
        try {
            acl = new ACLEngineBean().load(aclId);
        } catch (Throwable t) {
            throw new FxInvalidParameterException("ex.briefcase.invalidAcl", "acl");
        }
        if (!ticket.mayCreateACL(aclId, ticket.getUserId())) {
            throw new FxNoAccessException("ex.briefcase.noCreatePermission", acl.getLabel());
        }

    }
    if (forcedLifeCycleInfo != null && !ticket.isGlobalSupervisor()) {
        throw new FxNoAccessException("ex.briefcase.lciPermission");
    }
    Connection con = null;
    PreparedStatement ps = null;
    String sql;
    String sourceQuery = "";

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

        // Obtain a new id
        long newId = seq.getId(FxSystemSequencer.BRIEFCASE);

        sql = "INSERT INTO " + DatabaseConst.TBL_BRIEFCASE + "(" + //1,   2,  3        ,  4         , 5 ,    6        7         8              9      , 10     , 11
                "ID,NAME,DESCRIPTION,SOURCE_QUERY,ACL,CREATED_BY,CREATED_AT,MODIFIED_BY,MODIFIED_AT,MANDATOR,ICON_ID)"
                + "VALUES (?,?,?,?,?,?,?,?,?,?,1)";
        final long NOW = System.currentTimeMillis();
        ps = con.prepareStatement(sql);
        ps.setLong(1, newId);
        ps.setString(2, name);
        ps.setString(3, description);
        ps.setString(4, sourceQuery);
        if (aclId != null && aclId != -1) {
            ps.setLong(5, aclId);
        } else {
            ps.setNull(5, java.sql.Types.NUMERIC);
        }
        if (forcedLifeCycleInfo != null) {
            ps.setLong(6, forcedLifeCycleInfo.getCreatorId());
            ps.setLong(7, forcedLifeCycleInfo.getCreationTime());
            ps.setLong(8, forcedLifeCycleInfo.getModificatorId());
            ps.setLong(9, forcedLifeCycleInfo.getModificationTime());
        } else {
            ps.setLong(6, ticket.getUserId());
            ps.setLong(7, NOW);
            ps.setLong(8, ticket.getUserId());
            ps.setLong(9, NOW);
        }
        ps.setLong(10, ticket.getMandatorId());
        ps.executeUpdate();
        return newId;
    } catch (SQLException exc) {
        final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(exc);
        if (ctx != null) {
            EJBUtils.rollback(ctx);
        } else {
            try {
                if (con != null)
                    con.rollback();
            } catch (SQLException e) {
                LOG.warn(e.getMessage(), e);
            }
        }
        if (uniqueConstraintViolation) {
            throw new FxEntryExistsException(LOG, "ex.briefcase.nameAlreadyExists", name);
        } else {
            throw new FxCreateException(LOG, exc, "ex.briefcase.createFailed");
        }
    } finally {
        closeObjects(BriefcaseEngineBean.class, con, ps);
    }
}

From source file:com.flexive.ejb.beans.search.SearchEngineBean.java

/**
 * {@inheritDoc}//from w  w w  .j  a v a 2 s . c o  m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long getLastContentChange(boolean live) {
    Connection con = null;
    Statement stmt = null;
    try {
        con = Database.getDbConnection();
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(StorageManager.getLastContentChangeStatement(live));
        rs.next();
        return rs.getLong(1);
    } catch (Exception e) {
        //noinspection ThrowableInstanceNeverThrown
        throw new FxLoadException(LOG, e, "ex.sqlSearch.lastContentChange", e).asRuntimeException();
    } finally {
        Database.closeObjects(this.getClass(), con, stmt);
    }
}

From source file:com.sfs.ucm.controller.HelpContentAction.java

/**
 * Remove help entry action//from ww  w . jav  a  2 s  .com
 * 
 * @throws UCMException
 */
@Log
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void remove() throws UCMException {
    try {
        em.remove(this.helpItem);

        // refresh list
        loadList();
        this.selected = false;

        // queue message
        this.logger.info("Help Item {} deleted successfully", this.helpItem.getKeyword());
        facesContextMessage.infoMessage("messages", "Help Item {0} deleted successfully",
                this.helpItem.getKeyword());
    } catch (Exception e) {
        logger.error("Error occurred removing Help Content. {}", e.getMessage());
        throw new UCMException(e);
    }
}

From source file:be.fedict.eid.pkira.blm.model.contracthandler.ContractHandlerBean.java

/** {@inheritDoc} */
@Override/*from   ww w  .  j  av a 2 s  .c  om*/
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public String revokeCertificate(String requestMsg) {
    CertificateRevocationResponseBuilder responseBuilder = new CertificateRevocationResponseBuilder();
    CertificateRevocationRequestType request = null;
    try {
        // Parse the request
        request = contractParser.unmarshalRequestMessage(requestMsg, CertificateRevocationRequestType.class);

        // Validate the fields
        fieldValidator.validateContract(request);

        // Validate the signature
        String signer = signatureVerifier.verifySignature(requestMsg, request);

        // Lookup the certificate
        Certificate certificate = findCertificate(request);

        // Check the authorization
        Registration registration = getMatchingRegistration(signer, certificate);

        // Check the legal notice
        checkLegalNotice(request, registration);

        // Persist the contract
        AbstractContract contract = saveContract(registration, requestMsg, request, signer);

        // Call XKMS
        xkmsService.revoke(contract, certificate.getCertificateType(), request.getCertificate());

        // Delete the certificate
        contractRepository.removeCertificate(certificate);

        certificate.cancelNotificationMail();

        // Return result message
        fillResponseFromRequest(responseBuilder, request, ResultType.SUCCESS, "Success");
    } catch (ContractHandlerBeanException e) {
        fillResponseFromRequest(responseBuilder, request, e.getResultType(), e.getMessage());
    } catch (RuntimeException e) {
        log.error("Error while processing the contract", e);
        fillResponseFromRequest(responseBuilder, request, ResultType.GENERAL_FAILURE,
                "An error occurred while processing the contract.");
    } catch (SchedulerException e) {
        log.error("Error while scheduling the notification mail.", e);
    }

    return contractParser.marshalResponseMessage(responseBuilder.toResponseType(),
            CertificateRevocationResponseType.class);
}

From source file:gov.medicaid.screening.dao.impl.SocialWorkLicenseDAOBean.java

/**
 * Searches for Podiatric Medicine Licenses by license number.
 *
 * @param criteria the search criteria/*from w ww  .j a  v  a  2  s .c  o m*/
 * @return the search result with the applicable providers
 * @throws IllegalArgumentException if criteria is null
 * @throws IllegalArgumentException If criteria.pageNumber < 0
 * @throws IllegalArgumentException If criteria.pageSize < 1 unless criteria.pageNumber <= 0
 * @throws ServiceException If an error occurs while performing the operation
 */
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public SearchResult<License> searchByLicenseNumber(SocialWorkLicenseSearchByLicenseNumberCriteria criteria)
        throws ServiceException {
    String signature = "SocialWorkLicenseDAOBean#searchByLicenseNumber";
    LogUtil.traceEntry(getLog(), signature, new String[] { "criteria" }, new Object[] { criteria });

    if (criteria == null) {
        throw new IllegalArgumentException(ErrorCode.MITA10005.getDesc());
    }

    if (criteria.getPageNumber() < 0 || (criteria.getPageNumber() > 0 && criteria.getPageSize() < 0)) {
        throw new IllegalArgumentException(ErrorCode.MITA10027.getDesc());
    }

    if (criteria.getLicenseNumber() <= 0) {
        throw new IllegalArgumentException(ErrorCode.MITA10004.getDesc());
    }

    return LogUtil.traceExit(getLog(), signature, doSearch(criteria));
}

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)
@TransactionTimeout(UPLOAD_TIMEOUT)
public CaArrayFile addFile(Project project, File file)
        throws ProposalWorkflowException, InconsistentProjectStateException {
    LogUtil.logSubsystemEntry(LOG, project, file);
    checkIfProjectSaveAllowed(project);
    final CaArrayFile caArrayFile = doAddFile(project, file, file.getName());
    LogUtil.logSubsystemExit(LOG);
    return caArrayFile;
}

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

/** {@inheritDoc} */
@Override//from  www .  j a v a 2s . co m
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long create(long fromStepId, long toStepId, long groupId) throws FxApplicationException {
    FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.WorkflowManagement);
    // Sanity checks.
    // StepImp.loadStep(..) throws a FxNotFoundException if the steps do not exist.
    Step fromStep;
    Step toStep;

    if (CacheAdmin.getEnvironment().getUserGroup(groupId) == null) {
        throw new FxNotFoundException("ex.usergroup.groupNotFound.id", groupId);
    }

    fromStep = CacheAdmin.getEnvironment().getStep(fromStepId);
    toStep = CacheAdmin.getEnvironment().getStep(toStepId);

    // from and to step must be in the same workflow or we may not connect them
    if (fromStep.getWorkflowId() != toStep.getWorkflowId()) {
        throw new FxInvalidParameterException("STEP_FROM", "ex.routes.create.differentWorkflows", fromStepId,
                fromStep.getWorkflowId(), toStepId, toStep.getWorkflowId());
    }
    if (fromStepId == toStepId) {
        throw new FxInvalidParameterException("STEP_FROM", "ex.routes.create.loop");
    }

    // Create the route
    Connection con = null;
    Statement stmt = null;
    String sql;
    String routeString = "[from=" + fromStep.getId() + ",to=" + toStep.getId() + ",group=" + groupId + "]";
    boolean success = false;

    try {

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

        // Create the new route
        stmt = con.createStatement();
        long routeId = seq.getId(FxSystemSequencer.ROUTE);
        sql = "INSERT INTO " + TBL_WORKFLOW_ROUTES + " (ID,FROM_STEP,TO_STEP,USERGROUP) VALUES (" + routeId
                + "," + fromStep.getId() + "," + toStep.getId() + "," + groupId + ")";
        stmt.executeUpdate(sql);

        // Return the new id
        success = true;
        return routeId;
    } catch (SQLException exc) {
        if (StorageManager.isUniqueConstraintViolation(exc)) {
            throw new FxEntryExistsException(LOG, "ex.routes.create.exists");
        } else {
            throw new FxCreateException(LOG, "ex.routes.create", exc, routeString, exc.getMessage());
        }
    } finally {
        Database.closeObjects(RouteEngineBean.class, con, stmt);
        if (!success) {
            EJBUtils.rollback(ctx);
        } else {
            StructureLoader.reloadWorkflows(FxContext.get().getDivisionId());
        }
    }
}

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

/**
 * {@inheritDoc}/*from ww  w  .j  a v a  2 s  .c o  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long create(String name, FxString label, long mandatorId, String color, String description,
        ACLCategory category) throws FxApplicationException {

    final UserTicket ticket = FxContext.getUserTicket();
    final FxEnvironment environment = CacheAdmin.getEnvironment();
    // Security
    if (!ticket.isInRole(Role.MandatorSupervisor))
        FxPermissionUtils.checkRole(ticket, Role.ACLManagement);
    if (!ticket.isGlobalSupervisor()) {
        if (ticket.getMandatorId() != mandatorId) {
            String mandatorName = environment.getMandator(mandatorId).getName();
            throw new FxNoAccessException("ex.acl.mayNotCreateForForeignMandator", mandatorName);
        }
    }

    // Parameter checks
    color = FxFormatUtils.processColorString("COLOR", color);
    description = checkDescription(description);
    name = checkName(name);
    label = checkLabel(label);
    if (category == null)
        throw new FxInvalidParameterException("CATEGORY", "ex.acl.categoryMissing");

    Connection con = null;
    PreparedStatement ps = null;
    String sql;

    try {

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

        // Obtain a new id
        int newId = (int) seq.getId(FxSystemSequencer.ACL);
        sql = "INSERT INTO " + TBL_ACLS + "(" +
        //       1      2     3          4              5       6        7         8              9
                "ID,CAT_TYPE,COLOR,DESCRIPTION,MANDATOR,NAME,CREATED_BY,CREATED_AT,MODIFIED_BY,MODIFIED_AT)"
                + "VALUES (?,?,?,?,?,?,?,?,?,?)";
        final long NOW = System.currentTimeMillis();
        ps = con.prepareStatement(sql);
        ps.setInt(1, newId);
        ps.setInt(2, category.getId());
        ps.setString(3, color);
        ps.setString(4, description);
        ps.setLong(5, mandatorId);
        ps.setString(6, name);
        ps.setLong(7, ticket.getUserId());
        ps.setLong(8, NOW);
        ps.setLong(9, ticket.getUserId());
        ps.setLong(10, NOW);
        ps.executeUpdate();

        Database.storeFxString(label, con, TBL_ACLS, "LABEL", "ID", newId);
        try {
            StructureLoader.updateACL(FxContext.get().getDivisionId(), this.load(newId));
        } catch (FxLoadException e) {
            LOG.error(e, e);
        } catch (FxNotFoundException e) {
            LOG.error(e, e);
        }
        ACL created = CacheAdmin.getEnvironment().getACL(newId);
        EJBLookup.getHistoryTrackerEngine().trackData(ConversionEngine.getXStream().toXML(created),
                "history.acl.create", created.getName());
        return newId;
    } catch (SQLException exc) {
        final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(exc);
        EJBUtils.rollback(ctx);
        if (uniqueConstraintViolation) {
            throw new FxEntryExistsException("ex.acl.aclAlreadyExists", name);
        } else {
            throw new FxCreateException(LOG, exc, "ex.acl.createFailed", exc.getMessage());
        }
    } finally {
        Database.closeObjects(ACLEngineBean.class, con, ps);
    }
}