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.search.ResultPreferencesEngineBean.java

/**
 * {@inheritDoc}/*from   w  w w.  jav a 2s .co  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void saveInSource(ResultPreferences preferences, long typeId, ResultViewType viewType,
        ResultLocation location) throws FxApplicationException {
    final LoadResult result = loadWithType(typeId, viewType, location);
    // save for the root type
    save(preferences, result.getTypeId(), viewType, location);
}

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

/** {@inheritDoc} */
@Override// ww  w . j a v a2s. co m
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public String signCertificate(String requestMsg) {
    CertificateSigningResponseBuilder responseBuilder = new CertificateSigningResponseBuilder();
    CertificateSigningRequestType request = null;
    int certificateId = -1;
    List<String> certificates = new ArrayList<String>();
    CertificateSigningContract contract = null;

    try {
        // Parse the request
        request = contractParser.unmarshalRequestMessage(requestMsg, CertificateSigningRequestType.class);

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

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

        // Check if the user is authorized
        CertificateType certificateType = mapCertificateType(request);
        Registration registration = getMatchingRegistration(signer, request.getDistinguishedName(),
                request.getAlternativeName(), certificateType);

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

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

        // Call XKMS
        String certificateAsPem = xkmsService.sign(contract, request.getCSR());
        if (certificateAsPem == null) {
            throw new ContractHandlerBeanException(ResultType.BACKEND_ERROR,
                    "Error contacting the backend service.");
        }

        // Persist the certificate
        CertificateInfo certificateInfo;
        try {
            certificateInfo = certificateParser.parseCertificate(certificateAsPem);
        } catch (CryptoException e) {
            throw new ContractHandlerBeanException(ResultType.GENERAL_FAILURE,
                    "Error processing received certificate.");
        }

        User requester = registration.getRequester();
        String requesterName = requester.getName();
        Certificate certificate = new Certificate(certificateAsPem, certificateInfo, requesterName, contract);
        scheduleNotificationMail(registration, certificateInfo, certificate);
        contractRepository.persistCertificate(certificate);

        // Send the mail
        sendCertificateByMail(certificate, registration);

        // All ok: build result
        certificateId = certificate.getId();

        certificates.add(certificateInfo.getPemEncoded());
        for (CertificateChainCertificate chain = certificate
                .getCertificateChainCertificate(); chain != null; chain = chain.getIssuer()) {
            certificates.add(chain.getCertificateData());
        }

        fillResponseFromRequest(responseBuilder, request, ResultType.SUCCESS, "Success");
        updateContract(contract, ResultType.SUCCESS, "Success");
    } catch (ContractHandlerBeanException e) {
        fillResponseFromRequest(responseBuilder, request, e.getResultType(), e.getMessage());

        if (contract != null) {
            updateContract(contract, 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.");

        if (contract != null) {
            updateContract(contract, ResultType.GENERAL_FAILURE,
                    "An error occurred while processing the contract.");
        }
    }

    CertificateSigningResponseType responseType = responseBuilder.toResponseType(certificateId, certificates);
    return contractParser.marshalResponseMessage(responseType, CertificateSigningResponseType.class);
}

From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java

License:asdf

/** Local interface only */
@Override//from  www.jav a  2s .co m
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public CertificateDataWrapper storeCertificateNoAuth(AuthenticationToken adminForLogging, Certificate incert,
        String username, String cafp, int status, int type, int certificateProfileId, String tag,
        long updateTime) {
    if (log.isTraceEnabled()) {
        log.trace(">storeCertificateNoAuth(" + username + ", " + cafp + ", " + status + ", " + type + ")");
    }
    final PublicKey pubk = enrichEcPublicKey(incert.getPublicKey(), cafp);
    // 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;
    final boolean useBase64CertTable = CesecoreConfiguration.useBase64CertTable();
    Base64CertData base64CertData = null;
    if (useBase64CertTable) {
        // use special table for encoded data if told so.
        base64CertData = new Base64CertData(incert);
        this.entityManager.persist(new Base64CertData(incert));
    }
    data1 = new CertificateData(incert, pubk, username, cafp, status, type, certificateProfileId, tag,
            updateTime, useBase64CertTable);
    this.entityManager.persist(data1);

    final String serialNo = CertTools.getSerialNumberAsString(incert);
    final String msg = INTRES.getLocalizedMessage("store.storecert", username, data1.getFingerprint(),
            data1.getSubjectDN(), data1.getIssuerDN(), serialNo);
    Map<String, Object> details = new LinkedHashMap<String, Object>();
    details.put("msg", msg);
    final String caId = String.valueOf(CertTools.getIssuerDN(incert).hashCode());
    logSession.log(EventTypes.CERT_STORED, EventStatus.SUCCESS, ModuleTypes.CERTIFICATE, ServiceTypes.CORE,
            adminForLogging.toString(), caId, serialNo, username, details);
    if (log.isTraceEnabled()) {
        log.trace("<storeCertificateNoAuth()");
    }
    return new CertificateDataWrapper(incert, data1, base64CertData);
}

From source file:gov.nih.nci.caarray.application.file.FileManagementServiceBean.java

/**
 * {@inheritDoc}/* w ww.j ava  2  s . c  o m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void importArrayDesignDetails(ArrayDesign arrayDesign) {
    arrayDesign.getDesignFileSet().updateStatus(FileStatus.IN_QUEUE);
    this.projectDao.save(arrayDesign.getDesignFiles());
    final AbstractFileManagementJob job = this.jobFactory
            .createArrayDesignFileImportJob(CaArrayUsernameHolder.getUser(), arrayDesign);
    this.jobSubmitter.submitJob(job);
}

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

/**
 * {@inheritDoc}/* w  w  w  . ja v a  2s.com*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void syncPhraseSequencer(long mandatorId) {
    FxContext.startRunningAsSystem();
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();
        ps = con.prepareStatement("SELECT MAX(ID) FROM " + TBL_PHRASE + " WHERE MANDATOR=?");
        ps.setLong(1, mandatorId);
        ResultSet rs = ps.executeQuery();
        if (rs != null && rs.next()) {
            long max = rs.getLong(1) + 1;
            final String SEQ_NAME = "PhraseSeq_" + mandatorId;
            if (seq.sequencerExists(SEQ_NAME))
                seq.removeSequencer(SEQ_NAME);
            seq.createSequencer(SEQ_NAME, false, max);
        }
    } catch (SQLException e) {
        EJBUtils.rollback(ctx);
        throw new FxDbException(LOG, e, "ex.db.sqlError", e.getMessage()).asRuntimeException();
    } catch (FxApplicationException e) {
        EJBUtils.rollback(ctx);
        throw e.asRuntimeException();
    } finally {
        FxContext.stopRunningAsSystem();
        Database.closeObjects(PhraseEngineBean.class, con, ps);
    }
}

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

/** {@inheritDoc} */
@Override//from   w ww . java  2 s  . c  o  m
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void saveSystemDefault(ResultPreferences preferences, long typeId, ResultViewType viewType,
        ResultLocation... locations) throws FxApplicationException {
    if (preferences.getSelectedColumns().isEmpty()) {
        throw new FxInvalidParameterException("preferences", "ex.ResultPreferences.save.empty");
    }
    for (ResultLocation location : locations) {
        // div conf already checks for supervisor access
        divisionConfiguration.put(SystemParameters.USER_RESULT_PREFERENCES, getKey(typeId, viewType, location),
                preferences);
    }
}

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

/**
 * save basic flow action/* w w  w . j a v a 2s .c  om*/
 * 
 * @throws UCMException
 */
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void saveBasicFlow() throws UCMException {
    try {
        this.basicFlowStep.setModifiedBy(this.authUser.getUsername());
        if (validate()) {
            if (this.basicFlowStep.getId() == null) {
                this.useCase.getBasicFlow().addFlowStep(this.basicFlowStep);
            }

            // force testcase update
            Timestamp now = new Timestamp(System.currentTimeMillis());
            this.useCase.setModifiedDate(now);

            em.persist(this.useCase);
            logger.info("Saved Basic Flow");
            this.facesContextMessage.infoMessage("Basic Flow saved successfully");

            this.basicStepSelected = true;

            // resort steps
            Collections.sort(this.useCase.getBasicFlow().getFlowSteps(), FLOWSTEP_ORDER);

        }
    } catch (Exception e) {
        throw new UCMException(e);
    }
}

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

/**
 * {@inheritDoc}/*  w ww  .j a  v  a  2  s  . co  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void installBinary(long binaryId, String resourceName) throws FxApplicationException {
    Connection con = null;
    try {
        ContentStorage storage = StorageManager.getContentStorage(TypeStorageMode.Hierarchical);
        String binaryName = resourceName;
        String subdir = "";
        if (binaryName.indexOf('/') > 0) {
            binaryName = binaryName.substring(binaryName.lastIndexOf('/') + 1);
            subdir = resourceName.substring(0, resourceName.lastIndexOf('/') + 1);
        }
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        con = getConnection();
        long length = 0;
        String[] files = FxSharedUtils
                .loadFromInputStream(
                        cl.getResourceAsStream("fxresources/binaries/" + subdir + "resourceindex.flexive"), -1)
                .replaceAll("\r", "").split("\n");
        for (String file : files) {
            if (file.startsWith(binaryName + "|")) {
                length = Long.parseLong(file.split("\\|")[1]);
                break;
            }
        }
        if (length == 0)
            throw new FxApplicationException("ex.scripting.load.resource.failed", resourceName);
        storage.storeBinary(con, binaryId, 1, 1, binaryName, length,
                cl.getResourceAsStream("fxresources/binaries/" + resourceName));
    } catch (SQLException e) {
        throw new FxDbException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        try {
            if (con != null)
                con.close();
        } catch (SQLException e) {
            //ignore
        }
    }
}

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

/**
 * {@inheritDoc}/*from  www .j av a 2s  .c o m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void modify(long id, String name, String description, Long aclId) throws FxApplicationException {

    // Anything to do?
    if (name != null && name.trim().length() == 0) {
        name = null;
    }
    if (name == null && description == null && aclId == null) {
        return;
    }

    // Lookup the briefcase
    Briefcase br = load(id);
    if (br == null) {
        throw new FxNotFoundException("ex.briefcase.notFound", ("#" + id));
    }
    // Permission checks
    checkEditBriefcase(br);
    // Delete operation
    Connection con = null;
    PreparedStatement ps = null;
    try {
        // Obtain a database connection
        con = Database.getDbConnection();
        String sSql = "update " + DatabaseConst.TBL_BRIEFCASE + " set" + ((name == null) ? "" : " name=?, ")
                + ((aclId == null) ? "" : " acl=?, ") + ((description == null) ? "" : " description=?, ")
                + "mandator=mandator where id=" + id;
        ps = con.prepareStatement(sSql);
        int pos = 1;
        if (name != null)
            ps.setString(pos++, name);
        if (aclId != null) {
            if (aclId == -1) {
                ps.setNull(pos++, java.sql.Types.NUMERIC);
            } else {
                ps.setLong(pos++, aclId);
            }
        }
        if (description != null)
            ps.setString(pos, description);
        ps.executeUpdate();
    } catch (SQLException exc) {
        EJBUtils.rollback(ctx);
        throw new FxLoadException(LOG, exc, "ex.briefcase.modifyFailed", br.getName());
    } finally {
        closeObjects(BriefcaseEngineBean.class, con, ps);
    }
}

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

/**
 * save business rule action//from  w ww .  j a v  a 2s.c om
 * 
 * @throws UCMException
 */
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void saveBusinessRule() {
    try {
        if (validate()) {
            this.specificationRule.setModifiedBy(authUser.getUsername());
            if (this.specificationRule.getId() == null) {
                this.specification.addSpecificationRule(this.specificationRule);
            }
            em.persist(this.specification);
            logger.info("Saved {}", this.specificationRule.getArtifact());
            this.facesContextMessage.infoMessage("{0} saved successfully",
                    this.specificationRule.getArtifact());
            this.selected = true;
        }
    } catch (Exception e) {
        throw new UCMException(e);
    }
}