Example usage for javax.ejb TransactionAttributeType REQUIRES_NEW

List of usage examples for javax.ejb TransactionAttributeType REQUIRES_NEW

Introduction

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

Prototype

TransactionAttributeType REQUIRES_NEW

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

Click Source Link

Document

The container must invoke an enterprise bean method whose transaction attribute is set to REQUIRES_NEW with a new transaction context.

Usage

From source file:ch.puzzle.itc.mobiliar.business.deploy.boundary.DeploymentBoundary.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
private void handlePreDeploymentSuccessful(DeploymentEntity deployment) {
    DeploymentState previousState = deployment.getDeploymentState();

    deployment.setDeploymentState(DeploymentState.READY_FOR_DEPLOYMENT);
    deployment.appendStateMessage("All NodeJobs successful, updated deployment state from " + previousState
            + " to " + deployment.getDeploymentState() + " at " + new Date());
    log.info("All NodeJobs of deployment " + deployment.getId() + " successful, updated deployment state from "
            + previousState + " to " + deployment.getDeploymentState().name());
    deploymentEvent.fire(new DeploymentEvent(DeploymentEventType.UPDATE, deployment.getId(),
            deployment.getDeploymentState()));
}

From source file:gwap.rest.LocationService.java

@POST
@Consumes(MediaType.APPLICATION_JSON)// w w w. j av a  2 s  . c  o  m
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@Transactional
public Response createNewLocation(String payloadString) {
    JSONObject payload = parse(payloadString);

    Location location = new Location();
    String name = (String) payload.get("name");
    location.setName(name);
    location.setType(LocationType.APP);

    GeoPoint geoPoint = new GeoPoint();
    geoPoint.setLatitude(Float.parseFloat(payload.get("latitude").toString()));
    geoPoint.setLongitude(Float.parseFloat(payload.get("longitude").toString()));
    entityManager.persist(geoPoint);

    entityManager.persist(location);
    entityManager.flush();
    LocationGeoPoint locationGeoPoint = new LocationGeoPoint();
    locationGeoPoint.setGeoPoint(geoPoint);
    locationGeoPoint.setLocation(location);
    entityManager.persist(locationGeoPoint);
    location.getGeoRepresentation().add(locationGeoPoint);

    ArtResource artResource = new ArtResource();
    Calendar now = GregorianCalendar.getInstance();
    artResource.setDateCreated(new SimpleDateFormat("dd.MM.yyyy").format(now.getTime()));
    artResource.setShownLocation(location);
    artResource.setSkip(true); // should not show up for artigo tagging
    entityManager.persist(artResource);

    ArtResourceTeaser artResourceTeaser = new ArtResourceTeaser();
    artResourceTeaser.setDescription(payload.get("description").toString());
    artResourceTeaser.setLanguage("de");
    artResourceTeaser.setResource(artResource);
    entityManager.persist(artResourceTeaser);
    artResource.getTeasers().add(artResourceTeaser);

    artResource.getId();
    VirtualTagging virtualTagging = new VirtualTagging();
    virtualTagging.setResource(artResource);

    VirtualTaggingType virtualTaggingType = entityManager.find(VirtualTaggingType.class,
            Long.parseLong(payload.get("topic").toString()));
    virtualTagging.getVirtualTaggingTypes().add(virtualTaggingType);
    entityManager.persist(virtualTagging);
    entityManager.flush();

    //TODO: Save uploaded image

    log.info("Uploaded new Image from App with id: #0", artResource.getId());
    return Response.status(Response.Status.CREATED).build();
}

From source file:org.rhq.enterprise.server.resource.group.ResourceGroupManagerBean.java

@SuppressWarnings("unchecked")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void setResourceType(int resourceGroupId) throws ResourceGroupDeleteException {
    Query query = entityManager.createNamedQuery(ResourceType.QUERY_GET_EXPLICIT_RESOURCE_TYPE_COUNTS_BY_GROUP);
    query.setParameter("groupId", resourceGroupId);

    Subject overlord = subjectManager.getOverlord();
    ResourceGroup resourceGroup = getResourceGroupById(overlord, resourceGroupId, null);

    List results = query.getResultList();
    if (results.size() == 1) {
        Object[] info = (Object[]) results.get(0);
        int resourceTypeId = (Integer) info[0];

        ResourceType flyWeightType = new ResourceType();
        flyWeightType.setId(resourceTypeId);
        resourceGroup.setResourceType(flyWeightType);
    } else {//from  w  ww.  ja  v a 2  s .com
        if (resourceGroup.getResourceType() != null) {
            // converting compatible group to mixed group, remove all corresponding compatible constructs
            removeCompatibleGroupConstructs(overlord, resourceGroup);
        }
        resourceGroup.setResourceType(null);
    }
}

From source file:org.rhq.enterprise.server.content.ContentManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public ContentServiceRequest createRetrieveBitsRequest(int resourceId, String username,
        int installedPackageId) {
    Resource resource = entityManager.find(Resource.class, resourceId);

    ContentServiceRequest persistedRequest = new ContentServiceRequest(resource, username,
            ContentRequestType.GET_BITS);
    persistedRequest.setStatus(ContentRequestStatus.IN_PROGRESS);

    long timestamp = System.currentTimeMillis();

    // Load the InstalledPackage to get its package version for the relationship
    InstalledPackage ip = entityManager.find(InstalledPackage.class, installedPackageId);
    PackageVersion packageVersion = ip.getPackageVersion();

    // Create the history entity
    InstalledPackageHistory history = new InstalledPackageHistory();
    history.setContentServiceRequest(persistedRequest);
    history.setPackageVersion(packageVersion);
    history.setResource(resource);//from   w w w. ja  v a2  s .  c  o  m
    history.setStatus(InstalledPackageHistoryStatus.BEING_RETRIEVED);
    history.setTimestamp(timestamp);

    persistedRequest.addInstalledPackageHistory(history);

    entityManager.persist(persistedRequest);

    return persistedRequest;
}

From source file:ch.puzzle.itc.mobiliar.business.deploy.boundary.DeploymentService.java

/**
 * We update the information about a deployment that has been executed.
 *
 * @param generationModus  - if the deployment was in simulation or realistic mode
 * @param deploymentId     - the deployment id of the deployment that has been executed.
 * @param errorMessage     - the error message if any other
 * @param resourceId       - the ApplicationServe used for deployment
 * @param generationResult/*w ww .  j av a  2  s .  c  o  m*/
 */
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public DeploymentEntity updateDeploymentInfo(GenerationModus generationModus, final Integer deploymentId,
        final String errorMessage, final Integer resourceId, final GenerationResult generationResult) {
    // don't lock a deployment for predeployment as there is no need to update the deployment.
    if (GenerationModus.PREDEPLOY.equals(generationModus) && errorMessage == null) {
        log.fine("Predeploy script finished at " + new Date());
        return em.find(DeploymentEntity.class, deploymentId);
    }
    DeploymentEntity deployment = em.find(DeploymentEntity.class, deploymentId,
            LockModeType.PESSIMISTIC_FORCE_INCREMENT);

    // set as used for deployment
    if (resourceId != null) {
        ResourceEntity as = em.find(ResourceEntity.class, resourceId);
        deployment.setResource(as);
    }

    if (GenerationModus.DEPLOY.equals(generationModus)) {
        if (errorMessage == null) {
            String nodeInfo = getNodeInfoForDeployment(generationResult);
            deployment.appendStateMessage("Successfully deployed at " + new Date() + "\n" + nodeInfo);
            deployment.setDeploymentState(DeploymentState.success);
        } else {
            deployment.appendStateMessage(errorMessage);
            deployment.setDeploymentState(DeploymentState.failed);
        }
    } else if (GenerationModus.PREDEPLOY.equals(generationModus)) {
        deployment.appendStateMessage(errorMessage);
        deployment.setDeploymentState(DeploymentState.failed);
    } else {
        if (errorMessage == null) {
            String nodeInfo = getNodeInfoForDeployment(generationResult);
            deployment.appendStateMessage("Successfully generated at " + new Date() + "\n" + nodeInfo);
            deployment.setBuildSuccess(true);
        } else {
            deployment.appendStateMessage(errorMessage);
            deployment.setBuildSuccess(false);
        }
        if (deployment.getDeploymentConfirmed() != null && deployment.getDeploymentConfirmed()) {
            deployment.setDeploymentState(DeploymentState.scheduled);
        } else {
            deployment.setDeploymentState(DeploymentState.requested);
        }
    }
    deployment.setSimulating(false);
    return deployment;
}

From source file:org.rhq.enterprise.server.content.ContentManagerBean.java

@TransactionTimeout(45 * 60)
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void completeRetrievePackageBitsRequest(ContentServiceResponse response, InputStream bitStream) {
    log.info("Completing retrieve package bits response: " + response);

    // Load persisted request
    ContentServiceRequest persistedRequest = entityManager.find(ContentServiceRequest.class,
            response.getRequestId());//from w  ww.  j av  a 2  s .c  o  m

    // There is some inconsistency if we're completing a request that was not in the database
    if (persistedRequest == null) {
        log.error("Attempting to complete a request that was not found in the database: "
                + response.getRequestId());
        return;
    }
    Resource resource = persistedRequest.getResource();

    InstalledPackageHistory initialRequestHistory = persistedRequest.getInstalledPackageHistory().iterator()
            .next();
    PackageVersion packageVersion = initialRequestHistory.getPackageVersion();

    if (response.getStatus() == ContentRequestStatus.SUCCESS) {
        // Read the stream from the agent and store in the package version
        try {
            log.debug("Saving content for response: " + response);

            PackageBits packageBits = initializePackageBits(null);

            // Could use the following, but only on jdk6 as builds
            // @since 1.6
            // void setBinaryStream(int parameterIndex, java.io.InputStream x) throws SQLException;

            Long length = packageVersion.getFileSize();
            if (length == null) {
                File tmpFile = File.createTempFile("rhq", ".stream");
                FileOutputStream fos = new FileOutputStream(tmpFile);
                length = StreamUtil.copy(bitStream, fos, true);

                bitStream = new FileInputStream(tmpFile);
            }
            Connection conn = null;
            PreparedStatement ps = null;

            try {
                PackageBits bits = entityManager.find(PackageBits.class, packageBits.getId());
                String pkgName = "(set packageName)";
                if ((packageVersion != null) && (packageVersion.getGeneralPackage() != null)) {
                    //update it to whatever package name is if we can get to it.
                    pkgName = packageVersion.getGeneralPackage().getName();
                }
                bits = loadPackageBits(bitStream, packageVersion.getId(), pkgName, packageVersion.getVersion(),
                        bits, null);

                entityManager.merge(bits);
            } finally {

                if (ps != null) {
                    try {
                        ps.close();
                    } catch (Exception e) {
                        log.warn("Failed to close prepared statement for package version [" + packageVersion
                                + "]");
                    }
                }

                if (conn != null) {
                    try {
                        conn.close();
                    } catch (Exception e) {
                        log.warn("Failed to close connection for package version [" + packageVersion + "]");
                    }
                }
            }

        } catch (Exception e) {
            log.error("Error while reading content from agent stream", e);
            // TODO: don't want to throw exception here? does the tx rollback automatically anyway?
        }
    }

    // Update the persisted request
    persistedRequest.setErrorMessage(response.getErrorMessage());
    persistedRequest.setStatus(response.getStatus());

    // Add a new audit trail entry
    InstalledPackageHistory completedHistory = new InstalledPackageHistory();
    completedHistory.setContentServiceRequest(persistedRequest);
    completedHistory.setResource(resource);
    completedHistory.setTimestamp(System.currentTimeMillis());
    completedHistory.setPackageVersion(packageVersion);

    if (response.getStatus() == ContentRequestStatus.SUCCESS) {
        completedHistory.setStatus(InstalledPackageHistoryStatus.RETRIEVED);
    } else {
        completedHistory.setStatus(InstalledPackageHistoryStatus.FAILED);
        completedHistory.setErrorMessage(response.getErrorMessage());
    }

}

From source file:org.rhq.enterprise.server.measurement.MeasurementScheduleManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public int insertSchedulesFor(int[] batchIds) throws Exception {
    /* // w w w  .ja  va2s  . co  m
     * JM: (April 15th, 2009)
     * 
     *     the "res.id" token on the final line does not get the "res" alias from the outer query appropriately;
     *     instead, it tries to reference the table name itself as "RHQ_RESOURCE.ID", which bombs with[2] on 
     *     postgres; i thought of using "WHERE ms.resource.uuid = res.uuid" which would work because UUID column 
     *     name is not reused for any other entity in the model, let alone on any table used in this query; however,
     *     this felt like a hack, and I wasn't sure whether UUID would be unique across very large inventories; if
     *     it's not, there is a slight chance that the insert query could do the wrong thing (albeit rare), so I 
     *     erred on the side of correctness and went with native sql which allowed me to use the proper id alias in 
     *     the correlated subquery; correctness aside, keeping the logic using resource id should allow the query 
     *     optimizer to use indexes instead of having to look up the rows on the resource table to get the uuid
     *
     * [1] - http://opensource.atlassian.com/projects/hibernate/browse/HHH-1397
     * [2] - ERROR: invalid reference to FROM-clause entry for table "rhq_resource"
     *
     * Query insertHQL = entityManager.createQuery("" //
     *     + "INSERT INTO MeasurementSchedule( enabled, interval, definition, resource ) \n"
     *     + "     SELECT md.defaultOn, md.defaultInterval, md, res \n"
     *     + "       FROM Resource res, ResourceType rt, MeasurementDefinition md \n"
     *     + "      WHERE res.id IN ( :resourceIds ) \n"
     *     + "        AND res.resourceType.id = rt.id \n"
     *     + "        AND rt.id = md.resourceType.id \n"
     *     + "        AND md.id NOT IN ( SELECT ms.definition.id \n" //
     *     + "                             FROM MeasurementSchedule ms \n" //
     *     + "                            WHERE ms.resource.id = res.id )");
     */

    Connection conn = null;
    PreparedStatement insertStatement = null;

    int created = -1;
    try {
        conn = dataSource.getConnection();
        DatabaseType dbType = DatabaseTypeFactory.getDatabaseType(conn);

        String insertQueryString = null;
        if (dbType instanceof PostgresqlDatabaseType) {
            insertQueryString = MeasurementSchedule.NATIVE_QUERY_INSERT_SCHEDULES_POSTGRES;
        } else if (dbType instanceof OracleDatabaseType || dbType instanceof H2DatabaseType) {
            insertQueryString = MeasurementSchedule.NATIVE_QUERY_INSERT_SCHEDULES_ORACLE;
        } else if (dbType instanceof SQLServerDatabaseType) {
            insertQueryString = MeasurementSchedule.NATIVE_QUERY_INSERT_SCHEDULES_SQL_SERVER;
        } else {
            throw new IllegalArgumentException("Unknown database type, can't continue: " + dbType);
        }

        insertQueryString = JDBCUtil.transformQueryForMultipleInParameters(insertQueryString, "@@RESOURCES@@",
                batchIds.length);
        insertStatement = conn.prepareStatement(insertQueryString);

        JDBCUtil.bindNTimes(insertStatement, batchIds, 1);

        // first create whatever schedules may be needed
        created = insertStatement.executeUpdate();
        if (log.isDebugEnabled()) {
            log.debug("Batch created [" + created + "] default measurement schedules for resource batch ["
                    + batchIds + "]");
        }
    } finally {
        if (insertStatement != null) {
            try {
                insertStatement.close();
            } catch (Exception e) {
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    }
    return created;
}

From source file:ch.puzzle.itc.mobiliar.business.deploy.boundary.DeploymentBoundary.java

/**
 * We update the information about a deployment that has been executed.
 *
 * @param generationModus  - if the deployment was in simulation or realistic mode
 * @param deploymentId     - the deployment id of the deployment that has been executed.
 * @param errorMessage     - the error message if any other
 * @param resourceId       - the ApplicationServe used for deployment
 * @param generationResult//from w ww.java 2 s . c o m
 * @param reason           - the DeploymentFailureReason (if any)
 */
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public DeploymentEntity updateDeploymentInfo(GenerationModus generationModus, final Integer deploymentId,
        final String errorMessage, final Integer resourceId, final GenerationResult generationResult,
        DeploymentFailureReason reason) {
    // don't lock a deployment for predeployment as there is no need to update the deployment.
    if (GenerationModus.PREDEPLOY.equals(generationModus) && errorMessage == null) {
        log.fine("Predeploy script finished at " + new Date());
        return em.find(DeploymentEntity.class, deploymentId);
    }
    DeploymentEntity deployment = em.find(DeploymentEntity.class, deploymentId,
            LockModeType.PESSIMISTIC_FORCE_INCREMENT);

    // set as used for deployment
    if (resourceId != null) {
        ResourceEntity as = em.find(ResourceEntity.class, resourceId);
        deployment.setResource(as);
    }

    if (GenerationModus.DEPLOY.equals(generationModus)) {
        if (errorMessage == null) {
            String nodeInfo = getNodeInfoForDeployment(generationResult);
            deployment.appendStateMessage("Successfully deployed at " + new Date() + "\n" + nodeInfo);
            deployment.setDeploymentState(DeploymentState.success);
        } else {
            deployment.appendStateMessage(errorMessage);
            deployment.setDeploymentState(DeploymentState.failed);
            if (reason == null) {
                reason = DeploymentFailureReason.DEPLOYMENT_GENERATION;
            }
            deployment.setReason(reason);
        }
    } else if (GenerationModus.PREDEPLOY.equals(generationModus)) {
        deployment.appendStateMessage(errorMessage);
        deployment.setDeploymentState(DeploymentState.failed);
        if (reason == null) {
            reason = DeploymentFailureReason.PRE_DEPLOYMENT_GENERATION;
        }
        deployment.setReason(reason);
    } else {
        if (errorMessage == null) {
            String nodeInfo = getNodeInfoForDeployment(generationResult);
            deployment.appendStateMessage("Successfully generated at " + new Date() + "\n" + nodeInfo);
            deployment.setBuildSuccess(true);
        } else {
            deployment.appendStateMessage(errorMessage);
            deployment.setBuildSuccess(false);
        }
        if (deployment.getDeploymentConfirmed() != null && deployment.getDeploymentConfirmed()) {
            deployment.setDeploymentState(DeploymentState.scheduled);
        } else {
            deployment.setDeploymentState(DeploymentState.requested);
        }
    }
    deployment.setSimulating(false);
    return deployment;
}

From source file:org.rhq.enterprise.server.content.RepoManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public RepoSyncResults getMostRecentSyncResults(Subject subject, int repoId) {
    Repo found = this.getRepo(subject, repoId);
    List<RepoSyncResults> syncResults = found.getSyncResults();

    int latestIndex = syncResults.size() - 1;
    if (syncResults != null && (!syncResults.isEmpty()) && syncResults.get(latestIndex) != null) {
        return syncResults.get(latestIndex);
    } else {// ww  w. j a  va  2 s.c o  m
        return null;
    }
}

From source file:org.rhq.enterprise.server.content.ContentSourceManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
@TransactionTimeout(40 * 60)//  w  w  w  . ja  v a2s  .c  o  m
private PackageBits preparePackageBits(Subject subject, InputStream bitsStream,
        PackageVersionContentSource pvcs) {
    PackageVersionContentSourcePK pk = pvcs.getPackageVersionContentSourcePK();
    int contentSourceId = pk.getContentSource().getId();
    int packageVersionId = pk.getPackageVersion().getId();
    String packageVersionLocation = pvcs.getLocation();

    PackageBits packageBits = null;

    try {

        Connection conn = null;
        PreparedStatement ps = null;
        PreparedStatement ps2 = null;
        try {
            packageBits = createPackageBits(pk.getContentSource().getDownloadMode() == DownloadMode.DATABASE);

            PackageVersion pv = entityManager.find(PackageVersion.class, packageVersionId);
            pv.setPackageBits(packageBits); // associate entities
            entityManager.flush(); // not sure this is necessary

            if (pk.getContentSource().getDownloadMode() == DownloadMode.DATABASE) {
                packageBits = entityManager.find(PackageBits.class, packageBits.getId());

                conn = dataSource.getConnection();
                //we are loading the PackageBits saved in the previous step
                //we need to lock the row which will be updated so we are using FOR UPDATE
                ps = conn.prepareStatement(
                        "SELECT BITS FROM " + PackageBits.TABLE_NAME + " WHERE ID = ? FOR UPDATE");
                ps.setInt(1, packageBits.getId());
                ResultSet rs = ps.executeQuery();
                try {
                    while (rs.next()) {

                        //We can not create a blob directly because BlobImpl from Hibernate is not acceptable
                        //for oracle and Connection.createBlob is not working on postgres.
                        //This blob will be not empty because we saved there a bytes from String("a").
                        Blob blb = rs.getBlob(1);

                        StreamUtil.copy(bitsStream, blb.setBinaryStream(1), false);
                        bitsStream.close();
                        ps2 = conn.prepareStatement(
                                "UPDATE " + PackageBits.TABLE_NAME + " SET bits = ? where id = ?");
                        ps2.setBlob(1, blb);
                        ps2.setInt(2, packageBits.getId());
                        if (ps2.execute()) {
                            throw new Exception("Did not download the package bits to the DB for ");
                        }
                        ps2.close();
                    }
                } finally {
                    rs.close();
                }
                ps.close();
                conn.close();

            } else {
                //CONTENT IS ALLREADY LOADED
            }
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Exception e) {
                    log.warn("Failed to close prepared statement for package bits [" + packageVersionLocation
                            + "] on content source [" + contentSourceId + "]");
                }
            }

            if (ps2 != null) {
                try {
                    ps2.close();
                } catch (Exception e) {
                    log.warn("Failed to close prepared statement for package bits [" + packageVersionLocation
                            + "] on content source [" + contentSourceId + "]");
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    log.warn("Failed to close connection for package bits [" + packageVersionLocation
                            + "] on content source [" + contentSourceId + "]");
                }
            }
        }
    } catch (Throwable t) {
        // put the cause in here using ThrowableUtil because it'll dump SQL nextException messages too
        throw new RuntimeException("Did not download the package bits for [" + pvcs + "]. Cause: "
                + ThrowableUtil.getAllMessages(t), t);
    } finally {
        if (bitsStream != null) {
            try {
                bitsStream.close();
            } catch (Exception e) {
                log.warn("Failed to close stream to package bits located at [" + packageVersionLocation
                        + "] on content source [" + contentSourceId + "]");
            }
        }
    }

    return packageBits;
}