Example usage for org.springframework.transaction.support DefaultTransactionDefinition setName

List of usage examples for org.springframework.transaction.support DefaultTransactionDefinition setName

Introduction

In this page you can find the example usage for org.springframework.transaction.support DefaultTransactionDefinition setName.

Prototype

public final void setName(String name) 

Source Link

Document

Set the name of this transaction.

Usage

From source file:com.krawler.spring.crm.common.documentController.java

public ModelAndView deleteDocumentFromModule(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject jobj = new JSONObject();
    KwlReturnObject kmsg = null;/*from w  w  w.  ja  va2 s  .  c o  m*/
    //Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    String docid = "";
    String details = "";
    String auditAction = "";
    if (request.getParameter("docid") != null)
        docid = request.getParameter("docid");
    String map = request.getParameter("mapid");
    String refId = request.getParameter("recid");
    String docName = request.getParameter("docName");
    try {
        crmDocumentDAOObj.deleteDocumentFromModule(docid);
        if (map.equals("0")) {
            CrmCampaign c = (CrmCampaign) hibernateTemplate.get(CrmCampaign.class, refId);
            details = " Campaign - ";
            details += StringUtil.isNullOrEmpty(c.getCampaignname()) ? "" : c.getCampaignname();
            auditAction = AuditAction.CAMPAIGN_DOC_DELETED;
        } else if (map.equals("1")) {
            CrmLead l = (CrmLead) hibernateTemplate.get(CrmLead.class, refId);
            details = " Lead - ";
            details += StringUtil.isNullOrEmpty(l.getFirstname()) ? "" : l.getFirstname() + " ";
            details += StringUtil.isNullOrEmpty(l.getLastname()) ? "" : l.getLastname();
            auditAction = AuditAction.LEAD_DOC_DELETED;
        } else if (map.equals("2")) {
            CrmContact c = (CrmContact) hibernateTemplate.get(CrmContact.class, refId);
            details = " Contact - ";
            details += StringUtil.isNullOrEmpty(c.getFirstname()) ? "" : c.getFirstname() + " ";
            details += StringUtil.isNullOrEmpty(c.getLastname()) ? "" : c.getLastname();
            auditAction = AuditAction.CONTACT_DOC_DELETED;
        } else if (map.equals("3")) {
            CrmProduct p = (CrmProduct) hibernateTemplate.get(CrmProduct.class, refId);
            details = " Product - ";
            details += StringUtil.isNullOrEmpty(p.getProductname()) ? "" : p.getProductname();
            auditAction = AuditAction.PRODUCT_DOC_DELETED;
        } else if (map.equals("4")) {
            CrmAccount a = (CrmAccount) hibernateTemplate.get(CrmAccount.class, refId);
            details = " Account - ";
            details += StringUtil.isNullOrEmpty(a.getAccountname()) ? "" : a.getAccountname();
            auditAction = AuditAction.ACCOUNT_DOC_DELETED;
        } else if (map.equals("5")) {
            CrmOpportunity o = (CrmOpportunity) hibernateTemplate.get(CrmOpportunity.class, refId);
            details = " Opportunity - ";
            details += StringUtil.isNullOrEmpty(o.getOppname()) ? "" : o.getOppname();
            auditAction = AuditAction.OPPORTUNITY_DOC_DELETED;
        } else if (map.equals("6")) {
            CrmCase c = (CrmCase) hibernateTemplate.get(CrmCase.class, refId);
            details = " Case - ";
            details += StringUtil.isNullOrEmpty(c.getSubject()) ? "" : c.getSubject();
            auditAction = AuditAction.CASE_DOC_DELETED;
        } else if (map.equals("7")) {
            CrmActivityMaster am = (CrmActivityMaster) hibernateTemplate.get(CrmActivityMaster.class, refId);
            details = " Activity - ";
            details += StringUtil.isNullOrEmpty(am.getFlag()) ? "" : am.getFlag() + " ";
            details += StringUtil.isNullOrEmpty(am.getCrmCombodataByStatusid().getValue()) ? ""
                    : am.getCrmCombodataByStatusid().getValue();
            auditAction = AuditAction.ACTIVITY_DOC_DELETED;
        } else if (map.equals("-1")) {
            details = " My - Document ";
            auditAction = AuditAction.MY_DOC_DELETED;
        }
        auditTrailDAOObj.insertAuditLog(auditAction, " Docment: '" + docName + "' , deleted for " + details,
                request, refId, docid);

        //    auditTrailDAOObj.insertAuditLog(AuditAction.DOC_TAG_ADDED,
        //            " Document - '" + newTag + "' tag added for "+d.getDocname(),
        //            request, d.getDocid());
        txnManager.commit(status);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", jobj.toString());
}

From source file:com.krawler.spring.crm.common.documentController.java

public ModelAndView addDocuments(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject jobj = new JSONObject();
    JSONObject myjobj = new JSONObject();
    List fileItems = null;/*  w  w  w .  j a v a 2 s.co m*/
    String details = "";
    KwlReturnObject kmsg = null;
    String auditAction = "";
    String id = java.util.UUID.randomUUID().toString();
    // PrintWriter out = null;
    //Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {
        response.setContentType("text/html;charset=UTF-8");
        // out = response.getWriter();
        String userid = sessionHandlerImpl.getUserid(request);
        String companyID = sessionHandlerImpl.getCompanyid(request);
        String map = request.getParameter("mapid");
        HashMap<String, String> arrParam = new HashMap<String, String>();
        boolean fileUpload = false;
        ArrayList<FileItem> fi = new ArrayList<FileItem>();
        if (request.getParameter("fileAdd") != null) {
            DiskFileUpload fu = new DiskFileUpload();
            fileItems = fu.parseRequest(request);
            crmDocumentDAOObj.parseRequest(fileItems, arrParam, fi, fileUpload);
        }
        String docID = "";
        for (int cnt = 0; cnt < fi.size(); cnt++) {
            kmsg = crmDocumentDAOObj.uploadFile(fi.get(cnt), userid, companyID, getServletContext());
            Docs doc = (Docs) kmsg.getEntityList().get(0);
            docID = doc.getDocid();
            String refid = arrParam.get("refid");
            jobj.put("userid", userid);
            jobj.put("docid", docID);
            jobj.put("companyid", companyID);
            jobj.put("id", id);
            jobj.put("map", map);
            jobj.put("refid", refid);
            crmDocumentDAOObj.saveDocumentMapping(jobj);
            String randomid = java.util.UUID.randomUUID().toString();
            crmDocumentDAOObj.insertDocumentOwnerEntry(randomid, userid, docID);
            if (map.equals("0")) {
                CrmCampaign c = (CrmCampaign) hibernateTemplate.get(CrmCampaign.class, refid);
                details = " Campaign - ";
                details += StringUtil.isNullOrEmpty(c.getCampaignname()) ? "" : c.getCampaignname();
                auditAction = AuditAction.CAMPAIGN_DOC_UPLOAD;
            } else if (map.equals("1")) {
                CrmLead l = (CrmLead) hibernateTemplate.get(CrmLead.class, refid);
                details = " Lead - ";
                details += StringUtil.isNullOrEmpty(l.getFirstname()) ? "" : l.getFirstname() + " ";
                details += StringUtil.isNullOrEmpty(l.getLastname()) ? "" : l.getLastname();
                auditAction = AuditAction.LEAD_DOC_UPLOAD;
            } else if (map.equals("2")) {
                CrmContact c = (CrmContact) hibernateTemplate.get(CrmContact.class, refid);
                details = " Contact - ";
                details += StringUtil.isNullOrEmpty(c.getFirstname()) ? "" : c.getFirstname() + " ";
                details += StringUtil.isNullOrEmpty(c.getLastname()) ? "" : c.getLastname();
                auditAction = AuditAction.CONTACT_DOC_UPLOAD;
            } else if (map.equals("3")) {
                CrmProduct p = (CrmProduct) hibernateTemplate.get(CrmProduct.class, refid);
                details = " Product - ";
                details += StringUtil.isNullOrEmpty(p.getProductname()) ? "" : p.getProductname();
                auditAction = AuditAction.PRODUCT_DOC_UPLOAD;
            } else if (map.equals("4")) {
                CrmAccount a = (CrmAccount) hibernateTemplate.get(CrmAccount.class, refid);
                details = " Account - ";
                details += StringUtil.isNullOrEmpty(a.getAccountname()) ? "" : a.getAccountname();
                auditAction = AuditAction.ACCOUNT_DOC_UPLOAD;
            } else if (map.equals("5")) {
                CrmOpportunity o = (CrmOpportunity) hibernateTemplate.get(CrmOpportunity.class, refid);
                details = " Opportunity - ";
                details += StringUtil.isNullOrEmpty(o.getOppname()) ? "" : o.getOppname();
                auditAction = AuditAction.OPPORTUNITY_DOC_UPLOAD;
            } else if (map.equals("6")) {
                CrmCase c = (CrmCase) hibernateTemplate.get(CrmCase.class, refid);
                details = " Case - ";
                details += StringUtil.isNullOrEmpty(c.getSubject()) ? "" : c.getSubject();
                auditAction = AuditAction.CASE_DOC_UPLOAD;
            } else if (map.equals("7")) {
                CrmActivityMaster am = (CrmActivityMaster) hibernateTemplate.get(CrmActivityMaster.class,
                        refid);
                details = " Activity - ";
                details += StringUtil.isNullOrEmpty(am.getFlag()) ? "" : am.getFlag() + " ";
                details += StringUtil.isNullOrEmpty(am.getCrmCombodataByStatusid().getValue()) ? ""
                        : am.getCrmCombodataByStatusid().getValue();
                auditAction = AuditAction.ACTIVITY_DOC_UPLOAD;
            } else if (map.equals("-1")) {
                details = " My - Document ";
                auditAction = AuditAction.MY_DOC_UPLOAD;
            }
            auditTrailDAOObj.insertAuditLog(auditAction,
                    " Docment: '" + doc.getDocname() + "' , uploaded for " + details, request, refid, id);
        }
        myjobj.put("ID", docID);
        txnManager.commit(status);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    } finally {
        // out.close();
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
}

From source file:org.ohmage.query.impl.DocumentQueries.java

public void deleteDocument(String documentId) throws DataAccessException {
    // Begin transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Document delete.");

    try {/*from   w w w.  ja  v a  2s  .  c o m*/
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        String documentUrl = getDocumentUrl(documentId);

        try {
            getJdbcTemplate().update(SQL_DELETE_DOCUMENT, new Object[] { documentId });
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException(
                    "Error executing SQL '" + SQL_DELETE_DOCUMENT + "' with parameter: " + documentId, e);
        }

        try {
            if (!(new File((new URL(documentUrl)).getFile())).delete()) {
                LOGGER.warn(
                        "The document no longer existed, so the deletion only removed the entry from the database.");
            }
        } catch (MalformedURLException e) {
            LOGGER.warn(
                    "The URL was malformed, meaning that we couldn't have referenced the file anyway. Cannot delete the file.",
                    e);
        } catch (SecurityException e) {
            LOGGER.warn(
                    "Failed to delete the file because the security manager stopped us. Are we attempting to delete a file that isn't part of the heirarchy?",
                    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: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 {//from  w  w w  . j  a  v  a 2  s .c o  m
        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:com.krawler.spring.importFunctionality.ImportUtil.java

/**
 * @param requestParams/*from w ww . j ava 2  s .co m*/
 * @param txnManager
 * @param kwlCommonTablesDAOObj
 * @param importDao
 * @return
 */
public static JSONObject validateFileData(HashMap<String, Object> requestParams,
        HibernateTransactionManager txnManager, kwlCommonTablesDAO kwlCommonTablesDAOObj, ImportDAO importDao,
        fieldManagerDAO fieldManagerDAOobj) {
    JSONObject jobj = new JSONObject();
    String msg = "";
    boolean issuccess = true;

    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("import_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = txnManager.getTransaction(def);
    boolean commitedEx = false;

    int total = 0, failed = 0, fileSize = 0;
    String fileName = "", extn = "";
    Modules module = null;
    String exceededLimit = "no", channelName = "";
    try {
        String companyid = (String) requestParams.get("companyid");
        String mode = (String) requestParams.get("modName");
        fileName = (String) requestParams.get("filename");
        extn = fileName.substring(fileName.lastIndexOf(".") + 1);
        channelName = "/ValidateFile/" + fileName;

        Object extraObj = requestParams.get("extraObj");
        JSONObject extraParams = (JSONObject) requestParams.get("extraParams");

        String jsondata = (String) requestParams.get("resjson");
        JSONObject rootcsvjobj = new JSONObject(jsondata);
        JSONArray mapping = rootcsvjobj.getJSONArray("root");

        String dateFormat = null, dateFormatId = (String) requestParams.get("dateFormat");
        if (extn.equalsIgnoreCase("csv") && !StringUtil.isNullOrEmpty(dateFormatId)) {
            KWLDateFormat kdf = (KWLDateFormat) kwlCommonTablesDAOObj
                    .getClassObject(KWLDateFormat.class.getName(), dateFormatId);
            dateFormat = kdf != null ? kdf.getJavaForm() : null;
        }

        String classPath = "", primaryKey = "", uniqueKeyMethodName = "", uniqueKeyHbmName = "";
        try {
            List list = importDao.getModuleObject(mode);
            module = (Modules) list.get(0); //Will throw null pointer if no module entry found
        } catch (Exception ex) {
            throw new DataInvalidateException("Column config not available for module " + mode);
        }

        try {
            classPath = module.getPojoClassPathFull().toString();
            primaryKey = module.getPrimaryKey_MethodName().toString();
        } catch (Exception ex) {
            throw new DataInvalidateException("Please set proper properties for module " + mode);
        }
        uniqueKeyMethodName = module.getUniqueKey_MethodName();
        uniqueKeyHbmName = module.getUniqueKey_HbmName();

        JSONArray columnConfig = getModuleColumnConfig1(module.getId(), companyid, fieldManagerDAOobj,
                module.getModuleName(), false);
        String tableName = importDao.getTableName(fileName);
        KwlReturnObject kresult = importDao.getFileData(tableName, new HashMap<String, Object>());
        List fileDataList = kresult.getEntityList();
        Iterator itr = fileDataList.iterator();

        importDao.markRecordValidation(tableName, -1, 1, "", ""); //reset all invalidation
        JSONArray recordJArr = new JSONArray(), columnsJArr = new JSONArray(), DataJArr = new JSONArray();
        if (itr.hasNext()) { //
            Object[] fileData = (Object[]) itr.next();
            JSONObject jtemp = new JSONObject();
            jtemp.put("header", "Row No.");
            jtemp.put("dataIndex", "col0");
            jtemp.put("width", 50);
            columnsJArr.put(jtemp);

            for (int i = 1; i < fileData.length - 3; i++) { //Discard columns, id at index 0 and isvalid,validationlog at last 2.
                jtemp = new JSONObject();
                jtemp.put("header", fileData[i] == null ? "" : fileData[i].toString());
                jtemp.put("dataIndex", "col" + i);
                columnsJArr.put(jtemp);
            }

            jtemp = new JSONObject();
            jtemp.put("header", "Validation Log");
            //                jtemp.put("hidden", true);
            jtemp.put("dataIndex", "validateLog");
            columnsJArr.put(jtemp);

            //Create record Obj for grid's store
            for (int i = 0; i < fileData.length - 1; i++) {
                jtemp = new JSONObject();
                jtemp.put("name", "col" + i);
                recordJArr.put(jtemp);
            }
            jtemp = new JSONObject();
            jtemp.put("name", "validateLog");
            recordJArr.put(jtemp);
        }

        try {
            jobj.put("record", recordJArr);
            jobj.put("columns", columnsJArr);
            jobj.put("data", DataJArr);
            jobj.put("count", failed);
            jobj.put("valid", 0);
            jobj.put("totalrecords", total);
            jobj.put("isHeader", true);
            jobj.put("finishedValidation", false);
            ServerEventManager.publish(channelName, jobj.toString(),
                    (ServletContext) requestParams.get("servletContext"));
        } catch (Exception ex) {
            throw ex;
        }

        fileSize = fileDataList.size() - 1;
        fileSize = fileSize >= IMPORT_LIMIT ? IMPORT_LIMIT : fileSize; // fileSize used for showing progress bar[Client Side]

        jobj.put("isHeader", false);
        int recIndex = 0;
        Session session = txnManager.getSessionFactory().getCurrentSession();
        int batchCounter = 0;
        while (itr.hasNext()) {
            Object[] fileData = (Object[]) itr.next();
            tempFileData = null;
            tempFileData = fileData;
            recIndex = (Integer) fileData[0];
            HashMap<String, Object> dataMap = new HashMap<String, Object>();
            HashMap<String, Object> columnHeaderMap = new HashMap<String, Object>();
            HashMap<String, Object> columnCSVindexMap = new HashMap<String, Object>();
            JSONArray customfield = new JSONArray();
            for (int k = 0; k < mapping.length(); k++) {
                JSONObject mappingJson = mapping.getJSONObject(k);
                String datakey = mappingJson.getString("columnname");
                Object dataValue = cleanHTML((String) fileData[mappingJson.getInt("csvindex") + 1]); //+1 for id column at index-0
                dataMap.put(datakey, dataValue);
                columnHeaderMap.put(datakey, mappingJson.getString("csvheader"));
                columnCSVindexMap.put(datakey, mappingJson.getInt("csvindex") + 1);
            }

            for (int j = 0; j < extraParams.length(); j++) {
                String datakey = (String) extraParams.names().get(j);
                Object dataValue = extraParams.get(datakey);
                dataMap.put(datakey, dataValue);
            }

            try {
                if (total >= IMPORT_LIMIT) {
                    exceededLimit = "yes";
                    break;
                }
                //Update processing status at client side
                if (total > 0 && total % 10 == 0) {
                    try {
                        ServerEventManager.publish(channelName,
                                "{parsedCount:" + total + ",invalidCount:" + failed + ", fileSize:" + fileSize
                                        + ", finishedValidation:false}",
                                (ServletContext) requestParams.get("servletContext"));
                    } catch (Exception ex) {
                        throw ex;
                    }
                }

                //                    CheckUniqueRecord(requestParams, dataMap, classPath, uniqueKeyMethodName, uniqueKeyHbmName);
                validateDataMAP2(requestParams, dataMap, columnConfig, customfield, columnHeaderMap,
                        columnCSVindexMap, dateFormat, importDao, new HashMap<String, String>());
            } catch (Exception ex) {
                failed++;
                String errorMsg = ex.getMessage(), invalidColumns = "";
                try {
                    JSONObject errorLog = new JSONObject(errorMsg);
                    errorMsg = errorLog.getString("errorMsg");
                    invalidColumns = errorLog.getString("invalidColumns");
                } catch (JSONException jex) {
                }

                importDao.markRecordValidation(tableName, recIndex, 0, errorMsg, invalidColumns);
                if (batchCounter % 30 == 0) {
                    session.flush();
                    session.clear();
                }
                batchCounter++;
                JSONObject jtemp = new JSONObject();
                if (tempFileData != null) {
                    for (int i = 0; i < tempFileData.length - 2; i++) {
                        jtemp.put("col" + i, tempFileData[i] == null ? "" : tempFileData[i].toString());
                    }
                } else {
                    for (int i = 0; i < fileData.length - 2; i++) {
                        jtemp.put("col" + i, fileData[i] == null ? "" : fileData[i].toString());
                    }
                }
                jtemp.put("invalidcolumns", invalidColumns);
                jtemp.put("validateLog", errorMsg);
                DataJArr.put(jtemp);

                //                    try {
                //                        jtemp.put("count", failed);
                //                        jtemp.put("totalrecords", total+1);
                //                        jtemp.put("fileSize", fileSize);
                //                        jtemp.put("finishedValidation", false);
                //                        ServerEventManager.publish(channelName, jtemp.toString(), (ServletContext) requestParams.get("servletContext"));
                //                    } catch(Exception dex) {
                //                        throw dex;
                //                    }
            }
            total++;
        }

        int success = total - failed;
        if (total == 0) {
            msg = "Empty file.";
        } else if (success == 0) {
            msg = "All the records are invalid.";
        } else if (success == total) {
            msg = "All the records are valid.";
        } else {
            msg = "" + success + " valid record" + (success > 1 ? "s" : "") + "";
            msg += (failed == 0 ? "." : " and " + failed + " invalid record" + (failed > 1 ? "s" : "") + ".");
        }

        jobj.put("record", recordJArr);
        jobj.put("columns", columnsJArr);
        jobj.put("data", DataJArr);
        jobj.put("count", failed);
        jobj.put("valid", success);
        jobj.put("totalrecords", total);

        try {
            ServerEventManager.publish(channelName,
                    "{parsedCount:" + total + ",invalidCount:" + failed + ", fileSize:" + fileSize
                            + ", finishedValidation:true}",
                    (ServletContext) requestParams.get("servletContext"));
        } catch (Exception ex) {
            throw ex;
        }

        try {
            txnManager.commit(status);
        } catch (Exception ex) {
            commitedEx = true;
            throw ex;
        }
    } catch (Exception e) {
        if (!commitedEx) { //if exception occurs during commit then dont call rollback
            txnManager.rollback(status);
        }
        issuccess = false;
        msg = "" + e.getMessage();
        Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        try {
            jobj.put("success", issuccess);
            jobj.put("msg", msg);
            jobj.put("exceededLimit", exceededLimit);
        } catch (JSONException ex) {
            Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return jobj;
}

From source file:com.krawler.spring.importFunctionality.ImportUtil.java

/**
 * @param requestParams/*from  w ww . java 2 s. c o m*/
 * @param txnManager
 * @param KwlCommonTablesDAOObj
 * @param importDao
 * @param fieldManagerDAOobj
 * @return
 */
public static JSONObject importFileData(HashMap<String, Object> requestParams,
        HibernateTransactionManager txnManager, kwlCommonTablesDAO KwlCommonTablesDAOObj, ImportDAO importDao,
        fieldManagerDAO fieldManagerDAOobj) {

    JSONObject jobj = new JSONObject();
    String msg = "";
    boolean issuccess = true;

    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("import_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = txnManager.getTransaction(def);
    boolean commitedEx = false;

    int total = 0, failed = 0;
    String fileName = "", tableName = "", extn = "";
    Modules module = null;

    try {
        String moduleID = "";
        String mode = (String) requestParams.get("modName");
        fileName = (String) requestParams.get("filename");
        String companyid = (String) requestParams.get("companyid");
        extn = fileName.substring(fileName.lastIndexOf(".") + 1);
        StringBuilder failedRecords = new StringBuilder();

        String dateFormat = null, dateFormatId = (String) requestParams.get("dateFormat");
        if (extn.equalsIgnoreCase("csv") && !StringUtil.isNullOrEmpty(dateFormatId)) {
            KWLDateFormat kdf = (KWLDateFormat) KwlCommonTablesDAOObj
                    .getClassObject(KWLDateFormat.class.getName(), dateFormatId);
            dateFormat = kdf != null ? kdf.getJavaForm() : null;
        }

        Object extraObj = requestParams.get("extraObj");
        JSONObject extraParams = (JSONObject) requestParams.get("extraParams");

        String jsondata = (String) requestParams.get("resjson");
        JSONObject rootcsvjobj = new JSONObject(jsondata);
        JSONArray mapping = rootcsvjobj.getJSONArray("root");

        String classPath = "", primaryKey = "", uniqueKeyMethodName = "", uniqueKeyHbmName = "";
        try {
            List list = importDao.getModuleObject(mode);
            module = (Modules) list.get(0); //Will throw null pointer if no module entry found
        } catch (Exception ex) {
            throw new DataInvalidateException("Column config not available for module " + mode);
        }

        try {
            classPath = module.getPojoClassPathFull().toString();
            primaryKey = module.getPrimaryKey_MethodName().toString();
            moduleID = module.getId();
        } catch (Exception ex) {
            throw new DataInvalidateException("Please set proper properties for module " + mode);
        }
        uniqueKeyMethodName = module.getUniqueKey_MethodName();
        uniqueKeyHbmName = module.getUniqueKey_HbmName();

        JSONArray columnConfig = getModuleColumnConfig1(module.getId(), companyid, fieldManagerDAOobj,
                module.getModuleName(), true);
        tableName = importDao.getTableName(fileName);
        HashMap<String, Object> filterParams = new HashMap<String, Object>();
        //            filterParams.put("isvalid", 1); //To fetch valid records
        KwlReturnObject kresult = importDao.getFileData(tableName, filterParams); //Fetch all valid records
        List fileDataList = kresult.getEntityList();
        Iterator itr = fileDataList.iterator();
        if (itr.hasNext()) {
            Object[] fileData = (Object[]) itr.next(); //Skip header row
            failedRecords.append(createCSVrecord(fileData) + "\"Error Message\"");//failedRecords.append("\"Row No.\","+createCSVrecord(fileData)+"\"Error Message\"");
        }
        int recIndex = 0;
        importDao.markRecordValidation(tableName, -1, 1, "", ""); //reset all invalidation
        int batchCounter = 0;
        Session session = txnManager.getSessionFactory().getCurrentSession();

        /*-Auto no custom column changes*/
        String customdataclasspath = "";
        int intModuleId = 0;
        if (moduleID.equals(Constants.MODULEID_LEAD)) {
            intModuleId = Constants.Crm_lead_moduleid;
            customdataclasspath = Constants.Crm_lead_custom_data_classpath;
        } else if (moduleID.equals(Constants.MODULEID_ACCOUNT)) {
            intModuleId = Constants.Crm_account_moduleid;
            customdataclasspath = Constants.Crm_account_custom_data_classpath;
        } else if (moduleID.equals(Constants.MODULEID_CONTACT)) {
            intModuleId = Constants.Crm_contact_moduleid;
            customdataclasspath = Constants.Crm_contact_custom_data_classpath;
        } else if (moduleID.equals(Constants.MODULEID_OPPORTUNITY)) {
            intModuleId = Constants.Crm_opportunity_moduleid;
            customdataclasspath = Constants.Crm_opportunity_custom_data_classpath;
        } else if (moduleID.equals(Constants.MODULEID_CASE)) {
            intModuleId = Constants.Crm_case_moduleid;
            customdataclasspath = Constants.Crm_case_custom_data_classpath;
        } else if (moduleID.equals(Constants.MODULEID_PRODUCT)) {
            intModuleId = Constants.Crm_product_moduleid;
            customdataclasspath = Constants.Crm_product_custom_data_classpath;
        }
        List autoNoFieldName = new ArrayList();
        HashMap<String, String> autoNoMap = new HashMap<String, String>();
        HashMap<String, Object> fieldrequestParams = new HashMap<String, Object>();
        fieldrequestParams.put("isexport", true);
        fieldrequestParams.put("filter_names", Arrays.asList("companyid", "moduleid", "fieldtype"));
        fieldrequestParams.put("filter_values",
                Arrays.asList(companyid, intModuleId, Constants.CUSTOM_FIELD_AUTONUMBER));
        KwlReturnObject AutoNoFieldMap = fieldManagerDAOobj.getFieldParams(fieldrequestParams);
        if (AutoNoFieldMap.getEntityList().size() != 0) {
            List<FieldParams> autNoList = AutoNoFieldMap.getEntityList();
            for (FieldParams obj : autNoList) {
                String maxNo = fieldManagerDAOobj.getMaxAutoNumber(
                        Constants.Custom_column_Prefix + obj.getColnum(), customdataclasspath, companyid,
                        obj.getPrefix(), obj.getSuffix());
                Integer maxNumber = Integer.parseInt(maxNo) + 1;
                autoNoMap.put(obj.getFieldname(), maxNumber.toString());
                autoNoFieldName.add(obj.getFieldname());
                autoNoMap.put(obj.getFieldname() + "_" + Constants.CUSTOM_FIELD_PREFIX, obj.getPrefix());
                autoNoMap.put(obj.getFieldname() + "_" + Constants.CUSTOM_FIELD_SUFFIX, obj.getSuffix());
            }
        }
        // End
        while (itr.hasNext()) {
            total++;
            Object[] fileData = (Object[]) itr.next();
            recIndex = (Integer) fileData[0];
            HashMap<String, Object> dataMap = new HashMap<String, Object>();
            HashMap<String, Object> columnHeaderMap = new HashMap<String, Object>();
            HashMap<String, Object> columnCSVindexMap = new HashMap<String, Object>();
            JSONArray customfield = new JSONArray();
            for (int k = 0; k < mapping.length(); k++) {
                JSONObject mappingJson = mapping.getJSONObject(k);
                String datakey = mappingJson.getString("columnname");
                Object dataValue = cleanHTML(fileData[mappingJson.getInt("csvindex") + 1] == null ? null
                        : String.valueOf(fileData[mappingJson.getInt("csvindex") + 1])); //+1 for id column at index-0
                dataMap.put(datakey, dataValue);
                columnHeaderMap.put(datakey, mappingJson.getString("csvheader"));
                columnCSVindexMap.put(datakey, mappingJson.getInt("csvindex") + 1);
            }

            for (int j = 0; j < extraParams.length(); j++) {
                String datakey = (String) extraParams.names().get(j);
                Object dataValue = extraParams.get(datakey);
                dataMap.put(datakey, dataValue);
            }

            Object object = null;
            try {
                //                    CheckUniqueRecord(requestParams, dataMap, classPath, uniqueKeyMethodName, uniqueKeyHbmName);
                validateDataMAP2(requestParams, dataMap, columnConfig, customfield, columnHeaderMap,
                        columnCSVindexMap, dateFormat, importDao, autoNoMap);
                object = importDao.saveRecord(requestParams, dataMap, null, mode, classPath, primaryKey,
                        extraObj, customfield);
                if (batchCounter % 100 == 0) {
                    session.flush();
                    session.clear();
                }
                batchCounter++;
            } catch (Exception ex) {
                failed++;
                String errorMsg = ex.getMessage(), invalidColumns = "";
                try {
                    JSONObject errorLog = new JSONObject(errorMsg);
                    errorMsg = errorLog.getString("errorMsg");
                    invalidColumns = errorLog.getString("invalidColumns");
                } catch (JSONException jex) {
                }
                failedRecords.append("\n" + createCSVrecord(fileData) + "\"" + errorMsg + "\"");//failedRecords.append("\n"+(total)+","+createCSVrecord(fileData)+"\""+ex.getMessage()+"\"");
                importDao.markRecordValidation(tableName, recIndex, 0, errorMsg, invalidColumns);
            }
        }

        if (failed > 0) {
            createFailureFiles(fileName, failedRecords, ".csv");
        }

        int success = total - failed;
        if (total == 0) {
            msg = "Empty file.";
        } else if (success == 0) {
            msg = "Failed to import all the records.";
        } else if (success == total) {
            msg = "All records are imported successfully.";
        } else {
            msg = "Imported " + success + " record" + (success > 1 ? "s" : "") + " successfully";
            msg += (failed == 0 ? "."
                    : " and failed to import " + failed + " record" + (failed > 1 ? "s" : "") + ".");
        }

        try {
            txnManager.commit(status);
            importDao.linkCustomData(mode);
        } catch (Exception ex) {
            commitedEx = true;
            throw ex;
        }
    } catch (Exception e) {
        if (!commitedEx) { //if exception occurs during commit then dont call rollback
            txnManager.rollback(status);
        }
        issuccess = false;
        msg = "" + e.getMessage();
        Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        DefaultTransactionDefinition ldef = new DefaultTransactionDefinition();
        ldef.setName("import_Tx");
        ldef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus lstatus = txnManager.getTransaction(ldef);
        boolean exCommit = false;
        try {
            //Insert Integration log

            requestParams.put("modulename", module.getModuleName());
            requestParams.put("validflag", 2);
            if (!module.getModuleName().equals("Target") && !module.getModuleName().equals("Calibration"))
                fieldManagerDAOobj.validateimportrecords(requestParams);

            HashMap<String, Object> logDataMap = new HashMap<String, Object>();
            String logId = (String) requestParams.get("logId");
            if (!StringUtil.isNullOrEmpty(logId)) {
                logDataMap.put("Id", logId);
            }
            failed = issuccess ? failed : total;
            logDataMap.put("FileName", ImportLog.getActualFileName(fileName));
            logDataMap.put("StorageName", fileName);
            logDataMap.put("Log", msg);
            logDataMap.put("Type", fileName.substring(fileName.lastIndexOf(".") + 1));
            logDataMap.put("TotalRecs", total);
            logDataMap.put("Rejected", failed);
            logDataMap.put("Module", module.getId());
            logDataMap.put("ImportDate", new Date());
            logDataMap.put("User", (String) requestParams.get("userid"));
            logDataMap.put("Company", (String) requestParams.get("companyid"));
            importDao.saveImportLog(logDataMap);
            importDao.removeFileTable(tableName);//Remove table after importing all records
            try {
                txnManager.commit(lstatus);
            } catch (Exception ex) {
                exCommit = true;
                throw ex;
            }
        } catch (Exception ex) {
            if (!exCommit) { //if exception occurs during commit then dont call rollback
                txnManager.rollback(lstatus);
            }
            Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            jobj.put("success", issuccess);
            jobj.put("msg", msg);
            jobj.put("totalrecords", total);
            jobj.put("successrecords", total - failed);
            jobj.put("failedrecords", failed);
            jobj.put("filename", ImportLog.getActualFileName(fileName));
        } catch (JSONException ex) {
            Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return jobj;
}

From source file:org.ohmage.query.impl.DocumentQueries.java

public String createDocument(byte[] contents, String name, String description,
        Document.PrivacyState privacyState, Map<String, Document.Role> campaignRoleMap,
        Map<String, Document.Role> classRoleMap, String creatorUsername) throws DataAccessException {

    // Create a new, random UUID to use to save this file.
    String uuid = UUID.randomUUID().toString();

    // getDirectory() is used as opposed to accessing the current leaf
    // directory class variable as it will do sanitation in case it hasn't
    // been initialized or is full.
    File documentDirectory = getDirectory();
    File newFile = new File(documentDirectory.getAbsolutePath() + "/" + uuid);
    String url = "file://" + newFile.getAbsolutePath();

    // Write the document to the file system.
    try {//w w  w  .j av  a 2s.c om
        FileOutputStream os = new FileOutputStream(newFile);
        os.write(contents);
        os.flush();
        os.close();
    } catch (IOException e) {
        throw new DataAccessException("Error writing the new document to the system.", e);
    }
    long fileLength = newFile.length();

    // Parse the name and get the extension.
    String extension = getExtension(name);

    // Create the transaction.
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Creating a new document.");

    try {
        // Begin the transaction.
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        // Insert the file in the DB.
        try {
            getJdbcTemplate().update(SQL_INSERT_DOCUMENT, new Object[] { uuid, name, description, extension,
                    url, fileLength, privacyState.toString() });
        } catch (org.springframework.dao.DataAccessException e) {
            if (newFile.delete()) {
                LOGGER.warn("Could not delete the file that was just created: " + newFile.toString());
            }
            transactionManager.rollback(status);
            throw new DataAccessException("Error executing SQL '" + SQL_INSERT_DOCUMENT + "' with parameters: "
                    + uuid + ", " + name + ", " + description + ", " + extension + ", " + url + ", "
                    + fileLength + ", " + privacyState, e);
        }

        // Insert the creator in the DB.
        try {
            getJdbcTemplate().update(SQL_INSERT_DOCUMENT_USER_CREATOR, new Object[] { uuid, creatorUsername });
        } catch (org.springframework.dao.DataAccessException e) {
            if (newFile.delete()) {
                LOGGER.warn("Could not delete the file that was just created: " + newFile.toString());
            }
            transactionManager.rollback(status);
            throw new DataAccessException("Error executing SQL '" + SQL_INSERT_DOCUMENT_USER_CREATOR
                    + "' with parameters: " + uuid + ", " + creatorUsername, e);
        }

        // Insert this user's user-role in the DB.
        try {
            getJdbcTemplate().update(SQL_INSERT_USER_ROLE,
                    new Object[] { uuid, creatorUsername, Document.Role.OWNER.toString() });
        } catch (org.springframework.dao.DataAccessException e) {
            if (newFile.delete()) {
                LOGGER.warn("Could not delete the file that was just created: " + newFile.toString());
            }
            transactionManager.rollback(status);
            throw new DataAccessException("Error executing SQL '" + SQL_INSERT_USER_ROLE + "' with parameters: "
                    + uuid + ", " + creatorUsername + ", " + Document.Role.OWNER, e);
        }

        // Insert any campaign associations in the DB.
        if (campaignRoleMap != null) {
            for (String campaignId : campaignRoleMap.keySet()) {
                // Attempt to insert it into the database.
                try {
                    getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_ROLE,
                            new Object[] { uuid, campaignId, campaignRoleMap.get(campaignId).toString() });
                } catch (org.springframework.dao.DataAccessException e) {
                    if (newFile.delete()) {
                        LOGGER.warn("Could not delete the file that was just created: " + newFile.toString());
                    }
                    transactionManager.rollback(status);
                    throw new DataAccessException(
                            "Error executing SQL '" + SQL_INSERT_CAMPAIGN_ROLE + "' with parameters: " + uuid
                                    + ", " + campaignId + ", " + campaignRoleMap.get(campaignId),
                            e);
                }
            }
        }

        // Insert any class associations in the DB.
        if (classRoleMap != null) {
            for (String classId : classRoleMap.keySet()) {
                // Attempt to insert it into the database.
                try {
                    getJdbcTemplate().update(SQL_INSERT_CLASS_ROLE,
                            new Object[] { uuid, classId, classRoleMap.get(classId).toString() });
                } catch (org.springframework.dao.DataAccessException e) {
                    if (newFile.delete()) {
                        LOGGER.warn("Could not delete the file that was just created: " + newFile.toString());
                    }
                    transactionManager.rollback(status);
                    throw new DataAccessException("Error executing SQL '" + SQL_INSERT_CLASS_ROLE
                            + "' with parameters: " + uuid + ", " + classId + ", " + classRoleMap.get(classId),
                            e);
                }
            }
        }

        // Commit the transaction.
        try {
            transactionManager.commit(status);
        } catch (TransactionException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error while committing the transaction.", e);
        }

        return uuid;
    } 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 deleteCampaign(String campaignId) throws DataAccessException {
    // Create the transaction.
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Deleting a campaign.");

    try {/*  w  ww .ja  v  a 2  s  .c  o  m*/
        // Begin the transaction.
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        try {
            getJdbcTemplate().update(SQL_DELETE_CAMPAIGN, campaignId);
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException(
                    "Error executing SQL '" + SQL_DELETE_CAMPAIGN + "' with parameter: " + campaignId, 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   w  w w. j a va  2  s. co 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.CampaignQueries.java

public void updateCampaign(String campaignId, String xml, String description,
        Campaign.RunningState runningState, Campaign.PrivacyState privacyState, Collection<String> classesToAdd,
        Collection<String> classesToRemove, Map<String, Set<Campaign.Role>> usersAndRolesToAdd,
        Map<String, Set<Campaign.Role>> usersAndRolesToRemove) throws DataAccessException {

    // Create the transaction.
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Updating a campaign.");

    try {/* w  w w.  j  a  v a 2 s .  com*/
        // Begin the transaction.
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        // Update the XML if it is present.
        if (xml != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_XML, new Object[] { xml, campaignId });
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException("Error executing SQL '" + SQL_UPDATE_XML + "' with parameters: "
                        + xml + ", " + campaignId, e);
            }
        }

        // Update the description if it is present.
        if (description != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_DESCRIPTION, new Object[] { description, campaignId });
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException("Error executing SQL '" + SQL_UPDATE_DESCRIPTION
                        + "' with parameters: " + description + ", " + campaignId, e);
            }
        }

        // Update the running state if it is present.
        if (runningState != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_RUNNING_STATE,
                        new Object[] { runningState.toString(), campaignId });
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException("Error executing SQL '" + SQL_UPDATE_RUNNING_STATE
                        + "' with parameters: " + runningState + ", " + campaignId, e);
            }
        }

        // Update the privacy state if it is present.
        if (privacyState != null) {
            try {
                getJdbcTemplate().update(SQL_UPDATE_PRIVACY_STATE,
                        new Object[] { privacyState.toString(), campaignId });
            } catch (org.springframework.dao.DataAccessException e) {
                transactionManager.rollback(status);
                throw new DataAccessException("Error executing SQL '" + SQL_UPDATE_PRIVACY_STATE
                        + "' with parameters: " + privacyState + ", " + campaignId, e);
            }
        }

        // Add the specific users with specific roles.
        if (usersAndRolesToAdd != null) {
            for (String username : usersAndRolesToAdd.keySet()) {
                for (Campaign.Role role : usersAndRolesToAdd.get(username)) {
                    try {
                        getJdbcTemplate().update(SQL_INSERT_USER_ROLE_CAMPAIGN,
                                new Object[] { username, campaignId, role.toString() });
                    } catch (org.springframework.dao.DuplicateKeyException e) {
                        // This means that the user already had the role in
                        // the campaign. We can ignore this.
                    } catch (org.springframework.dao.DataAccessException e) {
                        transactionManager.rollback(status);
                        throw new DataAccessException("Error executing SQL '" + SQL_INSERT_USER_ROLE_CAMPAIGN
                                + "' with parameters: " + username + ", " + campaignId + ", " + role, e);
                    }
                }
            }
        }

        // Remove the specific users and their roles.
        if (usersAndRolesToRemove != null) {
            for (String username : usersAndRolesToRemove.keySet()) {
                for (Campaign.Role role : usersAndRolesToRemove.get(username)) {
                    try {
                        getJdbcTemplate().update(SQL_DELETE_USER_ROLE_CAMPAIGN,
                                new Object[] { username, campaignId, role.toString() });
                    } catch (org.springframework.dao.DataAccessException e) {
                        transactionManager.rollback(status);
                        throw new DataAccessException("Error executing SQL '" + SQL_DELETE_USER_ROLE_CAMPAIGN
                                + "' with parameters: " + username + ", " + campaignId + ", " + role, e);
                    }
                }
            }
        }

        if (classesToRemove != null) {
            // For all of the classes that are associated with the campaign
            // but are not in the classIds list,
            for (String classId : classesToRemove) {
                // For each of the users in the class, if they are only 
                // associated with the campaign through this class then 
                // remove them.
                List<String> usernames;
                try {
                    usernames = userClassQueries.getUsersInClass(classId);
                } catch (DataAccessException e) {
                    transactionManager.rollback(status);
                    throw e;
                }

                for (String username : usernames) {
                    // If the user is not associated with the campaign 
                    // through any other class, they are removed from the
                    // campaign.
                    int numClasses;
                    try {
                        numClasses = userCampaignClassQueries
                                .getNumberOfClassesThroughWhichUserIsAssociatedWithCampaign(username,
                                        campaignId);
                    } catch (DataAccessException e) {
                        transactionManager.rollback(status);
                        throw e;
                    }
                    if (numClasses == 1) {
                        // Retrieve the default roles that the user was 
                        // given when they joined the class.
                        List<Campaign.Role> roles;
                        try {
                            roles = getJdbcTemplate().query(SQL_GET_USER_DEFAULT_ROLES,
                                    new Object[] { username, campaignId, classId },
                                    new RowMapper<Campaign.Role>() {
                                        @Override
                                        public Campaign.Role mapRow(ResultSet rs, int rowNum)
                                                throws SQLException {
                                            return Campaign.Role.getValue(rs.getString("role"));
                                        }
                                    });
                        } catch (org.springframework.dao.DataAccessException e) {
                            transactionManager.rollback(status);
                            throw new DataAccessException("Error executing SQL '" + SQL_GET_USER_DEFAULT_ROLES
                                    + "' with parameters: " + username + ", " + campaignId + ", " + classId, e);
                        }

                        for (Campaign.Role role : roles) {
                            try {
                                getJdbcTemplate().update(SQL_DELETE_USER_ROLE_CAMPAIGN,
                                        new Object[] { username, campaignId, role.toString() });
                            } catch (org.springframework.dao.DataAccessException e) {
                                transactionManager.rollback(status);
                                throw new DataAccessException("Error executing SQL '"
                                        + SQL_DELETE_USER_ROLE_CAMPAIGN + "' with parameters: " + username
                                        + ", " + campaignId + ", " + role, e);
                            }
                        }
                    }
                }

                // Remove the campaign, class association.
                try {
                    getJdbcTemplate().update(SQL_DELETE_CAMPAIGN_CLASS, new Object[] { campaignId, classId });
                } catch (org.springframework.dao.DataAccessException e) {
                    transactionManager.rollback(status);
                    throw new DataAccessException("Error executing SQL '" + SQL_DELETE_CAMPAIGN_CLASS
                            + "' with parameters: " + campaignId + ", " + classId, e);
                }
            }
        }

        if (classesToAdd != null) {
            // For all of the classes that are in the classIds list but not
            // associated with the campaign,
            for (String classId : classesToAdd) {
                associateCampaignAndClass(transactionManager, status, campaignId, classId);
            }
        }

        // 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);
    }
}