0001: /*******************************************************************************
0002: * Copyright (c) 2006 The Regents of the University of California
0003: *
0004: * Licensed under the Educational Community License, Version 1.0 (the "License");
0005: * you may not use this file except in compliance with the License.
0006: * You may obtain a copy of the License at
0007: *
0008: * http://www.opensource.org/licenses/ecl1.php
0009: *
0010: * Unless required by applicable law or agreed to in writing, software
0011: * distributed under the License is distributed on an "AS IS" BASIS,
0012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0013: * See the License for the specific language governing permissions and
0014: * limitations under the License.
0015: ******************************************************************************/package org.sakaiproject.tool.gradebook.ui;
0016:
0017: import java.io.BufferedInputStream;
0018: import java.io.BufferedReader;
0019: import java.io.IOException;
0020: import java.io.InputStream;
0021: import java.io.InputStreamReader;
0022: import java.io.Serializable;
0023: import java.util.ArrayList;
0024: import java.util.Date;
0025: import java.util.HashMap;
0026: import java.util.Iterator;
0027: import java.util.List;
0028: import java.util.Map;
0029:
0030: import javax.faces.context.FacesContext;
0031: import javax.faces.model.SelectItem;
0032: import javax.servlet.http.HttpServletRequest;
0033:
0034: import org.apache.commons.logging.Log;
0035: import org.apache.commons.logging.LogFactory;
0036: import org.apache.myfaces.custom.fileupload.UploadedFile;
0037: import org.sakaiproject.section.api.coursemanagement.EnrollmentRecord;
0038: import org.sakaiproject.section.api.coursemanagement.User;
0039: import org.sakaiproject.service.gradebook.shared.ConflictingAssignmentNameException;
0040: import org.sakaiproject.service.gradebook.shared.ConflictingSpreadsheetNameException;
0041: import org.sakaiproject.tool.gradebook.Assignment;
0042: import org.sakaiproject.tool.gradebook.AssignmentGradeRecord;
0043: import org.sakaiproject.tool.gradebook.Comment;
0044: import org.sakaiproject.tool.gradebook.jsf.FacesUtil;
0045:
0046: public class SpreadsheetUploadBean extends GradebookDependentBean
0047: implements Serializable {
0048:
0049: private String title;
0050: private UploadedFile upFile;
0051: private static final Log logger = LogFactory
0052: .getLog(SpreadsheetUploadBean.class);
0053: private Spreadsheet spreadsheet;
0054: private Map rosterMap;
0055: private List assignmentList;
0056: private List studentRows;
0057: private List assignmentHeaders;
0058: private Map selectedAssignment;
0059: private List assignmentColumnSelectItems;
0060: private boolean saved = false;
0061: private String columnCount;
0062: private String rowCount;
0063: private boolean hasUnknownUser;
0064: private Long spreadsheetId;
0065: private Map scores;
0066: private Assignment assignment;
0067: private Long assignmentId;
0068: private Integer selectedCommentsColumnId = 0;
0069:
0070: public SpreadsheetUploadBean() {
0071:
0072: //initialize rosteMap which is map of displayid and user objects
0073: rosterMap = new HashMap();
0074: List enrollments = getAvailableEnrollments();
0075: if (logger.isDebugEnabled())
0076: logger.debug("enrollment size " + enrollments.size());
0077:
0078: Iterator iter;
0079: iter = enrollments.iterator();
0080: while (iter.hasNext()) {
0081: EnrollmentRecord enr;
0082: enr = (EnrollmentRecord) iter.next();
0083: if (logger.isDebugEnabled())
0084: logger.debug("displayid "
0085: + enr.getUser().getDisplayId() + " userid "
0086: + enr.getUser().getUserUid());
0087: rosterMap.put(enr.getUser().getDisplayId(), enr.getUser());
0088: }
0089:
0090: }
0091:
0092: public String getTitle() {
0093: return title;
0094: }
0095:
0096: public void setTitle(String title) {
0097: this .title = title;
0098: }
0099:
0100: public UploadedFile getUpFile() {
0101: return upFile;
0102: }
0103:
0104: public void setUpFile(UploadedFile upFile) {
0105: if (logger.isDebugEnabled())
0106: logger.debug("upload file name " + upFile.getName());
0107: this .upFile = upFile;
0108: }
0109:
0110: public Spreadsheet getSpreadsheet() {
0111: return spreadsheet;
0112: }
0113:
0114: public void setSpreadsheet(Spreadsheet spreadsheet) {
0115: this .spreadsheet = spreadsheet;
0116: }
0117:
0118: public Map getRosterMap() {
0119: return rosterMap;
0120: }
0121:
0122: public void setRosterMap(Map rosterMap) {
0123: this .rosterMap = rosterMap;
0124: }
0125:
0126: public Long getSpreadsheetId() {
0127: return spreadsheetId;
0128: }
0129:
0130: public void setSpreadsheetId(Long spreadsheetId) {
0131: this .spreadsheetId = spreadsheetId;
0132: }
0133:
0134: public List getSpreadsheets() {
0135: this .setPageName("spreadsheetListing");
0136: return getGradebookManager().getSpreadsheets(getGradebookId());
0137: }
0138:
0139: public String deleteItem() {
0140: return "spreadsheetRemove";
0141: }
0142:
0143: public List getAssignmentList() {
0144: return assignmentList;
0145: }
0146:
0147: public void setAssignmentList(List assignmentList) {
0148: this .assignmentList = assignmentList;
0149: }
0150:
0151: public List getStudentRows() {
0152: return studentRows;
0153: }
0154:
0155: public void setStudentRows(List studentRows) {
0156: this .studentRows = studentRows;
0157: }
0158:
0159: public List getAssignmentHeaders() {
0160: return assignmentHeaders;
0161: }
0162:
0163: public void setAssignmentHeaders(List assignmentHeaders) {
0164: this .assignmentHeaders = assignmentHeaders;
0165: }
0166:
0167: public Map getSelectedAssignment() {
0168: return selectedAssignment;
0169: }
0170:
0171: public void setSelectedAssignment(Map selectedAssignment) {
0172: this .selectedAssignment = selectedAssignment;
0173: }
0174:
0175: public List getAssignmentColumnSelectItems() {
0176: return assignmentColumnSelectItems;
0177: }
0178:
0179: public void setAssignmentColumnSelectItems(
0180: List assignmentColumnSelectItems) {
0181: this .assignmentColumnSelectItems = assignmentColumnSelectItems;
0182: }
0183:
0184: public boolean isSaved() {
0185: return saved;
0186: }
0187:
0188: public void setSaved(boolean saved) {
0189: this .saved = saved;
0190: }
0191:
0192: public String getColumnCount() {
0193: return FacesUtil.getLocalizedString(
0194: "upload_preview_column_count",
0195: new String[] { columnCount });
0196: }
0197:
0198: public void setColumnCount(String columnCount) {
0199: this .columnCount = columnCount;
0200: }
0201:
0202: public String getRowCount() {
0203: return FacesUtil.getLocalizedString("upload_preview_row_count",
0204: new String[] { rowCount });
0205: }
0206:
0207: public void setRowCount(String rowCount) {
0208: this .rowCount = rowCount;
0209: }
0210:
0211: public String getRowStyles() {
0212: StringBuffer sb = new StringBuffer();
0213: for (Iterator iter = studentRows.iterator(); iter.hasNext();) {
0214: SpreadsheetRow row = (SpreadsheetRow) iter.next();
0215: if (row.isKnown()) {
0216: sb.append("internal,");
0217: } else {
0218: sb.append("external,");
0219: }
0220: }
0221: if (logger.isDebugEnabled())
0222: logger.debug(sb.toString());
0223: return sb.toString();
0224: }
0225:
0226: public boolean getHasUnknownUser() {
0227: return hasUnknownUser;
0228: }
0229:
0230: public void setHasUnknownUser(boolean hasUnknownUser) {
0231: this .hasUnknownUser = hasUnknownUser;
0232: }
0233:
0234: public Map getScores() {
0235: return scores;
0236: }
0237:
0238: public void setScores(Map scores) {
0239: this .scores = scores;
0240: }
0241:
0242: public Assignment getAssignment() {
0243: return assignment;
0244: }
0245:
0246: public void setAssignment(Assignment assignment) {
0247: this .assignment = assignment;
0248: }
0249:
0250: public Long getAssignmentId() {
0251: return assignmentId;
0252: }
0253:
0254: public void setAssignmentId(Long assignmentId) {
0255: this .assignmentId = assignmentId;
0256: }
0257:
0258: //view file from db
0259: public String viewItem() {
0260:
0261: if (logger.isDebugEnabled())
0262: logger.debug("loading viewItem()");
0263:
0264: org.sakaiproject.tool.gradebook.Spreadsheet sp = getGradebookManager()
0265: .getSpreadsheet(spreadsheetId);
0266: StringBuffer sb = new StringBuffer();
0267: sb.append(sp.getContent());
0268:
0269: List contents = new ArrayList();
0270:
0271: String lineitems[] = sb.toString().split("\n");
0272: for (int i = 0; i < lineitems.length; i++) {
0273: if (logger.isDebugEnabled())
0274: logger.debug("line item contents \n" + lineitems[i]);
0275: contents.add(lineitems[i]);
0276: }
0277:
0278: if (logger.isDebugEnabled())
0279: logger.debug(sp.toString());
0280:
0281: spreadsheet = new Spreadsheet();
0282: spreadsheet.setTitle(sp.getName());
0283: spreadsheet.setDate(sp.getDateCreated());
0284: spreadsheet.setUserId(sp.getCreator());
0285: spreadsheet.setLineitems(contents);
0286:
0287: assignmentList = new ArrayList();
0288: studentRows = new ArrayList();
0289: assignmentColumnSelectItems = new ArrayList();
0290: //
0291: // assignmentHeaders = new ArrayList();
0292:
0293: SpreadsheetHeader header = new SpreadsheetHeader(
0294: (String) spreadsheet.getLineitems().get(0));
0295: assignmentHeaders = header.getHeaderWithoutUser();
0296:
0297: //generate spreadsheet rows
0298: Iterator it = spreadsheet.getLineitems().iterator();
0299: int rowcount = 0;
0300: int unknownusers = 0;
0301: while (it.hasNext()) {
0302: String line = (String) it.next();
0303: if (rowcount > 0) {
0304: SpreadsheetRow row = new SpreadsheetRow(line);
0305: studentRows.add(row);
0306: //check the number of unkonw users in spreadsheet
0307: if (!row.isKnown())
0308: unknownusers = unknownusers + 1;
0309: if (logger.isDebugEnabled())
0310: logger.debug("row added" + rowcount);
0311: }
0312: rowcount++;
0313: }
0314: rowCount = String.valueOf(rowcount - 1);
0315: if (unknownusers > 0) {
0316: this .hasUnknownUser = true;
0317: }
0318:
0319: //create a numeric list of assignment headers
0320:
0321: if (logger.isDebugEnabled())
0322: logger.debug("creating assignment List ---------");
0323: for (int i = 0; i < assignmentHeaders.size(); i++) {
0324: assignmentList.add(new Integer(i));
0325: if (logger.isDebugEnabled())
0326: logger.debug("col added" + i);
0327: }
0328: columnCount = String.valueOf(assignmentHeaders.size());
0329:
0330: for (int i = 0; i < assignmentHeaders.size(); i++) {
0331: SelectItem item = new SelectItem(new Integer(i + 1),
0332: (String) assignmentHeaders.get(i));
0333: if (logger.isDebugEnabled())
0334: logger.debug("creating selectItems " + item.getValue());
0335: assignmentColumnSelectItems.add(item);
0336: }
0337:
0338: if (logger.isDebugEnabled())
0339: logger.debug("Map initialized " + studentRows.size());
0340: if (logger.isDebugEnabled())
0341: logger.debug("assignmentList " + assignmentList.size());
0342:
0343: return "spreadsheetPreview";
0344: }
0345:
0346: //process file and preview
0347: public String processFile() throws Exception {
0348:
0349: if (logger.isDebugEnabled())
0350: logger.debug("check if upFile is intialized");
0351: if (upFile == null) {
0352: if (logger.isDebugEnabled())
0353: logger.debug("upFile not initialized");
0354: FacesUtil
0355: .addErrorMessage(getLocalizedString("upload_view_failure"));
0356: return null;
0357: }
0358:
0359: if (logger.isDebugEnabled()) {
0360: logger.debug("file size " + upFile.getSize() + "file name "
0361: + upFile.getName() + "file Content Type "
0362: + upFile.getContentType() + "");
0363: }
0364:
0365: if (logger.isDebugEnabled())
0366: logger.debug("check that the file is csv file");
0367: if (!upFile.getName().endsWith("csv")) {
0368: FacesUtil.addErrorMessage(getLocalizedString(
0369: "upload_view_filetype_error", new String[] { upFile
0370: .getName() }));
0371: return null;
0372: }
0373: /**
0374: logger.debug("check that file content type");
0375:
0376: logger.debug("check the file content type");
0377: if(!upFile.getContentType().equalsIgnoreCase("application/vnd.ms-excel")){
0378: FacesUtil.addErrorMessage(getLocalizedString("upload_view_filetype_error",new String[] {upFile.getName()}));
0379: return null;
0380: }
0381: **/
0382:
0383: InputStream inputStream = new BufferedInputStream(upFile
0384: .getInputStream());
0385: List contents;
0386: contents = csvtoArray(inputStream);
0387: spreadsheet = new Spreadsheet();
0388: spreadsheet.setDate(new Date());
0389: spreadsheet.setTitle(this .getTitle());
0390: spreadsheet.setFilename(upFile.getName());
0391: spreadsheet.setLineitems(contents);
0392:
0393: assignmentList = new ArrayList();
0394: studentRows = new ArrayList();
0395: assignmentColumnSelectItems = new ArrayList();
0396: //
0397: // assignmentHeaders = new ArrayList();
0398:
0399: SpreadsheetHeader header;
0400: try {
0401: header = new SpreadsheetHeader((String) spreadsheet
0402: .getLineitems().get(0));
0403: assignmentHeaders = header.getHeaderWithoutUser();
0404: } catch (IndexOutOfBoundsException ioe) {
0405: if (logger.isDebugEnabled())
0406: logger
0407: .debug(ioe
0408: + " there is a problem with the uploaded spreadsheet");
0409: FacesUtil
0410: .addErrorMessage(getLocalizedString("upload_view_filecontent_error"));
0411: return null;
0412: }
0413:
0414: //generate spreadsheet rows
0415: Iterator it = spreadsheet.getLineitems().iterator();
0416: int rowcount = 0;
0417: int unknownusers = 0;
0418: while (it.hasNext()) {
0419: String line = (String) it.next();
0420: if (rowcount > 0) {
0421: SpreadsheetRow row = new SpreadsheetRow(line);
0422: studentRows.add(row);
0423: //check the number of unkonw users in spreadsheet
0424: if (!row.isKnown())
0425: unknownusers = unknownusers + 1;
0426: if (logger.isDebugEnabled())
0427: logger.debug("row added" + rowcount);
0428: }
0429: rowcount++;
0430: }
0431: rowCount = String.valueOf(rowcount - 1);
0432: if (unknownusers > 0) {
0433: this .hasUnknownUser = true;
0434: }
0435:
0436: //create a numeric list of assignment headers
0437:
0438: if (logger.isDebugEnabled())
0439: logger.debug("creating assignment List ---------");
0440: for (int i = 0; i < assignmentHeaders.size(); i++) {
0441: assignmentList.add(new Integer(i));
0442: if (logger.isDebugEnabled())
0443: logger.debug("col added" + i);
0444: }
0445: columnCount = String.valueOf(assignmentHeaders.size());
0446:
0447: for (int i = 0; i < assignmentHeaders.size(); i++) {
0448: SelectItem item = new SelectItem(new Integer(i + 1),
0449: (String) assignmentHeaders.get(i));
0450: if (logger.isDebugEnabled())
0451: logger.debug("creating selectItems " + item.getValue());
0452: assignmentColumnSelectItems.add(item);
0453: }
0454:
0455: if (logger.isDebugEnabled())
0456: logger.debug("Map initialized " + studentRows.size());
0457: if (logger.isDebugEnabled())
0458: logger.debug("assignmentList " + assignmentList.size());
0459:
0460: if (studentRows.size() < 1) {
0461: FacesUtil
0462: .addErrorMessage(getLocalizedString("upload_view_filecontent_error"));
0463: return null;
0464: }
0465:
0466: return "spreadsheetUploadPreview";
0467: }
0468:
0469: /**
0470: * method converts an input stream to an List consist of strings
0471: * representing a line
0472: *
0473: * @param inputStream
0474: * @return contents
0475: */
0476: private List csvtoArray(InputStream inputStream) throws IOException {
0477:
0478: /**
0479: * TODO this well probably be removed
0480: */
0481:
0482: if (logger.isDebugEnabled())
0483: logger.debug("csvtoArray()");
0484: List contents = new ArrayList();
0485: BufferedReader reader = new BufferedReader(
0486: new InputStreamReader(inputStream));
0487: String line;
0488: while ((line = reader.readLine()) != null) {
0489: //logger.debug("contents of line: "+line);
0490: contents.add(line);
0491: }
0492: return contents;
0493:
0494: }
0495:
0496: /**
0497: * method to save CSV to database
0498: *
0499: * @return String
0500: */
0501: public String saveFile() {
0502:
0503: StringBuffer sb = new StringBuffer();
0504: List contents = spreadsheet.getLineitems();
0505: Iterator it = contents.iterator();
0506: while (it.hasNext()) {
0507: String line = (String) it.next();
0508: sb.append(line + '\n');
0509: }
0510:
0511: String filename = spreadsheet.getFilename();
0512:
0513: /** temporary presistence code
0514: *
0515: */
0516: if (logger.isDebugEnabled())
0517: logger.debug("string to save " + sb.toString());
0518: try {
0519: getGradebookManager().createSpreadsheet(
0520: getGradebookId(),
0521: spreadsheet.getTitle(),
0522: this .getUserDirectoryService().getUserDisplayName(
0523: getUserUid()), new Date(), sb.toString());
0524: } catch (ConflictingSpreadsheetNameException e) {
0525: if (logger.isDebugEnabled())
0526: logger.debug(e);
0527: FacesUtil
0528: .addErrorMessage(getLocalizedString("upload_preview_save_failure"));
0529: return null;
0530: }
0531: FacesUtil.addRedirectSafeMessage(getLocalizedString(
0532: "upload_preview_save_confirmation",
0533: new String[] { filename }));
0534:
0535: this .setPageName("spreadsheetListing");
0536: return "spreadsheetListing";
0537: }
0538:
0539: public String importData() {
0540:
0541: FacesContext facesContext = FacesContext.getCurrentInstance();
0542: HttpServletRequest request = (HttpServletRequest) facesContext
0543: .getExternalContext().getRequest();
0544:
0545: if (logger.isDebugEnabled())
0546: logger.debug("processFile()");
0547: String selectedColumn = request.getParameter("form:assignment");
0548: if (logger.isDebugEnabled())
0549: logger.debug("the selected column is " + selectedColumn);
0550:
0551: selectedAssignment = new HashMap();
0552: try {
0553: selectedAssignment.put("Assignment", assignmentHeaders
0554: .get(Integer.parseInt(selectedColumn) - 1));
0555: } catch (Exception e) {
0556: if (logger.isDebugEnabled())
0557: logger.debug("no assignment selected");
0558: FacesUtil
0559: .addErrorMessage(getLocalizedString("import_preview_assignment_selection_failure"));
0560: return null;
0561: }
0562:
0563: Iterator it = studentRows.iterator();
0564: if (logger.isDebugEnabled())
0565: logger
0566: .debug("number of student rows "
0567: + studentRows.size());
0568: int i = 0;
0569: while (it.hasNext()) {
0570:
0571: if (logger.isDebugEnabled())
0572: logger.debug("row " + i);
0573: SpreadsheetRow row = (SpreadsheetRow) it.next();
0574: List line = row.getRowcontent();
0575:
0576: String userid = "";
0577: String user = (String) line.get(0);
0578: try {
0579: userid = ((User) rosterMap.get(line.get(0)))
0580: .getUserUid();
0581: } catch (Exception e) {
0582: if (logger.isDebugEnabled())
0583: logger.debug("user " + user
0584: + "is not known to the system");
0585: userid = "";
0586: }
0587:
0588: String points;
0589: try {
0590: int index = Integer.parseInt(selectedColumn);
0591: if (line.size() > index) {
0592: points = (String) line.get(index);
0593: } else {
0594: logger.info("unable to find any points for "
0595: + userid + " in spreadsheet");
0596: points = "";
0597: }
0598: } catch (NumberFormatException e) {
0599: if (logger.isDebugEnabled())
0600: logger.error(e);
0601: points = "";
0602: }
0603: if (logger.isDebugEnabled())
0604: logger.debug("user " + user + " userid " + userid
0605: + " points " + points);
0606: if (!"".equals(points) && (!"".equals(userid))) {
0607: selectedAssignment.put(userid, points);
0608: }
0609: i++;
0610: }
0611: if (logger.isDebugEnabled())
0612: logger.debug("scores to import " + i);
0613:
0614: spreadsheet.setSelectedAssignment(selectedAssignment);
0615:
0616: if (assignment == null) {
0617: assignment = new Assignment();
0618: assignment.setReleased(true);
0619: }
0620:
0621: try {
0622: scores = spreadsheet.getSelectedAssignment();
0623: assignment.setName((String) scores.get("Assignment"));
0624: } catch (NullPointerException npe) {
0625: if (logger.isDebugEnabled())
0626: logger.debug("scores not set");
0627: }
0628:
0629: return "spreadsheetImport";
0630: }
0631:
0632: //save grades and comments
0633: public String saveGrades() {
0634:
0635: if (logger.isDebugEnabled())
0636: logger.debug("create assignment and save grades");
0637: if (logger.isDebugEnabled())
0638: logger.debug("first check if all variables are numeric");
0639:
0640: logger.debug("********************" + scores);
0641:
0642: Iterator iter = scores.entrySet().iterator();
0643: while (iter.hasNext()) {
0644: Map.Entry entry = (Map.Entry) iter.next();
0645: String points = (String) entry.getValue();
0646: try {
0647: if (logger.isDebugEnabled())
0648: logger.debug("checking if " + points
0649: + " is a numeric value");
0650: if (!entry.getKey().equals("Assignment"))
0651: Double.parseDouble(points);
0652: } catch (NumberFormatException e) {
0653: if (logger.isDebugEnabled())
0654: logger.debug(points + " is not a numeric value");
0655: FacesUtil
0656: .addRedirectSafeMessage(getLocalizedString("import_assignment_notsupported"));
0657:
0658: return "spreadsheetPreview";
0659: }
0660:
0661: }
0662:
0663: try {
0664: assignmentId = getGradebookManager().createAssignment(
0665: getGradebookId(), assignment.getName(),
0666: assignment.getPointsPossible(),
0667: assignment.getDueDate(),
0668: new Boolean(assignment.isNotCounted()),
0669: new Boolean(assignment.isReleased()));
0670: FacesUtil.addRedirectSafeMessage(getLocalizedString(
0671: "add_assignment_save", new String[] { assignment
0672: .getName() }));
0673:
0674: assignment = getGradebookManager().getAssignment(
0675: assignmentId);
0676: List gradeRecords = new ArrayList();
0677:
0678: //initialize comment List
0679: List comments = new ArrayList();
0680: //check if a comments column is selected for the defalt select item value is
0681: // 0 which mean no comments to be imported
0682: if (selectedCommentsColumnId != null
0683: && selectedCommentsColumnId > 0)
0684: comments = createCommentList(assignment);
0685:
0686: if (logger.isDebugEnabled())
0687: logger.debug("remove title entry form map");
0688: scores.remove("Assignment");
0689: if (logger.isDebugEnabled())
0690: logger
0691: .debug("iterate through scores and and save assignment grades");
0692:
0693: Iterator it = scores.entrySet().iterator();
0694: while (it.hasNext()) {
0695:
0696: Map.Entry entry = (Map.Entry) it.next();
0697: String uid = (String) entry.getKey();
0698: String points = (String) entry.getValue();
0699: AssignmentGradeRecord asnGradeRecord = new AssignmentGradeRecord(
0700: assignment, uid, Double.valueOf(points));
0701: gradeRecords.add(asnGradeRecord);
0702: if (logger.isDebugEnabled())
0703: logger.debug("added grades for " + uid
0704: + " - points scored " + points);
0705:
0706: }
0707:
0708: if (logger.isDebugEnabled())
0709: logger.debug("persist grade records to database");
0710: getGradebookManager().updateAssignmentGradesAndComments(
0711: assignment, gradeRecords, comments);
0712: getGradebookBean().getEventTrackingService().postEvent(
0713: "gradebook.importItem",
0714: "/gradebook/" + getGradebookId() + "/"
0715: + assignment.getName() + "/"
0716: + getAuthzLevel());
0717: return "spreadsheetPreview";
0718: } catch (ConflictingAssignmentNameException e) {
0719: if (logger.isErrorEnabled())
0720: logger.error(e);
0721: FacesUtil
0722: .addErrorMessage(getLocalizedString("add_assignment_name_conflict_failure"));
0723: }
0724:
0725: return null;
0726: }
0727:
0728: /**
0729: * method creates a collection of comment
0730: * objects from a the saved spreadsheet and
0731: * selected column. requires an assignment as parameter to set the
0732: * gradableObject property of the comment
0733: *
0734: * @param assignmentTobeCommented
0735: * @return List of comment comment objects
0736: */
0737: public List createCommentList(Assignment assignmentTobeCommented) {
0738:
0739: List comments = new ArrayList();
0740: Iterator it = studentRows.iterator();
0741: while (it.hasNext()) {
0742: SpreadsheetRow row = (SpreadsheetRow) it.next();
0743: List line = row.getRowcontent();
0744:
0745: String userid = "";
0746: String user = (String) line.get(0);
0747: try {
0748: userid = ((User) rosterMap.get(line.get(0)))
0749: .getUserUid();
0750: String commentText = (String) line
0751: .get(selectedCommentsColumnId.intValue());
0752: if ((!commentText.equals(""))) {
0753: Comment comment = new Comment(userid, commentText,
0754: assignmentTobeCommented);
0755: comments.add(comment);
0756: }
0757: } catch (Exception e) {
0758: if (logger.isDebugEnabled())
0759: logger.debug("student is required and " + user
0760: + "is not known to this gradebook");
0761: }
0762: }
0763: return comments;
0764: }
0765:
0766: public Integer getSelectedCommentsColumnId() {
0767: return selectedCommentsColumnId;
0768: }
0769:
0770: public void setSelectedCommentsColumnId(
0771: Integer selectedCommentsColumnId) {
0772: this .selectedCommentsColumnId = selectedCommentsColumnId;
0773: }
0774:
0775: /**
0776: *
0777: */
0778:
0779: public class Spreadsheet implements Serializable {
0780:
0781: private String title;
0782: private Date date;
0783: private String userId;
0784: private String contents;
0785: private String displayName;
0786: private Long gradebookId;
0787: private String filename;
0788: private List lineitems;
0789: private Map selectedAssignment;
0790:
0791: public Spreadsheet(String title, Date date, String userId,
0792: String contents) {
0793:
0794: if (logger.isDebugEnabled())
0795: logger.debug("loading Spreadsheet()");
0796: this .title = title;
0797: this .date = date;
0798: this .userId = userId;
0799: this .contents = contents;
0800: }
0801:
0802: public Spreadsheet() {
0803: if (logger.isDebugEnabled())
0804: logger.debug("loading Spreadsheet()");
0805: }
0806:
0807: public String getUserId() {
0808: return userId;
0809: }
0810:
0811: public void setUserId(String userId) {
0812: this .userId = userId;
0813: }
0814:
0815: public Date getDate() {
0816: return date;
0817: }
0818:
0819: public void setDate(Date date) {
0820: this .date = date;
0821: }
0822:
0823: public String getTitle() {
0824: return title;
0825: }
0826:
0827: public void setTitle(String title) {
0828: this .title = title;
0829: }
0830:
0831: public String getContents() {
0832: return contents;
0833: }
0834:
0835: public void setContents(String contents) {
0836: this .contents = contents;
0837: }
0838:
0839: public String getDisplayName() {
0840: return displayName;
0841: }
0842:
0843: public void setDisplayName(String displayName) {
0844: this .displayName = displayName;
0845: }
0846:
0847: public Long getGradebookId() {
0848: return gradebookId;
0849: }
0850:
0851: public void setGradebookId(Long gradebookId) {
0852: this .gradebookId = gradebookId;
0853: }
0854:
0855: public String getFilename() {
0856: return filename;
0857: }
0858:
0859: public void setFilename(String filename) {
0860: this .filename = filename;
0861: }
0862:
0863: public List getLineitems() {
0864: return lineitems;
0865: }
0866:
0867: public void setLineitems(List lineitems) {
0868: this .lineitems = lineitems;
0869: }
0870:
0871: public Map getSelectedAssignment() {
0872: //logger.debug(this.selectedAssignment);
0873: return selectedAssignment;
0874: }
0875:
0876: public void setSelectedAssignment(Map selectedAssignment) {
0877: this .selectedAssignment = selectedAssignment;
0878: //logger.debug(selectedAssignment);
0879: }
0880:
0881: public String toString() {
0882: return "Spreadsheet{" + "title='" + title + '\''
0883: + ", date=" + date + ", userId='" + userId + '\''
0884: + ", contents='" + contents + '\''
0885: + ", displayName='" + displayName + '\''
0886: + ", gradebookId=" + gradebookId + ", filename='"
0887: + filename + '\'' + ", lineitems=" + lineitems
0888: + ", selectedAssignment=" + selectedAssignment
0889: + '}';
0890: }
0891: }
0892:
0893: /**
0894: * spreadsheet header class
0895: */
0896:
0897: public class SpreadsheetHeader implements Serializable {
0898:
0899: private List header;
0900: private int columnCount;
0901:
0902: public List getHeader() {
0903: return header;
0904: }
0905:
0906: public void setHeader(List header) {
0907: this .header = header;
0908: }
0909:
0910: public int getColumnCount() {
0911: return columnCount;
0912: }
0913:
0914: public void setColumnCount(int columnCount) {
0915: this .columnCount = columnCount;
0916: }
0917:
0918: public List getHeaderWithoutUser() {
0919: List head = header;
0920: head.remove(0);
0921: return head;
0922: }
0923:
0924: public SpreadsheetHeader(String source) {
0925:
0926: if (logger.isDebugEnabled())
0927: logger.debug("creating header from " + source);
0928: header = new ArrayList();
0929: CSV csv = new CSV();
0930: header = csv.parse(source);
0931: columnCount = header.size();
0932:
0933: }
0934:
0935: }
0936:
0937: /**
0938: * spreadsheetRow class
0939: */
0940: public class SpreadsheetRow implements Serializable {
0941:
0942: private List rowcontent;
0943: private int columnCount;
0944: private String userDisplayName;
0945: private String userId;
0946: private String userUid;
0947: private boolean isKnown;
0948:
0949: public SpreadsheetRow(String source) {
0950:
0951: if (logger.isDebugEnabled())
0952: logger.debug("creating row from string " + source);
0953: rowcontent = new ArrayList();
0954: CSV csv = new CSV();
0955: rowcontent = csv.parse(source);
0956:
0957: try {
0958: if (logger.isDebugEnabled())
0959: logger.debug("getuser name for "
0960: + rowcontent.get(0));
0961: //userDisplayName = getUserDirectoryService().getUserDisplayName(tokens[0]);
0962: userId = (String) rowcontent.get(0);
0963: userDisplayName = ((User) rosterMap.get(userId))
0964: .getDisplayName();
0965: userUid = ((User) rosterMap.get(userId)).getUserUid();
0966: isKnown = true;
0967: if (logger.isDebugEnabled())
0968: logger.debug("get userid " + rowcontent.get(0)
0969: + "username is " + userDisplayName);
0970:
0971: } catch (NullPointerException e) {
0972: logger.error("User " + rowcontent.get(0)
0973: + " is unknown to this gradebook: " + e);
0974: userDisplayName = "unknown student";
0975: userId = (String) rowcontent.get(0);
0976: userUid = null;
0977: isKnown = false;
0978:
0979: }
0980:
0981: }
0982:
0983: public List getRowcontent() {
0984:
0985: return rowcontent;
0986: }
0987:
0988: public void setRowcontent(List rowcontent) {
0989: this .rowcontent = rowcontent;
0990: }
0991:
0992: public int getColumnCount() {
0993: return columnCount;
0994: }
0995:
0996: public void setColumnCount(int columnCount) {
0997: this .columnCount = columnCount;
0998: }
0999:
1000: public String getUserDisplayName() {
1001: return userDisplayName;
1002: }
1003:
1004: public void setUserDisplayName(String userDisplayName) {
1005: this .userDisplayName = userDisplayName;
1006: }
1007:
1008: public String getUserId() {
1009: return userId;
1010: }
1011:
1012: public void setUserId(String userId) {
1013: this .userId = userId;
1014: }
1015:
1016: public String getUserUid() {
1017: return userUid;
1018: }
1019:
1020: public void setUserUid(String userUid) {
1021: this .userUid = userUid;
1022: }
1023:
1024: public boolean isKnown() {
1025: return isKnown;
1026: }
1027:
1028: public void setKnown(boolean known) {
1029: isKnown = known;
1030: }
1031: }
1032:
1033: //csv class to handle
1034:
1035: /** Parse comma-separated values (CSV), a common Windows file format.
1036: * Sample input: "LU",86.25,"11/4/1998","2:19PM",+4.0625
1037: * <p>
1038: * Inner logic adapted from a C++ original that was
1039: * Copyright (C) 1999 Lucent Technologies
1040: * Excerpted from 'The Practice of Programming'
1041: * by Brian W. Kernighan and Rob Pike.
1042: * <p>
1043: * Included by permission of the http://tpop.awl.com/ web site,
1044: * which says:
1045: * "You may use this code for any purpose, as long as you leave
1046: * the copyright notice and book citation attached." I have done so.
1047: * @author Brian W. Kernighan and Rob Pike (C++ original)
1048: * @author Ian F. Darwin (translation into Java and removal of I/O)
1049: * @author Ben Ballard (rewrote advQuoted to handle '""' and for readability)
1050: */
1051: class CSV {
1052:
1053: public static final char DEFAULT_SEP = ',';
1054:
1055: /** Construct a CSV parser, with the default separator (`,'). */
1056: public CSV() {
1057: this (DEFAULT_SEP);
1058: }
1059:
1060: /** Construct a CSV parser with a given separator.
1061: * @param sep The single char for the separator (not a list of
1062: * separator characters)
1063: */
1064: public CSV(char sep) {
1065: fieldSep = sep;
1066: }
1067:
1068: /** The fields in the current String */
1069: protected List list = new ArrayList();
1070:
1071: /** the separator char for this parser */
1072: protected char fieldSep;
1073:
1074: /** parse: break the input String into fields
1075: * @return java.util.Iterator containing each field
1076: * from the original as a String, in order.
1077: */
1078: public List parse(String line) {
1079: StringBuffer sb = new StringBuffer();
1080: list.clear(); // recycle to initial state
1081: int i = 0;
1082:
1083: if (line.length() == 0) {
1084: list.add(line);
1085: return list;
1086: }
1087:
1088: do {
1089: sb.setLength(0);
1090: if (i < line.length() && line.charAt(i) == '"')
1091: i = advQuoted(line, sb, ++i); // skip quote
1092: else
1093: i = advPlain(line, sb, i);
1094: list.add(sb.toString());
1095: i++;
1096: } while (i < line.length());
1097: if (logger.isDebugEnabled()) {
1098: StringBuffer logBuffer = new StringBuffer("Parsed "
1099: + line + " as: ");
1100: for (Iterator iter = list.iterator(); iter.hasNext();) {
1101: logBuffer.append(iter.next());
1102: if (iter.hasNext()) {
1103: logBuffer.append(", ");
1104: }
1105: }
1106: logger.debug("Parsed source string " + line + " as "
1107: + logBuffer.toString() + ", length="
1108: + list.size());
1109: }
1110: return list;
1111:
1112: }
1113:
1114: /** advQuoted: quoted field; return index of next separator */
1115: protected int advQuoted(String s, StringBuffer sb, int i) {
1116: int j;
1117: int len = s.length();
1118: for (j = i; j < len; j++) {
1119: if (s.charAt(j) == '"' && j + 1 < len) {
1120: if (s.charAt(j + 1) == '"') {
1121: j++; // skip escape char
1122: } else if (s.charAt(j + 1) == fieldSep) { //next delimeter
1123: j++; // skip end quotes
1124: break;
1125: }
1126: } else if (s.charAt(j) == '"' && j + 1 == len) { // end quotes at end of line
1127: break; //done
1128: }
1129: sb.append(s.charAt(j)); // regular character.
1130: }
1131: return j;
1132: }
1133:
1134: /** advPlain: unquoted field; return index of next separator */
1135: protected int advPlain(String s, StringBuffer sb, int i) {
1136: int j;
1137:
1138: j = s.indexOf(fieldSep, i); // look for separator
1139: if (j == -1) { // none found
1140: sb.append(s.substring(i));
1141: return s.length();
1142: } else {
1143: sb.append(s.substring(i, j));
1144: return j;
1145: }
1146: }
1147: }
1148: }
|