List of usage examples for java.text SimpleDateFormat applyPattern
public void applyPattern(String pattern)
From source file:org.sakaiproject.contentreview.turnitin.TurnitinReviewServiceImpl.java
/** * Update Assignment. This method is not currently called by Assignments 1. *//*from w w w . j a v a2 s . c o m*/ public void updateAssignment(String siteId, String taskId) throws SubmissionException { log.info("updateAssignment(" + siteId + " , " + taskId + ")"); // get the assignment reference String taskTitle = getAssignmentTitle(taskId); log.debug("Creating assignment for site: " + siteId + ", task: " + taskId + " tasktitle: " + taskTitle); SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); dform.applyPattern(TURNITIN_DATETIME_FORMAT); Calendar cal = Calendar.getInstance(); // set this to yesterday so we avoid timezpne problems etc cal.add(Calendar.DAY_OF_MONTH, -1); String dtstart = dform.format(cal.getTime()); // set the due dates for the assignments to be in 5 month's time // turnitin automatically sets each class end date to 6 months after it // is created // the assignment end date must be on or before the class end date // TODO use the 'secret' function to change this to longer cal.add(Calendar.MONTH, 5); String dtdue = dform.format(cal.getTime()); String fcmd = "3"; // new assignment String fid = "4"; // function id String utp = "2"; // user type 2 = instructor String s_view_report = "1"; // erater String erater = "0"; String ets_handbook = "1"; String ets_dictionary = "en"; String ets_spelling = "1"; String ets_style = "1"; String ets_grammar = "1"; String ets_mechanics = "1"; String ets_usage = "1"; String cid = siteId; String assignid = taskId; String assign = taskTitle; String ctl = siteId; String assignEnc = assign; try { if (assign.contains("&")) { // log.debug("replacing & in assingment title"); assign = assign.replace('&', 'n'); } assignEnc = assign; log.debug("Assign title is " + assignEnc); } catch (Exception e) { e.printStackTrace(); } Map params = TurnitinAPIUtil.packMap(turnitinConn.getBaseTIIOptions(), "assign", assignEnc, "assignid", assignid, "cid", cid, "ctl", ctl, "dtdue", dtdue, "dtstart", dtstart, "fcmd", fcmd, "fid", fid, "s_view_report", s_view_report, "utp", utp, "erater", erater, "ets_handbook", ets_handbook, "ets_dictionary", ets_dictionary, "ets_spelling", ets_spelling, "ets_style", ets_style, "ets_grammar", ets_grammar, "ets_mechanics", ets_mechanics, "ets_usage", ets_usage); params.putAll(getInstructorInfo(siteId)); Document document = null; try { document = turnitinConn.callTurnitinReturnDocument(params); } catch (TransientSubmissionException tse) { log.error("Error on API call in updateAssignment siteid: " + siteId + " taskid: " + taskId, tse); return; } catch (SubmissionException se) { log.error("Error on API call in updateAssignment siteid: " + siteId + " taskid: " + taskId, se); return; } Element root = document.getDocumentElement(); int rcode = new Integer( ((CharacterData) (root.getElementsByTagName("rcode").item(0).getFirstChild())).getData().trim()) .intValue(); if ((rcode > 0 && rcode < 100) || rcode == 419) { log.debug("Create Assignment successful"); } else { log.debug("Assignment creation failed with message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData() .trim() + ". Code: " + rcode); throw new SubmissionException("Create Assignment not successful. Message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData() .trim() + ". Code: " + rcode); } }
From source file:org.sakaiproject.contentreview.turnitin.TurnitinReviewServiceImpl.java
@SuppressWarnings({ "deprecation", "unchecked" }) public void checkForReportsBulk() { SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); dform.applyPattern(TURNITIN_DATETIME_FORMAT); log.info("Fetching reports from Turnitin"); // get the list of all items that are waiting for reports List<ContentReviewItem> awaitingReport = crqs.getAwaitingReports(getProviderId()); Iterator<ContentReviewItem> listIterator = awaitingReport.iterator(); HashMap<String, Integer> reportTable = new HashMap<String, Integer>(); log.debug("There are " + awaitingReport.size() + " submissions awaiting reports"); ContentReviewItem currentItem;/* w ww . j av a 2 s. c o m*/ while (listIterator.hasNext()) { currentItem = (ContentReviewItem) listIterator.next(); // has the item reached its next retry time? if (currentItem.getNextRetryTime() == null) currentItem.setNextRetryTime(new Date()); if (currentItem.getNextRetryTime().after(new Date())) { // we haven't reached the next retry time log.info("next retry time not yet reached for item: " + currentItem.getId()); crqs.update(currentItem); continue; } if (currentItem.getRetryCount() == null) { currentItem.setRetryCount(Long.valueOf(0)); currentItem.setNextRetryTime(this.getNextRetryTime(0)); } else if (currentItem.getRetryCount().intValue() > maxRetry) { currentItem.setStatus(ContentReviewConstants.CONTENT_REVIEW_SUBMISSION_ERROR_RETRY_EXCEEDED_CODE); crqs.update(currentItem); continue; } else { log.debug("Still have retries left, continuing. ItemID: " + currentItem.getId()); // Moving down to check for report generate speed. // long l = currentItem.getRetryCount().longValue(); // l++; // currentItem.setRetryCount(Long.valueOf(l)); // currentItem.setNextRetryTime(this.getNextRetryTime(Long.valueOf(l))); // dao.update(currentItem); } if (currentItem.getExternalId() == null || currentItem.getExternalId().equals("")) { currentItem.setStatus(Long.valueOf(4)); crqs.update(currentItem); continue; } if (!reportTable.containsKey(currentItem.getExternalId())) { // get the list from turnitin and see if the review is available log.debug("Attempting to update hashtable with reports for site " + currentItem.getSiteId()); String fcmd = "2"; String fid = "10"; try { User user = userDirectoryService.getUser(currentItem.getUserId()); } catch (Exception e) { log.error("Unable to look up user: " + currentItem.getUserId() + " for contentItem: " + currentItem.getId(), e); } String cid = currentItem.getSiteId(); String tem = getTEM(cid); String utp = "2"; String assignid = currentItem.getTaskId(); String assign = currentItem.getTaskId(); String ctl = currentItem.getSiteId(); // TODO FIXME Current sgithens // Move the update setRetryAttempts to here, and first call and // check the assignment from TII to see if the generate until // due is enabled. In that case we don't want to waste retry // attempts and should just continue. try { // TODO FIXME This is broken at the moment because we need // to have a userid, but this is assuming it's coming from // the thread, but we're in a quartz job. // Map curasnn = getAssignment(currentItem.getSiteId(), // currentItem.getTaskId()); // TODO FIXME Parameterize getAssignment method to take user // information Map getAsnnParams = TurnitinAPIUtil.packMap(turnitinConn.getBaseTIIOptions(), "assign", getAssignmentTitle(currentItem.getTaskId()), "assignid", currentItem.getTaskId(), "cid", currentItem.getSiteId(), "ctl", currentItem.getSiteId(), "fcmd", "7", "fid", "4", "utp", "2"); getAsnnParams.putAll(getInstructorInfo(currentItem.getSiteId())); Map curasnn = turnitinConn.callTurnitinReturnMap(getAsnnParams); if (curasnn.containsKey("object")) { Map curasnnobj = (Map) curasnn.get("object"); String reportGenSpeed = (String) curasnnobj.get("generate"); String duedate = (String) curasnnobj.get("dtdue"); SimpleDateFormat retform = ((SimpleDateFormat) DateFormat.getDateInstance()); retform.applyPattern(TURNITIN_DATETIME_FORMAT); Date duedateObj = null; try { if (duedate != null) { duedateObj = retform.parse(duedate); } } catch (ParseException pe) { log.warn("Unable to parse turnitin dtdue: " + duedate, pe); } if (reportGenSpeed != null && duedateObj != null && reportGenSpeed.equals("2") && duedateObj.after(new Date())) { log.info( "Report generate speed is 2, skipping for now. ItemID: " + currentItem.getId()); // If there was previously a transient error for // this item, reset the status if (ContentReviewConstants.CONTENT_REVIEW_REPORT_ERROR_RETRY_CODE .equals(currentItem.getStatus())) { currentItem.setStatus( ContentReviewConstants.CONTENT_REVIEW_SUBMITTED_AWAITING_REPORT_CODE); currentItem.setLastError(null); currentItem.setErrorCode(null); crqs.update(currentItem); } continue; } else { log.debug("Incrementing retry count for currentItem: " + currentItem.getId()); long l = currentItem.getRetryCount().longValue(); l++; currentItem.setRetryCount(Long.valueOf(l)); currentItem.setNextRetryTime(this.getNextRetryTime(Long.valueOf(l))); crqs.update(currentItem); } } } catch (SubmissionException e) { log.error("Unable to check the report gen speed of the asnn for item: " + currentItem.getId(), e); } catch (TransientSubmissionException e) { log.error("Unable to check the report gen speed of the asnn for item: " + currentItem.getId(), e); } Map params = new HashMap(); // try { params = TurnitinAPIUtil.packMap(turnitinConn.getBaseTIIOptions(), "fid", fid, "fcmd", fcmd, "tem", tem, "assign", assign, "assignid", assignid, "cid", cid, "ctl", ctl, "utp", utp); params.putAll(getInstructorInfo(currentItem.getSiteId())); Document document = null; try { document = turnitinConn.callTurnitinReturnDocument(params); } catch (TransientSubmissionException e) { log.warn("Update failed due to TransientSubmissionException error: " + e.toString(), e); currentItem.setStatus(ContentReviewConstants.CONTENT_REVIEW_REPORT_ERROR_RETRY_CODE); currentItem.setLastError(e.getMessage()); crqs.update(currentItem); break; } catch (SubmissionException e) { log.warn("Update failed due to SubmissionException error: " + e.toString(), e); currentItem.setStatus(ContentReviewConstants.CONTENT_REVIEW_REPORT_ERROR_RETRY_CODE); currentItem.setLastError(e.getMessage()); crqs.update(currentItem); break; } Element root = document.getDocumentElement(); if (((CharacterData) (root.getElementsByTagName("rcode").item(0).getFirstChild())).getData().trim() .compareTo("72") == 0) { log.debug("Report list returned successfully"); NodeList objects = root.getElementsByTagName("object"); String objectId; String similarityScore; String overlap = ""; log.debug(objects.getLength() + " objects in the returned list"); for (int i = 0; i < objects.getLength(); i++) { similarityScore = ((CharacterData) (((Element) (objects.item(i))) .getElementsByTagName("similarityScore").item(0).getFirstChild())).getData().trim(); objectId = ((CharacterData) (((Element) (objects.item(i))).getElementsByTagName("objectID") .item(0).getFirstChild())).getData().trim(); if (similarityScore.compareTo("-1") != 0) { overlap = ((CharacterData) (((Element) (objects.item(i))) .getElementsByTagName("overlap").item(0).getFirstChild())).getData().trim(); reportTable.put(objectId, Integer.valueOf(overlap)); } else { reportTable.put(objectId, Integer.valueOf(-1)); } log.debug("objectId: " + objectId + " similarity: " + similarityScore + " overlap: " + overlap); } } else { log.debug("Report list request not successful"); log.debug(document.getTextContent()); } } int reportVal; // check if the report value is now there (there may have been a // failure to get the list above) if (reportTable.containsKey(currentItem.getExternalId())) { reportVal = ((Integer) (reportTable.get(currentItem.getExternalId()))).intValue(); log.debug("reportVal for " + currentItem.getExternalId() + ": " + reportVal); if (reportVal != -1) { currentItem.setReviewScore(reportVal); currentItem.setStatus(ContentReviewConstants.CONTENT_REVIEW_SUBMITTED_REPORT_AVAILABLE_CODE); currentItem.setDateReportReceived(new Date()); crqs.update(currentItem); log.debug("new report received: " + currentItem.getExternalId() + " -> " + currentItem.getReviewScore()); } } } log.info("Finished fetching reports from Turnitin"); }
From source file:org.sakaiproject.contentreview.turnitin.TurnitinReviewServiceImpl.java
/** * Creates or Updates an Assignment//from www . jav a 2 s .c o m * * This method will look at the current user or default instructor for it's * user information. * * * @param siteId * @param taskId * @param extraAsnnOpts * @throws SubmissionException * @throws TransientSubmissionException */ @SuppressWarnings("unchecked") public void createAssignment(String siteId, String taskId, Map extraAsnnOpts) throws SubmissionException, TransientSubmissionException { // get the assignment reference String taskTitle = ""; if (extraAsnnOpts.containsKey("title")) { taskTitle = extraAsnnOpts.get("title").toString(); } else { getAssignmentTitle(taskId); } log.debug("Creating assignment for site: " + siteId + ", task: " + taskId + " tasktitle: " + taskTitle); SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); dform.applyPattern(TURNITIN_DATETIME_FORMAT); Calendar cal = Calendar.getInstance(); // set this to yesterday so we avoid timezone problems etc // TII-143 seems this now causes problems may need a finner tweak than 1 // day like midnight +1 min or something cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 1); // cal.add(Calendar.DAY_OF_MONTH, -1); String dtstart = dform.format(cal.getTime()); String today = dtstart; // set the due dates for the assignments to be in 5 month's time // turnitin automatically sets each class end date to 6 months after it // is created // the assignment end date must be on or before the class end date String fcmd = "2"; // new assignment boolean asnnExists = false; // If this assignment already exists, we should use fcmd 3 to update it. Map tiiresult = this.getAssignment(siteId, taskId); if (tiiresult.get("rcode") != null && tiiresult.get("rcode").equals("85")) { fcmd = "3"; asnnExists = true; } /* * Some notes about start and due dates. This information is accurate as * of Nov 12, 2009 and was determined by testing and experimentation * with some Sash scripts. * * A turnitin due date, must be after the start date. This makes sense * and follows the logic in both Assignments 1 and 2. * * When *creating* a new Turnitin Assignment, the start date must be * todays date or later. The format for dates only includes the day, and * not any specific times. I believe that, in order to make up for time * zone differences between your location and the turnitin cloud, it can * be basically the current day anywhere currently, with some slack. For * instance I can create an assignment for yesterday, but not for 2 days * ago. Doing so causes an error. * * However! For an existing turnitin assignment, you appear to have the * liberty of changing the start date to sometime in the past. You can * also change an assignment to have a due date in the past as long as * it is still after the start date. * * So, to avoid errors when syncing information, or adding turnitin * support to new or existing assignments we will: * * 1. If the assignment already exists we'll just save it. * * 2. If the assignment does not exist, we will save it once using * todays date for the start and due date, and then save it again with * the proper dates to ensure we're all tidied up and in line. * * Also, with our current class creation, due dates can be 5 years out, * but not further. This seems a bit lower priortity, but we still * should figure out an appropriate way to deal with it if it does * happen. * */ // TODO use the 'secret' function to change this to longer cal.add(Calendar.MONTH, 5); String dtdue = dform.format(cal.getTime()); log.debug("Set date due to: " + dtdue); if (extraAsnnOpts != null && extraAsnnOpts.containsKey("dtdue")) { dtdue = extraAsnnOpts.get("dtdue").toString(); log.debug("Settign date due from external to: " + dtdue); extraAsnnOpts.remove("dtdue"); } String fid = "4"; // function id String utp = "2"; // user type 2 = instructor String s_view_report = "1"; if (extraAsnnOpts != null && extraAsnnOpts.containsKey("s_view_report")) { s_view_report = extraAsnnOpts.get("s_view_report").toString(); extraAsnnOpts.remove("s_view_report"); } // erater String erater = (serverConfigurationService.getBoolean("turnitin.option.erater.default", false)) ? "1" : "0"; String ets_handbook = "1"; String ets_dictionary = "en"; String ets_spelling = "1"; String ets_style = "1"; String ets_grammar = "1"; String ets_mechanics = "1"; String ets_usage = "1"; try { if (extraAsnnOpts != null && extraAsnnOpts.containsKey("erater")) { erater = extraAsnnOpts.get("erater").toString(); extraAsnnOpts.remove("erater"); ets_handbook = extraAsnnOpts.get("ets_handbook").toString(); extraAsnnOpts.remove("ets_handbook"); ets_dictionary = extraAsnnOpts.get("ets_dictionary").toString(); extraAsnnOpts.remove("ets_dictionary"); ets_spelling = extraAsnnOpts.get("ets_spelling").toString(); extraAsnnOpts.remove("ets_spelling"); ets_style = extraAsnnOpts.get("ets_style").toString(); extraAsnnOpts.remove("ets_style"); ets_grammar = extraAsnnOpts.get("ets_grammar").toString(); extraAsnnOpts.remove("ets_grammar"); ets_mechanics = extraAsnnOpts.get("ets_mechanics").toString(); extraAsnnOpts.remove("ets_mechanics"); ets_usage = extraAsnnOpts.get("ets_usage").toString(); extraAsnnOpts.remove("ets_usage"); } } catch (Exception e) { log.info("(createAssignment)erater extraAsnnOpts. " + e); } String cid = siteId; String assignid = taskId; String ctl = siteId; Map params = TurnitinAPIUtil.packMap(turnitinConn.getBaseTIIOptions(), "assign", taskTitle, "assignid", assignid, "cid", cid, "ctl", ctl, "dtdue", dtdue, "dtstart", dtstart, "fcmd", "3", "fid", fid, "s_view_report", s_view_report, "utp", utp, "erater", erater, "ets_handbook", ets_handbook, "ets_dictionary", ets_dictionary, "ets_spelling", ets_spelling, "ets_style", ets_style, "ets_grammar", ets_grammar, "ets_mechanics", ets_mechanics, "ets_usage", ets_usage); // Save instructorInfo up here to reuse for calls in this // method, since theoretically getInstructorInfo could return // different instructors for different invocations and we need // the same one since we're using a session id. Map instructorInfo = getInstructorInfo(siteId); params.putAll(instructorInfo); if (extraAsnnOpts != null) { for (Object key : extraAsnnOpts.keySet()) { if (extraAsnnOpts.get(key) == null) { continue; } params = TurnitinAPIUtil.packMap(params, key.toString(), extraAsnnOpts.get(key).toString()); } } // We only need to use a session id if we are creating this // assignment for the first time. String sessionid = null; Map sessionParams = null; if (!asnnExists) { // Try adding the user in case they don't exist TII-XXX addTurnitinInstructor(instructorInfo); sessionParams = turnitinConn.getBaseTIIOptions(); sessionParams.putAll(instructorInfo); sessionParams.put("utp", utp); sessionid = TurnitinSessionFuncs.getTurnitinSession(turnitinConn, sessionParams); Map firstparams = new HashMap(); firstparams.putAll(params); firstparams.put("session-id", sessionid); firstparams.put("dtstart", today); // Make the due date in the future Calendar caldue = Calendar.getInstance(); caldue.add(Calendar.MONTH, 5); String dtdue_first = dform.format(caldue.getTime()); firstparams.put("dtdue", dtdue_first); log.debug("date due is: " + dtdue); log.debug("Start date: " + today); firstparams.put("fcmd", "2"); Document firstSaveDocument = turnitinConn.callTurnitinReturnDocument(firstparams); Element root = firstSaveDocument.getDocumentElement(); int rcode = new Integer( ((CharacterData) (root.getElementsByTagName("rcode").item(0).getFirstChild())).getData().trim()) .intValue(); if ((rcode > 0 && rcode < 100) || rcode == 419) { log.debug("Create FirstDate Assignment successful"); log.debug("tii returned " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())) .getData().trim() + ". Code: " + rcode); } else { log.debug("FirstDate Assignment creation failed with message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())) .getData().trim() + ". Code: " + rcode); // log.debug(root); throw new TransientSubmissionException("FirstDate Create Assignment not successful. Message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())) .getData().trim() + ". Code: " + rcode, Integer.valueOf(rcode)); } } log.debug("going to attempt second update"); if (sessionid != null) { params.put("session-id", sessionid); } Document document = turnitinConn.callTurnitinReturnDocument(params); Element root = document.getDocumentElement(); int rcode = new Integer( ((CharacterData) (root.getElementsByTagName("rcode").item(0).getFirstChild())).getData().trim()) .intValue(); if ((rcode > 0 && rcode < 100) || rcode == 419) { log.debug("Create Assignment successful"); log.debug("tii returned " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData() .trim() + ". Code: " + rcode); } else { log.debug("Assignment creation failed with message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData() .trim() + ". Code: " + rcode); // log.debug(root); throw new TransientSubmissionException("Create Assignment not successful. Message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData() .trim() + ". Code: " + rcode, Integer.valueOf(rcode)); } if (sessionid != null) { TurnitinSessionFuncs.logoutTurnitinSession(turnitinConn, sessionid, sessionParams); } }
From source file:org.sakaiproject.contentreview.impl.turnitin.TurnitinReviewServiceImpl.java
/** * Update Assignment. This method is not currently called by Assignments 1. * @param siteId// www . ja v a2 s . c o m * @param taskId * @throws org.sakaiproject.contentreview.exception.SubmissionException */ public void updateAssignment(String siteId, String taskId) throws SubmissionException { log.info("updateAssignment(" + siteId + " , " + taskId + ")"); //get the assignment reference String taskTitle = getAssignmentTitle(taskId); log.debug("Creating assignment for site: " + siteId + ", task: " + taskId + " tasktitle: " + taskTitle); SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); dform.applyPattern(TURNITIN_DATETIME_FORMAT); Calendar cal = Calendar.getInstance(); //set this to yesterday so we avoid timezpne problems etc cal.add(Calendar.DAY_OF_MONTH, -1); String dtstart = dform.format(cal.getTime()); //set the due dates for the assignments to be in 5 month's time //turnitin automatically sets each class end date to 6 months after it is created //the assignment end date must be on or before the class end date //TODO use the 'secret' function to change this to longer cal.add(Calendar.MONTH, 5); String dtdue = dform.format(cal.getTime()); String fcmd = "3"; //new assignment String fid = "4"; //function id String utp = "2"; //user type 2 = instructor String s_view_report = "1"; //erater String erater = "0"; String ets_handbook = "1"; String ets_dictionary = "en"; String ets_spelling = "1"; String ets_style = "1"; String ets_grammar = "1"; String ets_mechanics = "1"; String ets_usage = "1"; String cid = siteId; String assignid = taskId; String assign = taskTitle; String ctl = siteId; String assignEnc = assign; try { if (assign.contains("&")) { //log.debug("replacing & in assignment title"); assign = assign.replace('&', 'n'); } assignEnc = assign; log.debug("Assign title is " + assignEnc); } catch (Exception e) { log.debug(e); } Map params = TurnitinAPIUtil.packMap(turnitinConn.getBaseTIIOptions(), "assign", assignEnc, "assignid", assignid, "cid", cid, "ctl", ctl, "dtdue", dtdue, "dtstart", dtstart, "fcmd", fcmd, "fid", fid, "s_view_report", s_view_report, "utp", utp, "erater", erater, "ets_handbook", ets_handbook, "ets_dictionary", ets_dictionary, "ets_spelling", ets_spelling, "ets_style", ets_style, "ets_grammar", ets_grammar, "ets_mechanics", ets_mechanics, "ets_usage", ets_usage); params.putAll(getInstructorInfo(siteId)); Document document; try { document = turnitinConn.callTurnitinReturnDocument(params); } catch (TransientSubmissionException | SubmissionException tse) { log.error("Error on API call in updateAssignment siteid: " + siteId + " taskid: " + taskId, tse); return; } Element root = document.getDocumentElement(); int rcode = new Integer( ((CharacterData) (root.getElementsByTagName("rcode").item(0).getFirstChild())).getData().trim()); if ((rcode > 0 && rcode < 100) || rcode == 419) { log.debug("Create Assignment successful"); } else { log.debug("Assignment creation failed with message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData() .trim() + ". Code: " + rcode); throw new SubmissionException("Create Assignment not successful. Message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData() .trim() + ". Code: " + rcode); } }
From source file:org.sakaiproject.contentreview.impl.turnitin.TurnitinReviewServiceImpl.java
@SuppressWarnings({ "deprecation", "unchecked" }) public void checkForReportsBulk() { SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); dform.applyPattern(TURNITIN_DATETIME_FORMAT); log.info("Fetching reports from Turnitin"); // get the list of all items that are waiting for reports // but skip items with externalId = null, this happens when the LTI integration's callback fails. In this case, they'll be resubmitted by the queue job. // For the Sakai API integration, we should never enter the report state with externalId = null List<ContentReviewItem> awaitingReport = dao.findByProperties(ContentReviewItem.class, new String[] { "status", "externalId" }, new Object[] { ContentReviewItem.SUBMITTED_AWAITING_REPORT_CODE, "" }, new int[] { dao.EQUALS, dao.NOT_NULL }); awaitingReport.addAll(dao.findByProperties(ContentReviewItem.class, new String[] { "status", "externalId" }, new Object[] { ContentReviewItem.REPORT_ERROR_RETRY_CODE, "" }, new int[] { dao.EQUALS, dao.NOT_NULL })); Iterator<ContentReviewItem> listIterator = awaitingReport.iterator(); HashMap<String, Integer> reportTable = new HashMap<>(); log.debug("There are " + awaitingReport.size() + " submissions awaiting reports"); ContentReviewItem currentItem;/*ww w . j a v a 2s . com*/ while (listIterator.hasNext()) { currentItem = (ContentReviewItem) listIterator.next(); try { // has the item reached its next retry time? if (currentItem.getNextRetryTime() == null) currentItem.setNextRetryTime(new Date()); else if (currentItem.getNextRetryTime().after(new Date())) { //we haven't reached the next retry time log.info("next retry time not yet reached for item: " + currentItem.getId()); dao.update(currentItem); continue; } if (currentItem.getRetryCount() == null) { currentItem.setRetryCount(Long.valueOf(0)); currentItem.setNextRetryTime(this.getNextRetryTime(0)); } else if (currentItem.getRetryCount().intValue() > maxRetry) { processError(currentItem, ContentReviewItem.SUBMISSION_ERROR_RETRY_EXCEEDED, null, null); continue; } else { log.debug("Still have retries left, continuing. ItemID: " + currentItem.getId()); // Moving down to check for report generate speed. //long l = currentItem.getRetryCount().longValue(); //l++; //currentItem.setRetryCount(Long.valueOf(l)); //currentItem.setNextRetryTime(this.getNextRetryTime(Long.valueOf(l))); //dao.update(currentItem); } Site s; try { s = siteService.getSite(currentItem.getSiteId()); } catch (IdUnusedException iue) { log.warn("checkForReportsBulk: Site " + currentItem.getSiteId() + " not found!" + iue.getMessage()); long l = currentItem.getRetryCount(); l++; currentItem.setRetryCount(l); currentItem.setNextRetryTime(this.getNextRetryTime(l)); currentItem.setLastError("Site not found"); dao.update(currentItem); continue; } ////////////////////////////// NEW LTI INTEGRATION /////////////////////////////// Optional<Date> dateOpt = getAssignmentCreationDate(currentItem.getTaskId()); if (dateOpt.isPresent() && siteAdvisor.siteCanUseLTIReviewServiceForAssignment(s, dateOpt.get())) { log.debug("getReviewScore using the LTI integration"); Map<String, String> ltiProps = new HashMap<>(); ltiProps = putInstructorInfo(ltiProps, currentItem.getSiteId()); String paperId = currentItem.getExternalId(); if (paperId == null) { log.warn("Could not find TII paper id for the content " + currentItem.getContentId()); long l = currentItem.getRetryCount(); l++; currentItem.setRetryCount(l); currentItem.setNextRetryTime(this.getNextRetryTime(l)); currentItem.setLastError("Could not find TII paper id for the submission"); dao.update(currentItem); continue; } TurnitinReturnValue result = tiiUtil.makeLTIcall(TurnitinLTIUtil.INFO_SUBMISSION, paperId, ltiProps); if (result.getResult() >= 0) { currentItem.setReviewScore(result.getResult()); currentItem.setStatus(ContentReviewItem.SUBMITTED_REPORT_AVAILABLE_CODE); currentItem.setDateReportReceived(new Date()); currentItem.setLastError(null); currentItem.setErrorCode(null); dao.update(currentItem); try { ContentResource resource = contentHostingService .getResource(currentItem.getContentId()); boolean itemUpdated = updateItemAccess(resource.getId()); if (!itemUpdated) { log.error("Could not update cr item access status"); } } catch (PermissionException | IdUnusedException | TypeException ex) { log.error("Could not update cr item access status", ex); } //log.debug("new report received: " + currentItem.getExternalId() + " -> " + currentItem.getReviewScore()); log.debug("new report received: " + paperId + " -> " + currentItem.getReviewScore()); } else { if (result.getResult() == -7) { log.debug("report is still pending for paper " + paperId); currentItem.setStatus(ContentReviewItem.SUBMITTED_AWAITING_REPORT_CODE); currentItem.setLastError(result.getErrorMessage()); currentItem.setErrorCode(result.getResult()); } else { log.error("Error making LTI call"); long l = currentItem.getRetryCount(); l++; currentItem.setRetryCount(l); currentItem.setNextRetryTime(this.getNextRetryTime(l)); currentItem.setStatus(ContentReviewItem.REPORT_ERROR_RETRY_CODE); currentItem.setLastError("Report Data Error: " + result.getResult()); } dao.update(currentItem); } continue; } ////////////////////////////// OLD API INTEGRATION /////////////////////////////// if (currentItem.getExternalId() == null || currentItem.getExternalId().equals("")) { currentItem.setStatus(Long.valueOf(4)); dao.update(currentItem); continue; } if (!reportTable.containsKey(currentItem.getExternalId())) { // get the list from turnitin and see if the review is available log.debug("Attempting to update hashtable with reports for site " + currentItem.getSiteId()); String fcmd = "2"; String fid = "10"; try { User user = userDirectoryService.getUser(currentItem.getUserId()); } catch (Exception e) { log.error("Unable to look up user: " + currentItem.getUserId() + " for contentItem: " + currentItem.getId(), e); } String cid = currentItem.getSiteId(); String tem = getTEM(cid); String utp = "2"; String assignid = currentItem.getTaskId(); String assign = currentItem.getTaskId(); String ctl = currentItem.getSiteId(); // TODO FIXME Current sgithens // Move the update setRetryAttempts to here, and first call and // check the assignment from TII to see if the generate until // due is enabled. In that case we don't want to waste retry // attempts and should just continue. try { // TODO FIXME This is broken at the moment because we need // to have a userid, but this is assuming it's coming from // the thread, but we're in a quartz job. //Map curasnn = getAssignment(currentItem.getSiteId(), currentItem.getTaskId()); // TODO FIXME Parameterize getAssignment method to take user information Map getAsnnParams = TurnitinAPIUtil.packMap(turnitinConn.getBaseTIIOptions(), "assign", getAssignmentTitle(currentItem.getTaskId()), "assignid", currentItem.getTaskId(), "cid", currentItem.getSiteId(), "ctl", currentItem.getSiteId(), "fcmd", "7", "fid", "4", "utp", "2"); getAsnnParams.putAll(getInstructorInfo(currentItem.getSiteId())); Map curasnn = turnitinConn.callTurnitinReturnMap(getAsnnParams); if (curasnn.containsKey("object")) { Map curasnnobj = (Map) curasnn.get("object"); String reportGenSpeed = (String) curasnnobj.get("generate"); String duedate = (String) curasnnobj.get("dtdue"); SimpleDateFormat retform = ((SimpleDateFormat) DateFormat.getDateInstance()); retform.applyPattern(TURNITIN_DATETIME_FORMAT); Date duedateObj = null; try { if (duedate != null) { duedateObj = retform.parse(duedate); } } catch (ParseException pe) { log.warn("Unable to parse turnitin dtdue: " + duedate, pe); } if (reportGenSpeed != null && duedateObj != null && reportGenSpeed.equals("2") && duedateObj.after(new Date())) { log.info("Report generate speed is 2, skipping for now. ItemID: " + currentItem.getId()); // If there was previously a transient error for this item, reset the status if (ContentReviewItem.REPORT_ERROR_RETRY_CODE.equals(currentItem.getStatus())) { currentItem.setStatus(ContentReviewItem.SUBMITTED_AWAITING_REPORT_CODE); currentItem.setLastError(null); currentItem.setErrorCode(null); dao.update(currentItem); } continue; } else { log.debug("Incrementing retry count for currentItem: " + currentItem.getId()); long l = currentItem.getRetryCount(); l++; currentItem.setRetryCount(l); currentItem.setNextRetryTime(this.getNextRetryTime(l)); dao.update(currentItem); } } } catch (SubmissionException | TransientSubmissionException e) { log.error( "Unable to check the report gen speed of the asnn for item: " + currentItem.getId(), e); } Map params = TurnitinAPIUtil.packMap(turnitinConn.getBaseTIIOptions(), "fid", fid, "fcmd", fcmd, "tem", tem, "assign", assign, "assignid", assignid, "cid", cid, "ctl", ctl, "utp", utp); params.putAll(getInstructorInfo(currentItem.getSiteId())); Document document; try { document = turnitinConn.callTurnitinReturnDocument(params); } catch (TransientSubmissionException e) { log.warn("Update failed due to TransientSubmissionException error: " + e.toString(), e); currentItem.setStatus(ContentReviewItem.REPORT_ERROR_RETRY_CODE); currentItem.setLastError(e.getMessage()); dao.update(currentItem); break; } catch (SubmissionException e) { log.warn("Update failed due to SubmissionException error: " + e.toString(), e); currentItem.setStatus(ContentReviewItem.REPORT_ERROR_RETRY_CODE); currentItem.setLastError(e.getMessage()); dao.update(currentItem); break; } Element root = document.getDocumentElement(); if (((CharacterData) (root.getElementsByTagName("rcode").item(0).getFirstChild())).getData() .trim().compareTo("72") == 0) { log.debug("Report list returned successfully"); NodeList objects = root.getElementsByTagName("object"); String objectId; String similarityScore; String overlap = ""; log.debug(objects.getLength() + " objects in the returned list"); for (int i = 0; i < objects.getLength(); i++) { similarityScore = ((CharacterData) (((Element) (objects.item(i))) .getElementsByTagName("similarityScore").item(0).getFirstChild())).getData() .trim(); objectId = ((CharacterData) (((Element) (objects.item(i))) .getElementsByTagName("objectID").item(0).getFirstChild())).getData().trim(); if (similarityScore.compareTo("-1") != 0) { overlap = ((CharacterData) (((Element) (objects.item(i))) .getElementsByTagName("overlap").item(0).getFirstChild())).getData().trim(); reportTable.put(objectId, Integer.valueOf(overlap)); } else { reportTable.put(objectId, -1); } log.debug("objectId: " + objectId + " similarity: " + similarityScore + " overlap: " + overlap); } } else { log.debug("Report list request not successful"); log.debug(document.getTextContent()); } } int reportVal; // check if the report value is now there (there may have been a // failure to get the list above) if (reportTable.containsKey(currentItem.getExternalId())) { reportVal = ((reportTable.get(currentItem.getExternalId()))); log.debug("reportVal for " + currentItem.getExternalId() + ": " + reportVal); if (reportVal != -1) { currentItem.setReviewScore(reportVal); currentItem.setStatus(ContentReviewItem.SUBMITTED_REPORT_AVAILABLE_CODE); currentItem.setDateReportReceived(new Date()); currentItem.setLastError(null); currentItem.setErrorCode(null); dao.update(currentItem); try { ContentResource resource = contentHostingService .getResource(currentItem.getContentId()); boolean itemUpdated = updateItemAccess(resource.getId()); if (!itemUpdated) { log.error("Could not update cr item access status"); } } catch (PermissionException | IdUnusedException | TypeException ex) { log.error("Could not update cr item access status", ex); } log.debug("new report received: " + currentItem.getExternalId() + " -> " + currentItem.getReviewScore()); } } } catch (Exception e) { log.error(e.getMessage() + "\n" + e.getStackTrace()); } } log.info("Finished fetching reports from Turnitin"); }
From source file:org.sakaiproject.contentreview.impl.turnitin.TurnitinReviewServiceImpl.java
/** * Syncs an assignment and handles individual student extensions *///w ww .j a v a 2 s . c o m public void syncAssignment(String siteId, String taskId, Map<String, Object> extraAsnnOpts, Date extensionDate) throws SubmissionException, TransientSubmissionException { Site s = null; try { s = siteService.getSite(siteId); } catch (IdUnusedException iue) { log.warn("createAssignment: Site " + siteId + " not found!" + iue.getMessage()); throw new TransientSubmissionException( "Create Assignment not successful. Site " + siteId + " not found"); } org.sakaiproject.assignment.api.Assignment asn; try { asn = assignmentService.getAssignment(taskId); } catch (IdUnusedException | PermissionException e) { asn = null; } ////////////////////////////// NEW LTI INTEGRATION /////////////////////////////// Optional<Date> asnCreationDateOpt = getAssignmentCreationDate(asn); if (asnCreationDateOpt.isPresent() && siteAdvisor.siteCanUseLTIReviewServiceForAssignment(s, asnCreationDateOpt.get())) { log.debug("Creating new TII assignment using the LTI integration"); String asnId = asnRefToId(taskId); // taskId is an assignment reference, but we sometimes only want the assignment id String ltiId = getActivityConfigValue(TurnitinConstants.STEALTHED_LTI_ID, asnId, TurnitinConstants.SAKAI_ASSIGNMENT_TOOL_ID, TurnitinConstants.PROVIDER_ID); String ltiReportsId = null; ltiReportsId = s.getProperties().getProperty("turnitin_reports_lti_id"); log.debug("This assignment has associated the following LTI Reports id: " + ltiReportsId); Map<String, String> ltiProps = new HashMap<>(); if (extraAsnnOpts == null) { throw new TransientSubmissionException("Create Assignment not successful. Empty extraAsnnOpts map"); } ltiProps.put("context_id", siteId); ltiProps.put("context_title", s.getTitle()); String contextLabel = s.getTitle(); if (s.getShortDescription() != null) { contextLabel = s.getShortDescription(); } ltiProps.put("context_label", contextLabel); ltiProps.put("resource_link_id", taskId); String title = extraAsnnOpts.get("title").toString(); ltiProps.put("resource_link_title", title); String description = extraAsnnOpts.get("instructions").toString(); if (description != null) { description = description.replaceAll("\\<.*?>", "");//TODO improve this int instructionsMax = serverConfigurationService.getInt("contentreview.instructions.max", 1000); if (description.length() > instructionsMax) { description = description.substring(0, instructionsMax); } } ltiProps.put("resource_link_description", description); // TII-245 if (!StringUtils.isBlank(ltiId)) { // This is an existing LTI instance, need to handle student extensions handleIndividualExtension(extensionDate, taskId, extraAsnnOpts); } String custom = BasicLTIConstants.RESOURCE_LINK_ID + "=" + taskId; custom += "\n" + BasicLTIConstants.RESOURCE_LINK_TITLE + "=" + title; custom += "\n" + BasicLTIConstants.RESOURCE_LINK_DESCRIPTION + "=" + description; try { long timestampOpen = (Long) extraAsnnOpts.get("timestampOpen"); long timestampDue = (Long) extraAsnnOpts.get("timestampDue"); // TII-245 - add a buffer to the TII due date to give time for the process queue job timestampDue += serverConfigurationService.getInt("contentreview.due.date.queue.job.buffer.minutes", 0) * 60000; ZonedDateTime open = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestampOpen), ZoneOffset.UTC); ZonedDateTime due = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestampDue), ZoneOffset.UTC); // Turnitin requires dates in ISO8601 format. The example from their documentation is "2014-12-10T07:43:43Z". // This matches the Java formatter ISO_INSTANT String isoStart = open.format(DateTimeFormatter.ISO_INSTANT); String isoDue = due.format(DateTimeFormatter.ISO_INSTANT); ltiProps.put("startdate", isoStart); ltiProps.put("duedate", isoDue); ltiProps.put("feedbackreleasedate", isoDue); custom += "\n" + "startdate=" + isoStart; custom += "\n" + "duedate=" + isoDue; custom += "\n" + "feedbackreleasedate=" + isoDue; } catch (DateTimeException e) { log.error(e); throw new TransientSubmissionException( "Create Assignment not successful. Invalid open and/or due date."); } ltiProps = putInstructorInfo(ltiProps, siteId); /* * Force TII max points to 100 so we can interpret the result as a direct percentage. * This is done because Assignments now has the ability to grade to an arbitrary number of decimal places. * Due to the limitation of TII requiring whole integers for grading, we would have to inflate the grade by a * factor to the power of the number of decimal places allowed. This would result in unusually large numbers * on the TII, which could be confusing for the end user. */ ltiProps.put("maxpoints", "100"); custom += "\n" + "maxpoints=100"; ltiProps.put("studentpapercheck", extraAsnnOpts.get("s_paper_check").toString()); ltiProps.put("journalcheck", extraAsnnOpts.get("journal_check").toString()); ltiProps.put("internetcheck", extraAsnnOpts.get("internet_check").toString()); ltiProps.put("institutioncheck", extraAsnnOpts.get("institution_check").toString()); ltiProps.put("allow_non_or_submissions", extraAsnnOpts.get("allow_any_file").toString()); //ONLY FOR TII UK //ltiProps.setProperty("anonymous_marking_enabled", extraAsnnOpts.get("s_paper_check")); custom += "\n" + "studentpapercheck=" + extraAsnnOpts.get("s_paper_check").toString(); custom += "\n" + "journalcheck=" + extraAsnnOpts.get("journal_check").toString(); custom += "\n" + "internetcheck=" + extraAsnnOpts.get("internet_check").toString(); custom += "\n" + "institutioncheck=" + extraAsnnOpts.get("institution_check").toString(); custom += "\n" + "allow_non_or_submissions=" + extraAsnnOpts.get("allow_any_file").toString(); if (extraAsnnOpts.containsKey("exclude_type") && extraAsnnOpts.containsKey("exclude_value")) { //exclude type 0=none, 1=words, 2=percentages String typeAux = "words"; if (extraAsnnOpts.get("exclude_type").toString().equals("2")) { typeAux = "percentage"; } ltiProps.put("exclude_type", typeAux); ltiProps.put("exclude_value", extraAsnnOpts.get("exclude_value").toString()); custom += "\n" + "exclude_type=" + typeAux; custom += "\n" + "exclude_value=" + extraAsnnOpts.get("exclude_value").toString(); } ltiProps.put("late_accept_flag", extraAsnnOpts.get("late_accept_flag").toString()); ltiProps.put("report_gen_speed", extraAsnnOpts.get("report_gen_speed").toString()); ltiProps.put("s_view_reports", extraAsnnOpts.get("s_view_report").toString()); ltiProps.put("submit_papers_to", extraAsnnOpts.get("submit_papers_to").toString()); custom += "\n" + "late_accept_flag=" + extraAsnnOpts.get("late_accept_flag").toString(); custom += "\n" + "report_gen_speed=" + extraAsnnOpts.get("report_gen_speed").toString(); custom += "\n" + "s_view_reports=" + extraAsnnOpts.get("s_view_report").toString(); custom += "\n" + "submit_papers_to=" + extraAsnnOpts.get("submit_papers_to").toString(); if (extraAsnnOpts.containsKey("exclude_biblio")) { ltiProps.put("use_biblio_exclusion", extraAsnnOpts.get("exclude_biblio").toString()); custom += "\n" + "use_biblio_exclusion=" + extraAsnnOpts.get("exclude_biblio").toString(); } if (extraAsnnOpts.containsKey("exclude_quoted")) { ltiProps.put("use_quoted_exclusion", extraAsnnOpts.get("exclude_quoted").toString()); custom += "\n" + "use_quoted_exclusion=" + extraAsnnOpts.get("exclude_quoted").toString(); } //adding callback url String callbackUrl = serverConfigurationService.getServerUrl() + "/sakai-contentreview-tool-tii/tii-servlet"; log.debug("callbackUrl: " + callbackUrl); ltiProps.put("ext_resource_tool_placement_url", callbackUrl); TurnitinReturnValue result = tiiUtil.makeLTIcall(TurnitinLTIUtil.BASIC_ASSIGNMENT, null, ltiProps); if (result.getResult() < 0) { log.error("Error making LTI call"); throw new TransientSubmissionException( "Create Assignment not successful. Check the logs to see message."); } Properties sakaiProps = new Properties(); String globalId = tiiUtil.getGlobalTurnitinLTIToolId(); String globalReportsId = tiiUtil.getGlobalTurnitinReportsLTIToolId(); if (globalId == null) { throw new TransientSubmissionException( "Create Assignment not successful. TII LTI global id not set"); } if (globalReportsId == null) { throw new TransientSubmissionException( "Create Assignment not successful. TII Reports LTI global id not set"); } sakaiProps.setProperty(LTIService.LTI_SITE_ID, siteId); sakaiProps.setProperty(LTIService.LTI_TITLE, title); log.debug("Storing custom params: " + custom); sakaiProps.setProperty(LTIService.LTI_CUSTOM, custom); SecurityAdvisor advisor = new SimpleSecurityAdvisor(sessionManager.getCurrentSessionUserId(), "site.upd", "/site/!admin"); Object ltiContent = null; Object ltiReportsContent = null; try { securityService.pushAdvisor(advisor); sakaiProps.setProperty(LTIService.LTI_TOOL_ID, globalId); if (StringUtils.isEmpty(ltiId)) { ltiContent = tiiUtil.insertTIIToolContent(globalId, sakaiProps); } else {//don't create lti tool if exists ltiContent = tiiUtil.updateTIIToolContent(ltiId, sakaiProps); } // replace the property sakaiProps.setProperty(LTIService.LTI_TOOL_ID, globalReportsId); if (StringUtils.isEmpty(ltiReportsId)) { ltiReportsContent = tiiUtil.insertTIIToolContent(globalReportsId, sakaiProps); } else { ltiReportsContent = tiiUtil.updateTIIToolContent(ltiReportsId, sakaiProps); } } catch (Exception e) { throw new TransientSubmissionException( "Create Assignment not successful. Error trying to insert TII tool content: " + e.getMessage()); } finally { securityService.popAdvisor(advisor); } if (ltiContent == null) { throw new TransientSubmissionException( "Create Assignment not successful. Could not create LTI tool for the task: " + custom); } else if (ltiReportsContent == null) { throw new TransientSubmissionException( "Create Assignment not successful. Could not create LTI Reports tool for the task: " + custom); } else if (!StringUtils.isEmpty(ltiId) && !Boolean.TRUE.equals(ltiContent)) { // if ltiId is not empty, the lti already exists, so we did an update. ltiContent is Boolean.TRUE if the update was successful throw new TransientSubmissionException( "Update Assignment not successful. Error updating LTI stealthed tool: " + ltiId); } else if (ltiReportsId != null && !Boolean.TRUE.equals(ltiReportsContent)) { throw new TransientSubmissionException( "Update Assignment not successful. Error updating LTI reports stealthed tool: " + ltiReportsContent); } else if (StringUtils.isEmpty(ltiId) && !(ltiContent instanceof Long)) { // if ltiId is empty, the lti is new, so we did an insert. ltiContent is a Long primary key if the update was successful throw new TransientSubmissionException( "Create Assignment not successful. Error creating LTI stealthed tool: " + ltiContent); } else if (ltiReportsId == null && !(ltiReportsContent instanceof Long)) { throw new TransientSubmissionException( "Create Assignment not successful. Error creating LTI stealthed tool: " + ltiReportsContent); } if (StringUtils.isEmpty(ltiId) || ltiReportsId == null) {//we inserted, need to record the IDs log.debug("LTI content tool id: " + ltiContent); try { if (ltiReportsId == null) { ResourcePropertiesEdit rpe = s.getPropertiesEdit(); rpe.addProperty("turnitin_reports_lti_id", String.valueOf(ltiReportsContent)); siteService.save(s); } } catch (IdUnusedException e) { log.error("Could not store reports LTI tool ID " + ltiReportsContent + " for site " + s.getId(), e); throw new TransientSubmissionException( "Create Assignment not successful. Error storing LTI stealthed reports tool: " + ltiReportsContent); } catch (PermissionException e) { log.error("Could not store reports LTI tool ID " + ltiReportsContent + " for site " + s.getId(), e); throw new TransientSubmissionException( "Create Assignment not successful. Error storing LTI stealthed reports tool: " + ltiReportsContent); } boolean added = saveOrUpdateActivityConfigEntry(TurnitinConstants.STEALTHED_LTI_ID, String.valueOf(ltiContent), asnId, TurnitinConstants.SAKAI_ASSIGNMENT_TOOL_ID, TurnitinConstants.PROVIDER_ID, true); if (!added) { log.error("Could not store LTI tool ID " + ltiContent + " for assignment " + taskId); throw new TransientSubmissionException( "Create Assignment not successful. Error storing LTI stealthed tool: " + ltiContent); } } //add submissions to the queue if there is any try { log.debug("Adding previous submissions"); //this will be done always - no problem, extra checks log.debug("Assignment " + asn.getId() + " - " + asn.getTitle()); List<AssignmentSubmission> submissions = assignmentService.getSubmissions(asn); if (submissions != null) { for (AssignmentSubmission sub : submissions) { //if submitted if (sub.getSubmitted()) { log.debug("Submission " + sub.getId()); boolean allowAnyFile = asn.getContent().isAllowAnyFile(); List<ContentResource> resources = getAllAcceptableAttachments(sub, allowAnyFile); // determine the owner of the submission for purposes of content review String ownerId = asn.isGroup() ? sub.getSubmittedForGroupByUserId() : sub.getSubmitterId(); if (ownerId.isEmpty()) { String msg = "Unable to submit content items to review service for submission %s to assignment %s. " + "An appropriate owner for the submission cannot be determined."; log.warn(String.format(msg, sub.getId(), asn.getId())); continue; } for (ContentResource resource : resources) { //if it wasnt added if (getFirstItemByContentId(resource.getId()) == null) { log.debug("was not added"); queueContent(ownerId, null, asn.getReference(), resource.getId(), sub.getId(), false); } //else - is there anything or any status we should check? } } } } } catch (Exception e) { log.warn("Error while tying to queue previous submissions."); } return; } ////////////////////////////// OLD API INTEGRATION /////////////////////////////// //get the assignment reference String taskTitle = ""; if (extraAsnnOpts.containsKey("title")) { taskTitle = extraAsnnOpts.get("title").toString(); } else { getAssignmentTitle(taskId); } log.debug("Creating assignment for site: " + siteId + ", task: " + taskId + " tasktitle: " + taskTitle); SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); dform.applyPattern(TURNITIN_DATETIME_FORMAT); Calendar cal = Calendar.getInstance(); //set this to yesterday so we avoid timezone problems etc //TII-143 seems this now causes problems may need a finner tweak than 1 day like midnight +1 min or something cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 1); //cal.add(Calendar.DAY_OF_MONTH, -1); String dtstart = dform.format(cal.getTime()); String today = dtstart; //set the due dates for the assignments to be in 5 month's time //turnitin automatically sets each class end date to 6 months after it is created //the assignment end date must be on or before the class end date String fcmd = "2"; //new assignment boolean asnnExists = false; // If this assignment already exists, we should use fcmd 3 to update it. Map tiiresult = this.getAssignment(siteId, taskId); if (tiiresult.get("rcode") != null && tiiresult.get("rcode").equals("85")) { fcmd = "3"; asnnExists = true; } /* Some notes about start and due dates. This information is * accurate as of Nov 12, 2009 and was determined by testing * and experimentation with some Sash scripts. * * A turnitin due date, must be after the start date. This makes * sense and follows the logic in both Assignments 1 and 2. * * When *creating* a new Turnitin Assignment, the start date * must be todays date or later. The format for dates only * includes the day, and not any specific times. I believe that, * in order to make up for time zone differences between your * location and the turnitin cloud, it can be basically the * current day anywhere currently, with some slack. For instance * I can create an assignment for yesterday, but not for 2 days * ago. Doing so causes an error. * * However! For an existing turnitin assignment, you appear to * have the liberty of changing the start date to sometime in * the past. You can also change an assignment to have a due * date in the past as long as it is still after the start date. * * So, to avoid errors when syncing information, or adding * turnitin support to new or existing assignments we will: * * 1. If the assignment already exists we'll just save it. * * 2. If the assignment does not exist, we will save it once using * todays date for the start and due date, and then save it again with * the proper dates to ensure we're all tidied up and in line. * * Also, with our current class creation, due dates can be 5 * years out, but not further. This seems a bit lower priortity, * but we still should figure out an appropriate way to deal * with it if it does happen. * */ //TODO use the 'secret' function to change this to longer cal.add(Calendar.MONTH, 5); String dtdue = dform.format(cal.getTime()); log.debug("Set date due to: " + dtdue); if (extraAsnnOpts != null && extraAsnnOpts.containsKey("dtdue")) { dtdue = extraAsnnOpts.get("dtdue").toString(); log.debug("Settign date due from external to: " + dtdue); extraAsnnOpts.remove("dtdue"); } String fid = "4"; //function id String utp = "2"; //user type 2 = instructor String s_view_report = "1"; if (extraAsnnOpts != null && extraAsnnOpts.containsKey("s_view_report")) { s_view_report = extraAsnnOpts.get("s_view_report").toString(); extraAsnnOpts.remove("s_view_report"); } //erater String erater = (serverConfigurationService.getBoolean("turnitin.option.erater.default", false)) ? "1" : "0"; String ets_handbook = "1"; String ets_dictionary = "en"; String ets_spelling = "1"; String ets_style = "1"; String ets_grammar = "1"; String ets_mechanics = "1"; String ets_usage = "1"; try { if (extraAsnnOpts != null && extraAsnnOpts.containsKey("erater")) { erater = extraAsnnOpts.get("erater").toString(); extraAsnnOpts.remove("erater"); ets_handbook = extraAsnnOpts.get("ets_handbook").toString(); extraAsnnOpts.remove("ets_handbook"); ets_dictionary = extraAsnnOpts.get("ets_dictionary").toString(); extraAsnnOpts.remove("ets_dictionary"); ets_spelling = extraAsnnOpts.get("ets_spelling").toString(); extraAsnnOpts.remove("ets_spelling"); ets_style = extraAsnnOpts.get("ets_style").toString(); extraAsnnOpts.remove("ets_style"); ets_grammar = extraAsnnOpts.get("ets_grammar").toString(); extraAsnnOpts.remove("ets_grammar"); ets_mechanics = extraAsnnOpts.get("ets_mechanics").toString(); extraAsnnOpts.remove("ets_mechanics"); ets_usage = extraAsnnOpts.get("ets_usage").toString(); extraAsnnOpts.remove("ets_usage"); } } catch (Exception e) { log.info("(createAssignment)erater extraAsnnOpts. " + e); } String cid = siteId; String assignid = taskId; String ctl = siteId; Map params = TurnitinAPIUtil.packMap(turnitinConn.getBaseTIIOptions(), "assign", taskTitle, "assignid", assignid, "cid", cid, "ctl", ctl, "dtdue", dtdue, "dtstart", dtstart, "fcmd", "3", "fid", fid, "s_view_report", s_view_report, "utp", utp, "erater", erater, "ets_handbook", ets_handbook, "ets_dictionary", ets_dictionary, "ets_spelling", ets_spelling, "ets_style", ets_style, "ets_grammar", ets_grammar, "ets_mechanics", ets_mechanics, "ets_usage", ets_usage); // Save instructorInfo up here to reuse for calls in this // method, since theoretically getInstructorInfo could return // different instructors for different invocations and we need // the same one since we're using a session id. Map instructorInfo = getInstructorInfo(siteId); params.putAll(instructorInfo); if (extraAsnnOpts != null) { for (Object key : extraAsnnOpts.keySet()) { if (extraAsnnOpts.get(key) == null) { continue; } params = TurnitinAPIUtil.packMap(params, key.toString(), extraAsnnOpts.get(key).toString()); } } // We only need to use a session id if we are creating this // assignment for the first time. String sessionid = null; Map sessionParams = null; if (!asnnExists) { // Try adding the user in case they don't exist TII-XXX addTurnitinInstructor(instructorInfo); sessionParams = turnitinConn.getBaseTIIOptions(); sessionParams.putAll(instructorInfo); sessionParams.put("utp", utp); sessionid = TurnitinSessionFuncs.getTurnitinSession(turnitinConn, sessionParams); Map firstparams = new HashMap(); firstparams.putAll(params); firstparams.put("session-id", sessionid); firstparams.put("dtstart", today); // Make the due date in the future Calendar caldue = Calendar.getInstance(); caldue.add(Calendar.MONTH, 5); String dtdue_first = dform.format(caldue.getTime()); firstparams.put("dtdue", dtdue_first); log.debug("date due is: " + dtdue); log.debug("Start date: " + today); firstparams.put("fcmd", "2"); Document firstSaveDocument = turnitinConn.callTurnitinReturnDocument(firstparams); Element root = firstSaveDocument.getDocumentElement(); int rcode = new Integer(((CharacterData) (root.getElementsByTagName("rcode").item(0).getFirstChild())) .getData().trim()); if ((rcode > 0 && rcode < 100) || rcode == 419) { log.debug("Create FirstDate Assignment successful"); log.debug("tii returned " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())) .getData().trim() + ". Code: " + rcode); } else { log.debug("FirstDate Assignment creation failed with message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())) .getData().trim() + ". Code: " + rcode); //log.debug(root); throw new TransientSubmissionException("FirstDate Create Assignment not successful. Message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())) .getData().trim() + ". Code: " + rcode, rcode); } } log.debug("going to attempt second update"); if (sessionid != null) { params.put("session-id", sessionid); } Document document = turnitinConn.callTurnitinReturnDocument(params); Element root = document.getDocumentElement(); int rcode = new Integer( ((CharacterData) (root.getElementsByTagName("rcode").item(0).getFirstChild())).getData().trim()); if ((rcode > 0 && rcode < 100) || rcode == 419) { log.debug("Create Assignment successful"); log.debug("tii returned " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData() .trim() + ". Code: " + rcode); } else { log.debug("Assignment creation failed with message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData() .trim() + ". Code: " + rcode); //log.debug(root); throw new TransientSubmissionException("Create Assignment not successful. Message: " + ((CharacterData) (root.getElementsByTagName("rmessage").item(0).getFirstChild())).getData() .trim() + ". Code: " + rcode, rcode); } if (sessionid != null) { TurnitinSessionFuncs.logoutTurnitinSession(turnitinConn, sessionid, sessionParams); } }
From source file:com.rr.missouri.ui.surveys.surveyController.java
/** * The '/editSurvey' GET request will build out the survey and display the first page of the survey. * * @param i The encrypted survey id/*from w w w . ja va 2s. c o m*/ * @param v The encrypted decryption key * * @param session * @return * @throws Exception */ @RequestMapping(value = { "/editSurvey", "/viewSurvey" }, method = RequestMethod.GET) public ModelAndView editSurvey(@RequestParam String i, @RequestParam String v, HttpSession session, HttpServletRequest request) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/takeSurvey"); mav.addObject("surveys", surveys); //Set the survey answer array to get ready to hold data if (session.getAttribute("questionAnswers") != null) { session.removeAttribute("questionAnswers"); } session.setAttribute("questionAnswers", new ArrayList<surveyQuestionAnswers>()); if (session.getAttribute("selectedContentCriterias") != null) { session.removeAttribute("selectedContentCriterias"); } session.setAttribute("selectedContentCriterias", new ArrayList<surveyContentCriteria>()); if (session.getAttribute("districtList") != null) { session.removeAttribute("districtList"); } session.setAttribute("districtList", new ArrayList<district>()); if (session.getAttribute("seenPages") != null) { session.removeAttribute("seenPages"); } session.setAttribute("seenPages", new ArrayList<Integer>()); int clientId = 0; /* Decrypt the url */ decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(i, v); String[] result = obj.toString().split((",")); int submittedSurveyId = Integer.parseInt(result[0].substring(4)); /* Get the survey details */ submittedSurveys submittedSurveyDetails = surveyManager.getSubmittedSurvey(submittedSurveyId); surveys surveyDetails = surveyManager.getSurveyDetails(submittedSurveyDetails.getSurveyId()); User userDetails = (User) session.getAttribute("userDetails"); survey survey = new survey(); survey.setClientId(clientId); survey.setSurveyId(submittedSurveyDetails.getSurveyId()); survey.setSurveyTitle(surveyDetails.getTitle()); survey.setPrevButton(surveyDetails.getPrevButtonText()); survey.setNextButton(surveyDetails.getNextButtonText()); survey.setSaveButton(surveyDetails.getDoneButtonText()); survey.setSubmittedSurveyId(submittedSurveyId); survey.setEntityIds(surveyManager.getSubmittedSurveyEntities(submittedSurveyId, userDetails)); encryptObject encrypt = new encryptObject(); Map<String, String> map; //Encrypt the use id to pass in the url map = new HashMap<String, String>(); map.put("id", Integer.toString(submittedSurveyDetails.getSurveyId())); map.put("topSecret", topSecret); String[] encrypted = encrypt.encryptObject(map); survey.setEncryptedId(encrypted[0]); survey.setEncryptedSecret(encrypted[1]); /* Get the pages */ List<SurveyPages> surveyPages = surveyManager.getSurveyPages(submittedSurveyDetails.getSurveyId(), false, 0, 0, 0); SurveyPages currentPage = surveyManager.getSurveyPage(submittedSurveyDetails.getSurveyId(), true, 1, clientId, 0, 0, submittedSurveyId, 0); survey.setPageTitle(currentPage.getPageTitle()); survey.setPageDesc(currentPage.getPageDesc()); survey.setSurveyPageQuestions(currentPage.getSurveyQuestions()); survey.setTotalPages(surveyPages.size()); survey.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId()); survey.setPageId(currentPage.getId()); /* Need to update any date functions */ if (survey.getSurveyPageQuestions() != null && survey.getSurveyPageQuestions().size() > 0) { for (SurveyQuestions question : survey.getSurveyPageQuestions()) { if (question.getAnswerTypeId() == 6) { if (question.getQuestionValue().length() > 0 && !question.getQuestionValue().contains("^^^^^")) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat df2 = new SimpleDateFormat("M/dd/yy"); SimpleDateFormat df3 = new SimpleDateFormat("M/dd/yyyy"); SimpleDateFormat df4 = new SimpleDateFormat("M/d/yy"); SimpleDateFormat df5 = new SimpleDateFormat("M/d/yyyy"); SimpleDateFormat df6 = new SimpleDateFormat("MM/d/yyyy"); SimpleDateFormat df7 = new SimpleDateFormat("MM/d/yy"); SimpleDateFormat df8 = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat df9 = new SimpleDateFormat("MM/dd/yy"); Date formattedDate; try { formattedDate = df.parse(question.getQuestionValue()); } catch (Exception ex) { try { formattedDate = df2.parse(question.getQuestionValue()); } catch (Exception ex2) { try { formattedDate = df3.parse(question.getQuestionValue()); } catch (Exception ex3) { try { formattedDate = df4.parse(question.getQuestionValue()); } catch (Exception ex4) { try { formattedDate = df5.parse(question.getQuestionValue()); } catch (Exception ex5) { try { formattedDate = df6.parse(question.getQuestionValue()); } catch (Exception ex6) { try { formattedDate = df7.parse(question.getQuestionValue()); } catch (Exception ex7) { try { formattedDate = df8.parse(question.getQuestionValue()); } catch (Exception ex8) { formattedDate = df9.parse(question.getQuestionValue()); } } } } } } } } if (question.getDateFormatType() == 2) { //dd/mm/yyyy df.applyPattern("dd/MM/yyyy"); } else { //mm/dd/yyyy df.applyPattern("MM/dd/yyyy"); } String formattedDateasString = df.format(formattedDate); question.setQuestionValue(formattedDateasString); } } } } mav.addObject("survey", survey); mav.addObject("surveyPages", surveyPages); List<Integer> selectedEntities = surveyManager.getSurveyEntities(submittedSurveyId); /* Get a list of available schools for the selected districts */ if (selectedEntities != null && !selectedEntities.isEmpty() && !"".equals(selectedEntities)) { List<district> districtList = (List<district>) session.getAttribute("districtList"); for (Integer entityId : selectedEntities) { List<school> schoolList = new ArrayList<school>(); district district = new district(); district.setDistrictId(entityId); programHierarchyDetails districtDetails = hierarchymanager.getProgramHierarchyItemDetails(entityId); district.setDistrictName(districtDetails.getName()); Integer userId = 0; if (userDetails.getRoleId() == 3) { userId = userDetails.getId(); } List schools = hierarchymanager.getProgramOrgHierarchyItems(programId, 3, entityId, userId); if (!schools.isEmpty() && schools.size() > 0) { for (ListIterator iter = schools.listIterator(); iter.hasNext();) { Object[] row = (Object[]) iter.next(); school school = new school(); school.setSchoolId(Integer.parseInt(row[0].toString())); school.setSchoolName(row[1].toString()); //Encrypt the use id to pass in the url map = new HashMap<String, String>(); map.put("id", Integer.toString(Integer.parseInt(row[0].toString()))); map.put("topSecret", topSecret); String[] encrypted2 = encrypt.encryptObject(map); school.setEncryptedId(encrypted2[0]); school.setEncryptedSecret(encrypted2[1]); schoolList.add(school); } district.setSchoolList(schoolList); } districtList.add(district); } mav.addObject("selDistricts", districtList); } mav.addObject("selSurvey", submittedSurveyDetails.getSurveyId()); mav.addObject("selectedEntities", selectedEntities.toString().replace("[", "").replace("]", "")); mav.addObject("qNum", 0); mav.addObject("currPageNum", 1); boolean disabled = false; if ("/surveys/viewSurvey".equals(request.getServletPath())) { disabled = true; } mav.addObject("disabled", disabled); return mav; }
From source file:com.rr.moheals.ui.surveys.surveyController.java
/** * The '/editSurvey' GET request will build out the survey and display the first page of the survey. * * @param i The encrypted survey id//from w w w . jav a2 s . c o m * @param v The encrypted decryption key * * @param session * @return * @throws Exception */ @RequestMapping(value = { "/editSurvey", "/viewSurvey" }, method = RequestMethod.GET) public ModelAndView editSurvey(@RequestParam String i, @RequestParam String v, HttpSession session, HttpServletRequest request) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/takeSurvey"); mav.addObject("surveys", surveys); //Set the survey answer array to get ready to hold data if (session.getAttribute("questionAnswers") != null) { session.removeAttribute("questionAnswers"); } session.setAttribute("questionAnswers", new ArrayList<surveyQuestionAnswers>()); if (session.getAttribute("selectedContentCriterias") != null) { session.removeAttribute("selectedContentCriterias"); } session.setAttribute("selectedContentCriterias", new ArrayList<surveyContentCriteria>()); if (session.getAttribute("countyList") != null) { session.removeAttribute("countyList"); } session.setAttribute("countyList", new ArrayList<county>()); if (session.getAttribute("seenPages") != null) { session.removeAttribute("seenPages"); } session.setAttribute("seenPages", new ArrayList<Integer>()); int clientId = 0; /* Decrypt the url */ decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(i, v); String[] result = obj.toString().split((",")); int submittedSurveyId = Integer.parseInt(result[0].substring(4)); /* Get the survey details */ submittedSurveys submittedSurveyDetails = surveyManager.getSubmittedSurvey(submittedSurveyId); surveys surveyDetails = surveyManager.getSurveyDetails(submittedSurveyDetails.getSurveyId()); User userDetails = (User) session.getAttribute("userDetails"); survey survey = new survey(); survey.setClientId(clientId); survey.setSurveyId(submittedSurveyDetails.getSurveyId()); survey.setSurveyTitle(surveyDetails.getTitle()); survey.setPrevButton(surveyDetails.getPrevButtonText()); survey.setNextButton(surveyDetails.getNextButtonText()); survey.setSaveButton(surveyDetails.getDoneButtonText()); survey.setSubmittedSurveyId(submittedSurveyId); survey.setEntityIds(surveyManager.getSubmittedSurveyEntities(submittedSurveyId, userDetails)); encryptObject encrypt = new encryptObject(); Map<String, String> map; //Encrypt the use id to pass in the url map = new HashMap<String, String>(); map.put("id", Integer.toString(submittedSurveyDetails.getSurveyId())); map.put("topSecret", topSecret); String[] encrypted = encrypt.encryptObject(map); survey.setEncryptedId(encrypted[0]); survey.setEncryptedSecret(encrypted[1]); /* Get the pages */ List<SurveyPages> surveyPages = surveyManager.getSurveyPages(submittedSurveyDetails.getSurveyId(), false, 0, 0, 0); SurveyPages currentPage = surveyManager.getSurveyPage(submittedSurveyDetails.getSurveyId(), true, 1, clientId, 0, 0, submittedSurveyId, 0); survey.setPageTitle(currentPage.getPageTitle()); survey.setPageDesc(currentPage.getPageDesc()); survey.setSurveyPageQuestions(currentPage.getSurveyQuestions()); survey.setTotalPages(surveyPages.size()); survey.setLastPageId(surveyPages.get(surveyPages.size() - 1).getId()); survey.setPageId(currentPage.getId()); /* Need to update any date functions */ if (survey.getSurveyPageQuestions() != null && survey.getSurveyPageQuestions().size() > 0) { for (SurveyQuestions question : survey.getSurveyPageQuestions()) { if (question.getAnswerTypeId() == 6) { if (question.getQuestionValue().length() > 0) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat df2 = new SimpleDateFormat("M/dd/yy"); SimpleDateFormat df3 = new SimpleDateFormat("M/dd/yyyy"); SimpleDateFormat df4 = new SimpleDateFormat("M/d/yy"); SimpleDateFormat df5 = new SimpleDateFormat("M/d/yyyy"); SimpleDateFormat df6 = new SimpleDateFormat("MM/d/yyyy"); SimpleDateFormat df7 = new SimpleDateFormat("MM/d/yy"); SimpleDateFormat df8 = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat df9 = new SimpleDateFormat("MM/dd/yy"); Date formattedDate; try { formattedDate = df.parse(question.getQuestionValue()); } catch (Exception ex) { try { formattedDate = df2.parse(question.getQuestionValue()); } catch (Exception ex2) { try { formattedDate = df3.parse(question.getQuestionValue()); } catch (Exception ex3) { try { formattedDate = df4.parse(question.getQuestionValue()); } catch (Exception ex4) { try { formattedDate = df5.parse(question.getQuestionValue()); } catch (Exception ex5) { try { formattedDate = df6.parse(question.getQuestionValue()); } catch (Exception ex6) { try { formattedDate = df7.parse(question.getQuestionValue()); } catch (Exception ex7) { try { formattedDate = df8.parse(question.getQuestionValue()); } catch (Exception ex8) { formattedDate = df9.parse(question.getQuestionValue()); } } } } } } } } if (question.getDateFormatType() == 2) { //dd/mm/yyyy df.applyPattern("dd/MM/yyyy"); } else { //mm/dd/yyyy df.applyPattern("MM/dd/yyyy"); } String formattedDateasString = df.format(formattedDate); question.setQuestionValue(formattedDateasString); } } } } mav.addObject("survey", survey); mav.addObject("surveyPages", surveyPages); List<Integer> selectedEntities = surveyManager.getSurveyEntities(submittedSurveyId); /* Get a list of available health Departments for the selected districts */ if (selectedEntities != null && !selectedEntities.isEmpty() && !"".equals(selectedEntities)) { List<county> countyList = (List<county>) session.getAttribute("countyList"); for (Integer entityId : selectedEntities) { List<healthDepartment> healthDepartmentList = new ArrayList<healthDepartment>(); county county = new county(); county.setCountyId(entityId); programHierarchyDetails districtDetails = hierarchymanager.getProgramHierarchyItemDetails(entityId); county.setCountyName(districtDetails.getName()); Integer userId = 0; if (userDetails.getRoleId() == 3) { userId = userDetails.getId(); } List healthDepartments = hierarchymanager.getProgramOrgHierarchyItems(programId, 2, entityId, userId); if (!healthDepartments.isEmpty() && healthDepartments.size() > 0) { for (ListIterator iter = healthDepartments.listIterator(); iter.hasNext();) { Object[] row = (Object[]) iter.next(); healthDepartment healthDepartment = new healthDepartment(); healthDepartment.setHealthDepartmentId(Integer.parseInt(row[0].toString())); healthDepartment.setHealthDepartmentName(row[1].toString()); //Encrypt the use id to pass in the url map = new HashMap<String, String>(); map.put("id", Integer.toString(Integer.parseInt(row[0].toString()))); map.put("topSecret", topSecret); String[] encrypted2 = encrypt.encryptObject(map); healthDepartment.setEncryptedId(encrypted2[0]); healthDepartment.setEncryptedSecret(encrypted2[1]); healthDepartmentList.add(healthDepartment); } county.setHealthDepartmentList(healthDepartmentList); } countyList.add(county); } mav.addObject("selCounties", countyList); } mav.addObject("selSurvey", submittedSurveyDetails.getSurveyId()); mav.addObject("selectedEntities", selectedEntities.toString().replace("[", "").replace("]", "")); mav.addObject("qNum", 0); mav.addObject("currPageNum", 1); boolean disabled = false; if ("/surveys/viewSurvey".equals(request.getServletPath())) { disabled = true; } mav.addObject("disabled", disabled); return mav; }
From source file:be.ibridge.kettle.trans.step.textfileinput.TextFileInput.java
public static final Value convertValue(String pol, String field_name, int field_type, String field_format, int field_length, int field_precision, String num_group, String num_decimal, String num_currency, String nullif, String ifNull, int trim_type, DecimalFormat ldf, DecimalFormatSymbols ldfs, SimpleDateFormat ldaf, DateFormatSymbols ldafs) throws Exception { Value value = new Value(field_name, field_type); // build a value! // If no nullif field is supplied, take the default. String null_value = nullif;//from www . j a va 2s . co m if (null_value == null) { switch (field_type) { case Value.VALUE_TYPE_BOOLEAN: null_value = Const.NULL_BOOLEAN; break; case Value.VALUE_TYPE_STRING: null_value = Const.NULL_STRING; break; case Value.VALUE_TYPE_BIGNUMBER: null_value = Const.NULL_BIGNUMBER; break; case Value.VALUE_TYPE_NUMBER: null_value = Const.NULL_NUMBER; break; case Value.VALUE_TYPE_INTEGER: null_value = Const.NULL_INTEGER; break; case Value.VALUE_TYPE_DATE: null_value = Const.NULL_DATE; break; case Value.VALUE_TYPE_BINARY: null_value = Const.NULL_BINARY; break; default: null_value = Const.NULL_NONE; break; } } String null_cmp = Const.rightPad(new StringBuffer(null_value), pol.length()); if (pol == null || pol.length() == 0 || pol.equalsIgnoreCase(null_cmp)) { if (ifNull != null && ifNull.length() != 0) pol = ifNull; } if (pol == null || pol.length() == 0 || pol.equalsIgnoreCase(null_cmp)) { value.setNull(); } else { if (value.isNumeric()) { try { StringBuffer strpol = new StringBuffer(pol); switch (trim_type) { case TextFileInputMeta.TYPE_TRIM_LEFT: while (strpol.length() > 0 && strpol.charAt(0) == ' ') strpol.deleteCharAt(0); break; case TextFileInputMeta.TYPE_TRIM_RIGHT: while (strpol.length() > 0 && strpol.charAt(strpol.length() - 1) == ' ') strpol.deleteCharAt(strpol.length() - 1); break; case TextFileInputMeta.TYPE_TRIM_BOTH: while (strpol.length() > 0 && strpol.charAt(0) == ' ') strpol.deleteCharAt(0); while (strpol.length() > 0 && strpol.charAt(strpol.length() - 1) == ' ') strpol.deleteCharAt(strpol.length() - 1); break; default: break; } pol = strpol.toString(); if (value.isNumber()) { if (field_format != null) { ldf.applyPattern(field_format); if (num_decimal != null && num_decimal.length() >= 1) ldfs.setDecimalSeparator(num_decimal.charAt(0)); if (num_group != null && num_group.length() >= 1) ldfs.setGroupingSeparator(num_group.charAt(0)); if (num_currency != null && num_currency.length() >= 1) ldfs.setCurrencySymbol(num_currency); ldf.setDecimalFormatSymbols(ldfs); } value.setValue(ldf.parse(pol).doubleValue()); } else { if (value.isInteger()) { value.setValue(Long.parseLong(pol)); } else { if (value.isBigNumber()) { value.setValue(new BigDecimal(pol)); } else { throw new KettleValueException("Unknown numeric type: contact vendor!"); } } } } catch (Exception e) { throw (e); } } else { if (value.isString()) { value.setValue(pol); switch (trim_type) { case TextFileInputMeta.TYPE_TRIM_LEFT: value.ltrim(); break; case TextFileInputMeta.TYPE_TRIM_RIGHT: value.rtrim(); break; case TextFileInputMeta.TYPE_TRIM_BOTH: value.trim(); break; default: break; } if (pol.length() == 0) value.setNull(); } else { if (value.isDate()) { try { if (field_format != null) { ldaf.applyPattern(field_format); ldaf.setDateFormatSymbols(ldafs); } value.setValue(ldaf.parse(pol)); } catch (Exception e) { throw (e); } } else { if (value.isBinary()) { value.setValue(pol.getBytes()); } } } } } value.setLength(field_length, field_precision); return value; }
From source file:au.org.theark.core.dao.StudyDao.java
private boolean validDateFormat(String value) { String[] formatStrings = { Constants.DD_MM_YYYY }; boolean isInvalidFormat = false; for (String formatString : formatStrings) { try {/*from w w w . j a v a 2 s .c o m*/ SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance(); sdf.applyPattern(formatString); sdf.setLenient(false); sdf.parse(value); if (sdf.format(sdf.parse(value)).equals(value) && value.length() == sdf.toPattern().length()) { isInvalidFormat = true; } } catch (ParseException e) { isInvalidFormat = false; } } return isInvalidFormat; }