List of usage examples for java.text DecimalFormat parse
public Number parse(String source) throws ParseException
From source file:org.ohmage.domain.campaign.Campaign.java
/** * Processes a number prompt and returns a NumberPrompt object. * /*from www . j a v a 2s . co m*/ * @param id The prompt's unique identifier. * * @param condition The condition value. * * @param unit The prompt's visualization unit. * * @param text The prompt's text value. * * @param explanationText The prompt's explanation text value. * * @param skippable Whether or not this prompt is skippable. * * @param skipLabel The label to show to skip this prompt. * * @param displayLabel The label for this display type. * * @param defaultValue The default value given in the XML. * * @param properties The properties defined in the XML for this prompt. * * @param index The index of this prompt in its collection of survey items. * * @return A NumberPrompt object. * * @throws DomainException Thrown if the required properties are missing or * if any of the parameters are invalid. */ private static NumberPrompt processNumber(final String id, final String condition, final String unit, final String text, final String explanationText, final boolean skippable, final String skipLabel, final String displayLabel, final String defaultValue, final Map<String, LabelValuePair> properties, final int index) throws DomainException { // Create the decimal parser. DecimalFormat format = new DecimalFormat(); format.setParseBigDecimal(true); BigDecimal min; try { LabelValuePair minVlp = properties.get(NumberPrompt.XML_KEY_MIN); if (minVlp == null) { throw new DomainException("Missing the '" + NumberPrompt.XML_KEY_MIN + "' property: " + id); } min = (BigDecimal) format.parse(minVlp.getLabel()); } catch (ParseException e) { throw new DomainException( "The '" + NumberPrompt.XML_KEY_MIN + "' property is not a valid number: " + id, e); } BigDecimal max; try { LabelValuePair maxVlp = properties.get(NumberPrompt.XML_KEY_MAX); if (maxVlp == null) { throw new DomainException("Missing the '" + NumberPrompt.XML_KEY_MAX + "' property: " + id); } max = (BigDecimal) format.parse(maxVlp.getLabel()); } catch (ParseException e) { throw new DomainException("The '" + NumberPrompt.XML_KEY_MAX + "' property is not valid number: " + id, e); } BigDecimal parsedDefaultValue = null; try { if (defaultValue != null) { parsedDefaultValue = (BigDecimal) format.parse(defaultValue); } } catch (ParseException e) { throw new DomainException("The default value is not a valid number: " + id); } Boolean wholeNumber = null; LabelValuePair wholeNumberVlp = properties.get(NumberPrompt.XML_KEY_WHOLE_NUMBER); if (wholeNumberVlp != null) { wholeNumber = StringUtils.decodeBoolean(wholeNumberVlp.getLabel()); if (wholeNumber == null) { throw new DomainException( "The '" + NumberPrompt.XML_KEY_WHOLE_NUMBER + "' property is not a valid boolean: " + id); } } return new NumberPrompt(id, condition, unit, text, explanationText, skippable, skipLabel, displayLabel, min, max, parsedDefaultValue, index, wholeNumber); }
From source file:org.ohmage.domain.campaign.Campaign.java
/** * Processes a hours-before-now prompt and returns a HoursBeforeNowPrompt * object.//from w w w. ja v a2 s .c om * * @param id The prompt's unique identifier. * * @param condition The condition value. * * @param unit The prompt's visualization unit. * * @param text The prompt's text value. * * @param explanationText The prompt's explanation text value. * * @param skippable Whether or not this prompt is skippable. * * @param skipLabel The label to show to skip this prompt. * * @param displayLabel The label for this display type. * * @param defaultValue The default value given in the XML. * * @param properties The properties defined in the XML for this prompt. * * @param index The index of this prompt in its collection of survey items. * * @return A HoursBeforeNowPrompt object. * * @throws DomainException Thrown if the required properties are missing or * if any of the parameters are invalid. */ private static HoursBeforeNowPrompt processHoursBeforeNow(final String id, final String condition, final String unit, final String text, final String explanationText, final boolean skippable, final String skipLabel, final String displayLabel, final String defaultValue, final Map<String, LabelValuePair> properties, final int index) throws DomainException { // Create the decimal parser. DecimalFormat format = new DecimalFormat(); format.setParseBigDecimal(true); BigDecimal min; try { LabelValuePair minVlp = properties.get(HoursBeforeNowPrompt.XML_KEY_MIN); if (minVlp == null) { throw new DomainException("Missing the '" + HoursBeforeNowPrompt.XML_KEY_MIN + "' property: " + id); } min = (BigDecimal) format.parse(minVlp.getLabel()); } catch (ParseException e) { throw new DomainException( "The '" + HoursBeforeNowPrompt.XML_KEY_MIN + "' property is not a valid number: " + id, e); } BigDecimal max; try { LabelValuePair maxVlp = properties.get(HoursBeforeNowPrompt.XML_KEY_MAX); if (maxVlp == null) { throw new DomainException("Missing the '" + HoursBeforeNowPrompt.XML_KEY_MAX + "' property: " + id); } max = (BigDecimal) format.parse(maxVlp.getLabel()); } catch (ParseException e) { throw new DomainException( "The '" + HoursBeforeNowPrompt.XML_KEY_MAX + "' property is not valid number: " + id, e); } BigDecimal parsedDefaultValue = null; try { if (defaultValue != null) { parsedDefaultValue = (BigDecimal) format.parse(defaultValue); } } catch (ParseException e) { throw new DomainException("The default value is not a valid number: " + id); } return new HoursBeforeNowPrompt(id, condition, unit, text, explanationText, skippable, skipLabel, displayLabel, min, max, parsedDefaultValue, index); }
From source file:org.efaps.esjp.accounting.util.data.ImportDetails.java
protected List<Document> checkAccounts(final Parameter _parameter, final File _file, final Map<String, Instance> _docMap, final DateTime _date, final Boolean _inverse) throws IOException, EFapsException { final List<Document> ret = new ArrayList<>(); final CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(_file), "UTF-8")); final List<String[]> entries = reader.readAll(); reader.close();/*from w w w. ja v a2 s . com*/ entries.remove(0); int i = 1; final Map<String, Document> map = new HashMap<>(); for (final String[] row : entries) { i++; final String docNumber = row[0]; final String ruc = row[1]; final String dateStr = row[2]; final String accountStr = row[5]; final String accountDesc = row[4]; final DecimalFormat formater = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN); formater.setParseBigDecimal(true); final String amountMEStr = row[6]; final String amountMNStr = row[7]; final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.AccountAbstract); queryBldr.addWhereAttrEqValue(CIAccounting.AccountAbstract.Name, accountStr.trim()); final InstanceQuery query = queryBldr.getQuery(); query.executeWithoutAccessCheck(); if (query.next()) { ImportDetails.LOG.info("Found account: '{}' ", accountStr); final String[] docSplit = docNumber.split("-"); if (docSplit.length != 2 && _docMap != null) { ImportDetails.LOG.warn( "Document '{}' - Line: {} has no '-' to distinguish SerialNumber and No.", docNumber, i); } else { try { final Formatter criteria = new Formatter(); String name = docNumber; if (_docMap != null) { final String serialNo = docSplit[0]; final String docNo = docSplit[1]; final int serial = Integer.parseInt(serialNo.trim().replaceAll("\\D", "")); final int no = Integer.parseInt(docNo.trim().replaceAll("\\D", "")); criteria.format("%03d-%06d", serial, no); name = criteria.toString(); } Document doc; if (map.containsKey(name)) { doc = map.get(name); } else { if (_docMap != null && _docMap.containsKey(name)) { doc = new Document(name, _docMap.get(name), ruc, dateStr, accountDesc); } else { doc = new Document(name, null, ruc, dateStr, accountDesc); } } BigDecimal amountME = (BigDecimal) formater.parse(amountMEStr); BigDecimal amountMN = (BigDecimal) formater.parse(amountMNStr); if (_inverse) { amountME = amountME.negate(); amountMN = amountMN.negate(); } if (amountMN.compareTo(BigDecimal.ZERO) >= 0) { doc.addAmountMECredit(amountME); doc.addAmountMNCredit(amountMN); } else { doc.addAmountMEDebit(amountME); doc.addAmountMNDebit(amountMN); } final Map<String, Account> accounts = doc.getAccounts(); Account acc; if (accounts.containsKey(accountStr)) { acc = accounts.get(accountStr); } else { acc = new Account(accountStr, accountDesc); accounts.put(accountStr, acc); } acc.addAmountME(amountME); acc.addAmountMN(amountMN); acc.setInstance(query.getCurrentValue()); map.put(name, doc); criteria.close(); } catch (final NumberFormatException e) { ImportDetails.LOG.error("wrong format for document '{}'", docNumber); } catch (final ParseException e) { ImportDetails.LOG.error("wrong format for amounts '{}' - '{}'", amountMEStr, amountMNStr); } } } else { ImportDetails.LOG.error("Not found account: {}", accountStr); } } final Instance periodInst = getPeriodInstance(); for (final Document doc : map.values()) { final BigDecimal amountCreditMN = doc.getAmountMNCredit() != null ? doc.getAmountMNCredit() : BigDecimal.ZERO; final BigDecimal amountDebitMN = doc.getAmountMNDebit() != null ? doc.getAmountMNDebit() : BigDecimal.ZERO; final BigDecimal amountMN = amountCreditMN.add(amountDebitMN); final BigDecimal amountCreditME = doc.getAmountMECredit() != null ? doc.getAmountMECredit() : BigDecimal.ZERO; final BigDecimal amountDebitME = doc.getAmountMEDebit() != null ? doc.getAmountMEDebit() : BigDecimal.ZERO; final BigDecimal amountME = amountCreditME.add(amountDebitME); if (BigDecimal.ZERO.compareTo(amountMN) == 0 && BigDecimal.ZERO.compareTo(amountME) == 0) { ImportDetails.LOG.info( "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' and Credit with Debit Amount (MN): '{}' + '{}' are Zero (0)", doc.getName(), amountCreditME, amountDebitME, amountCreditMN, amountDebitMN); } else { ImportDetails.LOG.error( "For Document: '{}'. Sum of Credit with Debit Amount (ME): '{}' + '{}' = '{}' and Credit with Debit Amount (MN): '{}' + '{}' = '{}'", doc.getName(), amountCreditME, amountDebitME, amountME, amountCreditMN, amountDebitMN, amountMN); } final Insert insert = new Insert(CIAccounting.TransactionOpeningBalance); insert.add(CIAccounting.TransactionOpeningBalance.Date, _date); final StringBuilder descBldr = new StringBuilder() .append(doc.getInstance() != null ? doc.getInstance().getType().getLabel() : "Sin Documento") .append(": ").append(doc.getName()).append(" - RUC: ").append(doc.getRuc()).append(" - ") .append(doc.getDate()).append(" - ").append(doc.getDesc()); insert.add(CIAccounting.TransactionOpeningBalance.Description, descBldr.toString()); insert.add(CIAccounting.TransactionOpeningBalance.Status, Status.find(CIAccounting.TransactionStatus.Open)); insert.add(CIAccounting.TransactionOpeningBalance.PeriodLink, periodInst); insert.executeWithoutAccessCheck(); if (_docMap != null) { final Instance instance = insert.getInstance(); new Create().connectDocs2Transaction(_parameter, instance, doc.getInstance()); } final Map<String, Account> accounts = doc.getAccounts(); final Instance basCur = Currency.getBaseCurrency(); for (final Account acc : accounts.values()) { final Insert insertpos = new Insert( acc.getAmountMN().compareTo(BigDecimal.ZERO) > 0 ? CIAccounting.TransactionPositionCredit : CIAccounting.TransactionPositionDebit); insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance()); insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN()); insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur); insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1); insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance()); insertpos.executeWithoutAccessCheck(); } if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0 && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) <= 0) { Insert insertpos = null; Account acc = null; if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) { acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGDEBIT); acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate()); acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate()); insertpos = new Insert(CIAccounting.TransactionPositionDebit); } else { acc = getRoundingAccount(AccountingSettings.PERIOD_ROUNDINGCREDIT); acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN)); acc.addAmountME(amountDebitME.abs().subtract(amountCreditME)); insertpos = new Insert(CIAccounting.TransactionPositionCredit); } insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance()); insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN()); insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur); insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1); insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance()); insertpos.executeWithoutAccessCheck(); } else if (amountCreditMN.compareTo(amountDebitMN.abs()) != 0 && amountCreditMN.subtract(amountDebitMN.abs()).abs().compareTo(new BigDecimal("0.05")) > 0) { Insert insertpos = null; final Account acc = getRoundingAccount(AccountingSettings.PERIOD_TRANSFERACCOUNT); ; if (amountCreditMN.compareTo(amountDebitMN.abs()) > 0) { acc.addAmountMN(amountCreditMN.subtract(amountDebitMN.abs()).negate()); acc.addAmountME(amountCreditME.subtract(amountDebitME.abs()).negate()); insertpos = new Insert(CIAccounting.TransactionPositionDebit); } else { acc.addAmountMN(amountDebitMN.abs().subtract(amountCreditMN)); acc.addAmountME(amountDebitME.abs().subtract(amountCreditME)); insertpos = new Insert(CIAccounting.TransactionPositionCredit); } insertpos.add(CIAccounting.TransactionPositionAbstract.AccountLink, acc.getInstance()); insertpos.add(CIAccounting.TransactionPositionAbstract.Amount, acc.getAmountMN()); insertpos.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, basCur); insertpos.add(CIAccounting.TransactionPositionAbstract.Rate, acc.getRateObject()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateAmount, acc.getAmountME()); insertpos.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, 1); insertpos.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance()); insertpos.executeWithoutAccessCheck(); } } return ret; }
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;/* w ww .j a v a 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:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java
/** * Contains logic to consistently output a String based version of a grade * Interprets the grade using the scale for display * * This should probably be moved to a static utility class - ern * * @param grade//from w ww . java 2 s. c o m * @param typeOfGrade * @param scaleFactor * @return */ @Override public String getGradeDisplay(String grade, Assignment.GradeType typeOfGrade, Integer scaleFactor) { String returnGrade = StringUtils.trimToEmpty(grade); if (scaleFactor == null) scaleFactor = getScaleFactor(); switch (typeOfGrade) { case SCORE_GRADE_TYPE: if (!returnGrade.isEmpty() && !"0".equals(returnGrade)) { int dec = new Double(Math.log10(scaleFactor)).intValue(); String decSeparator = formattedText.getDecimalSeparator(); String decimalGradePoint = returnGrade; try { Integer.parseInt(returnGrade); // if point grade, display the grade with factor decimal place if (returnGrade.length() > dec) { decimalGradePoint = returnGrade.substring(0, returnGrade.length() - dec) + decSeparator + returnGrade.substring(returnGrade.length() - dec); } else { String newGrade = "0".concat(decSeparator); for (int i = returnGrade.length(); i < dec; i++) { newGrade = newGrade.concat("0"); } decimalGradePoint = newGrade.concat(returnGrade); } } catch (NumberFormatException nfe1) { log.debug("Could not parse grade [{}] as an Integer trying as a Float, {}", returnGrade, nfe1.getMessage()); try { Float.parseFloat(returnGrade); decimalGradePoint = returnGrade; } catch (NumberFormatException nfe2) { log.debug("Could not parse grade [{}] as a Float, {}", returnGrade, nfe2.getMessage()); } } // get localized number format NumberFormat nbFormat = formattedText.getNumberFormat(dec, dec, false); DecimalFormat dcformat = (DecimalFormat) nbFormat; // show grade in localized number format try { Double dblGrade = dcformat.parse(decimalGradePoint).doubleValue(); decimalGradePoint = nbFormat.format(dblGrade); returnGrade = decimalGradePoint; } catch (Exception e) { log.warn("Could not parse grade [{}], {}", returnGrade, e.getMessage()); } } break; case UNGRADED_GRADE_TYPE: if (returnGrade.equalsIgnoreCase("gen.nograd")) { returnGrade = resourceLoader.getString("gen.nograd"); } break; case PASS_FAIL_GRADE_TYPE: if (returnGrade.equalsIgnoreCase("Pass")) { returnGrade = resourceLoader.getString("pass"); } else if (returnGrade.equalsIgnoreCase("Fail")) { returnGrade = resourceLoader.getString("fail"); } else { returnGrade = resourceLoader.getString("ungra"); } break; case CHECK_GRADE_TYPE: if (returnGrade.equalsIgnoreCase("Checked")) { returnGrade = resourceLoader.getString("gen.checked"); } else { returnGrade = resourceLoader.getString("ungra"); } break; default: if (returnGrade.isEmpty()) { returnGrade = resourceLoader.getString("ungra"); } } return returnGrade; }
From source file:org.nd4j.linalg.factory.Nd4j.java
/** * Read line via input streams// w ww . j a va 2s .c om * * @param ndarray the input stream ndarray * @param sep character, defaults to "," * @return NDArray */ public static INDArray readTxtString(InputStream ndarray, String sep) { /* We could dump an ndarray to a file with the tostring (since that is valid json) and use put/get to parse it as json But here we leverage our information of the tostring method to be more efficient With our current toString format we use tads along dimension (rank-1,rank-2) to write to the array in two dimensional chunks at a time. This is more efficient than setting each value at a time with putScalar. This also means we can read the file one line at a time instead of loading the whole thing into memory Future work involves enhancing the write json method to provide more features to make the load more efficient */ int lineNum = 0; int rowNum = 0; int tensorNum = 0; char theOrder = 'c'; int[] theShape = { 1, 1 }; int rank = 0; double[][] subsetArr = { { 0.0, 0.0 }, { 0.0, 0.0 } }; INDArray newArr = Nd4j.zeros(2, 2); BufferedReader reader = new BufferedReader(new InputStreamReader(ndarray)); LineIterator it = IOUtils.lineIterator(reader); DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US); format.setParseBigDecimal(true); try { while (it.hasNext()) { String line = it.nextLine(); lineNum++; line = line.replaceAll("\\s", ""); if (line.equals("") || line.equals("}")) continue; // is it from dl4j? if (lineNum == 2) { String[] lineArr = line.split(":"); String fileSource = lineArr[1].replaceAll("\\W", ""); if (!fileSource.equals("dl4j")) return null; } // parse ordering if (lineNum == 3) { String[] lineArr = line.split(":"); theOrder = lineArr[1].replaceAll("\\W", "").charAt(0); continue; } // parse shape if (lineNum == 4) { String[] lineArr = line.split(":"); String dropJsonComma = lineArr[1].split("]")[0]; String[] shapeString = dropJsonComma.replace("[", "").split(","); rank = shapeString.length; theShape = new int[rank]; for (int i = 0; i < rank; i++) { try { theShape[i] = Integer.parseInt(shapeString[i]); } catch (NumberFormatException nfe) { } ; } subsetArr = new double[theShape[rank - 2]][theShape[rank - 1]]; newArr = Nd4j.zeros(theShape, theOrder); continue; } //parse data if (lineNum > 5) { String[] entries = line.replace("\\],", "").replaceAll("\\[", "").replaceAll("\\],", "") .replaceAll("\\]", "").split(sep); for (int i = 0; i < theShape[rank - 1]; i++) { try { BigDecimal number = (BigDecimal) format.parse(entries[i]); subsetArr[rowNum][i] = number.doubleValue(); } catch (ParseException e) { e.printStackTrace(); } } rowNum++; if (rowNum == theShape[rank - 2]) { INDArray subTensor = Nd4j.create(subsetArr); newArr.tensorAlongDimension(tensorNum, rank - 1, rank - 2).addi(subTensor); rowNum = 0; tensorNum++; } } } } finally { LineIterator.closeQuietly(it); } return newArr; }
From source file:logdruid.util.DataMiner.java
public static FileMineResult fileMine(FileRecord fileRecord, Repository repo, Source source, boolean stats, boolean timings) { ExtendedTimeSeries ts = null;/*from ww w .ja v a 2 s . c om*/ PatternCache patternCache = new PatternCache(); Date startDate = null; Date endDate = null; DecimalFormat decimalFormat = new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.US)); FastDateFormat fastDateFormat = null; FileReader flstr = null; BufferedReader buf1st; Matcher matcher; Matcher matcher2; FixedMillisecond fMS = null; Boolean successMatch = false; DateFormat df = null; int statHit = 0; int statMatch = 0; int eventHit = 0; int eventMatch = 0; long[] arrayBefore; Map<Recording, String> recMatch = new HashMap<Recording, String>(); Map<String, ExtendedTimeSeries> statMap = new HashMap<String, ExtendedTimeSeries>(); Map<String, ExtendedTimeSeries> eventMap = new HashMap<String, ExtendedTimeSeries>(); Map<String, Map<Date, FileLine>> RIFileLineDateMap = new HashMap<String, Map<Date, FileLine>>(); Map<String, long[]> matchTimings = new HashMap<String, long[]>(); long recordingMatchStart = 0; long recordingMatchEnd = 0; try { if (logger.isDebugEnabled()) { logger.debug("++file: " + repo.getBaseSourcePath() + " + " + (String) fileRecord.getCompletePath().toString()); } flstr = new FileReader(fileRecord.getCompletePath()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } buf1st = new BufferedReader(flstr); String line; try { recMatch = getRegexp(repo, source); int lineCount = 1; while ((line = buf1st.readLine()) != null) { // check against one Recording pattern at a tim // if (logger.isDebugEnabled()) { // logger.debug("line " + line); // } Iterator recMatchIte = recMatch.entrySet().iterator(); while (recMatchIte.hasNext()) { if (timings) { recordingMatchStart = ManagementFactory.getThreadMXBean() .getThreadCpuTime(Thread.currentThread().getId()); } Map.Entry me = (Map.Entry) recMatchIte.next(); Recording rec = (Recording) me.getKey(); matcher = patternCache.getPattern((String) (rec.getRegexp())).matcher(line); if (matcher.find()) { Boolean isStatRecording = rec.getClass().equals(StatRecording.class); if (stats) { if (isStatRecording) { statMatch++; } else { eventMatch++; } } // logger.info("1**** matched: " + line); ArrayList<RecordingItem> recordingItem = ((Recording) rec).getRecordingItem(); int cnt = 0; matcher2 = patternCache.getPattern((String) me.getValue()).matcher(line); successMatch = false; if (matcher2.find()) { if (stats) { if (isStatRecording) { statHit++; } else { eventHit++; } } int count = 1; Date date1 = null; // handling capture for each recording item Iterator<RecordingItem> recItemIte2 = recordingItem.iterator(); while (recItemIte2.hasNext()) { RecordingItem recItem2 = recItemIte2.next(); // logger.info("3A**** " + // recItem2.getType()); if (recItem2.getType().equals("date")) { try { df = repo.getDateFormat(rec.getDateFormatID()); if (logger.isDebugEnabled()) logger.debug("4**** rec name" + rec.getName() + " df: " + df.getId()); fastDateFormat = FastDateFormat.getInstance(df.getDateFormat()); date1 = fastDateFormat.parse(matcher2.group(count)); if (logger.isDebugEnabled()) logger.debug( "4b**** " + df.getDateFormat() + " date: " + date1.toString()); // logger.info("4**** " + // date1.toString()); } catch (ParseException e) { // TODO Auto-generated catch // block e.printStackTrace(); } } else if (date1 != null) { if (recItem2.isSelected()) { if (logger.isDebugEnabled()) { logger.debug("FileRecord: " + fileRecord.getFile().getName() + ", Source: " + source.getSourceName() + ", " + recItem2.getName() + ", " + fileRecord.getFile().getName() + ", " + lineCount); } // recording line of match in file in map RIFileLineDateMap - note the FileLine object use an int to identify the files to save memory Map<Date, FileLine> dateFileLineMap = null; if (RIFileLineDateMap.containsKey(recItem2.getName())) { dateFileLineMap = RIFileLineDateMap.get(recItem2.getName()); } else { dateFileLineMap = new HashMap<Date, FileLine>(); } dateFileLineMap.put(date1, new FileLine(fileRecord.getId(), lineCount)); if (logger.isDebugEnabled()) { logger.debug(fileRecord.getFile().getName() + " dateFileLineMap put: " + date1 + "fileLine: " + new FileLine(fileRecord.getId(), lineCount)); logger.debug(fileRecord.getFile().getName() + " FileRecord: " + fileRecord.getFile().getName() + ", RIFileLineDateMap.put: " + recItem2.getName() + ", line: " + lineCount + " RIFileLineDateMap size: " + RIFileLineDateMap.size() + " dateFileLineMap size: " + dateFileLineMap.size()); } RIFileLineDateMap.put(recItem2.getName(), dateFileLineMap); if (startDate == null) { startDate = date1; } if (endDate == null) { endDate = date1; } if (date1.after(startDate)) { endDate = date1; } else if (date1.before(startDate)) { startDate = date1; } if (isStatRecording) { if (statMap.containsKey(recItem2.getName())) { ts = statMap.get(recItem2.getName()); } else { ts = new ExtendedTimeSeries(recItem2.getName(), FixedMillisecond.class); if (logger.isDebugEnabled()) logger.debug( "5**** Adding record to Map: " + recItem2.getName()); } fMS = new FixedMillisecond(date1); if (matcher2.group(count) == null) { logger.info("null in match on " + recItem2.getName() + " at " + fileRecord.getFile().getName() + " line cnt:" + lineCount); logger.info("line : " + line); } try { if (recItem2.getType().equals("long")) { ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS, Long.valueOf((String) matcher2.group(count))))); } else { ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem(fMS, Double.parseDouble(String.valueOf(decimalFormat .parse((String) matcher2.group(count))))))); } } catch (ParseException e) { // TODO Auto-generated catch // block e.printStackTrace(); } if (stats) { //int[] array = { statMatch, statHit }; int[] array = ts.getStat(); array[1] = array[1] + 1; array[0] = array[0] + 1; ts.setStat(array); if (logger.isDebugEnabled()) logger.debug("stats " + array[0] + " " + array[1]); } statMap.put(recItem2.getName(), ts); // performance: add the // TmeSeriesDataItem to the // TimeSeries instead of updating // the TimeSeries in the Map } else { // rec.getClass().equals(EventRecording.class) if (eventMap.containsKey(recItem2.getName())) { ts = eventMap.get(recItem2.getName()); } else { ts = new ExtendedTimeSeries(recItem2.getName(), FixedMillisecond.class); if (logger.isDebugEnabled()) logger.debug( "5**** Adding record to Map: " + recItem2.getName()); } fMS = new FixedMillisecond(date1); if (((RecordingItem) recItem2).getProcessingType() .equals("occurrences")) { TimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS); if (t != null) { ts.getTimeSeries() .addOrUpdate((new TimeSeriesDataItem(fMS, 101))); // + // (double)t.getValue() // need some way to show several occurrences } else { ts.getTimeSeries().add((new TimeSeriesDataItem(fMS, 100))); } } else if (((RecordingItem) recItem2).getProcessingType() .equals("sum")) { TimeSeriesDataItem t = ts.getTimeSeries().getDataItem(fMS); if (t != null) { if (!recItem2.getType().equals("date")) { try { ts.getTimeSeries().addOrUpdate((new TimeSeriesDataItem( fMS, Double.parseDouble(String .valueOf(decimalFormat .parse(matcher2.group(count))) + ts.getTimeSeries().getDataItem(fMS) .getValue())))); logger.info( ts.getTimeSeries().getDataItem(fMS).getValue()); } catch (ParseException e) { // TODO // Auto-generated // catch block e.printStackTrace(); } } } else { try { ts.getTimeSeries() .add((new TimeSeriesDataItem(fMS, Double .parseDouble(String.valueOf(decimalFormat .parse(matcher2.group(count))))))); } catch (ParseException e) { // TODO Auto-generated // catch block e.printStackTrace(); } } } else if (((RecordingItem) recItem2).getProcessingType() .equals("capture")) { } else { if (!recItem2.getType().equals("date")) { try { ts.getTimeSeries() .addOrUpdate((new TimeSeriesDataItem(fMS, Double .parseDouble(String.valueOf(decimalFormat .parse(matcher2.group(count))))))); } catch (ParseException e) { // TODO Auto-generated // catch block e.printStackTrace(); } } // ts.addOrUpdate((new // TimeSeriesDataItem(fMS, // 100))); } // logger.debug(recItem2.getName() + // " " + // Double.parseDouble((matcher2.group(count)))); if (stats) { int[] array = ts.getStat(); array[1] = array[1] + 1; array[0] = array[0] + 1; ts.setStat(array); if (logger.isDebugEnabled()) logger.debug("stats " + array[0] + " " + array[1]); } eventMap.put(recItem2.getName(), ts); } } } count++; // logger.info("event statistics: "+eventMatch + // " and " +eventHit + // " ; stat statistics: "+statMatch + " and " // +statHit); } } if (timings) { recordingMatchEnd = ManagementFactory.getThreadMXBean() .getThreadCpuTime(Thread.currentThread().getId()); if (matchTimings.containsKey(rec.getName())) { arrayBefore = matchTimings.get(rec.getName()); // logger.info(file.getName() + " contains " + // arrayBefore); // 0-> sum of time for success matching of given // recording ; 1-> sum of time for failed // matching ; 2-> count of match attempts, // 3->count of success attempts long[] array = { arrayBefore[0] + recordingMatchEnd - recordingMatchStart, arrayBefore[1], arrayBefore[2] + 1, arrayBefore[3] + 1 }; // logger.info(file.getName() + // " add success to" + rec.getName() + " 0: "+ // array[0] + " 1: "+ array[1]+ " 2: "+ array[2] // +" 3: "+ array[3]); matchTimings.put(rec.getName(), array); } else { long[] array = { recordingMatchEnd - recordingMatchStart, 0, 1, 1 }; matchTimings.put(rec.getName(), array); // logger.info(file.getName() + " first success" // + rec.getName() + " 0: "+ array[0] + " 1: "+ // array[1]+ " 2: "+ array[2] +" 3: "+ // array[3]); } } } else { if (timings) { recordingMatchEnd = ManagementFactory.getThreadMXBean() .getThreadCpuTime(Thread.currentThread().getId()); if (matchTimings.containsKey(rec.getName())) { arrayBefore = matchTimings.get(rec.getName()); // 0-> sum of time for success matching of given // recording ; 1-> sum of time for failed // matching ; 2-> count of match attempts, // 3->count of success attempts long[] array = { arrayBefore[0], arrayBefore[1] + recordingMatchEnd - recordingMatchStart, arrayBefore[2] + 1, arrayBefore[3] }; matchTimings.put(rec.getName(), array); } else { long[] array = { 0, recordingMatchEnd - recordingMatchStart, 1, 0 }; matchTimings.put(rec.getName(), array); } } } } lineCount++; // timing } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { buf1st.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * if (logger.isInfoEnabled()) { Iterator Ite = * matchTimings.entrySet().iterator(); long successTotalTime=0; long * failedTotalTime=0; // 0-> sum of time for success matching of given * // recording ; 1-> sum of time for failed // matching ; 2-> count of * match attempts, // 3->count of success attempts // long[] array; * while (Ite.hasNext()) { Map.Entry pairs = (Map.Entry) Ite.next(); * long[] array = (long[]) pairs.getValue(); logger.info(file.getName() * + " - "+ pairs.getKey() + " / success all time: " + array[0] + * " failed all time: " + array[1] + " attempt count: " + array[2] + * " success count: " + array[3] + " failed count:" * +(array[2]-array[3])); successTotalTime=successTotalTime+array[0]; * failedTotalTime=failedTotalTime+array[1]; } logger.info("success: " * +successTotalTime + " failed: " + failedTotalTime); Ite = * matchTimings.entrySet().iterator(); while (Ite.hasNext()) { Map.Entry * pairs = (Map.Entry) Ite.next(); long[] array = (long[]) * pairs.getValue(); logger.info(file.getName() + " percents - "+ * pairs.getKey() + " / % success time: " + (( successTotalTime!=0) ? * ((double)((double)array[0] / successTotalTime)*100) : 0 ) + * " % failed time: " + (( failedTotalTime!=0) ?((double)array[1]/ * failedTotalTime)*100 :0) + " attempt cost: " + ((array[2]!=0) ? * ((double)successTotalTime + failedTotalTime ) /array[2]:0 )+ * " success cost: " + ((array[3]!=0) ? ((double)successTotalTime ) * /array[3] : 0) + " failed cost:" + ((array[2]-array[3]!=0) ? * ((double)failedTotalTime/(array[2]-array[3])) : 0) ); } } */ return new FileMineResult(fileRecord, statMap, eventMap, matchTimings, RIFileLineDateMap, startDate, endDate); }
From source file:org.sakaiproject.assignment.tool.AssignmentAction.java
/** * read review grade information form and see if any grading information has been changed * @param data/* w w w .ja v a 2s .c om*/ * @param state * @param gradeOption * @return */ public boolean saveReviewGradeForm(RunData data, SessionState state, String gradeOption) { String assessorUserId = UserDirectoryService.getCurrentUser().getId(); if (state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID) != null && !assessorUserId.equals(state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID))) { //this is only set during the read only view, so just return return false; } ParameterParser params = data.getParameters(); String submissionRef = params.getString("submissionId"); String submissionId = null; if (submissionRef != null) { int i = submissionRef.lastIndexOf(Entity.SEPARATOR); if (i == -1) { submissionId = submissionRef; } else { submissionId = submissionRef.substring(i + 1); } } if (submissionId != null) { //call the DB to make sure this user can edit this assessment, otherwise it wouldn't exist PeerAssessmentItem item = assignmentPeerAssessmentService.getPeerAssessmentItem(submissionId, assessorUserId); if (item != null) { //find the original assessment item and compare to see if it has changed //if so, save it boolean changed = false; if (submissionId.equals(item.getSubmissionId()) && assessorUserId.equals(item.getAssessorUserId())) { //Grade String g = StringUtils.trimToNull(params.getCleanString(GRADE_SUBMISSION_GRADE)); Integer score = item.getScore(); if (g != null && !"".equals(g)) { try { String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); if (assignmentId == null) { addAlert(state, rb.getString("peerassessment.alert.saveerrorunkown")); } else { Assignment a = getAssignment(assignmentId, "saveReviewGradeForm", state); if (a == null) { addAlert(state, rb.getString("peerassessment.alert.saveerrorunkown")); } else { int factor = a.getContent().getFactor(); int dec = (int) Math.log10(factor); String decSeparator = FormattedText.getDecimalSeparator(); g = StringUtils.replace(g, (",".equals(decSeparator) ? "." : ","), decSeparator); NumberFormat nbFormat = FormattedText.getNumberFormat(dec, dec, false); DecimalFormat dcformat = (DecimalFormat) nbFormat; Double dScore = dcformat.parse(g).doubleValue(); if (dScore < 0) { addAlert(state, rb.getString("peerassessment.alert.saveinvalidscore")); } else if (dScore <= a.getContent().getMaxGradePoint() / (double) factor) { //scores are saved as whole values //so a score of 1.3 would be stored as 13 score = (int) Math.round(dScore * factor); } else { addAlert(state, rb.getFormattedMessage("plesuse4", new Object[] { g, a.getContent().getMaxGradePoint() / (double) factor })); } } } } catch (Exception e) { addAlert(state, rb.getString("peerassessment.alert.saveinvalidscore")); } } boolean scoreChanged = false; if (score != null && item.getScore() == null || score == null && item.getScore() != null || (score != null && item.getScore() != null && !score.equals(item.getScore()))) { //Score changed changed = true; scoreChanged = true; item.setScore(score); } //Comment: boolean checkForFormattingErrors = true; String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT), checkForFormattingErrors); if (feedbackComment != null && item.getComment() == null || feedbackComment == null && item.getComment() != null || (feedbackComment != null && item.getComment() != null && !feedbackComment.equals(item.getComment()))) { //comment changed changed = true; item.setComment(feedbackComment); } //Submitted if ("submit".equals(gradeOption)) { if (item.getScore() != null || (item.getComment() != null && !"".equals(item.getComment().trim()))) { item.setSubmitted(true); changed = true; } else { addAlert(state, rb.getString("peerassessment.alert.savenoscorecomment")); } } if (("submit".equals(gradeOption) || "save".equals(gradeOption)) && state.getAttribute(STATE_MESSAGE) == null) { if (changed) { //save this in the DB assignmentPeerAssessmentService.savePeerAssessmentItem(item); if (scoreChanged) { //need to re-calcuate the overall score: boolean saved = assignmentPeerAssessmentService.updateScore(submissionId); if (saved) { //we need to make sure the GB is updated correctly (or removed) String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); if (assignmentId != null) { Assignment a = getAssignment(assignmentId, "saveReviewGradeForm", state); if (a != null) { String aReference = a.getReference(); String associateGradebookAssignment = StringUtils .trimToNull(a.getProperties().getProperty( AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); // update grade in gradebook integrateGradebook(state, aReference, associateGradebookAssignment, null, null, null, -1, null, submissionId, "update", -1); } } } } state.setAttribute(GRADE_SUBMISSION_DONE, Boolean.TRUE); if ("submit".equals(gradeOption)) { state.setAttribute(GRADE_SUBMISSION_SUBMIT, Boolean.TRUE); } } } //update session state: List<PeerAssessmentItem> peerAssessmentItems = (List<PeerAssessmentItem>) state .getAttribute(PEER_ASSESSMENT_ITEMS); if (peerAssessmentItems != null) { for (int i = 0; i < peerAssessmentItems.size(); i++) { PeerAssessmentItem sItem = peerAssessmentItems.get(i); if (sItem.getSubmissionId().equals(item.getSubmissionId()) && sItem.getAssessorUserId().equals(item.getAssessorUserId())) { //found it, just update it peerAssessmentItems.set(i, item); state.setAttribute(PEER_ASSESSMENT_ITEMS, peerAssessmentItems); break; } } } } return changed; } else { addAlert(state, rb.getString("peerassessment.alert.saveerrorunkown")); } } else { addAlert(state, rb.getString("peerassessment.alert.saveerrorunkown")); } return false; }
From source file:org.sakaiproject.assignment.tool.AssignmentAction.java
protected String build_student_review_edit_context(VelocityPortlet portlet, Context context, RunData data, SessionState state) {//from w w w .j a va 2 s.c o m int gradeType = -1; context.put("context", state.getAttribute(STATE_CONTEXT_STRING)); List<PeerAssessmentItem> peerAssessmentItems = (List<PeerAssessmentItem>) state .getAttribute(PEER_ASSESSMENT_ITEMS); String assignmentId = (String) state.getAttribute(VIEW_ASSIGNMENT_ID); User sessionUser = (User) state.getAttribute(STATE_USER); String assessorId = sessionUser.getId(); if (state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID) != null) { assessorId = (String) state.getAttribute(PEER_ASSESSMENT_ASSESSOR_ID); } int factor = AssignmentService.getScaleFactor(); int dec = (int) Math.log10(factor); Assignment assignment = getAssignment(assignmentId, "build_student_review_edit_context", state); if (assignment != null) { context.put("assignment", assignment); if (assignment.getContent() != null) { gradeType = assignment.getContent().getTypeOfGrade(); factor = assignment.getContent().getFactor(); dec = (int) Math.log10(factor); } context.put("peerAssessmentInstructions", assignment.getPeerAssessmentInstructions() == null ? "" : assignment.getPeerAssessmentInstructions()); } String submissionId = ""; SecurityAdvisor secAdv = new SecurityAdvisor() { @Override public SecurityAdvice isAllowed(String userId, String function, String reference) { if ("asn.submit".equals(function) || "asn.submit".equals(function) || "asn.grade".equals(function)) { return SecurityAdvice.ALLOWED; } return null; } }; AssignmentSubmission s = null; try { //surround with a try/catch/finally for the security advisor m_securityService.pushAdvisor(secAdv); s = getSubmission((String) state.getAttribute(GRADE_SUBMISSION_SUBMISSION_ID), "build_student_review_edit_context", state); m_securityService.popAdvisor(secAdv); } catch (Exception e) { M_log.error(e.getMessage(), e); } finally { if (secAdv != null) { m_securityService.popAdvisor(secAdv); } } if (s != null) { submissionId = s.getId(); context.put("submission", s); ResourceProperties p = s.getProperties(); if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT) != null) { context.put("prevFeedbackText", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_TEXT)); } if (p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT) != null) { context.put("prevFeedbackComment", p.getProperty(ResourceProperties.PROP_SUBMISSION_PREVIOUS_FEEDBACK_COMMENT)); } if (p.getProperty(PROP_SUBMISSION_PREVIOUS_FEEDBACK_ATTACHMENTS) != null) { context.put("prevFeedbackAttachments", getPrevFeedbackAttachments(p)); } if ((s.getFeedbackText() == null) || (s.getFeedbackText().length() == 0)) { context.put("value_feedback_text", s.getSubmittedText()); } else { context.put("value_feedback_text", s.getFeedbackFormattedText()); } context.put("value_feedback_text", s.getSubmittedText()); List v = EntityManager.newReferenceList(); Iterator attachments = s.getFeedbackAttachments().iterator(); while (attachments.hasNext()) { v.add(attachments.next()); } context.put("value_feedback_attachment", v); state.setAttribute(ATTACHMENTS, v); } if (peerAssessmentItems != null && submissionId != null) { //find the peerAssessmentItem for this submission: PeerAssessmentItem peerAssessmentItem = null; for (PeerAssessmentItem item : peerAssessmentItems) { if (submissionId.equals(item.getSubmissionId()) && assessorId.equals(item.getAssessorUserId())) { peerAssessmentItem = item; break; } } if (peerAssessmentItem != null) { //check if current user is the peer assessor, if not, only display data (no editing) if (!sessionUser.getId().equals(peerAssessmentItem.getAssessorUserId())) { context.put("view_only", true); try { User reviewer = UserDirectoryService.getUser(peerAssessmentItem.getAssessorUserId()); context.put("reviewer", reviewer); } catch (UserNotDefinedException e) { M_log.error(e.getMessage(), e); } } else { context.put("view_only", false); } //scores are saved as whole values //so a score of 1.3 would be stored as 13 //so a DB score of 13 needs to be 1.3: String decSeparator = FormattedText.getDecimalSeparator(); if (peerAssessmentItem.getScore() != null) { double score = peerAssessmentItem.getScore() / (double) factor; try { String rv = StringUtils.replace(Double.toString(score), (",".equals(decSeparator) ? "." : ","), decSeparator); NumberFormat nbFormat = FormattedText.getNumberFormat(dec, dec, false); DecimalFormat dcformat = (DecimalFormat) nbFormat; Double dblGrade = dcformat.parse(rv).doubleValue(); rv = nbFormat.format(dblGrade); context.put("value_grade", rv); context.put("display_grade", rv); } catch (Exception e) { M_log.warn(this + ":build_student_review_edit_context: Parse Error in display_Grade peerAssesmentItem" + e.getMessage()); } } else { context.put("value_grade", null); context.put("display_grade", ""); } context.put("item_removed", peerAssessmentItem.isRemoved()); context.put("value_feedback_comment", peerAssessmentItem.getComment()); //set previous/next values List userSubmissionsState = state.getAttribute(STATE_PAGEING_TOTAL_ITEMS) != null ? (List) state.getAttribute(STATE_PAGEING_TOTAL_ITEMS) : null; List<String> userSubmissions = new ArrayList<String>(); boolean instructorView = false; if (userSubmissionsState != null && userSubmissionsState.size() > 0 && userSubmissionsState.get(0) instanceof SubmitterSubmission) { //from instructor view for (SubmitterSubmission userSubmission : (List<SubmitterSubmission>) userSubmissionsState) { if (!userSubmissions.contains(userSubmission.getSubmission().getId()) && userSubmission.getSubmission().getSubmitted()) { userSubmissions.add(userSubmission.getSubmission().getId()); } } } else { //student view for (PeerAssessmentItem item : peerAssessmentItems) { if (!userSubmissions.contains(item.getSubmissionId()) && !item.isSubmitted()) { userSubmissions.add(item.getSubmissionId()); } } } if (userSubmissions != null) { context.put("totalReviews", userSubmissions.size()); //first setup map to make the navigation logic easier: Map<String, List<PeerAssessmentItem>> itemMap = new HashMap<String, List<PeerAssessmentItem>>(); for (String userSubmissionId : userSubmissions) { for (PeerAssessmentItem item : peerAssessmentItems) { if (userSubmissionId.equals(item.getSubmissionId())) { List<PeerAssessmentItem> items = itemMap.get(userSubmissionId); if (items == null) { items = new ArrayList<PeerAssessmentItem>(); } items.add(item); itemMap.put(item.getSubmissionId(), items); } } } for (int i = 0; i < userSubmissions.size(); i++) { String userSubmissionId = userSubmissions.get(i); if (userSubmissionId.equals(submissionId)) { //we found the right submission, now find the items context.put("reviewNumber", (i + 1)); List<PeerAssessmentItem> submissionItems = itemMap.get(submissionId); if (submissionItems != null) { for (int j = 0; j < submissionItems.size(); j++) { PeerAssessmentItem item = submissionItems.get(j); if (item.getAssessorUserId().equals(assessorId)) { context.put("anonNumber", i + 1); boolean goPT = false; boolean goNT = false; if ((i - 1) >= 0 || (j - 1) >= 0) { goPT = true; } if ((i + 1) < userSubmissions.size() || (j + 1) < submissionItems.size()) { goNT = true; } context.put("goPTButton", Boolean.valueOf(goPT)); context.put("goNTButton", Boolean.valueOf(goNT)); if (j > 0) { // retrieve the previous submission id context.put("prevSubmissionId", (submissionItems.get(j - 1).getSubmissionId())); context.put("prevAssessorId", (submissionItems.get(j - 1).getAssessorUserId())); } else if (i > 0) { //go to previous submission and grab the last item in that list int k = i - 1; while (k >= 0 && !itemMap.containsKey(userSubmissions.get(k))) { k--; } if (k >= 0 && itemMap.get(userSubmissions.get(k)).size() > 0) { List<PeerAssessmentItem> pItems = itemMap .get(userSubmissions.get(k)); PeerAssessmentItem pItem = pItems.get(pItems.size() - 1); context.put("prevSubmissionId", (pItem.getSubmissionId())); context.put("prevAssessorId", (pItem.getAssessorUserId())); } else { //no previous option, set to false context.put("goPTButton", Boolean.valueOf(false)); } } if (j < submissionItems.size() - 1) { // retrieve the next submission id context.put("nextSubmissionId", (submissionItems.get(j + 1).getSubmissionId())); context.put("nextAssessorId", (submissionItems.get(j + 1).getAssessorUserId())); } else if (i < userSubmissions.size() - 1) { //go to previous submission and grab the last item in that list int k = i + 1; while (k < userSubmissions.size() && !itemMap.containsKey(userSubmissions.get(k))) { k++; } if (k < userSubmissions.size() && itemMap.get(userSubmissions.get(k)).size() > 0) { List<PeerAssessmentItem> pItems = itemMap .get(userSubmissions.get(k)); PeerAssessmentItem pItem = pItems.get(0); context.put("nextSubmissionId", (pItem.getSubmissionId())); context.put("nextAssessorId", (pItem.getAssessorUserId())); } else { //no next option, set to false context.put("goNTButton", Boolean.valueOf(false)); } } } } } } } } } } context.put("assignment_expand_flag", state.getAttribute(GRADE_SUBMISSION_ASSIGNMENT_EXPAND_FLAG)); context.put("user", sessionUser); context.put("submissionTypeTable", submissionTypeTable()); context.put("instructorAttachments", state.getAttribute(ATTACHMENTS)); context.put("contentTypeImageService", state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE)); context.put("service", AssignmentService.getInstance()); // names context.put("name_grade_assignment_id", GRADE_SUBMISSION_ASSIGNMENT_ID); context.put("name_feedback_comment", GRADE_SUBMISSION_FEEDBACK_COMMENT); context.put("name_feedback_text", GRADE_SUBMISSION_FEEDBACK_TEXT); context.put("name_feedback_attachment", GRADE_SUBMISSION_FEEDBACK_ATTACHMENT); context.put("name_grade", GRADE_SUBMISSION_GRADE); context.put("name_allowResubmitNumber", AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); // put supplement item into context try { //surround with a try/catch/finally for the security advisor m_securityService.pushAdvisor(secAdv); supplementItemIntoContext(state, context, assignment, null); } catch (Exception e) { M_log.error(e.getMessage(), e); } finally { if (secAdv != null) { m_securityService.popAdvisor(secAdv); } } // put the grade confirmation message if applicable if (state.getAttribute(GRADE_SUBMISSION_DONE) != null) { context.put("gradingDone", Boolean.TRUE); state.removeAttribute(GRADE_SUBMISSION_DONE); if (state.getAttribute(PEER_ASSESSMENT_REMOVED_STATUS) != null) { context.put("itemRemoved", state.getAttribute(PEER_ASSESSMENT_REMOVED_STATUS)); state.removeAttribute(PEER_ASSESSMENT_REMOVED_STATUS); } } // put the grade confirmation message if applicable if (state.getAttribute(GRADE_SUBMISSION_SUBMIT) != null) { context.put("gradingSubmit", Boolean.TRUE); state.removeAttribute(GRADE_SUBMISSION_SUBMIT); } String template = (String) getContext(data).get("template"); return template + TEMPLATE_STUDENT_REVIEW_EDIT; }
From source file:org.sakaiproject.assignment.tool.AssignmentAction.java
/** * display grade properly//w w w . j av a 2 s. c o m */ private String displayGrade(SessionState state, String grade, int factor) { if (state.getAttribute(STATE_MESSAGE) == null) { if (grade != null && (grade.length() >= 1)) { int dec = (int) Math.log10(factor); NumberFormat nbFormat = FormattedText.getNumberFormat(dec, dec, false); DecimalFormat dcformat = (DecimalFormat) nbFormat; String decSeparator = FormattedText.getDecimalSeparator(); if (grade.indexOf(decSeparator) != -1) { if (grade.startsWith(decSeparator)) { grade = "0".concat(grade); } else if (grade.endsWith(decSeparator)) { for (int i = 0; i < dec; i++) { grade = grade.concat("0"); } } } else { try { Integer.parseInt(grade); int length = grade.length(); if (length > dec) { grade = grade.substring(0, grade.length() - dec) + decSeparator + grade.substring(grade.length() - dec); } else { String newGrade = "0".concat(decSeparator); for (int i = length; i < dec; i++) { newGrade = newGrade.concat("0"); } grade = newGrade.concat(grade); } } catch (NumberFormatException e) { // alert alertInvalidPoint(state, grade, factor); M_log.warn(this + ":displayGrade cannot parse grade into integer grade = " + grade + e.getMessage()); } } try { // show grade in localized number format Double dblGrade = dcformat.parse(grade).doubleValue(); grade = nbFormat.format(dblGrade); } catch (Exception e) { // alert alertInvalidPoint(state, grade, factor); M_log.warn(this + ":displayGrade cannot parse grade into integer grade = " + grade + e.getMessage()); } } else { grade = ""; } } return grade; }