List of usage examples for org.springframework.jdbc.datasource DataSourceTransactionManager DataSourceTransactionManager
public DataSourceTransactionManager(DataSource dataSource)
From source file:org.ohmage.query.impl.AnnotationQueries.java
@Override public void updateAnnotation(final UUID annotationId, final String annotationText, final String client, final long time, final DateTimeZone timezone) throws DataAccessException { // Create the transaction. DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Updating an annotation."); try {/* w w w . java 2 s . co m*/ // Begin the transaction. PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); try { getJdbcTemplate().update(SQL_UPDATE_ANNOTATION, time, timezone.getID(), client, annotationText, annotationId.toString()); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error executing SQL '" + SQL_UPDATE_ANNOTATION + "' with parameters: " + time + ", " + timezone.getID() + ", " + client + ", " + annotationText + ", " + annotationId.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:ca.nrc.cadc.uws.server.JobDAO.java
public JobDAO(DataSource dataSource, JobSchema jobSchema, IdentityManager identManager, StringIDGenerator idGenerator) { this.jobSchema = jobSchema; this.identManager = identManager; this.idGenerator = idGenerator; this.defaultTransactionDef = new DefaultTransactionDefinition(); defaultTransactionDef.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_REPEATABLE_READ); this.transactionManager = new DataSourceTransactionManager(dataSource); this.jdbc = new JdbcTemplate(dataSource); }
From source file:org.ohmage.query.impl.UserClassQueries.java
public void addUserToClassWithRole(final String username, final String classId, final Clazz.Role classRole) throws DataAccessException { // Create the transaction. DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Adding a user to a class."); try {//from www . ja v a2 s.c o m // Begin the transaction. PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); // Insert the new user. try { getJdbcTemplate().update(SQL_INSERT_USER_CLASS, new Object[] { username, classId, classRole.toString() }); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error while executing SQL '" + SQL_INSERT_USER_CLASS + "' with parameters: " + username + ", " + classId + ", " + classRole.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.CampaignQueries.java
public void createCampaign(final Campaign campaign, final Collection<String> classIds, final String creatorUsername) throws DataAccessException { // Create the transaction. DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Creating a new campaign."); try {//from www . j a v a 2s . c o m // Begin the transaction. PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); String iconUrlString = null; URL iconUrl = campaign.getIconUrl(); if (iconUrl != null) { iconUrlString = iconUrl.toString(); } String xml; try { xml = campaign.getXml(); } catch (DomainException e) { transactionManager.rollback(status); throw new DataAccessException("The XML could not be saved."); } // Create the campaign. try { getJdbcTemplate().update(SQL_INSERT_CAMPAIGN, new Object[] { campaign.getId(), campaign.getName(), xml, campaign.getDescription(), iconUrlString, campaign.getAuthoredBy(), campaign.getRunningState().toString(), campaign.getPrivacyState().toString() }); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error executing SQL '" + SQL_INSERT_CAMPAIGN + "' with parameters: " + campaign.getId() + ", " + campaign.getName() + ", " + xml + ", " + campaign.getDescription() + ", " + iconUrlString + ", " + campaign.getAuthoredBy() + ", " + campaign.getRunningState().toString() + ", " + campaign.getPrivacyState().toString(), e); } // Create the set of survey and prompt IDs for this campaign. final Set<String> surveyIds = new HashSet<String>(); final Set<String> promptIds = new HashSet<String>(); // Loop through all of the surveys and add the survey and prompt // IDs. for (Survey survey : campaign.getSurveys().values()) { // Get this survey's ID. surveyIds.add(survey.getId()); Queue<SurveyItem> surveyItems = new LinkedList<SurveyItem>(); surveyItems.addAll(survey.getSurveyItems().values()); while (surveyItems.size() > 0) { SurveyItem surveyItem = surveyItems.poll(); if (surveyItem instanceof RepeatableSet) { RepeatableSet repeatableSet = (RepeatableSet) surveyItem; for (SurveyItem rsSurveyItem : repeatableSet.getSurveyItems().values()) { surveyItems.add(rsSurveyItem); } } else if (surveyItem instanceof Prompt) { promptIds.add(((Prompt) surveyItem).getId()); } } } // Get the campaign's ID. final String campaignId = campaign.getId(); // Compile the list of parameters for the survey ID lookup table. List<Object[]> surveyParameters = new ArrayList<Object[]>(surveyIds.size()); for (String surveyId : surveyIds) { Object[] params = new Object[2]; params[0] = surveyId; params[1] = campaignId; surveyParameters.add(params); } // The SQL to write the data. final String surveyIdLookupBatchSql = "INSERT INTO " + "campaign_survey_lookup(survey_id, campaign_id) " + "VALUES (?, (SELECT id FROM campaign WHERE urn = ?))"; // Add the survey IDs to the lookup table. try { getJdbcTemplate().batchUpdate(surveyIdLookupBatchSql, surveyParameters); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error executing SQL '" + surveyIdLookupBatchSql + "'.", e); } // Compile the list of parameters for the prompt ID lookup table. List<Object[]> promptParameters = new ArrayList<Object[]>(surveyIds.size()); for (String promptId : promptIds) { Object[] params = new Object[2]; params[0] = promptId; params[1] = campaignId; promptParameters.add(params); } // The SQL to write the data. final String promptIdLookupBatchSql = "INSERT INTO " + "campaign_prompt_lookup(prompt_id, campaign_id) " + "VALUES (?, (SELECT id FROM campaign WHERE urn = ?))"; // Add the prompt IDs to the lookup table. try { getJdbcTemplate().batchUpdate(promptIdLookupBatchSql, promptParameters); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error executing SQL '" + promptIdLookupBatchSql + "'.", e); } // Add each of the classes to the campaign. for (String classId : classIds) { associateCampaignAndClass(transactionManager, status, campaign.getId(), classId); } // Add the requesting user as the author. This may have already // happened above. try { getJdbcTemplate().update(SQL_INSERT_USER_ROLE_CAMPAIGN, creatorUsername, campaign.getId(), Campaign.Role.AUTHOR.toString()); } catch (org.springframework.dao.DataIntegrityViolationException e) { // The user was already an author of this campaign implying // that it's one of the default campaign roles based on a class // role that the 'creatorUsername' has. e.printStackTrace(); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error executing SQL '" + SQL_INSERT_USER_ROLE_CAMPAIGN + "' with parameters: " + creatorUsername + ", " + campaign.getId() + ", " + Campaign.Role.AUTHOR.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.UserQueries.java
public void createUser(final String username, final String hashedPassword, final String emailAddress, final Boolean admin, final Boolean enabled, final Boolean newAccount, final Boolean campaignCreationPrivilege) throws DataAccessException { Boolean tAdmin = admin;/*w ww. j a va 2s. c o m*/ if (tAdmin == null) { tAdmin = false; } Boolean tEnabled = enabled; if (tEnabled == null) { tEnabled = false; } Boolean tNewAccount = newAccount; if (tNewAccount == null) { tNewAccount = true; } Boolean tCampaignCreationPrivilege = campaignCreationPrivilege; if (tCampaignCreationPrivilege == null) { try { tCampaignCreationPrivilege = PreferenceCache.instance() .lookup(PreferenceCache.KEY_DEFAULT_CAN_CREATE_PRIVILIEGE).equals("true"); } catch (CacheMissException e) { throw new DataAccessException("Cache doesn't know about 'known' value: " + PreferenceCache.KEY_DEFAULT_CAN_CREATE_PRIVILIEGE, e); } } // Create the transaction. DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Creating a new user."); try { // Begin the transaction. PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); // Insert the new user. try { getJdbcTemplate().update(SQL_INSERT_USER, new Object[] { username, hashedPassword, emailAddress, tAdmin, tEnabled, tNewAccount, tCampaignCreationPrivilege }); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error while executing SQL '" + SQL_INSERT_USER + "' with parameters: " + username + ", " + hashedPassword + ", " + emailAddress + ", " + tAdmin + ", " + tEnabled + ", " + tNewAccount + ", " + tCampaignCreationPrivilege, 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.AnnotationQueries.java
@Override public void deleteAnnotation(final UUID annotationId) throws DataAccessException { // Create the transaction. DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Deleting an annotation."); try {/* w w w .j a v a 2 s. c om*/ // Begin the transaction. PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); try { getJdbcTemplate().update(SQL_DELETE_ANNOTATION, annotationId.toString()); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error executing SQL '" + SQL_DELETE_ANNOTATION + "' with parameter: " + annotationId.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:dao.FlowsDAO.java
public static ObjectNode getPagedFlowsByProject(String applicationName, String project, int page, int size) { ObjectNode result;// w w w .j a v a 2s . c o m if (StringUtils.isBlank(applicationName) || StringUtils.isBlank(project)) { result = Json.newObject(); result.put("count", 0); result.put("page", page); result.put("itemsPerPage", size); result.put("totalPages", 0); result.set("flows", Json.toJson("")); return result; } String application = applicationName.replace(".", " "); Integer appID = getApplicationIDByName(applicationName); if (appID != 0) { javax.sql.DataSource ds = getJdbcTemplate().getDataSource(); DataSourceTransactionManager tm = new DataSourceTransactionManager(ds); TransactionTemplate txTemplate = new TransactionTemplate(tm); final int applicationID = appID; result = txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { ObjectNode resultNode = Json.newObject(); long count = 0; List<Flow> pagedFlows = new ArrayList<Flow>(); List<Map<String, Object>> rows = null; if (StringUtils.isNotBlank(project) && (!project.equalsIgnoreCase("root"))) { rows = getJdbcTemplate().queryForList(GET_PAGED_FLOWS_BY_APP_ID_AND_PROJECT_NAME, applicationID, project, (page - 1) * size, size); } else { rows = getJdbcTemplate().queryForList(GET_PAGED_FLOWS_WITHOUT_PROJECT_BY_APP_ID, applicationID, (page - 1) * size, size); } try { count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class); } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } for (Map row : rows) { Flow flow = new Flow(); flow.id = (Long) row.get("flow_id"); flow.level = (Integer) row.get("flow_level"); flow.name = (String) row.get("flow_name"); flow.path = (String) row.get("flow_path"); flow.appCode = (String) row.get("app_code"); flow.group = project; if (StringUtils.isNotBlank(flow.path)) { int index = flow.path.indexOf(":"); if (index != -1) { flow.path = flow.path.substring(0, index); } } Object created = row.get("created_time"); if (created != null) { flow.created = DateFormat.format(created.toString()); } Object modified = row.get("modified_time"); if (modified != null) { flow.modified = DateFormat.format(row.get("modified_time").toString()); } int jobCount = 0; if (flow.id != null && flow.id != 0) { try { jobCount = getJdbcTemplate().queryForObject(GET_JOB_COUNT_BY_APP_ID_AND_FLOW_ID, new Object[] { appID, flow.id }, Integer.class); flow.jobCount = jobCount; } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } } pagedFlows.add(flow); } resultNode.set("flows", Json.toJson(pagedFlows)); resultNode.put("count", count); resultNode.put("page", page); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); return resultNode; } }); return result; } result = Json.newObject(); result.put("count", 0); result.put("page", page); result.put("itemsPerPage", size); result.put("totalPages", 0); result.set("flows", Json.toJson("")); return result; }
From source file:org.ohmage.query.impl.UserQueries.java
public void createUserRegistration(final String username, final String hashedPassword, final String emailAddress, final String registrationId) throws DataAccessException { // Get the public class. String publicClassId;/*from w w w . j ava 2s. c o m*/ try { publicClassId = PreferenceCache.instance().lookup(PreferenceCache.KEY_PUBLIC_CLASS_ID); } catch (CacheMissException e) { throw new DataAccessException("The public class is not configured"); } Boolean defaultCampaignCreationPrivilege; try { String privilegeString = PreferenceCache.instance() .lookup(PreferenceCache.KEY_DEFAULT_CAN_CREATE_PRIVILIEGE); if (privilegeString == null) { throw new DataAccessException("The default campaign creation privilege is missing."); } defaultCampaignCreationPrivilege = StringUtils.decodeBoolean(privilegeString); if (defaultCampaignCreationPrivilege == null) { throw new DataAccessException("The default campaign creation privilege is not a valid boolean."); } } catch (CacheMissException e) { throw new DataAccessException( "Cache doesn't know about 'known' value: " + PreferenceCache.KEY_DEFAULT_CAN_CREATE_PRIVILIEGE, e); } // Create the transaction. DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Creating a user registration request."); try { // Begin the transaction. PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); // Insert the new user. try { getJdbcTemplate().update(SQL_INSERT_USER, new Object[] { username, hashedPassword, emailAddress, false, false, false, defaultCampaignCreationPrivilege }); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error while executing SQL '" + SQL_INSERT_USER + "' with parameters: " + username + ", " + emailAddress + ", " + hashedPassword + ", " + false + ", " + false + ", " + false + ", " + "null", e); } // Insert the new user into the class. try { getJdbcTemplate().update(SQL_INSERT_USER_CLASS, new Object[] { username, publicClassId, Clazz.Role.RESTRICTED.toString() }); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException( "Error while executing SQL '" + SQL_INSERT_USER_CLASS + "' with parameters: " + username + ", " + publicClassId + ", " + Clazz.Role.RESTRICTED.toString(), e); } // Get the list of campaigns for this class. String sqlGetCampaignIds = "SELECT ca.urn " + "FROM campaign ca, class cl, campaign_class cc " + "WHERE cl.urn = ? " + "AND cl.id = cc.class_id " + "AND ca.id = cc.campaign_id"; List<String> campaignIds; try { campaignIds = getJdbcTemplate().query(sqlGetCampaignIds, new Object[] { publicClassId }, new SingleColumnRowMapper<String>()); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException( "Error executing SQL '" + sqlGetCampaignIds + "' with parameter: " + publicClassId, e); } // Construct the parameter map for the batch update. List<Object[]> batchParameters = new ArrayList<Object[]>(campaignIds.size()); for (String campaignId : campaignIds) { String[] parameters = new String[3]; parameters[0] = username; parameters[1] = campaignId; parameters[2] = Campaign.Role.PARTICIPANT.toString(); batchParameters.add(parameters); } // Perform the batch update. String sqlInsertUserCampaign = "INSERT INTO user_role_campaign" + "(user_id, campaign_id, user_role_id) " + "VALUES (" + "(SELECT id FROM user WHERE username = ?), " + "(SELECT id FROM campaign WHERE urn = ?), " + "(SELECT id FROM user_role WHERE role = ?)" + ")"; try { getJdbcTemplate().batchUpdate(sqlInsertUserCampaign, batchParameters); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error executing SQL '" + sqlInsertUserCampaign + "'.", e); } // Insert the user's registration information into the try { getJdbcTemplate().update(SQL_INSERT_REGISTRATION, new Object[] { username, registrationId, (new Date()).getTime() }); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error while executing SQL '" + SQL_INSERT_REGISTRATION + "' with parameters: " + username + ", " + registrationId + ", " + (new Date()).getTime(), 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:dao.FlowsDAO.java
public static ObjectNode getPagedJobsByFlow(String applicationName, Long flowId, int page, int size) { ObjectNode result;/*from ww w. j a va 2s . com*/ List<Job> pagedJobs = new ArrayList<Job>(); if (StringUtils.isBlank(applicationName) || (flowId <= 0)) { result = Json.newObject(); result.put("count", 0); result.put("page", page); result.put("itemsPerPage", size); result.put("totalPages", 0); result.set("jobs", Json.toJson("")); return result; } String application = applicationName.replace(".", " "); Integer appID = getApplicationIDByName(application); if (appID != 0) { javax.sql.DataSource ds = getJdbcTemplate().getDataSource(); DataSourceTransactionManager tm = new DataSourceTransactionManager(ds); TransactionTemplate txTemplate = new TransactionTemplate(tm); final long azkabanFlowId = flowId; result = txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { List<Map<String, Object>> rows = null; rows = getJdbcTemplate().queryForList(GET_PAGED_JOBS_BY_APP_ID_AND_FLOW_ID, appID, azkabanFlowId, (page - 1) * size, size); long count = 0; String flowName = ""; try { count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class); } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } for (Map row : rows) { Job job = new Job(); job.id = (Long) row.get("job_id"); job.name = (String) row.get("job_name"); job.path = (String) row.get("job_path"); job.path = (String) row.get("job_path"); job.refFlowGroup = (String) row.get("flow_group"); if (StringUtils.isNotBlank(job.path)) { int index = job.path.indexOf("/"); if (index != -1) { job.path = job.path.substring(0, index); } } job.type = (String) row.get("job_type"); Object created = row.get("created_time"); job.refFlowId = (Long) row.get("ref_flow_id"); if (created != null) { job.created = DateFormat.format(created.toString()); } Object modified = row.get("modified_time"); if (modified != null) { job.modified = DateFormat.format(modified.toString()); } if (StringUtils.isBlank(flowName)) { flowName = (String) row.get("flow_name"); } pagedJobs.add(job); } ObjectNode resultNode = Json.newObject(); resultNode.put("count", count); resultNode.put("flow", flowName); resultNode.put("page", page); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); resultNode.set("jobs", Json.toJson(pagedJobs)); return resultNode; } }); return result; } result = Json.newObject(); result.put("count", 0); result.put("page", page); result.put("itemsPerPage", size); result.put("totalPages", 0); result.set("jobs", Json.toJson("")); return result; }