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.configuration.GenericConfigurationImpl.java

/**
 * {@inheritDoc}//from   w  ww . j av a  2 s  .  c  o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Map<ParameterData, Serializable> getAllWithXStream(Map<String, XStream> instances)
        throws FxApplicationException {
    Connection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = getConnection();
        stmt = getSelectStatement(conn);
        final ResultSet rs = stmt.executeQuery();
        final Map<ParameterData, Serializable> result = new HashMap<ParameterData, Serializable>();
        while (rs.next()) {
            final String key = rs.getString(2);
            final String dbValue = rs.getString(3);
            final String className = rs.getString(4);
            final ParameterPathBean path = new ParameterPathBean(rs.getString(1), getDefaultScope());

            final Parameter parameter;
            if (className != null) {
                XStream customInstance = instances.get(className);
                if (customInstance == null) {
                    // check prefix matches
                    String longestPrefix = "";
                    for (String name : instances.keySet()) {
                        if (name.endsWith("*") && className.startsWith(name.substring(0, name.length() - 1))
                                && name.length() > longestPrefix.length()) {
                            customInstance = instances.get(name);
                            longestPrefix = name;
                        }
                    }
                }

                if (customInstance != null) {
                    // use custom XStream instance
                    parameter = ParameterFactory.newXStreamInstance(className,
                            new ParameterDataBean<Serializable>(path, key, null), customInstance);
                } else {
                    // common case - use the parameter factory to get the matching parameter instance for the given class name
                    parameter = ParameterFactory.newInstance(className,
                            new ParameterDataBean<Serializable>(path, key, null));
                }
            } else if ("true".equals(dbValue) || "false".equals(dbValue)) { // fallback for old configurations: try to determine the data type
                parameter = ParameterFactory.newInstance(Boolean.class, path, key, true, null);
            } else if (StringUtils.isNumeric(dbValue)) {
                parameter = ParameterFactory.newInstance(Integer.class, path, key, true, null);
            } else if (dbValue != null && dbValue.startsWith("<") && dbValue.endsWith(">")) {
                // assume that it's an objects serialized to XML
                parameter = ParameterFactory.newInstance(Object.class, path, key, true, null);
            } else {
                parameter = ParameterFactory.newInstance(String.class, path, key, true, null);
            }
            try {
                result.put(parameter.getData(), (Serializable) parameter.getValue(dbValue));
            } catch (XStreamException e) {
                LOG.warn(
                        "Not including parameter " + parameter + " because its value could not be deserialized",
                        e);
            }
        }
        return result;
    } catch (SQLException e) {
        throw new FxLoadException(LOG, e, "ex.db.sqlError", e.getMessage());
    } finally {
        Database.closeObjects(GenericConfigurationImpl.class, conn, stmt);
    }
}

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

/**
 * {@inheritDoc}//www  . ja  v a 2 s.  c o  m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long create(Account account, String password) throws FxApplicationException {
    return create(account, password, true);
}

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

/**
 * {@inheritDoc}//  w  ww. j a v  a  2 s . c  o  m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public LabeledExtract copyLabeledExtract(Project project, long extractId)
        throws ProposalWorkflowException, InconsistentProjectStateException {
    LogUtil.logSubsystemEntry(LOG, project, extractId);
    checkIfProjectSaveAllowed(project);
    final LabeledExtract le = this.searchDao.retrieve(LabeledExtract.class, extractId);
    final LabeledExtract copy = new LabeledExtract();
    copyInto(LabeledExtract.class, copy, le);
    copy.setLabel(le.getLabel());
    project.getExperiment().getLabeledExtracts().add(copy);
    copy.setExperiment(project.getExperiment());
    for (final Extract e : le.getExtracts()) {
        e.getLabeledExtracts().add(copy);
        copy.getExtracts().add(e);
    }
    this.projectDao.save(project);
    LogUtil.logSubsystemExit(LOG);
    return copy;
}

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

/**
 * {@inheritDoc}/*from   w w  w  .  j  a va  2 s  . c om*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void setMetaData(long id, Collection<FxReferenceMetaData<FxPK>> metadata) throws FxApplicationException {
    checkEditBriefcase(load(id));
    Connection con = null;

    try {
        con = Database.getDbConnection();
        replaceMetaData(con, id, metadata);
    } catch (SQLException e) {
        EJBUtils.rollback(ctx);
        throw new FxUpdateException(LOG, e);
    } finally {
        closeObjects(BriefcaseEngineBean.class, con, null);
    }
}

From source file:org.cesecore.keys.token.CryptoTokenManagementSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override// w w  w .j a  v  a  2 s.c o  m
public boolean updatePin(AuthenticationToken authenticationToken, Integer cryptoTokenId,
        char[] currentAuthenticationCode, char[] newAuthenticationCode, boolean updateOnly)
        throws AuthorizationDeniedException, CryptoTokenAuthenticationFailedException,
        CryptoTokenOfflineException {
    final String[] requiredAuthorization = new String[] {
            CryptoTokenRules.MODIFY_CRYPTOTOKEN.resource() + "/" + cryptoTokenId,
            CryptoTokenRules.ACTIVATE.resource() + "/" + cryptoTokenId,
            CryptoTokenRules.DEACTIVATE.resource() + "/" + cryptoTokenId };
    if (!accessControlSessionSession.isAuthorized(authenticationToken, requiredAuthorization)) {
        final String msg = INTRES.getLocalizedMessage("authorization.notuathorizedtoresource",
                Arrays.toString(requiredAuthorization), authenticationToken.toString());
        throw new AuthorizationDeniedException(msg);
    }
    CryptoToken cryptoToken = getCryptoToken(cryptoTokenId);
    final Properties cryptoTokenProperties = cryptoToken.getProperties();
    // Get current auto-activation pin (if any)
    final String oldAutoActivationPin = BaseCryptoToken.getAutoActivatePin(cryptoTokenProperties);
    if (oldAutoActivationPin == null && (updateOnly || newAuthenticationCode == null)) {
        // This is a NOOP call that will not lead to any change
        return false;
    }
    if (SoftCryptoToken.class.getName().equals(cryptoToken.getClass().getName())) {
        CryptoProviderTools.installBCProviderIfNotAvailable();
        final KeyStore keystore;
        try {
            keystore = KeyStore.getInstance("PKCS12", "BC");
            keystore.load(new ByteArrayInputStream(cryptoToken.getTokenData()), currentAuthenticationCode);
        } catch (Exception e) {
            final String msg = "Failed to use supplied current PIN." + " " + e;
            log.info(msg);
            throw new CryptoTokenAuthenticationFailedException(msg);
        }
        if (newAuthenticationCode == null) {
            // When no new pin is supplied, we will not modify the key-store and just remove the current auto-activation pin
            cryptoTokenProperties.remove(CryptoToken.AUTOACTIVATE_PIN_PROPERTY);
            cryptoToken.setProperties(cryptoTokenProperties);
        } else {
            try {
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                keystore.store(baos, newAuthenticationCode);
                baos.close();
                if (oldAutoActivationPin != null || !updateOnly) {
                    BaseCryptoToken.setAutoActivatePin(cryptoTokenProperties, new String(newAuthenticationCode),
                            true);
                } else {
                    log.debug(
                            "Auto-activation will not be used. Only changing pin for soft CryptoToken keystore.");
                }
                cryptoToken = CryptoTokenFactory.createCryptoToken(SoftCryptoToken.class.getName(),
                        cryptoTokenProperties, baos.toByteArray(), cryptoTokenId, cryptoToken.getTokenName());
            } catch (Exception e) {
                log.info("Unable to store soft keystore with new PIN: " + e);
                throw new CryptoTokenAuthenticationFailedException(
                        "Unable to store soft keystore with new PIN");
            }
        }
    } else {
        if (oldAutoActivationPin != null) {
            // If we have an old auto-activation pin we will compare the "current" with this value to avoid deactivating the token
            if (!oldAutoActivationPin.equals(new String(currentAuthenticationCode))) {
                final String msg = "Supplied PIN did not match auto-activation PIN.";
                log.info(msg);
                throw new CryptoTokenAuthenticationFailedException(msg);
            } else {
                log.debug(
                        "Successfully verified the PIN for non-soft CryptoToken by comparing supplied PIN to auto-activation PIN.");
            }
        } else {
            // If we don't have an auto-activation pin to compare the supplied PIN to, we need to verify the supplied
            // PIN can be used in a de-activation/activation cycle.
            final boolean wasInactive = !isCryptoTokenStatusActive(authenticationToken, cryptoTokenId);
            cryptoToken.deactivate();
            cryptoToken.activate(currentAuthenticationCode);
            if (wasInactive) {
                // Note that there is a small glitch here where the token was active, but we have no other options to verify the pin
                cryptoToken.deactivate();
            }
        }
        if (newAuthenticationCode == null) {
            cryptoTokenProperties.remove(CryptoToken.AUTOACTIVATE_PIN_PROPERTY);
        } else {
            BaseCryptoToken.setAutoActivatePin(cryptoTokenProperties, new String(newAuthenticationCode), true);
        }
        cryptoToken.setProperties(cryptoTokenProperties);
    }
    // Save the modified CryptoToken
    try {
        cryptoTokenSession.mergeCryptoToken(cryptoToken);
    } catch (CryptoTokenNameInUseException e) {
        // This should not happen here since we use the same name and id
        throw new RuntimeException(e);
    }
    securityEventsLoggerSession.log(EventTypes.CRYPTOTOKEN_UPDATEPIN, EventStatus.SUCCESS,
            ModuleTypes.CRYPTOTOKEN, ServiceTypes.CORE, authenticationToken.toString(),
            String.valueOf(cryptoTokenId), null, null,
            "Updated PIN of CryptoToken '" + cryptoToken.getTokenName() + "' with id " + cryptoTokenId);
    // Return the current auto-activation state
    return BaseCryptoToken.getAutoActivatePin(cryptoTokenProperties) != null;
}

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

/**
 * {@inheritDoc}/*w w  w.  j a v  a2  s  . c  o m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void saveDivisions(List<? extends DivisionData> divisions) throws FxApplicationException {
    removeAll(SystemParameters.GLOBAL_DATASOURCES);
    removeAll(SystemParameters.GLOBAL_DIVISIONS_DOMAINS);
    clearDivisionCache();
    for (DivisionData division : divisions) {
        // remove the "java:" prefix that may have been appended on some containers, use the canonical JDBC string
        final String storedDataSource = division.getDataSource().replaceFirst("^java:", "");
        // store parameters
        put(SystemParameters.GLOBAL_DATASOURCES, String.valueOf(division.getId()), storedDataSource);
        put(SystemParameters.GLOBAL_DIVISIONS_DOMAINS, String.valueOf(division.getId()),
                division.getDomainRegEx());
    }
    updateTimestamp();
}

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

/**
 * {@inheritDoc}//from ww  w .ja  va2s .c  o m
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void setPhraseHidden(String phraseKey, long mandator, boolean hidden) throws FxNoAccessException {
    setPhraseHidden(FxPhraseCategorySelection.CATEGORY_DEFAULT, phraseKey, mandator, hidden);
}

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

/**
 * {@inheritDoc}/*from   w w w. ja v  a2s .  c o m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void setPhraseHidden(int category, String phraseKey, long mandator, boolean hidden)
        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();
        ps = con.prepareStatement("UPDATE " + TBL_PHRASE + " SET HID=? WHERE PKEY=? AND MANDATOR=? AND CAT=?");
        ps.setBoolean(1, hidden);
        ps.setString(2, phraseKey);
        ps.setLong(3, mandator);
        ps.setInt(4, category);
        ps.executeUpdate();
    } 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:org.ejbca.core.ejb.ca.store.CertificateStoreSessionBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Override//w  w w .j  a  v  a 2 s.  c o  m
public void setArchivedStatus(Admin admin, String fingerprint) throws AuthorizationDeniedException {
    if (admin.getAdminType() != Admin.TYPE_INTERNALUSER) {
        throw new AuthorizationDeniedException("Unauthorized");
    }
    CertificateData rev = CertificateData.findByFingerprint(entityManager, fingerprint);
    if (rev != null) {
        rev.setStatus(SecConst.CERT_ARCHIVED);
        if (log.isDebugEnabled()) {
            log.debug("Set status ARCHIVED for certificate with fp: " + fingerprint + ", revocation reason is: "
                    + rev.getRevocationReason());
        }
    } else {
        String msg = intres.getLocalizedMessage("store.errorcertinfo", fingerprint);
        logSession.log(admin, 0, LogConstants.MODULE_CA, new java.util.Date(), null, null,
                LogConstants.EVENT_ERROR_UNKNOWN, msg);
        throw new EJBException(msg);
    }
}

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

/**
 * {@inheritDoc}//from  w  ww .  jav  a2s .  c om
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public String getRootLogin() throws FxApplicationException {
    return get(SystemParameters.GLOBAL_ROOT_LOGIN);
}