List of usage examples for java.text NumberFormat parse
public Number parse(String source) throws ParseException
From source file:org.springframework.beans.factory.DefaultListableBeanFactoryTests.java
@Test public void testCustomConverter() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); GenericConversionService conversionService = new DefaultConversionService(); conversionService.addConverter(new Converter<String, Float>() { @Override// w ww. ja va 2 s. c o m public Float convert(String source) { try { NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN); return nf.parse(source).floatValue(); } catch (ParseException ex) { throw new IllegalArgumentException(ex); } } }); lbf.setConversionService(conversionService); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("myFloat", "1,1"); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.setPropertyValues(pvs); lbf.registerBeanDefinition("testBean", bd); TestBean testBean = (TestBean) lbf.getBean("testBean"); assertTrue(testBean.getMyFloat().floatValue() == 1.1f); }
From source file:org.sakaiproject.component.gradebook.GradebookServiceHibernateImpl.java
/** * * @param doubleAsString/*from w ww . j ava2 s. co m*/ * @return a locale-aware Double value representation of the given String * @throws ParseException */ private Double convertStringToDouble(String doubleAsString) { Double scoreAsDouble = null; if (doubleAsString != null && !"".equals(doubleAsString)) { try { NumberFormat numberFormat = NumberFormat.getInstance(new ResourceLoader().getLocale()); Number numericScore = numberFormat.parse(doubleAsString.trim()); scoreAsDouble = numericScore.doubleValue(); } catch (ParseException e) { log.error(e); } } return scoreAsDouble; }
From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRdbmsClientImpl.java
/** * Gets a list of APIResponseTimeDTO objects containing information related to APIs belonging * to a particular provider along with their average response times. * * @param providerName Name of the API provider * @return a List of APIResponseTimeDTO objects, possibly empty * @throws org.wso2.carbon.apimgt.usage.client.exception.APIMgtUsageQueryServiceClientException on error *//* w w w . ja va2s .c o m*/ @Override public List<APIResponseTimeDTO> getProviderAPIServiceTime(String providerName, String fromDate, String toDate, int limit) throws APIMgtUsageQueryServiceClientException { Collection<APIResponseTime> responseTimes = getAPIResponseTimeData( APIUsageStatisticsClientConstants.API_VERSION_SERVICE_TIME_SUMMARY); List<API> providerAPIs = getAPIsByProvider(providerName); DecimalFormat format = new DecimalFormat("#.##"); NumberFormat numberFormat = NumberFormat.getInstance(Locale.getDefault()); List<APIResponseTimeDTO> apiResponseTimeUsage = new ArrayList<APIResponseTimeDTO>(); for (APIResponseTime responseTime : responseTimes) { for (API providerAPI : providerAPIs) { if (providerAPI.getId().getApiName().equals(responseTime.getApiName()) && providerAPI.getId().getVersion().equals(responseTime.getApiVersion()) && providerAPI.getContext().equals(responseTime.getContext())) { APIResponseTimeDTO responseTimeDTO = new APIResponseTimeDTO(); responseTimeDTO.setApiName(responseTime.getApiName()); //calculate the average response time double avgTime = responseTime.getResponseTime() / responseTime.getResponseCount(); //format the time try { responseTimeDTO.setServiceTime(numberFormat.parse(format.format(avgTime)).doubleValue()); } catch (ParseException e) { throw new APIMgtUsageQueryServiceClientException("Parse exception while formatting time"); } apiResponseTimeUsage.add(responseTimeDTO); } } } return getResponseTimeTopEntries(apiResponseTimeUsage, limit); }
From source file:de.qaware.chronix.importer.csv.FileImporter.java
/** * Reads the given file / folder and calls the bi consumer with the extracted points * * @param points//from w ww . jav a 2s.co m * @param folder * @param databases * @return */ public Pair<Integer, Integer> importPoints(Map<Attributes, Pair<Instant, Instant>> points, File folder, BiConsumer<List<ImportPoint>, Attributes>... databases) { final AtomicInteger pointCounter = new AtomicInteger(0); final AtomicInteger tsCounter = new AtomicInteger(0); final File metricsFile = new File(METRICS_FILE_PATH); LOGGER.info("Writing imported metrics to {}", metricsFile); LOGGER.info("Import supports csv files as well as gz compressed csv files."); try { final FileWriter metricsFileWriter = new FileWriter(metricsFile); Collection<File> files = new ArrayList<>(); if (folder.isFile()) { files.add(folder); } else { files.addAll(FileUtils.listFiles(folder, new String[] { "gz", "csv" }, true)); } AtomicInteger counter = new AtomicInteger(0); files.parallelStream().forEach(file -> { SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); NumberFormat nf = DecimalFormat.getInstance(numberLocal); InputStream inputStream = null; BufferedReader reader = null; try { inputStream = new FileInputStream(file); if (file.getName().endsWith("gz")) { inputStream = new GZIPInputStream(inputStream); } reader = new BufferedReader(new InputStreamReader(inputStream)); //Read the first line String headerLine = reader.readLine(); if (headerLine == null || headerLine.isEmpty()) { boolean deleted = deleteFile(file, inputStream, reader); LOGGER.debug("File is empty {}. File {} removed {}", file.getName(), deleted); return; } //Extract the attributes from the file name //E.g. first_second_third_attribute.csv String[] fileNameMetaData = file.getName().split("_"); String[] metrics = headerLine.split(csvDelimiter); Map<Integer, Attributes> attributesPerTimeSeries = new HashMap<>(metrics.length); for (int i = 1; i < metrics.length; i++) { String metric = metrics[i]; String metricOnlyAscii = Normalizer.normalize(metric, Normalizer.Form.NFD); metricOnlyAscii = metric.replaceAll("[^\\x00-\\x7F]", ""); Attributes attributes = new Attributes(metricOnlyAscii, fileNameMetaData); //Check if meta data is completely set if (isEmpty(attributes)) { boolean deleted = deleteFile(file, inputStream, reader); LOGGER.info("Attributes contains empty values {}. File {} deleted {}", attributes, file.getName(), deleted); continue; } if (attributes.getMetric().equals(".*")) { boolean deleted = deleteFile(file, inputStream, reader); LOGGER.info("Attributes metric{}. File {} deleted {}", attributes.getMetric(), file.getName(), deleted); continue; } attributesPerTimeSeries.put(i, attributes); tsCounter.incrementAndGet(); } Map<Integer, List<ImportPoint>> dataPoints = new HashMap<>(); String line; while ((line = reader.readLine()) != null) { String[] splits = line.split(csvDelimiter); String date = splits[0]; Instant dateObject; if (instantDate) { dateObject = Instant.parse(date); } else if (sdfDate) { dateObject = sdf.parse(date).toInstant(); } else { dateObject = Instant.ofEpochMilli(Long.valueOf(date)); } for (int column = 1; column < splits.length; column++) { String value = splits[column]; double numericValue = nf.parse(value).doubleValue(); ImportPoint point = new ImportPoint(dateObject, numericValue); if (!dataPoints.containsKey(column)) { dataPoints.put(column, new ArrayList<>()); } dataPoints.get(column).add(point); pointCounter.incrementAndGet(); } } dataPoints.values().forEach(Collections::sort); IOUtils.closeQuietly(reader); IOUtils.closeQuietly(inputStream); dataPoints.forEach((key, importPoints) -> { for (BiConsumer<List<ImportPoint>, Attributes> database : databases) { database.accept(importPoints, attributesPerTimeSeries.get(key)); } points.put(attributesPerTimeSeries.get(key), Pair.of(importPoints.get(0).getDate(), importPoints.get(importPoints.size() - 1).getDate())); //write the stats to the file Instant start = importPoints.get(0).getDate(); Instant end = importPoints.get(importPoints.size() - 1).getDate(); try { writeStatsLine(metricsFileWriter, attributesPerTimeSeries.get(key), start, end); } catch (IOException e) { LOGGER.error("Could not write stats line", e); } LOGGER.info("{} of {} time series imported", counter.incrementAndGet(), tsCounter.get()); }); } catch (Exception e) { LOGGER.info("Exception while reading points.", e); } finally { //close all streams IOUtils.closeQuietly(reader); IOUtils.closeQuietly(inputStream); } }); } catch (Exception e) { LOGGER.error("Exception occurred during reading points."); } return Pair.of(tsCounter.get(), pointCounter.get()); }
From source file:net.sourceforge.eclipsetrader.opentick.Feed.java
public void snapshot() { SimpleDateFormat usDateTimeParser = new SimpleDateFormat("MM/dd/yyyy h:mma"); SimpleDateFormat usDateParser = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat usTimeParser = new SimpleDateFormat("h:mma"); NumberFormat numberFormat = NumberFormat.getInstance(Locale.US); // Builds the url for quotes download String host = "quote.yahoo.com"; StringBuffer url = new StringBuffer("http://" + host + "/download/javasoft.beans?symbols="); for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) { Security security = (Security) iter.next(); url = url.append(security.getCode() + "+"); }//from w w w . ja v a 2 s . c om if (url.charAt(url.length() - 1) == '+') url.deleteCharAt(url.length() - 1); url.append("&format=sl1d1t1c1ohgvbap"); // Read the last prices String line = ""; try { HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); BundleContext context = OpenTickPlugin.getDefault().getBundle().getBundleContext(); ServiceReference reference = context.getServiceReference(IProxyService.class.getName()); if (reference != null) { IProxyService proxy = (IProxyService) context.getService(reference); IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE); if (data != null) { if (data.getHost() != null) client.getHostConfiguration().setProxy(data.getHost(), data.getPort()); if (data.isRequiresAuthentication()) client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(data.getUserId(), data.getPassword())); } } HttpMethod method = new GetMethod(url.toString()); method.setFollowRedirects(true); client.executeMethod(method); BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); while ((line = in.readLine()) != null) { String[] item = line.split(","); if (line.indexOf(";") != -1) item = line.split(";"); Double open = null, high = null, low = null, close = null; Quote quote = new Quote(); // 2 = Date // 3 = Time try { GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US); usDateTimeParser.setTimeZone(c.getTimeZone()); usDateParser.setTimeZone(c.getTimeZone()); usTimeParser.setTimeZone(c.getTimeZone()); String date = stripQuotes(item[2]); if (date.indexOf("N/A") != -1) date = usDateParser.format(Calendar.getInstance().getTime()); String time = stripQuotes(item[3]); if (time.indexOf("N/A") != -1) time = usTimeParser.format(Calendar.getInstance().getTime()); c.setTime(usDateTimeParser.parse(date + " " + time)); c.setTimeZone(TimeZone.getDefault()); quote.setDate(c.getTime()); } catch (Exception e) { System.out.println(e.getMessage() + ": " + line); } // 1 = Last price or N/A if (item[1].equalsIgnoreCase("N/A") == false) quote.setLast(numberFormat.parse(item[1]).doubleValue()); // 4 = Change // 5 = Open if (item[5].equalsIgnoreCase("N/A") == false) open = new Double(numberFormat.parse(item[5]).doubleValue()); // 6 = Maximum if (item[6].equalsIgnoreCase("N/A") == false) high = new Double(numberFormat.parse(item[6]).doubleValue()); // 7 = Minimum if (item[7].equalsIgnoreCase("N/A") == false) low = new Double(numberFormat.parse(item[7]).doubleValue()); // 8 = Volume if (item[8].equalsIgnoreCase("N/A") == false) quote.setVolume(numberFormat.parse(item[8]).intValue()); // 9 = Bid Price if (item[9].equalsIgnoreCase("N/A") == false) quote.setBid(numberFormat.parse(item[9]).doubleValue()); // 10 = Ask Price if (item[10].equalsIgnoreCase("N/A") == false) quote.setAsk(numberFormat.parse(item[10]).doubleValue()); // 11 = Close Price if (item[11].equalsIgnoreCase("N/A") == false) close = new Double(numberFormat.parse(item[11]).doubleValue()); // 0 = Code String symbol = stripQuotes(item[0]); for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) { Security security = (Security) iter.next(); if (symbol.equalsIgnoreCase(security.getCode())) security.setQuote(quote, open, high, low, close); } } in.close(); } catch (Exception e) { System.out.println(e.getMessage() + ": " + line); e.printStackTrace(); } }
From source file:org.sakaiproject.tool.messageforums.DiscussionForumTool.java
public boolean isNumber(String validateString) { NumberFormat numberFormat = DecimalFormat.getInstance(new ResourceLoader().getLocale()); try {//from ww w. j av a2 s . c o m double d = numberFormat.parse(validateString).doubleValue(); if (d >= 0) return true; else return false; } catch (ParseException e) { return false; } }
From source file:org.sakaiproject.tool.messageforums.DiscussionForumTool.java
public String processDfGradeSubmit() { GradebookService gradebookService = getGradebookService(); if (gradebookService == null) { // Maybe print an error message if it's possible to get into this state // setErrorMessage(getResourceBundleString(STATE_INCONSISTENT)); return null; }//w ww .j ava2s . c o m if (selectedMessageCount != 0) { setErrorMessage(getResourceBundleString(STATE_INCONSISTENT)); return null; } selectedMessageCount = 0; gbItemScore = gradePoint; gbItemComment = gradeComment; if (selectedAssign == null || selectedAssign.trim().length() == 0 || DEFAULT_GB_ITEM.equalsIgnoreCase(selectedAssign)) { setErrorMessage(getResourceBundleString(NO_ASSGN)); return null; } if (gradePoint == null || gradePoint.trim().length() == 0) { setErrorMessage(getResourceBundleString(NO_GRADE_PTS)); return null; } if (!validateGradeInput()) return null; NumberFormat nf = DecimalFormat.getInstance(new ResourceLoader().getLocale()); Double gradeAsDouble = null; double pointsPossibleAsDouble = 0.0; try { gradeAsDouble = new Double(nf.parse(gradePoint).doubleValue()); } catch (ParseException pe) { // we shouldn't get here if the validation above is working properly LOG.warn("Error converting grade " + gradePoint + " to Double"); return null; } if (gradeByPoints) { try { pointsPossibleAsDouble = nf.parse(gbItemPointsPossible).doubleValue(); if ((gradeAsDouble.doubleValue() > pointsPossibleAsDouble) && !grade_too_large_make_sure) { setErrorMessage(getResourceBundleString(TOO_LARGE_GRADE)); grade_too_large_make_sure = true; return null; } else { LOG.info("the user confirms he wants to give student higher grade"); } } catch (ParseException e) { LOG.warn("Unable to parse points possible " + gbItemPointsPossible + " to determine if entered grade is greater than points possible"); } } String studentUid = null; try { String selectedAssignName = ((SelectItem) assignments.get((Integer.valueOf(selectedAssign)).intValue())) .getLabel(); String gradebookUuid = ToolManager.getCurrentPlacement().getContext(); if (selectedMessage == null && selectedGradedUserId != null && !"".equals(selectedGradedUserId)) { studentUid = selectedGradedUserId; } else { studentUid = UserDirectoryService.getUser(selectedMessage.getMessage().getCreatedBy()).getId(); } Long gbItemId = gradebookService.getAssignment(gradebookUuid, selectedAssignName).getId(); gradebookService.saveGradeAndCommentForStudent(gradebookUuid, gbItemId, studentUid, gradePoint, gradeComment); if (selectedMessage != null) { Message msg = selectedMessage.getMessage(); msg.setGradeAssignmentName(selectedAssignName); msg.setTopic( (DiscussionTopic) forumManager.getTopicByIdWithMessages(selectedTopic.getTopic().getId())); forumManager.saveMessage(msg, false); } setSuccessMessage(getResourceBundleString(GRADE_SUCCESSFUL)); } catch (SecurityException se) { LOG.error("Security Exception - processDfGradeSubmit:" + se); setErrorMessage(getResourceBundleString("cdfm_no_gb_perm")); } catch (Exception e) { LOG.error("DiscussionForumTool - processDfGradeSubmit:" + e); e.printStackTrace(); } String eventRef = ""; if (selectedMessage != null) { eventRef = getEventReference(selectedMessage.getMessage()); } else if (selectedTopic != null) { eventRef = getEventReference(selectedTopic.getTopic()); } else if (selectedForum != null) { eventRef = getEventReference(selectedForum.getForum()); } LearningResourceStoreService lrss = (LearningResourceStoreService) ComponentManager .get("org.sakaiproject.event.api.LearningResourceStoreService"); Event event = EventTrackingService.newEvent(DiscussionForumService.EVENT_FORUMS_GRADE, eventRef, true); EventTrackingService.post(event); if (null != lrss) { try { lrss.registerStatement(getStatementForGrade(studentUid, lrss.getEventActor(event), selectedTopic.getTopic().getTitle(), gradeAsDouble), "msgcntr"); } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug(e); } } } gradeNotify = false; selectedAssign = DEFAULT_GB_ITEM; resetGradeInfo(); getThreadFromMessage(); return MESSAGE_VIEW; }
From source file:org.sakaiproject.assignment.impl.BaseAssignmentService.java
/** * Access and output the grades spreadsheet for the reference, either for an assignment or all assignments in a context. * * @param out/*w ww. j av a2 s . c o m*/ * The outputStream to stream the grades spreadsheet into. * @param ref * The reference, either to a specific assignment, or just to an assignment context. * @return Whether the grades spreadsheet is successfully output. * @throws IdUnusedException * if there is no object with this id. * @throws PermissionException * if the current user is not allowed to access this. */ public boolean getGradesSpreadsheet(final OutputStream out, final String ref) throws IdUnusedException, PermissionException { boolean retVal = false; String typeGradesString = REF_TYPE_GRADES + Entity.SEPARATOR; String[] parts = ref.substring(ref.indexOf(typeGradesString) + typeGradesString.length()) .split(Entity.SEPARATOR); String idSite = (parts.length > 1) ? parts[1] : parts[0]; String context = (parts.length > 1) ? SiteService.siteGroupReference(idSite, parts[3]) : SiteService.siteReference(idSite); // get site title for display purpose String siteTitle = ""; String sheetName = ""; try { siteTitle = (parts.length > 1) ? SiteService.getSite(idSite).getTitle() + " - " + SiteService.getSite(idSite).getGroup((String) parts[3]).getTitle() : SiteService.getSite(idSite).getTitle(); sheetName = (parts.length > 1) ? SiteService.getSite(idSite).getGroup((String) parts[3]).getTitle() : SiteService.getSite(idSite).getTitle(); } catch (Exception e) { // ignore exception M_log.debug(this + ":getGradesSpreadsheet cannot get site context=" + idSite + e.getMessage()); } // does current user allowed to grade any assignment? boolean allowGradeAny = false; List assignmentsList = getListAssignmentsForContext(idSite); for (int iAssignment = 0; !allowGradeAny && iAssignment < assignmentsList.size(); iAssignment++) { if (allowGradeSubmission(((Assignment) assignmentsList.get(iAssignment)).getReference())) { allowGradeAny = true; } } if (!allowGradeAny) { // not permitted to download the spreadsheet return false; } else { int rowNum = 0; HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(WorkbookUtil.createSafeSheetName(sheetName)); // Create a row and put some cells in it. Rows are 0 based. HSSFRow row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(rb.getString("download.spreadsheet.title")); // empty line row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(""); // site title row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(rb.getString("download.spreadsheet.site") + siteTitle); // download time row = sheet.createRow(rowNum++); row.createCell(0).setCellValue( rb.getString("download.spreadsheet.date") + TimeService.newTime().toStringLocalFull()); // empty line row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(""); HSSFCellStyle style = wb.createCellStyle(); // this is the header row number int headerRowNumber = rowNum; // set up the header cells row = sheet.createRow(rowNum++); int cellNum = 0; // user enterprise id column HSSFCell cell = row.createCell(cellNum++); cell.setCellStyle(style); cell.setCellValue(rb.getString("download.spreadsheet.column.name")); // user name column cell = row.createCell(cellNum++); cell.setCellStyle(style); cell.setCellValue(rb.getString("download.spreadsheet.column.userid")); // starting from this row, going to input user data Iterator assignments = new SortedIterator(assignmentsList.iterator(), new AssignmentComparator("duedate", "true")); // site members excluding those who can add assignments List members = new ArrayList(); // hashmap which stores the Excel row number for particular user HashMap user_row = new HashMap(); List allowAddAnySubmissionUsers = allowAddAnySubmissionUsers(context); for (Iterator iUserIds = new SortedIterator(allowAddAnySubmissionUsers.iterator(), new AssignmentComparator("sortname", "true")); iUserIds.hasNext();) { String userId = (String) iUserIds.next(); try { User u = UserDirectoryService.getUser(userId); members.add(u); // create the column for user first row = sheet.createRow(rowNum); // update user_row Hashtable user_row.put(u.getId(), Integer.valueOf(rowNum)); // increase row rowNum++; // put user displayid and sortname in the first two cells cellNum = 0; row.createCell(cellNum++).setCellValue(u.getSortName()); row.createCell(cellNum).setCellValue(u.getDisplayId()); } catch (Exception e) { M_log.warn(" getGradesSpreadSheet " + e.getMessage() + " userId = " + userId); } } int index = 0; // the grade data portion starts from the third column, since the first two are used for user's display id and sort name while (assignments.hasNext()) { Assignment a = (Assignment) assignments.next(); int assignmentType = a.getContent().getTypeOfGrade(); // for column header, check allow grade permission based on each assignment if (!a.getDraft() && allowGradeSubmission(a.getReference())) { // put in assignment title as the column header rowNum = headerRowNumber; row = sheet.getRow(rowNum++); cellNum = (index + 2); cell = row.createCell(cellNum); // since the first two column is taken by student id and name cell.setCellStyle(style); cell.setCellValue(a.getTitle()); for (int loopNum = 0; loopNum < members.size(); loopNum++) { // prepopulate the column with the "no submission" string row = sheet.getRow(rowNum++); cell = row.createCell(cellNum); cell.setCellType(1); cell.setCellValue(rb.getString("listsub.nosub")); } // begin to populate the column for this assignment, iterating through student list for (Iterator sIterator = getSubmissions(a).iterator(); sIterator.hasNext();) { AssignmentSubmission submission = (AssignmentSubmission) sIterator.next(); String userId = submission.getSubmitterId(); if (a.isGroup()) { User[] _users = submission.getSubmitters(); for (int i = 0; _users != null && i < _users.length; i++) { userId = _users[i].getId(); if (user_row.containsKey(userId)) { // find right row row = sheet.getRow(((Integer) user_row.get(userId)).intValue()); if (submission.getGraded() && submission.getGrade() != null) { // graded and released if (assignmentType == 3) { try { // numeric cell type? String grade = submission.getGradeForUser(userId) == null ? submission.getGradeDisplay() : submission.getGradeForUser(userId); int factor = submission.getAssignment().getContent().getFactor(); int dec = (int) Math.log10(factor); //We get float number no matter the locale it was managed with. NumberFormat nbFormat = FormattedText.getNumberFormat(dec, dec, null); float f = nbFormat.parse(grade).floatValue(); // remove the String-based cell first cell = row.getCell(cellNum); row.removeCell(cell); // add number based cell cell = row.createCell(cellNum); cell.setCellType(0); cell.setCellValue(f); style = wb.createCellStyle(); String format = "#,##0."; for (int j = 0; j < dec; j++) { format = format.concat("0"); } style.setDataFormat(wb.createDataFormat().getFormat(format)); cell.setCellStyle(style); } catch (Exception e) { // if the grade is not numeric, let's make it as String type // No need to remove the cell and create a new one, as the existing one is String type. cell = row.getCell(cellNum); cell.setCellType(1); cell.setCellValue(submission.getGradeForUser(userId) == null ? submission.getGradeDisplay() : submission.getGradeForUser(userId)); } } else { // String cell type cell = row.getCell(cellNum); cell.setCellValue(submission.getGradeForUser(userId) == null ? submission.getGradeDisplay() : submission.getGradeForUser(userId)); } } else if (submission.getSubmitted() && submission.getTimeSubmitted() != null) { // submitted, but no grade available yet cell = row.getCell(cellNum); cell.setCellValue(rb.getString("gen.nograd")); } } // if } } else { if (user_row.containsKey(userId)) { // find right row row = sheet.getRow(((Integer) user_row.get(userId)).intValue()); if (submission.getGraded() && submission.getGrade() != null) { // graded and released if (assignmentType == 3) { try { // numeric cell type? String grade = submission.getGradeDisplay(); int factor = submission.getAssignment().getContent().getFactor(); int dec = (int) Math.log10(factor); //We get float number no matter the locale it was managed with. NumberFormat nbFormat = FormattedText.getNumberFormat(dec, dec, null); float f = nbFormat.parse(grade).floatValue(); // remove the String-based cell first cell = row.getCell(cellNum); row.removeCell(cell); // add number based cell cell = row.createCell(cellNum); cell.setCellType(0); cell.setCellValue(f); style = wb.createCellStyle(); String format = "#,##0."; for (int j = 0; j < dec; j++) { format = format.concat("0"); } style.setDataFormat(wb.createDataFormat().getFormat(format)); cell.setCellStyle(style); } catch (Exception e) { // if the grade is not numeric, let's make it as String type // No need to remove the cell and create a new one, as the existing one is String type. cell = row.getCell(cellNum); cell.setCellType(1); // Setting grade display instead grade. cell.setCellValue(submission.getGradeDisplay()); } } else { // String cell type cell = row.getCell(cellNum); cell.setCellValue(submission.getGradeDisplay()); } } else if (submission.getSubmitted() && submission.getTimeSubmitted() != null) { // submitted, but no grade available yet cell = row.getCell(cellNum); cell.setCellValue(rb.getString("gen.nograd")); } } // if } } } index++; } // output try { wb.write(out); retVal = true; } catch (IOException e) { M_log.warn(" getGradesSpreadsheet Can not output the grade spread sheet for reference= " + ref); } return retVal; } }
From source file:org.sakaiproject.assignment.tool.AssignmentAction.java
/** * parse content inside uploaded zip file * @param state/*from w ww . j a v a2 s . co m*/ * @param hasSubmissionText * @param hasSubmissionAttachment * @param hasGradeFile * @param hasFeedbackText * @param hasComment * @param hasFeedbackAttachment * @param submissionTable * @param assignment * @param fileContentStream * @return */ private HashMap uploadAll_parseZipFile(SessionState state, boolean hasSubmissionText, boolean hasSubmissionAttachment, boolean hasGradeFile, boolean hasFeedbackText, boolean hasComment, boolean hasFeedbackAttachment, HashMap submissionTable, Assignment assignment, InputStream fileContentStream, String gradeFileFormat, HashMap anonymousSubmissionAndEidTable) { // a flag value for checking whether the zip file is of proper format: // should have a grades.csv file or grades.xls if there is no user folders boolean zipHasGradeFile = false; // and if have any folder structures, those folders should be named after at least one site user (zip file could contain user names who is no longer inside the site) boolean zipHasFolder = false; boolean zipHasFolderValidUserId = false; FileOutputStream tmpFileOut = null; File tempFile = null; // as stated from UI, we expected the zip file to have structure as follows // assignment_name/user_eid/files // or assignment_name/grades.csv or assignment_name/grades.xls boolean validZipFormat = true; try { tempFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ""); tmpFileOut = new FileOutputStream(tempFile); writeToStream(fileContentStream, tmpFileOut); tmpFileOut.flush(); tmpFileOut.close(); ZipFile zipFile = new ZipFile(tempFile, "UTF-8"); Enumeration<ZipEntry> zipEntries = zipFile.getEntries(); ZipEntry entry; while (zipEntries.hasMoreElements() && validZipFormat) { entry = zipEntries.nextElement(); String entryName = entry.getName(); if (!entry.isDirectory() && entryName.indexOf("/.") == -1) { // SAK-17606 String anonTitle = rb.getString("grading.anonymous.title"); if (entryName.endsWith("grades.csv") || entryName.endsWith("grades.xls")) { if (hasGradeFile && entryName.endsWith("grades.csv") && "csv".equals(gradeFileFormat)) { // at least the zip file has a grade.csv zipHasGradeFile = true; // read grades.cvs from zip CSVReader reader = new CSVReader(new InputStreamReader(zipFile.getInputStream(entry))); List<String[]> lines = reader.readAll(); if (lines != null) { for (int i = 3; i < lines.size(); i++) { String[] items = lines.get(i); if ((assignment.isGroup() && items.length > 3) || items.length > 4) { // has grade information try { String _the_eid = items[1]; if (!assignment.isGroup()) { // SAK-17606 User u = null; // check for anonymous grading if (!AssignmentService.getInstance() .assignmentUsesAnonymousGrading(assignment)) { u = UserDirectoryService .getUserByEid(items[IDX_GRADES_CSV_EID]); } else { // anonymous so pull the real eid out of our hash table String anonId = items[IDX_GRADES_CSV_EID]; String id = (String) anonymousSubmissionAndEidTable.get(anonId); u = UserDirectoryService.getUser(id); } if (u == null) throw new Exception("User not found!"); _the_eid = u.getId(); } UploadGradeWrapper w = (UploadGradeWrapper) submissionTable .get(_the_eid); if (w != null) { String itemString = assignment.isGroup() ? items[3] : items[4]; int gradeType = assignment.getContent().getTypeOfGrade(); if (gradeType == Assignment.SCORE_GRADE_TYPE) { validPointGrade(state, itemString, assignment.getContent().getFactor()); } // SAK-24199 - Applied patch provided with a few additional modifications. else if (gradeType == Assignment.PASS_FAIL_GRADE_TYPE) { itemString = validatePassFailGradeValue(state, itemString); } else { validLetterGrade(state, itemString); } if (state.getAttribute(STATE_MESSAGE) == null) { w.setGrade(gradeType == Assignment.SCORE_GRADE_TYPE ? scalePointGrade(state, itemString, assignment.getContent().getFactor()) : itemString); submissionTable.put(_the_eid, w); } } } catch (Exception e) { M_log.warn(this + ":uploadAll_parseZipFile " + e.getMessage()); } } } } } //end of csv grades import //Excel file import if (hasGradeFile && entryName.endsWith("grades.xls") && "excel".equals(gradeFileFormat)) { // at least the zip file has a grade.csv zipHasGradeFile = true; // read grades.xls from zip POIFSFileSystem fsFileSystem = new POIFSFileSystem(zipFile.getInputStream(entry)); HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem); HSSFSheet hssfSheet = workBook.getSheetAt(0); //Iterate the rows Iterator rowIterator = hssfSheet.rowIterator(); int count = 0; while (rowIterator.hasNext()) { HSSFRow hssfRow = (HSSFRow) rowIterator.next(); //We skip first row (= header row) if (count > 0) { double gradeXls = -1; String itemString = null; // has grade information try { String _the_eid = hssfRow.getCell(1).getStringCellValue(); if (!assignment.isGroup()) { if (!AssignmentService.getInstance() .assignmentUsesAnonymousGrading(assignment)) { User u = UserDirectoryService.getUserByEid( hssfRow.getCell(1).getStringCellValue()/*user eid*/); if (u == null) throw new Exception("User not found!"); _the_eid = u.getId(); } else { _the_eid = (String) anonymousSubmissionAndEidTable.get(_the_eid); } } UploadGradeWrapper w = (UploadGradeWrapper) submissionTable.get(_the_eid); if (w != null) { itemString = assignment.isGroup() ? hssfRow.getCell(3).toString() : hssfRow.getCell(4).toString(); int gradeType = assignment.getContent().getTypeOfGrade(); if (gradeType == Assignment.SCORE_GRADE_TYPE) { //Parse the string to double using the locale format try { itemString = assignment.isGroup() ? hssfRow.getCell(3).getStringCellValue() : hssfRow.getCell(4).getStringCellValue(); if ((itemString != null) && (itemString.trim().length() > 0)) { NumberFormat nbFormat = FormattedText.getNumberFormat(); gradeXls = nbFormat.parse(itemString).doubleValue(); } } catch (Exception e) { try { gradeXls = assignment.isGroup() ? hssfRow.getCell(3).getNumericCellValue() : hssfRow.getCell(4).getNumericCellValue(); } catch (Exception e2) { gradeXls = -1; } } if (gradeXls != -1) { // get localized number format NumberFormat nbFormat = FormattedText.getNumberFormat(); itemString = nbFormat.format(gradeXls); } else { itemString = ""; } validPointGrade(state, itemString, assignment.getContent().getFactor()); } else if (gradeType == Assignment.PASS_FAIL_GRADE_TYPE) { itemString = validatePassFailGradeValue(state, itemString); } else { validLetterGrade(state, itemString); } if (state.getAttribute(STATE_MESSAGE) == null) { w.setGrade( gradeType == Assignment.SCORE_GRADE_TYPE ? scalePointGrade(state, itemString, assignment.getContent().getFactor()) : itemString); submissionTable.put(_the_eid, w); } } } catch (Exception e) { M_log.warn(this + ":uploadAll_parseZipFile " + e.getMessage()); } } count++; } } //end of Excel grades import } else { String[] pathParts = entryName.split("/"); if (pathParts.length <= 2) { validZipFormat = false; } else { // get user eid part String userEid = ""; if (entryName.indexOf("/") != -1) { // there is folder structure inside zip if (!zipHasFolder) zipHasFolder = true; // remove the part of zip name userEid = entryName.substring(entryName.indexOf("/") + 1); // get out the user name part if (userEid.indexOf("/") != -1) { userEid = userEid.substring(0, userEid.indexOf("/")); } // SAK-17606 - get the eid part if ((userEid.indexOf("(") != -1) && !userEid.contains(anonTitle)) { userEid = userEid.substring(userEid.indexOf("(") + 1, userEid.indexOf(")")); } if (userEid.contains(anonTitle)) { // anonymous grading so we have to figure out the eid //get eid out of this slick table we made earlier userEid = (String) anonymousSubmissionAndEidTable.get(userEid); } userEid = StringUtils.trimToNull(userEid); if (!assignment.isGroup()) { try { User u = UserDirectoryService.getUserByEid(userEid/*user eid*/); if (u != null) userEid = u.getId(); } catch (Throwable _t) { } } } if (submissionTable.containsKey(userEid)) { if (!zipHasFolderValidUserId) zipHasFolderValidUserId = true; if (hasComment && entryName.indexOf("comments") != -1) { // read the comments file String comment = getBodyTextFromZipHtml(zipFile.getInputStream(entry), true); if (comment != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setComment(comment); submissionTable.put(userEid, r); } } if (hasFeedbackText && entryName.indexOf("feedbackText") != -1) { // upload the feedback text String text = getBodyTextFromZipHtml(zipFile.getInputStream(entry), false); if (text != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setFeedbackText(text); submissionTable.put(userEid, r); } } if (hasSubmissionText && entryName.indexOf("_submissionText") != -1) { // upload the student submission text String text = getBodyTextFromZipHtml(zipFile.getInputStream(entry), false); if (text != null) { UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setText(text); submissionTable.put(userEid, r); } } if (hasSubmissionAttachment) { // upload the submission attachment String submissionFolder = "/" + rb.getString("stuviewsubm.submissatt") + "/"; if (entryName.indexOf(submissionFolder) != -1) { // clear the submission attachment first UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); submissionTable.put(userEid, r); submissionTable = uploadZipAttachments(state, submissionTable, zipFile.getInputStream(entry), entry, entryName, userEid, "submission"); } } if (hasFeedbackAttachment) { // upload the feedback attachment String submissionFolder = "/" + rb.getString("download.feedback.attachment") + "/"; if (entryName.indexOf(submissionFolder) != -1) { // clear the feedback attachment first UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); submissionTable.put(userEid, r); submissionTable = uploadZipAttachments(state, submissionTable, zipFile.getInputStream(entry), entry, entryName, userEid, "feedback"); } } // if this is a timestamp file if (entryName.indexOf("timestamp") != -1) { byte[] timeStamp = readIntoBytes(zipFile.getInputStream(entry), entryName, entry.getSize()); UploadGradeWrapper r = (UploadGradeWrapper) submissionTable.get(userEid); r.setSubmissionTimestamp(new String(timeStamp)); submissionTable.put(userEid, r); } } } } } } } catch (IOException e) { // uploaded file is not a valid archive addAlert(state, rb.getString("uploadall.alert.zipFile")); M_log.warn(this + ":uploadAll_parseZipFile " + e.getMessage()); } finally { if (tmpFileOut != null) { try { tmpFileOut.close(); } catch (IOException e) { M_log.warn(this + ":uploadAll_parseZipFile: Error closing temp file output stream: " + e.toString()); } } if (fileContentStream != null) { try { fileContentStream.close(); } catch (IOException e) { M_log.warn(this + ":uploadAll_parseZipFile: Error closing file upload stream: " + e.toString()); } } //clean up the zip file if (tempFile != null && tempFile.exists()) { if (!tempFile.delete()) { M_log.warn("Failed to clean up temp file"); } } } //This is used so that the "Zip Error" message is only printed once boolean zipError = false; // generate error when there is no grade file and no folder structure if (!zipHasGradeFile && !zipHasFolder) { addAlert(state, rb.getString("uploadall.alert.incorrectFormat")); addAlert(state, rb.getString("uploadall.alert.noGradeFile")); zipError = true; } // generate error when there is folder structure but not matching one user id if (zipHasFolder && !zipHasFolderValidUserId) { if (zipError == false) addAlert(state, rb.getString("uploadall.alert.incorrectFormat")); addAlert(state, rb.getString("uploadall.alert.invalidUserId")); zipError = true; } // should have right structure of zip file if (!validZipFormat) { if (zipError == false) addAlert(state, rb.getString("uploadall.alert.incorrectFormat")); // alert if the zip is of wrong format addAlert(state, rb.getString("uploadall.alert.wrongZipFormat")); zipError = true; } return submissionTable; }
From source file:org.sakaiproject.assignment.tool.AssignmentAction.java
/** * valid grade for point based type/*from w w w .ja v a2 s.c o m*/ * returns a double value in a string from the localized input */ private String validPointGrade(SessionState state, String grade, int factor) { if (grade != null && !"".equals(grade)) { if (grade.startsWith("-")) { // check for negative sign addAlert(state, rb.getString("plesuse3")); } else { int dec = (int) Math.log10(factor); NumberFormat nbFormat = FormattedText.getNumberFormat(); DecimalFormat dcFormat = (DecimalFormat) nbFormat; String decSeparator = FormattedText.getDecimalSeparator(); // only the right decimal separator is allowed and no other grouping separator if ((",".equals(decSeparator) && grade.indexOf(".") != -1) || (".".equals(decSeparator) && grade.indexOf(",") != -1) || grade.indexOf(" ") != -1) { addAlert(state, rb.getString("plesuse1")); return grade; } // parse grade from localized number format int index = grade.indexOf(decSeparator); if (index != -1) { // when there is decimal points inside the grade, scale the number by "factor" // but only one decimal place is supported // for example, change 100.0 to 1000 if (!decSeparator.equals(grade)) { if (grade.length() > index + dec + 1) { // if there are more than "factor" decimal points addAlert(state, rb.getFormattedMessage("plesuse2", new Object[] { String.valueOf(dec) })); } else { // decimal points is the only allowed character inside grade // replace it with '1', and try to parse the new String into int String zeros = ""; for (int i = 0; i < dec; i++) { zeros = zeros.concat("0"); } String gradeString = grade.endsWith(decSeparator) ? grade.substring(0, index).concat(zeros) : grade.substring(0, index).concat(grade.substring(index + 1)); try { nbFormat.parse(gradeString); try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { M_log.warn(this + ":validPointGrade " + e.getMessage()); alertInvalidPoint(state, gradeString, factor); } } catch (ParseException e) { M_log.warn(this + ":validPointGrade " + e.getMessage()); addAlert(state, rb.getString("plesuse1")); } } } else { // grade is decSeparator addAlert(state, rb.getString("plesuse1")); } } else { // There is no decimal point; should be int number String gradeString = grade; for (int i = 0; i < dec; i++) { gradeString = gradeString.concat("0"); } try { nbFormat.parse(gradeString); try { Integer.parseInt(gradeString); } catch (NumberFormatException e) { M_log.warn(this + ":validPointGrade " + e.getMessage()); alertInvalidPoint(state, gradeString, factor); } } catch (ParseException e) { M_log.warn(this + ":validPointGrade " + e.getMessage()); addAlert(state, rb.getString("plesuse1")); } } } } return grade; }