List of usage examples for org.springframework.jdbc.datasource DataSourceTransactionManager DataSourceTransactionManager
public DataSourceTransactionManager(DataSource dataSource)
From source file:dao.DashboardDAO.java
public static ObjectNode getPagedOwnershipDatasetsByManagerId(String managerId, String platform, int option, int page, int size) { final DataSourceTransactionManager tm = new DataSourceTransactionManager(getJdbcTemplate().getDataSource()); final TransactionTemplate txTemplate = new TransactionTemplate(tm); return txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { final String datasetQuery; switch (option) { case 1: datasetQuery = GET_OWNERSHIP_CONFIRMED_DATASETS_FILTER_PLATFORM; break; case 2: datasetQuery = GET_OWNERSHIP_UNCONFIRMED_DATASETS_FILTER_PLATFORM; break; case 3: datasetQuery = GET_OWNERSHIP_DATASETS_FILTER_PLATFORM; break; default: datasetQuery = GET_OWNERSHIP_DATASETS_FILTER_PLATFORM; }/*from w ww. j a v a 2 s .co m*/ List<Map<String, Object>> rows = new ArrayList<>(size); long count = getPagedDashboardDatasets(managerId, datasetQuery, platform, null, page, size, rows); List<DashboardDataset> datasets = new ArrayList<>(); for (Map row : rows) { DashboardDataset dashboardDataset = new DashboardDataset(); dashboardDataset.datasetId = (Long) row.get("dataset_id"); dashboardDataset.datasetName = (String) row.get("name"); dashboardDataset.ownerId = (String) row.get("owner_id"); String confirmedOwnerId = (String) row.get("confirmed_owner_id"); if (StringUtils.isBlank(confirmedOwnerId) && option == 1) { confirmedOwnerId = "<other team>"; } dashboardDataset.confirmedOwnerId = confirmedOwnerId; datasets.add(dashboardDataset); } ObjectNode resultNode = Json.newObject(); resultNode.put("status", "ok"); resultNode.put("count", count); resultNode.put("page", page); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); resultNode.set("datasets", Json.toJson(datasets)); return resultNode; } }); }
From source file:org.ohmage.query.impl.ClassQueries.java
@Override public List<String> updateClass(String classId, String className, String classDescription, Map<String, Clazz.Role> userAndRolesToAdd, Collection<String> usersToRemove) throws DataAccessException { // Note: This function is ugly. We need to stop using a class as a // mechanism to add users to a campaign and start using it like a // group, where a user's roles in a campaign are the union of those // given to them directly from the user_role_campaign table and the // roles given to each of the classes to which they belong. // Create the transaction. DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Updating a class."); try {/*from ww w .j a v a 2 s . c o m*/ // Begin the transaction. PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); // Update the name if it's not null. if (className != null) { try { getJdbcTemplate().update(SQL_UPDATE_CLASS_NAME, new Object[] { className, classId }); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error while executing SQL '" + SQL_UPDATE_CLASS_NAME + "' with parameters: " + className + ", " + classId, e); } } // Update the description if it's not null. if (classDescription != null) { try { getJdbcTemplate().update(SQL_UPDATE_CLASS_DESCRIPTION, new Object[] { classDescription, classId }); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error while executing SQL '" + SQL_UPDATE_CLASS_DESCRIPTION + "' with parameters: " + classDescription + ", " + classId, e); } } // If either of the user lists are non-empty, we grab the list of // campaigns associated with the class now as it will be needed, // and we don't want to grab it multiple times. List<String> campaignIds = Collections.emptyList(); if ((usersToRemove != null) || (userAndRolesToAdd != null)) { try { campaignIds = campaignClassQueries.getCampaignsAssociatedWithClass(classId); } catch (DataAccessException e) { transactionManager.rollback(status); throw e; } } // Delete the users before adding the new ones. This facilitates // upgrading a user from one role to another. if (usersToRemove != null) { for (String username : usersToRemove) { // Get the user's role in the class before removing // it. Clazz.Role classRole; try { classRole = userClassQueries.getUserClassRole(classId, username); } catch (DataAccessException e) { transactionManager.rollback(status); throw e; } // To prevent a concurrency bug, the user may have already // been deleted from the class which will be indicated by // having a null value for the role. When this happens, we // may continue on with the next user. if (classRole == null) { continue; } // Remove the user from the class. try { getJdbcTemplate().update(SQL_DELETE_USER_FROM_CLASS, new Object[] { username, classId }); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error while executing SQL '" + SQL_DELETE_USER_FROM_CLASS + "' with parameters: " + username + ", " + classId, e); } // For all of the campaigns associated with the class, see // if the user is associated with any of them in any other // capacity, and, if not, dissociate them from the // campaign. for (String campaignId : campaignIds) { // If they are associated with the campaign through // no classes, then we are going to remove any // campaign-class associations that may exist. int numClasses; try { numClasses = userCampaignClassQueries .getNumberOfClassesThroughWhichUserIsAssociatedWithCampaign(username, campaignId); } catch (DataAccessException e) { transactionManager.rollback(status); throw e; } if (numClasses == 0) { // Get the default roles which are to be revoked // from the user. List<Campaign.Role> defaultRoles; try { defaultRoles = campaignClassQueries .getDefaultCampaignRolesForCampaignClass(campaignId, classId, classRole); } catch (DataAccessException e) { transactionManager.rollback(status); throw e; } // For each of the default roles, remove that role // from the user. for (Campaign.Role defaultRole : defaultRoles) { try { getJdbcTemplate().update(SQL_DELETE_USER_FROM_CAMPAIGN, new Object[] { username, campaignId, defaultRole.toString() }); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error executing SQL '" + SQL_DELETE_USER_FROM_CAMPAIGN + "' with parameters: " + username + ", " + campaignId + ", " + defaultRole, e); } } } } } } // Create the list of warning messages to be returned to the // caller. List<String> warningMessages = new LinkedList<String>(); // Add the users to the class. if (userAndRolesToAdd != null) { for (String username : userAndRolesToAdd.keySet()) { // Get the user's (new) role. Clazz.Role role = userAndRolesToAdd.get(username); boolean addDefaultRoles = false; try { if (!userClassQueries.userBelongsToClass(classId, username)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "The user did not exist in the class so the user is being added before any updates are attemped."); } getJdbcTemplate().update(SQL_INSERT_USER_CLASS, new Object[] { username, classId, role.toString() }); addDefaultRoles = true; } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "The user already has a role in the class so only updates will be performed."); } // Get the user's current role. Clazz.Role originalRole = null; try { originalRole = userClassQueries.getUserClassRole(classId, username); } catch (DataAccessException e) { transactionManager.rollback(status); throw e; } // If their new role is the same as their old role, we // will ignore this update. if (!role.equals(originalRole)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Changing user's class role from " + originalRole + " to " + role); } // Update their role to the new role. try { if (getJdbcTemplate().update(SQL_UPDATE_USER_CLASS, new Object[] { role.toString(), username, classId }) > 0) { warningMessages.add("The user '" + username + "' was already associated with the class '" + classId + "'. Their role has been updated from '" + originalRole + "' to '" + role + "'"); } } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error while executing SQL '" + SQL_UPDATE_USER_CLASS + "' with parameters: " + role + ", " + username + ", " + classId, e); } // For each of the campaigns associated with this // class, for (String campaignId : campaignIds) { // If they are only associated with this // campaign in this class. int numClasses; try { numClasses = userCampaignClassQueries .getNumberOfClassesThroughWhichUserIsAssociatedWithCampaign( username, campaignId); } catch (DataAccessException e) { transactionManager.rollback(status); throw e; } if (numClasses == 1) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("The user only belonged to the campaign " + campaignId + " via one class" + " and their class role is changing so all default campaign roles are being deleted."); } // Remove the current roles with the // campaign and add a new role with the // campaign. List<Campaign.Role> defaultRoles; try { defaultRoles = campaignClassQueries .getDefaultCampaignRolesForCampaignClass(campaignId, classId, originalRole); } catch (DataAccessException e) { transactionManager.rollback(status); throw e; } for (Campaign.Role defaultRole : defaultRoles) { try { getJdbcTemplate().update(SQL_DELETE_USER_FROM_CAMPAIGN, new Object[] { username, campaignId, defaultRole.toString() }); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error executing SQL '" + SQL_DELETE_USER_FROM_CAMPAIGN + "' with parameters: " + username + ", " + campaignId + ", " + defaultRole, e); } } } addDefaultRoles = true; } } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Nothing to do because the user's class role is not changing."); } } } } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error while executing SQL '" + SQL_INSERT_USER_CLASS + "' with parameters: " + username + ", " + classId + ", " + role, e); } catch (DataAccessException e) { transactionManager.rollback(status); throw e; } if (addDefaultRoles) { // For each of the campaign's associated with the // class, add them to the campaign with the default // roles. for (String campaignId : campaignIds) { List<Campaign.Role> defaultRoles; try { defaultRoles = campaignClassQueries .getDefaultCampaignRolesForCampaignClass(campaignId, classId, role); } catch (DataAccessException e) { transactionManager.rollback(status); throw e; } for (Campaign.Role defaultRole : defaultRoles) { try { final Object[] params = new Object[] { username, campaignId, defaultRole.toString() }; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Assigning the user a default campaign role of " + defaultRole + " in campaign " + campaignId); } // The user may already have the role in // the campaign via another class or the // user may have not been in any class // at all. if (!userCampaignQueries.getUserCampaignRoles(username, campaignId) .contains(defaultRole)) { getJdbcTemplate().update(SQL_INSERT_USER_CAMPAIGN, params); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("User already has this role in the campaign: " + Arrays.asList(params)); } } } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error executing SQL '" + SQL_INSERT_USER_CAMPAIGN + "' with parameters: " + username + ", " + campaignId + ", " + defaultRole, e); } catch (DataAccessException e) { transactionManager.rollback(status); throw e; } } } } } } // Commit the transaction. try { transactionManager.commit(status); } catch (TransactionException e) { transactionManager.rollback(status); throw new DataAccessException("Error while committing the transaction.", e); } return warningMessages; } catch (TransactionException e) { throw new DataAccessException("Error while attempting to rollback the transaction.", e); } }
From source file:dao.DashboardDAO.java
public static ObjectNode getPagedConfidentialDatasetsByManagerId(String managerId, String platform, int page, int size) { DataSourceTransactionManager tm = new DataSourceTransactionManager(getJdbcTemplate().getDataSource()); TransactionTemplate txTemplate = new TransactionTemplate(tm); return txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { List<Map<String, Object>> rows = new ArrayList<>(size); long count = getPagedDashboardDatasets(managerId, GET_CONFIDENTIAL_DATASETS_FILTER_PLATFORM, platform, null, page, size, rows); List<DashboardDataset> datasets = new ArrayList<>(); for (Map row : rows) { DashboardDataset dashboardDataset = new DashboardDataset(); dashboardDataset.datasetId = (Long) row.get("dataset_id"); dashboardDataset.datasetName = (String) row.get("name"); dashboardDataset.ownerId = (String) row.get("owner_id"); if (dashboardDataset.datasetId != null && dashboardDataset.datasetId > 0) { dashboardDataset.fields = getJdbcTemplate().queryForList( GET_CONFIDENTIAL_FIELDS_BY_DATASET_ID, String.class, dashboardDataset.datasetId); }//from ww w . ja v a 2s .co m datasets.add(dashboardDataset); } ObjectNode resultNode = Json.newObject(); resultNode.put("status", "ok"); resultNode.put("count", count); resultNode.put("page", page); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); resultNode.set("datasets", Json.toJson(datasets)); return resultNode; } }); }
From source file:dao.SearchDAO.java
public static ObjectNode getPagedDatasetByKeyword(String category, String keyword, String source, int page, int size) { List<Dataset> pagedDatasets = new ArrayList<Dataset>(); final JdbcTemplate jdbcTemplate = getJdbcTemplate(); javax.sql.DataSource ds = jdbcTemplate.getDataSource(); DataSourceTransactionManager tm = new DataSourceTransactionManager(ds); TransactionTemplate txTemplate = new TransactionTemplate(tm); ObjectNode result;/* w w w . j a v a 2s.co m*/ result = txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { List<Map<String, Object>> rows = null; if (StringUtils.isBlank(source) || source.toLowerCase().equalsIgnoreCase("all")) { String query = SEARCH_DATASET_WITH_PAGINATION.replace("$keyword", keyword); rows = jdbcTemplate.queryForList(query, (page - 1) * size, size); } else { String query = SEARCH_DATASET_BY_SOURCE_WITH_PAGINATION.replace("$keyword", keyword); rows = jdbcTemplate.queryForList(query, source, (page - 1) * size, size); } for (Map row : rows) { Dataset ds = new Dataset(); ds.id = (Long) row.get(DatasetRowMapper.DATASET_ID_COLUMN); ds.name = (String) row.get(DatasetRowMapper.DATASET_NAME_COLUMN); ds.source = (String) row.get(DatasetRowMapper.DATASET_SOURCE_COLUMN); ds.urn = (String) row.get(DatasetRowMapper.DATASET_URN_COLUMN); ds.schema = (String) row.get(DatasetRowMapper.DATASET_SCHEMA_COLUMN); pagedDatasets.add(ds); } long count = 0; try { count = jdbcTemplate.queryForObject("SELECT FOUND_ROWS()", Long.class); } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } ObjectNode resultNode = Json.newObject(); resultNode.put("count", count); resultNode.put("page", page); resultNode.put("category", category); resultNode.put("source", source); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); resultNode.set("data", Json.toJson(pagedDatasets)); return resultNode; } }); return result; }
From source file:dao.DatasetsDAO.java
public static ObjectNode getPagedDatasets(String urn, Integer page, Integer size, String user) { ObjectNode result = Json.newObject(); Integer userId = UserDAO.getUserIDByUserName(user); javax.sql.DataSource ds = getJdbcTemplate().getDataSource(); DataSourceTransactionManager tm = new DataSourceTransactionManager(ds); TransactionTemplate txTemplate = new TransactionTemplate(tm); final Integer id = userId; result = txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { ObjectNode resultNode = Json.newObject(); List<Dataset> pagedDatasets = new ArrayList<Dataset>(); List<Map<String, Object>> rows = null; if (id != null && id > 0) { if (StringUtils.isBlank(urn)) { rows = getJdbcTemplate().queryForList(SELECT_PAGED_DATASET_BY_CURRENT_USER, (page - 1) * size, size, id, id); } else { rows = getJdbcTemplate().queryForList(SELECT_PAGED_DATASET_BY_URN_CURRENT_USER, urn + "%", (page - 1) * size, size, id, id); }//w w w . ja va 2 s . c o m } else { if (StringUtils.isBlank(urn)) { rows = getJdbcTemplate().queryForList(SELECT_PAGED_DATASET, (page - 1) * size, size); } else { rows = getJdbcTemplate().queryForList(SELECT_PAGED_DATASET_BY_URN, urn + "%", (page - 1) * size, size); } } long count = 0; try { if (StringUtils.isBlank(urn)) { count = getJdbcTemplate().queryForObject(GET_PAGED_DATASET_COUNT, Long.class); } else { count = getJdbcTemplate().queryForObject(GET_PAGED_DATASET_COUNT_BY_URN, Long.class, urn + "%"); } } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } for (Map row : rows) { Dataset ds = new Dataset(); Timestamp modified = (Timestamp) row.get(DatasetWithUserRowMapper.DATASET_MODIFIED_TIME_COLUMN); ds.id = (Long) row.get(DatasetWithUserRowMapper.DATASET_ID_COLUMN); ds.name = (String) row.get(DatasetWithUserRowMapper.DATASET_NAME_COLUMN); ds.source = (String) row.get(DatasetWithUserRowMapper.DATASET_SOURCE_COLUMN); ds.urn = (String) row.get(DatasetWithUserRowMapper.DATASET_URN_COLUMN); ds.schema = (String) row.get(DatasetWithUserRowMapper.DATASET_SCHEMA_COLUMN); String strOwner = (String) row.get(DatasetWithUserRowMapper.DATASET_OWNER_ID_COLUMN); String strOwnerName = (String) row.get(DatasetWithUserRowMapper.DATASET_OWNER_NAME_COLUMN); Long sourceModifiedTime = (Long) row .get(DatasetWithUserRowMapper.DATASET_SOURCE_MODIFIED_TIME_COLUMN); String properties = (String) row.get(DatasetWithUserRowMapper.DATASET_PROPERTIES_COLUMN); try { if (StringUtils.isNotBlank(properties)) { ds.properties = Json.parse(properties); } } catch (Exception e) { Logger.error(e.getMessage()); } if (modified != null && sourceModifiedTime != null && sourceModifiedTime > 0) { ds.modified = modified; ds.formatedModified = modified.toString(); } String[] owners = null; if (StringUtils.isNotBlank(strOwner)) { owners = strOwner.split(","); } String[] ownerNames = null; if (StringUtils.isNotBlank(strOwnerName)) { ownerNames = strOwnerName.split(","); } ds.owners = new ArrayList<User>(); if (owners != null && ownerNames != null) { if (owners.length == ownerNames.length) { for (int i = 0; i < owners.length; i++) { User datasetOwner = new User(); datasetOwner.userName = owners[i]; if (datasetOwner.userName.equalsIgnoreCase(user)) { ds.isOwned = true; } if (StringUtils.isBlank(ownerNames[i]) || ownerNames[i].equalsIgnoreCase("*")) { datasetOwner.name = owners[i]; } else { datasetOwner.name = ownerNames[i]; } ds.owners.add(datasetOwner); } } else { Logger.error("getPagedDatasets get wrong owner and names. Dataset ID: " + Long.toString(ds.id) + " Owner: " + owners + " Owner names: " + ownerNames); } } Integer favoriteId = (Integer) row.get(DatasetWithUserRowMapper.FAVORITE_DATASET_ID_COLUMN); Long watchId = (Long) row.get(DatasetWithUserRowMapper.DATASET_WATCH_ID_COLUMN); Long schemaHistoryRecordCount = 0L; try { schemaHistoryRecordCount = getJdbcTemplate().queryForObject(CHECK_SCHEMA_HISTORY, Long.class, ds.id); } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } if (StringUtils.isNotBlank(ds.urn)) { if (ds.urn.substring(0, 4).equalsIgnoreCase(DatasetRowMapper.HDFS_PREFIX)) { ds.hdfsBrowserLink = Play.application().configuration().getString(HDFS_BROWSER_URL_KEY) + ds.urn.substring(DatasetRowMapper.HDFS_URN_PREFIX_LEN); } } if (favoriteId != null && favoriteId > 0) { ds.isFavorite = true; } else { ds.isFavorite = false; } if (watchId != null && watchId > 0) { ds.watchId = watchId; ds.isWatched = true; } else { ds.isWatched = false; ds.watchId = 0L; } if (schemaHistoryRecordCount != null && schemaHistoryRecordCount > 0) { ds.hasSchemaHistory = true; } else { ds.hasSchemaHistory = false; } pagedDatasets.add(ds); } resultNode.put("count", count); resultNode.put("page", page); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); resultNode.set("datasets", Json.toJson(pagedDatasets)); return resultNode; } }); return result; }
From source file:dao.DashboardDAO.java
public static ObjectNode getPagedDescriptionDatasetsByManagerId(String managerId, String platform, int option, int page, int size) { DataSourceTransactionManager tm = new DataSourceTransactionManager(getJdbcTemplate().getDataSource()); TransactionTemplate txTemplate = new TransactionTemplate(tm); return txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { Boolean isDatasetLevel = true; String description;/*w w w. java 2 s. c o m*/ final String datasetQuery; switch (option) { case 1: datasetQuery = GET_DATASETS_WITH_DESCRIPTION_FILTER_PLATFORM; description = "has dataset level description"; break; case 2: datasetQuery = GET_DATASETS_WITHOUT_DESCRIPTION_FILTER_PLATFORM; description = "no dataset level description"; break; case 3: datasetQuery = GET_DATASETS_WITH_FULL_FIELD_DESCRIPTION_FILTER_PLATFORM; description = "all fields have description"; isDatasetLevel = false; break; case 4: datasetQuery = GET_DATASETS_WITH_ANY_FIELD_DESCRIPTION_FILTER_PLATFORM; description = "has field description"; isDatasetLevel = false; break; case 5: datasetQuery = GET_DATASETS_WITH_NO_FIELD_DESCRIPTION_FILTER_PLATFORM; description = "no field description"; isDatasetLevel = false; break; case 6: datasetQuery = GET_ALL_DATASETS_BY_ID_FILTER_PLATFORM; description = ""; break; default: datasetQuery = GET_ALL_DATASETS_BY_ID_FILTER_PLATFORM; description = ""; } List<Map<String, Object>> rows = new ArrayList<>(size); long count = getPagedDashboardDatasets(managerId, datasetQuery, platform, null, page, size, rows); List<DashboardDataset> datasets = new ArrayList<>(); for (Map row : rows) { DashboardDataset dashboardDataset = new DashboardDataset(); dashboardDataset.datasetId = (Long) row.get("dataset_id"); dashboardDataset.datasetName = (String) row.get("name"); dashboardDataset.ownerId = (String) row.get("owner_id"); if (dashboardDataset.datasetId != null && dashboardDataset.datasetId > 0) { if (isDatasetLevel) { dashboardDataset.fields = getJdbcTemplate().queryForList(GET_DATASET_LEVEL_COMMENTS, String.class, dashboardDataset.datasetId); } else { dashboardDataset.fields = getJdbcTemplate().queryForList(GET_FIELDS_WITH_DESCRIPTION, String.class, dashboardDataset.datasetId); } } datasets.add(dashboardDataset); } ObjectNode resultNode = Json.newObject(); resultNode.put("status", "ok"); resultNode.put("count", count); resultNode.put("page", page); resultNode.put("description", description); resultNode.put("itemsPerPage", size); resultNode.put("isDatasetLevel", isDatasetLevel); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); resultNode.set("datasets", Json.toJson(datasets)); return resultNode; } }); }
From source file:org.ohmage.query.impl.DocumentQueries.java
public void updateDocument(final String documentId, final byte[] contents, final String name, final String description, final Document.PrivacyState privacyState, final Map<String, Document.Role> campaignAndRolesToAdd, final List<String> campaignsToRemove, final Map<String, Document.Role> classAndRolesToAdd, final Collection<String> classesToRemove, final Map<String, Document.Role> userAndRolesToAdd, final Collection<String> usersToRemove) throws DataAccessException { // Begin transaction DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Document update."); try {/* w w w . j a v a 2 s . c om*/ PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); try { updateName(documentId, name); updateDescription(documentId, description); updatePrivacyState(documentId, privacyState); // Update the campaign-document roles. updateEntityRoleList(documentId, campaignAndRolesToAdd, campaignsToRemove, SQL_INSERT_CAMPAIGN_ROLE, SQL_UPDATE_CAMPAIGN_ROLE, SQL_DELETE_CAMPAIGN_ROLE); // Update the class-document roles. updateEntityRoleList(documentId, classAndRolesToAdd, classesToRemove, SQL_INSERT_CLASS_ROLE, SQL_UPDATE_CLASS_ROLE, SQL_DELETE_CLASS_ROLE); // Update the user-document roles. updateEntityRoleList(documentId, userAndRolesToAdd, usersToRemove, SQL_INSERT_USER_ROLE, SQL_UPDATE_USER_ROLE, SQL_DELETE_USER_ROLE); // Update the contents last, so if there are any problems with // the other actions, then we fail before we write to the // system. updateContents(documentId, contents); } catch (IllegalArgumentException e) { // Rollback transaction and throw a DataAccessException. transactionManager.rollback(status); throw new DataAccessException("Error while executing the update.", e); } catch (CacheMissException e) { transactionManager.rollback(status); throw new DataAccessException("Error while reading from the cache.", e); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw e; } // Commit transaction. try { transactionManager.commit(status); } catch (TransactionException e) { transactionManager.rollback(status); throw new DataAccessException("Error while committing the transaction.", e); } } catch (TransactionException e) { throw new DataAccessException("Error while rolling back the transaction.", e); } }
From source file:dao.SearchDAO.java
public static ObjectNode getPagedMetricByKeyword(final String category, String keyword, int page, int size) { List<Metric> pagedMetrics = new ArrayList<Metric>(); final JdbcTemplate jdbcTemplate = getJdbcTemplate(); javax.sql.DataSource ds = jdbcTemplate.getDataSource(); DataSourceTransactionManager tm = new DataSourceTransactionManager(ds); TransactionTemplate txTemplate = new TransactionTemplate(tm); ObjectNode result;/*from w ww .j a v a2 s .c o m*/ result = txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { String query = SEARCH_METRIC_WITH_PAGINATION.replace("$keyword", keyword); List<Map<String, Object>> rows = null; rows = jdbcTemplate.queryForList(query, (page - 1) * size, size); for (Map row : rows) { Metric metric = new Metric(); metric.id = (Integer) row.get(MetricRowMapper.METRIC_ID_COLUMN); metric.name = (String) row.get(MetricRowMapper.METRIC_NAME_COLUMN); metric.refID = (String) row.get(MetricRowMapper.METRIC_REF_ID_COLUMN); metric.refIDType = (String) row.get(MetricRowMapper.METRIC_REF_ID_TYPE_COLUMN); metric.description = (String) row.get(MetricRowMapper.METRIC_DESCRIPTION_COLUMN); metric.dashboardName = (String) row.get(MetricRowMapper.METRIC_DASHBOARD_NAME_COLUMN); metric.category = (String) row.get(MetricRowMapper.METRIC_CATEGORY_COLUMN); metric.group = (String) row.get(MetricRowMapper.METRIC_GROUP_COLUMN); metric.source = "metric"; metric.urn = ""; if (StringUtils.isNotBlank(metric.dashboardName)) { metric.urn += metric.dashboardName + "/"; } if (StringUtils.isNotBlank(metric.group)) { metric.urn += metric.group + "/"; } if (StringUtils.isNotBlank(metric.name)) { metric.urn += metric.name; } ObjectNode schema = Json.newObject(); schema.put(MetricRowMapper.METRIC_REF_ID_COLUMN, metric.refID); schema.put(MetricRowMapper.METRIC_REF_ID_TYPE_COLUMN, metric.refIDType); schema.put(MetricRowMapper.METRIC_DESCRIPTION_COLUMN, metric.description); schema.put(MetricRowMapper.METRIC_DASHBOARD_NAME_COLUMN, metric.dashboardName); schema.put(MetricRowMapper.METRIC_CATEGORY_COLUMN, metric.category); schema.put(MetricRowMapper.METRIC_GROUP_COLUMN, metric.group); metric.schema = schema.toString(); pagedMetrics.add(metric); } long count = 0; try { count = jdbcTemplate.queryForObject("SELECT FOUND_ROWS()", Long.class); } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } ObjectNode resultNode = Json.newObject(); resultNode.put("count", count); resultNode.put("page", page); resultNode.put("category", category); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); resultNode.set("data", Json.toJson(pagedMetrics)); return resultNode; } }); return result; }
From source file:org.ohmage.query.impl.UserMobilityQueries.java
@Override public void updateMobilityPoint(final UUID mobilityId, final MobilityPoint.PrivacyState privacyState) throws DataAccessException { // Create the transaction. DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Updating a Mobility data point."); try {/*from ww w .j a v a 2 s.co m*/ // Begin the transaction. PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); if (privacyState != null) { String sql = "UPDATE mobility " + "SET privacy_state_id = (" + "SELECT id " + "FROM mobility_privacy_state " + "WHERE privacy_state = ?) " + "WHERE uuid = ?"; try { getJdbcTemplate().update(sql, new Object[] { privacyState.toString(), mobilityId.toString() }); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException( "Error executing SQL '" + sql + "' with parameter: " + privacyState.toString(), e); } } // Commit the transaction. try { transactionManager.commit(status); } catch (TransactionException e) { transactionManager.rollback(status); throw new DataAccessException("Error while committing the transaction.", e); } } catch (TransactionException e) { throw new DataAccessException("Error while attempting to rollback the transaction.", e); } }
From source file:org.ohmage.query.impl.SurveyResponseQueries.java
public void updateSurveyResponsesPrivacyState(final Set<UUID> surveyResponseIds, final SurveyResponse.PrivacyState newPrivacyState) throws DataAccessException { StringBuilder sqlBuilder = new StringBuilder(SQL_UPDATE_SURVEY_RESPONSES_PRIVACY_STATE); sqlBuilder.append(StringUtils.generateStatementPList(surveyResponseIds.size())); List<Object> parameters = new ArrayList<Object>(surveyResponseIds.size() + 1); parameters.add(newPrivacyState.toString()); for (UUID surveyResponseId : surveyResponseIds) { parameters.add(surveyResponseId.toString()); }/*w w w . j a v a 2 s . com*/ // Create the transaction. DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Updating a survey response."); try { // Begin the transaction. PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); try { getJdbcTemplate().update(sqlBuilder.toString(), parameters.toArray()); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error executing SQL '" + sqlBuilder.toString() + "' with parameters: " + parameters.toArray(), e); } // Commit the transaction. try { transactionManager.commit(status); } catch (TransactionException e) { transactionManager.rollback(status); throw new DataAccessException("Error while committing the transaction.", e); } } catch (TransactionException e) { throw new DataAccessException("Error while attempting to rollback the transaction.", e); } }