Example usage for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRED

List of usage examples for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRED

Introduction

In this page you can find the example usage for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRED.

Prototype

int PROPAGATION_REQUIRED

To view the source code for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRED.

Click Source Link

Document

Support a current transaction; create a new one if none exists.

Usage

From source file:edu.ur.hibernate.ir.file.db.FileVersionDAOTest.java

/**
 * Test add a file to an Version/*w w  w  .  ja  v  a 2 s  .com*/
 * @throws LocationAlreadyExistsException 
 */
@Test
public void versionAddFileDAOTest() throws IllegalFileSystemNameException, LocationAlreadyExistsException {

    // Start the transaction 
    TransactionDefinition td = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus ts = tm.getTransaction(td);

    RepositoryBasedTestHelper repoHelper = new RepositoryBasedTestHelper(ctx);
    Repository repo = repoHelper.createRepository("localFileServer", "displayName", "file_database",
            "my_repository", properties.getProperty("a_repo_path"), "default_folder");

    // save the repository commit transaction
    tm.commit(ts);

    // Start the transaction 
    ts = tm.getTransaction(td);

    // create the first file to store in the temporary folder
    String tempDirectory = properties.getProperty("ir_hibernate_temp_directory");
    File directory = new File(tempDirectory);

    // helper to create the file
    FileUtil testUtil = new FileUtil();
    testUtil.createDirectory(directory);

    File f = testUtil.creatFile(directory, "testFile",
            "Hello  - irFile This is text in a file - VersionedFileDAO test");

    // create the file in the file system.
    FileInfo fileInfo1 = repo.getFileDatabase().addFile(f, "newFile1");
    fileInfo1.setDisplayName("displayName1");
    tm.commit(ts);

    // Start the transaction - create a versioned file with a new version
    ts = tm.getTransaction(td);

    UserEmail userEmail = new UserEmail("email");

    IrUser user = new IrUser("aUser", "password");
    user.setPasswordEncoding("encoding");
    user.addUserEmail(userEmail, true);
    userDAO.makePersistent(user);
    VersionedFile vif = new VersionedFile(user, fileInfo1, "new file test");
    FileVersion version = vif.getCurrentVersion();
    versionedFileDAO.makePersistent(vif);
    tm.commit(ts);

    Long irFileId = version.getIrFile().getId();

    // Start the transaction 
    ts = tm.getTransaction(td);
    FileVersion other = versionDAO.getById(version.getId(), false);

    assert other != null : "Other should not be null";
    assert other.getVersionNumber() == version.getVersionNumber() : " Version numbers should be equal";

    versionedFileDAO.makeTransient(versionedFileDAO.getById(vif.getId(), false));
    irFileDAO.makeTransient(irFileDAO.getById(irFileId, false));
    userDAO.makeTransient(userDAO.getById(user.getId(), false));
    tm.commit(ts);

    // Start the transaction  - clean up the data
    ts = tm.getTransaction(td);
    repoHelper.cleanUpRepository();
    tm.commit(ts);
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.dao.jdbc.RedactionQueriesJDBCImpl.java

/**
 * Do redaction actions for a redacted item
 *
 * @param childUuids an array of child uuid's to redact
 * @param setToNotViewable whether to also set any shipped biospecimens in the list to not viewable
 *//*from   w ww  .  j  av a  2  s. c o m*/
public void redact(final SqlParameterSource[] childUuids, final boolean setToNotViewable) {

    // start TX
    DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
    transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
    try {
        getSimpleJdbcTemplate().batchUpdate(
                setToNotViewable ? REDACT_SHIPPED_BIOSPECIMEN : REDACT_SHIPPED_BIOSPECIMEN_KEEP_VIEWABLE,
                childUuids);
        if (setToNotViewable) {
            getSimpleJdbcTemplate().batchUpdate(REDACT_BIOSPECIMEN_BARCODE, childUuids);
        }
        if (isCommonSchema) {
            getSimpleJdbcTemplate().batchUpdate(REDACT_UUID_HIERARCHY, childUuids);
        }
        transactionManager.commit(status);
    } catch (Exception ex) {
        transactionManager.rollback(status);
        logger.info(ex.getMessage());
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.dao.jdbc.RedactionQueriesJDBCImpl.java

/**
 * Do rescission actions for a redacted item
 *
 * @param childUuids an array of child uuid's to redact
 *//*  www.ja va  2 s. co  m*/
public void rescind(final SqlParameterSource[] childUuids) {
    // start TX
    DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
    transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
    try {
        getSimpleJdbcTemplate().batchUpdate(RESCIND_SHIPPED_BIOSPECIMEN, childUuids);
        getSimpleJdbcTemplate().batchUpdate(RESCIND_BIOSPECIMEN_BARCODE, childUuids);
        if (isCommonSchema) {
            getSimpleJdbcTemplate().batchUpdate(RESCIND_UUID_HIERARCHY, childUuids);
        }
        transactionManager.commit(status);
    } catch (Exception ex) {
        transactionManager.rollback(status);
        logger.info(ex.getMessage());
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.live.service.BiospecimenMetadataPlatformsJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    logger.debug(" Updating platforms in uuid_hierarchy ");

    // start TX/*from  w  ww  . j a  v  a2 s. com*/
    DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
    transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
    try {
        uuidHierarchyQueries.deletePlatforms();
        uuidHierarchyQueries.updateAllUUIDHierarchyPlatforms();
        uuidHierarchyQueries.deduplicatePlatforms();
        transactionManager.commit(status);
    } catch (Exception e) {
        transactionManager.rollback(status);
        String errorMessage = "Unable to update platforms for uuid_hierarchy table due to an unexpected condition";
        // email full stack trace                
        sendErrorEmail(e, errorMessage);
        throw new JobExecutionException(errorMessage, e);
    }
}

From source file:hoot.services.controllers.job.ReviewResource.java

/**
 * <NAME>Conflated Data Review Service Mark Items as Reviewed</NAME>
 * <DESCRIPTION>/*w  w w.  j av a  2 s  .  co m*/
 *    After editing reviewable items, this method is called to mark the items as having been reviewed.
 * The inputs to the service method are either a JSON structure which describes the status of the review for
 * each reviewed item, or when setting a boolean true to mark all items as reviewed the structure is not required.
 * Also optionally for convenience sake, a OSM XML changeset may be included in the request to upload a
 * changeset in the same call which marks data as reviewed. If a changeset is uploaded, the service
 * automatically creates and closes the changeset that stores the uploaded data. The response from the server contains
 * the outcome of the changeset upload and the changeset ID created (if a changeset was uploaded) as well as the number
 * of submitted items that were actually marked as reviewed. Clients can compare this number to the number of
 *  items sent for review, and if they are not equal, further troubleshooting should occur.
 *  For each item in the reviewed items JSON, the service will:
 *  mark the reviewable item as reviewed, so that it will not be returned for review again
 *  append the UUID of the item the reviewed item was reviewed against to its "uuid" OSM tag
 *   remove the UUID of the item reviewed against from the "hoot:review:uuid" OSM tag of the reviewed item
 *   remove all OSM review tags from the reviewed item, if it no longer contains items to be reviewed against
 *   The caller is responsible for doing the following things, as the service will not automatically do them:
 *   Adding the "changeset" XML attribute to the elements in the XML changeset being uploaded, as is required by
 *    the standard OSM changeset upload service. The changeset ID attribute value may either be blank or populated with a number,
 *     however, the changeset ID will be overwritten with the ID of the changeset created by the service method execution.
 * </DESCRIPTION>
 * <PARAMETERS>
 *    <mapId>
 *    string; required; ID string or unique name of the map associated with the reviewable conflated data
 *    </mapId>
 *  <markAll>
 *  boolean; optional; defaults to false; indicates whether all items belonging to the map should be marked as reviewed
 *  </markAll>
 *  <markItemsReviewedRequest>
 *   JSON object; sent in request body payload; required; object is made up of:
 *   reviewedItems - JSON object; required if markAll is set to false; optional otherwise; lists the items which should be marked as reviewed
 *   reviewedItemsChangeset - XML string; optional; OSM changeset XML
 *  </markItemsReviewedRequest>
 * </PARAMETERS>
 * <OUTPUT>
 *    A number string to show how many items were marked as reviewed as a result of the service call.
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/job/review?mapId=1&markAll=false</URL>
 *    <REQUEST_TYPE>PUT</REQUEST_TYPE>
 *    <INPUT>
 * {
 *   "reviewedItems":
 *   [
 *     {
 *       "id": 2402,
 *       "type": "way",
 *       "reviewedAgainstId": 2403,
 *       "reviewedAgainstType": "way",
 *     },
 *     {
 *       "id": 2404,
 *       "type": "way",
 *       "reviewedAgainstId": 2405,
 *       "reviewedAgainstType": "way",
 *     },
 *   ]
 * }
 *   </INPUT>
 * <OUTPUT>
 * 2
 * </OUTPUT>
 * </EXAMPLE>
*
* Marks a set of reviewable items as reviewed and updates the tags of their corresponding OSM
* elements
*
* @param reviewItemsChangeset an OSM changeset to be uploaded into the services database
* @param mapId ID of the map for which items are being marked as reviewed
* @return the number of items marked as reviewed
* @throws Exception
* @see https://insightcloud.digitalglobe.com/redmine/projects/hootenany/wiki/User_-_Conflated_Data_Review_Service_2#Mark-Items-as-Reviewed
*/
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public MarkItemsReviewedResponse markItemsReviewed(MarkItemsReviewedRequest markItemsReviewedRequest,
        @QueryParam("mapId") String mapId, @DefaultValue("false") @QueryParam("markAll") boolean markAll)
        throws Exception {
    Connection conn = DbUtils.createConnection();
    final String errorMessageStart = "marking items as reviewed";
    MarkItemsReviewedResponse markItemsReviewedResponse = null;
    try {
        log.debug("markItemsReviewedRequest: " + markItemsReviewedRequest.toString());

        Map<String, Object> inputParams = new HashMap<String, Object>();
        inputParams.put("mapId", mapId);
        inputParams.put("markAll", markAll);
        ReviewInputParamsValidator inputParamsValidator = new ReviewInputParamsValidator(inputParams);
        mapId = (String) inputParamsValidator.validateAndParseInputParam("mapId", "", null, null, false, null);
        markAll = (Boolean) inputParamsValidator.validateAndParseInputParam("markAll", false, null, null, true,
                false);
        if (!markAll && (markItemsReviewedRequest.getReviewedItems() == null
                || markItemsReviewedRequest.getReviewedItems().getReviewedItems() == null
                || markItemsReviewedRequest.getReviewedItems().getReviewedItems().length == 0)) {
            throw new Exception("Invalid input parameter: markAll set to false and "
                    + "markItemsReviewedRequest.reviewedItems empty.");
        }

        log.debug("Initializing database connection...");

        log.debug("Intializing transaction...");
        TransactionStatus transactionStatus = transactionManager
                .getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
        conn.setAutoCommit(false);

        try {
            markItemsReviewedResponse = (new ReviewItemsMarker(conn, mapId))
                    .markItemsReviewed(markItemsReviewedRequest, markAll);
        } catch (Exception e) {
            log.debug("Rolling back database transaction for ReviewResource::markItemsAsReviewed...");
            transactionManager.rollback(transactionStatus);
            conn.rollback();
            throw e;
        }

        log.debug("Committing ReviewResource::markItemsAsReviewed. database transaction...");
        transactionManager.commit(transactionStatus);
        conn.commit();
    } catch (Exception e) {
        ReviewUtils.handleError(e, errorMessageStart, false);
    } finally {
        try {
            conn.setAutoCommit(true);
            DbUtils.closeConnection(conn);
        } catch (Exception e) {
            ReviewUtils.handleError(e, errorMessageStart, false);
        }
    }

    //TODO: MarkItemsReviewedResponse toString() not working
    //    if (markItemsReviewedResponse != null)
    //    {
    //      log.debug("Returning mark items reviewed response: " +
    //        StringUtils.abbreviate(markItemsReviewedResponse.toString(), 100) + " ...");
    //    }

    return markItemsReviewedResponse;
}

From source file:hoot.services.controllers.osm.ChangesetResource.java

/**
  * <NAME>Changeset Create</NAME>
  * <DESCRIPTION>//from   w  ww .  j  a v a2s.c  o  m
  * The Hootenanny Changeset Service implements a subset of the OSM
  * Changeset Service v0.6. It supports the OSM changeset upload process only.
  * It does not support the browsing of changeset contents.
  * </DESCRIPTION>
  * <PARAMETERS>
  *  <mapId>
  *  string; ID or name of the map to which the created changeset will belong
  *  </mapId>
  *  <changesetData>
  *  XML; payload data; an empty OSM xml changeset
  *  </changesetData>
  * </PARAMETERS>
  * <OUTPUT>
  *    ID of the created changeset
  * </OUTPUT>
  * <EXAMPLE>
  *    <URL>http://localhost:8080/hoot-services/osm/api/0.6/changeset/create?mapId=dc-admin</URL>
  *    <REQUEST_TYPE>PUT</REQUEST_TYPE>
  *    <INPUT>
  * Changeset OSM XML
  * See https://insightcloud.digitalglobe.com/redmine/projects/hootenany/wiki/User_-_OsmChangesetService#Changeset-Create
  *   </INPUT>
  * <OUTPUT>
  * 1
  * </OUTPUT>
  * </EXAMPLE>
 *
 * Service method endpoint for creating a new OSM changeset
 * 
 * @param changeset changeset create data
 * @param mapId ID of the map the changeset belongs to
 * @return Response containing the ID assigned to the new changeset
 * @throws Exception 
 * @todo why can't I get changesetData in as an XML doc?
 * @todo update for parsing multiple changesets in one request (#2894): duplicated changeset tag 
   keys are allowed but later changeset tag keys overwrite earlier ones; isn't that contradictory
   with the rest of the logic in this method?
 * @see https://insightcloud.digitalglobe.com/redmine/projects/hootenany/wiki/User_-_OsmChangesetService#Changeset-Create
 */
@PUT
@Path("/create")
@Consumes(MediaType.TEXT_XML)
@Produces(MediaType.TEXT_PLAIN)
public Response create(final String changesetData, @QueryParam("mapId") final String mapId) throws Exception {
    log.debug("Creating changeset for map with ID: " + mapId + " ...");

    Document changesetDoc = null;
    try {
        log.debug("Parsing changeset XML...");
        changesetDoc = XmlDocumentBuilder.parse(changesetData);
    } catch (Exception e) {
        ResourceErrorHandler.handleError("Error parsing changeset XML: "
                + StringUtils.abbreviate(changesetData, 100) + " (" + e.getMessage() + ")", Status.BAD_REQUEST,
                log);
    }

    Connection conn = DbUtils.createConnection();
    long changesetId = -1;
    try {
        log.debug("Initializing database connection...");

        long mapIdNum = -1;
        try {
            QMaps maps = QMaps.maps;
            //input mapId may be a map ID or a map name
            mapIdNum = ModelDaoUtils.getRecordIdForInputString(mapId, conn, maps, maps.id, maps.displayName);
        } catch (Exception e) {
            if (e.getMessage().startsWith("Multiple records exist")) {
                ResourceErrorHandler.handleError(
                        e.getMessage().replaceAll("records", "maps").replaceAll("record", "map"),
                        Status.NOT_FOUND, log);
            } else if (e.getMessage().startsWith("No record exists")) {
                ResourceErrorHandler.handleError(
                        e.getMessage().replaceAll("records", "maps").replaceAll("record", "map"),
                        Status.NOT_FOUND, log);
            }
            ResourceErrorHandler.handleError(
                    "Error requesting map with ID: " + mapId + " (" + e.getMessage() + ")", Status.BAD_REQUEST,
                    log);
        }

        long userId = -1;
        try {
            assert (mapIdNum != -1);
            log.debug("Retrieving user ID associated with map having ID: " + String.valueOf(mapIdNum) + " ...");

            QMaps maps = QMaps.maps;

            SQLQuery query = new SQLQuery(conn, DbUtils.getConfiguration());

            userId = query.from(maps).where(maps.id.eq(mapIdNum)).singleResult(maps.userId);

            log.debug("Retrieved user ID: " + userId);
        } catch (Exception e) {
            ResourceErrorHandler.handleError(
                    "Error locating user associated with map for changeset data: "
                            + StringUtils.abbreviate(changesetData, 100) + " (" + e.getMessage() + ")",
                    Status.BAD_REQUEST, log);
        }

        log.debug("Intializing transaction...");
        TransactionStatus transactionStatus = transactionManager
                .getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
        conn.setAutoCommit(false);

        try {
            changesetId = Changeset.createChangeset(changesetDoc, mapIdNum, userId, conn);
        } catch (Exception e) {
            log.error("Rolling back the database transaction...");
            transactionManager.rollback(transactionStatus);
            conn.rollback();

            ResourceErrorHandler.handleError("Error creating changeset: (" + e.getMessage() + ") "
                    + StringUtils.abbreviate(changesetData, 100), Status.BAD_REQUEST, log);
        }

        log.debug("Committing the database transaction...");
        transactionManager.commit(transactionStatus);
        conn.commit();
    } finally {
        conn.setAutoCommit(true);
        DbUtils.closeConnection(conn);
    }

    log.debug("Returning ID: " + changesetId + " for new changeset...");
    return Response.ok(String.valueOf(changesetId), MediaType.TEXT_PLAIN)
            .header("Content-type", MediaType.TEXT_PLAIN).build();
}

From source file:hoot.services.controllers.osm.ChangesetResource.java

/**
 * Service method endpoint for uploading OSM changeset diff data
 * //from  w w w .ja  va 2 s  .co  m
 * @param changeset OSM changeset diff data
 * @param changesetId ID of the changeset being uploaded; changeset with the ID must already exist
 * @return response acknowledging the result of the update operation with updated entity ID 
 * information
 * @throws Exception
 * @see http://wiki.openstreetmap.org/wiki/API_0.6 and 
 * http://wiki.openstreetmap.org/wiki/OsmChange
 * @todo why can't I pass in changesetDiff as an XML doc instead of a string?
 */
@POST
@Path("/{changesetId}/upload")
@Consumes(MediaType.TEXT_XML)
@Produces(MediaType.TEXT_XML)
public Response upload(final String changeset, @PathParam("changesetId") final long changesetId,
        @QueryParam("mapId") final String mapId) throws Exception {
    Connection conn = DbUtils.createConnection();
    Document changesetUploadResponse = null;
    try {
        log.debug("Intializing database connection...");

        log.debug("Intializing changeset upload transaction...");
        TransactionStatus transactionStatus = transactionManager
                .getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
        conn.setAutoCommit(false);

        try {
            if (mapId == null) {
                throw new Exception("Invalid map id.");
            }
            long mapid = Long.parseLong(mapId);
            changesetUploadResponse = (new ChangesetDbWriter(conn)).write(mapid, changesetId, changeset);
        } catch (Exception e) {
            log.error("Rolling back transaction for changeset upload...");
            transactionManager.rollback(transactionStatus);
            conn.rollback();
            handleError(e, changesetId, StringUtils.abbreviate(changeset, 100));
        }

        log.debug("Committing changeset upload transaction...");
        transactionManager.commit(transactionStatus);
        conn.commit();
    } finally {
        conn.setAutoCommit(true);
        DbUtils.closeConnection(conn);
    }

    log.debug("Returning changeset upload response: "
            + StringUtils.abbreviate(XmlDocumentBuilder.toString(changesetUploadResponse), 100) + " ...");
    return Response.ok(new DOMSource(changesetUploadResponse), MediaType.TEXT_XML)
            .header("Content-type", MediaType.TEXT_XML).build();
}

From source file:hoot.services.controllers.wps.MarkItemsReviewedProcesslet.java

@Override
public void process(ProcessletInputs inputParams, ProcessletOutputs outputParams,
        ProcessletExecutionInfo processletExecInfo) throws ProcessletException {
    final String errorMessageStart = "marking items as reviewed";
    Connection conn = DbUtils.createConnection();
    MarkItemsReviewedResponse markItemsReviewedResponse = null;
    try {//from  w  ww .j  av a2s.  c o m
        //Any changes to these default parameters must also be reflected in 
        //$HOOT_HOME/hoot-services/src/main/webapp/WEB-INF/workspace/MarkItemsReviewedProcesslet.xml
        //and vice versa.
        ReviewInputParamsValidator inputParamsValidator = new ReviewInputParamsValidator(inputParams);
        final String mapId = (String) inputParamsValidator.validateAndParseInputParam("mapId", "", null, null,
                false, null);
        final boolean markAll = (Boolean) inputParamsValidator.validateAndParseInputParam("markAll", false,
                null, null, true, false);
        final String reviewedItemsStr = (String) inputParamsValidator
                .validateAndParseInputParam("reviewedItems", "", null, null, true, null);
        ReviewedItems reviewedItems = null;
        if (reviewedItemsStr != null) {
            reviewedItems = (new ObjectMapper()).readValue(reviewedItemsStr, ReviewedItems.class);
        }
        if (!markAll && (reviewedItems == null || reviewedItems.getReviewedItems() == null
                || reviewedItems.getReviewedItems().length == 0)) {
            throw new Exception("Invalid input parameter: markAll set to false and "
                    + "markItemsReviewedRequest.reviewedItems empty.");
        }
        final String reviewedItemsChangesetStr = (String) inputParamsValidator
                .validateAndParseInputParam("reviewedItemsChangeset", "", null, null, true, "");
        MarkItemsReviewedRequest markItemsReviewedRequest = new MarkItemsReviewedRequest();
        markItemsReviewedRequest.setReviewedItems(reviewedItems);
        markItemsReviewedRequest.setReviewedItemsChangeset(reviewedItemsChangesetStr);

        log.debug("Initializing transaction manager...");
        PlatformTransactionManager transactionManager = appContext.getBean("transactionManager",
                PlatformTransactionManager.class);

        log.debug("Initializing database connection...");

        //TODO: verify that no other writes are seen during this transaction

        log.debug("Intializing transaction...");
        TransactionStatus transactionStatus = transactionManager
                .getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
        conn.setAutoCommit(false);

        try {
            markItemsReviewedResponse = (new ReviewItemsMarker(conn, mapId))
                    .markItemsReviewed(markItemsReviewedRequest, markAll);
        } catch (Exception e) {
            log.debug("Rolling back database transaction for MarkItemsReviewedProcesslet...");
            transactionManager.rollback(transactionStatus);
            conn.rollback();
            throw e;
        }

        log.debug("Committing MarkItemsReviewedProcesslet database transaction...");
        transactionManager.commit(transactionStatus);
        conn.commit();

        if (StringUtils.trimToNull(markItemsReviewedResponse.getChangesetUploadResponse()) != null) {
            log.debug("Returning changeset upload response: "
                    + StringUtils.abbreviate(markItemsReviewedResponse.getChangesetUploadResponse(), 100)
                    + " ...");
        } else {
            log.debug("Returning null changeset upload response...");
        }
        ((LiteralOutput) outputParams.getParameter("changesetUploadResponse"))
                .setValue(markItemsReviewedResponse.getChangesetUploadResponse());
        log.debug("Returning number of items marked as reviewed: "
                + markItemsReviewedResponse.getNumItemsMarkedReviewed() + " ...");
        ((LiteralOutput) outputParams.getParameter("numItemsMarkedReviewed"))
                .setValue(String.valueOf(markItemsReviewedResponse.getNumItemsMarkedReviewed()));
        log.debug("Returning changeset ID: " + markItemsReviewedResponse.getChangesetId() + " ...");
        ((LiteralOutput) outputParams.getParameter("changesetId"))
                .setValue(String.valueOf(markItemsReviewedResponse.getChangesetId()));
    } catch (Exception e) {
        try {
            ReviewUtils.handleError(e, errorMessageStart, true);
        } catch (Exception e2) {
            throw (ProcessletException) e2;
        }
    } finally {
        try {
            conn.setAutoCommit(true);
            DbUtils.closeConnection(conn);
        } catch (Exception e) {
            try {
                ReviewUtils.handleError(e, errorMessageStart, true);
            } catch (Exception e2) {
                throw (ProcessletException) e2;
            }
        }
    }
}

From source file:hoot.services.writers.review.ReviewPrepareDbWriter.java

/**
 * Prepares a map's conflated data for review
 *
 * @param command input parameters containing a map and job ID
 * @throws Exception/* w w w .  ja  v a2  s .co m*/
 */
public void exec(JSONObject command) throws Exception {
    if (command.containsKey("testDelayMilliseconds")) {
        Thread.sleep((Long) command.get("testDelayMilliseconds"));
    }
    if (command.containsKey("simulateFailure")) {
        simulateFailure = (Boolean) command.get("simulateFailure");
    }

    mapId = (Long) command.get("mapId");
    final String jobId = (String) command.get("jobId");
    log.debug("Executing review prepare job with ID: " + jobId + " for map with ID: " + String.valueOf(mapId)
            + " ...");

    //TODO: verify that no other writes are seen during this transaction

    try {
        log.debug("Initializing database driver...");
        conn = DbUtils.createConnection();

        log.debug("Intializing ReviewDbPreparer transaction...");
        TransactionStatus transactionStatus = transactionManager
                .getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
        conn.setAutoCommit(false);

        try {
            //see if map review info for this map already exists
            final ReviewMap mapReviewInfo = new SQLQuery(conn, DbUtils.getConfiguration(mapId)).from(reviewMap)
                    .where(reviewMap.mapId.eq(mapId)).singleResult(reviewMap);

            if (mapReviewInfo == null) {
                //if not, add new entry to review_map table
                ReviewMap mapReviewInfoRecord = new ReviewMap();
                mapReviewInfoRecord.setMapId(mapId);
                mapReviewInfoRecord.setReviewPrepareJobId((String) command.get("jobId"));
                /* if (mapReviewInfoRecord.insert() != 1)
                 {
                   throw new Exception("Error inserting map review info.");
                 }*/

                SQLInsertClause insert = new SQLInsertClause(conn, DbUtils.getConfiguration(mapId), reviewMap);
                if (insert.populate(mapReviewInfoRecord).execute() != 1) {
                    throw new Exception("Error inserting map review info.");
                }
            } else {
                //if so, overwrite any existing unreviewed data
                deleteExistingUnreviewedItems(mapId);

                //and then write new job id to the review map table
                SQLUpdateClause update = new SQLUpdateClause(conn, DbUtils.getConfiguration(mapId), reviewMap);

                if (update.where(reviewMap.mapId.eq(mapId)).set(reviewMap.reviewPrepareJobId, jobId)
                        .execute() != 1) {
                    throw new Exception("Error updating job entry in review table.");
                }

            }

            //two passes through the data have to be made; one to create the mappings from the unique
            //id's to the osm element id's and then a second to parse the review tags; there might
            //be a way to do this in one pass...

            getPreviouslyReviewedRecords();
            totalParseableRecords = getTotalParseableRecords(mapId);
            totalReviewableRecords = getTotalReviewableRecords(mapId);
            final boolean uuidsExist = parseElementUniqueIdTags(mapId);

            boolean reviewableItemsExist = false;
            final String noRecordsParsedMessage = "No records available for review for map with ID: " + mapId;
            if (!uuidsExist) {
                log.warn("Parsing unique element ID's: " + noRecordsParsedMessage);
            } else {
                //read the review tags from the OSM elements and write their data to services db review
                //tables
                reviewableItemsExist = parseElementReviewTags(mapId);
                if (!reviewableItemsExist) {
                    log.warn("Parsing review tags: " + noRecordsParsedMessage);
                }
            }
            if (!uuidsExist || !reviewableItemsExist) {
                finalStatusDetail = noRecordsParsedMessage;
            } else {
                finalStatusDetail = "Reviewable records successfully prepared.";
            }

            //There may be element id's written as a result of parseElementUniqueIdTags that don't
            //have associated review item records, because of the two pass write operation.  They
            //aren't currently hurting anything by existing and will be ignored, but its a good idea
            //to clean them out.
            removeUnusedElementIdMappings();
        } catch (Exception e) {
            log.debug("Rolling back transaction for ReviewDbPreparer...");
            //transactionManager.rollback(transactionStatus);
            transactionManager.rollback(transactionStatus);
            conn.rollback();
            throw e;
        }

        log.debug("Committing ReviewDbPreparer database transaction...");
        //transactionManager.commit(transactionStatus);
        transactionManager.commit(transactionStatus);
        conn.commit();
    } finally {
        conn.setAutoCommit(true);
        DbUtils.closeConnection(conn);
    }
}

From source file:info.jtrac.repository.HibernateJtracDao.java

/**
 * note that this is automatically configured to run on startup
 * as a spring bean "init-method"//from w  w w  .j av a  2 s.c o  m
 */
@PostConstruct
@Transactional(propagation = Propagation.REQUIRED)
public void createSchema() {
    try {
        entityManager.createQuery("from " + Item.class.getName() + " item where item.id = 1", Item.class)
                .getResultList();
        logger.info("database schema exists, normal startup");
    } catch (Exception e) {
        logger.warn("expected database schema does not exist, will create. Error is: " + e.getMessage());
        schemaHelper.createSchema();
        logger.info("inserting default admin user into database");
        TransactionStatus transactionStatus = transactionManager
                .getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
        storeUser(createAdminUser());
        transactionManager.commit(transactionStatus);
        logger.info("schema creation complete");
    }
    TransactionStatus transactionStatus = transactionManager
            .getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
    List<SpaceSequence> ssList = entityManager
            .createQuery("FROM " + SpaceSequence.class.getName(), SpaceSequence.class).getResultList();
    Map<Long, SpaceSequence> ssMap = new HashMap<Long, SpaceSequence>(ssList.size());
    for (SpaceSequence ss : ssList) {
        ssMap.put(ss.getId(), ss);
    }
    //      entityManager.flush();
    //      entityManager.createQuery("FROM User").getResultList()
    @SuppressWarnings("unchecked")
    List<Object[]> list = entityManager
            .createQuery("select item.space.id, max(item.sequenceNum) from Item item group by item.space.id")
            .getResultList();
    for (Object[] oa : list) {
        Long spaceId = (Long) oa[0];
        Long maxSeqNum = (Long) oa[1];
        SpaceSequence ss = ssMap.get(spaceId);
        logger.info("checking space sequence id: " + spaceId + ", max: " + maxSeqNum + ", next: "
                + ss.getNextSeqNum());
        if (ss.getNextSeqNum() <= maxSeqNum) {
            logger.warn("fixing sequence number for space id: " + spaceId + ", was: " + ss.getNextSeqNum()
                    + ", should be: " + (maxSeqNum + 1));
            ss.setNextSeqNum(maxSeqNum + 1);
            entityManager.merge(ss);
        }
    }
    transactionManager.commit(transactionStatus);
}