Example usage for java.lang Double doubleValue

List of usage examples for java.lang Double doubleValue

Introduction

In this page you can find the example usage for java.lang Double doubleValue.

Prototype

@HotSpotIntrinsicCandidate
public double doubleValue() 

Source Link

Document

Returns the double value of this Double object.

Usage

From source file:net.cbtltd.rest.interhome.A_Handler.java

/**
 * Create price and price detail//from   w  w  w .  j  av  a  2 s.co m
 * price=958.00
 * total=767.00
 * currencyCode=EUR
 * expirationPrePayment=0001-01-01
 * expirationResidue=2012-10-22
 * prepayment=0
 * specialCode=PR/00000002
 * specialDescription=20% Discount
 * minimum stay 7 nights
 * specialPrice=767.00
 * 
 * type=EXTRACOST_ON_PLACE, amount=3.30, code=LT, count=0, currency=CHF, description=, eitherOr=, isDefaultService=false, isIncluded=false, isInsurance=false, isMandatory=true, paymentInfo=Payable in resort per person/day, priceRule=PD, text=, type=Y4, validFrom=2012-12-01, validTo=2012-12-15], 
 * type=BOOKABLE_SERVICE_ON_INVOICE, amount=10.00, code=PET, count=0, currency=EUR, description=Pet, eitherOr=, isDefaultService=false, isIncluded=false, isInsurance=false, isMandatory=false, paymentInfo=Bookable extra per person/week, priceRule=U1, text=One pet is allowed in this property. Please reconfirm with our sales office if
   you need to take more than one animal with you., type=N1, validFrom=2012-12-01, validTo=2012-12-15], 
 * type=BOOKABLE_SERVICE_ON_INVOICE, amount=16.00, code=WOOD, count=0, currency=EUR, description=Tanne, eitherOr=, isDefaultService=false, isIncluded=false, isInsurance=false, isMandatory=false, paymentInfo=Bookable extra fixed price, priceRule=U1, text=, type=N1, validFrom=2012-12-01, validTo=2012-12-15], 
 * type=IN_PRICE_INCLUDED, amount=0, code=LI, count=0, currency=, description=Laundry (initial supply of bed linen and towels), eitherOr=, isDefaultService=false, isIncluded=true, isInsurance=false, isMandatory=true, paymentInfo=Included in the price, priceRule=, text=, type=Y2, validFrom=2012-12-01, validTo=2012-12-15], 
 * type=BOOKABLE_SERVICE_ON_INVOICE, amount=56.00, code=HCHR, count=4, currency=EUR, description=Highchair, eitherOr=, isDefaultService=false, isIncluded=false, isInsurance=false, isMandatory=false, paymentInfo=Bookable extra per day, priceRule=U1, text=, type=N1, validFrom=2012-12-01, validTo=2012-12-15], 
 * type=BOOKABLE_SERVICE_ON_INVOICE, amount=56.00, code=COT, count=1, currency=EUR, description=Cot (up to 2 years), eitherOr=, isDefaultService=false, isIncluded=false, isInsurance=false, isMandatory=false, paymentInfo=Bookable extra per day, priceRule=U1, text=Appropriate up to 2 years (max. 3 years), type=N1, validFrom=2012-12-01, validTo=2012-12-15], 
 * type=BOOKABLE_SERVICE_ON_INVOICE, amount=56.00, code=BUGY, count=2, currency=EUR, description=, eitherOr=, isDefaultService=false, isIncluded=false, isInsurance=false, isMandatory=false, paymentInfo=Bookable extra per day, priceRule=U1, text=, type=N1, validFrom=2012-12-01, validTo=2012-12-15], 
 * type=IN_PRICE_INCLUDED, amount=0, code=FC, count=0, currency=, description=Final cleaning, eitherOr=, isDefaultService=false, isIncluded=true, isInsurance=false, isMandatory=true, paymentInfo=Included in the price, priceRule=, text=, type=Y2, validFrom=2012-12-01, validTo=2012-12-15], 
 * type=EXTRACOST_ON_PLACE, amount=500.00, code=DK, count=0, currency=CHF, description=Breakage deposit by credit card Visa / Mastercard, eitherOr=, isDefaultService=false, isIncluded=false, isInsurance=false, isMandatory=true, paymentInfo=Payable in resort fixed price, priceRule=U1, text=, type=Y4, validFrom=2012-12-01, validTo=2012-12-15], 
 * type=BOOKABLE_SERVICE_ON_INVOICE, amount=1200.00, code=WIFI, count=5, currency=EUR, description=wireless internet access (WIFI), eitherOr=, isDefaultService=false, isIncluded=false, isInsurance=false, isMandatory=false, paymentInfo=Bookable extra per day, priceRule=U1, text=, type=N1, validFrom=2012-12-01, validTo=2012-12-15]
 *
 * @param sqlSession
 * @param reservation
 * @param productaltid
 * @throws Throwable
 */
private ReservationPrice computePrice(SqlSession sqlSession, Reservation reservation, String productaltid,
        String currency) throws Throwable {
    ReservationPrice reservationPrice = new ReservationPrice();
    List<QuoteDetail> quoteDetails = new ArrayList<QuoteDetail>();
    reservationPrice.setQuoteDetails(quoteDetails);
    PriceDetailInputValue rq = new PriceDetailInputValue();
    rq.setAccommodationCode(productaltid);
    rq.setCheckIn(format(reservation.getFromdate()));
    rq.setCheckOut(format(reservation.getTodate()));
    rq.setRetailerCode(reservation.getAgentname());
    rq.setSalesOfficeCode(getSalesOfficeCode(null));
    rq.setAdults(reservation.getAdult());
    rq.setChildren(reservation.getChild());
    rq.setBabies(reservation.getInfant());
    rq.setCurrencyCode(currency);
    rq.setLanguageCode(Language.Code.en.name());

    System.out.println("priceDetail rq=" + rq);
    PriceDetailRetunValue rs = getAuthenticatedPort(getRetailerCode(currency)).priceDetail(rq);
    System.out.println("priceDetail rs=" + rs);

    if (rs.isOk()) {
        reservation.setQuotedetail(new ArrayList<net.cbtltd.shared.Price>());
        net.cbtltd.shared.Price price = new net.cbtltd.shared.Price();
        price.setEntitytype(NameId.Type.Reservation.name());
        price.setEntityid(reservation.getId());
        sqlSession.getMapper(PriceMapper.class).deletebyexample(price);

        Double rack = rs.getPrice().doubleValue();
        Double total = rs.getTotal().doubleValue();
        Double prepayment = rs.getPrepayment().doubleValue();
        Double special = rs.getSpecialPrice() == null ? 0.0 : rs.getSpecialPrice().doubleValue();

        if (special > 0.0) {
            price = new net.cbtltd.shared.Price();
            price.setEntitytype(NameId.Type.Reservation.name());
            price.setEntityid(reservation.getId());
            price.setName(rs.getSpecialDescription());
            price.setState(net.cbtltd.shared.Price.CREATED);
            price.setType(getSpecial(rs.getSpecialCode()));
            price.setDate(parse(rs.getExpirationResidue()));
            price.setQuantity(1.0);
            price.setUnit(Unit.EA);
            price.setValue(special - prepayment);
            price.setCurrency(rs.getCurrencyCode());
            sqlSession.getMapper(PriceMapper.class).create(price);
            reservation.getQuotedetail().add(price);
            String specialPrice = (String.valueOf(special - rack));
            QuoteDetail quoteDetail = new QuoteDetail(specialPrice, price.getCurrency(),
                    "Special price discount", "", "", false);
            quoteDetails.add(quoteDetail);
        } else {
            price = new net.cbtltd.shared.Price();
            price.setEntitytype(NameId.Type.Reservation.name());
            price.setEntityid(reservation.getId());
            price.setType(net.cbtltd.shared.Price.RATE);
            price.setName(net.cbtltd.shared.Price.RATE);
            price.setState(net.cbtltd.shared.Price.CREATED);
            price.setDate(parse(rs.getExpirationResidue()));
            price.setQuantity(1.0);
            price.setUnit(Unit.EA);
            price.setValue(total - prepayment);
            price.setCurrency(rs.getCurrencyCode());
            sqlSession.getMapper(PriceMapper.class).create(price);
            reservation.getQuotedetail().add(price);
        }

        if (prepayment > 0.0) {
            price = new net.cbtltd.shared.Price();
            price.setEntitytype(NameId.Type.Reservation.name());
            price.setEntityid(reservation.getId());
            price.setType(net.cbtltd.shared.Price.DEPOSIT);
            price.setName(net.cbtltd.shared.Price.DEPOSIT);
            price.setState(net.cbtltd.shared.Price.CREATED);
            price.setDate(parse(rs.getExpirationPrePayment()));
            price.setQuantity(1.0);
            price.setUnit(Unit.EA);
            price.setValue(prepayment);
            price.setCurrency(rs.getCurrencyCode());
            sqlSession.getMapper(PriceMapper.class).create(price);
            reservation.getQuotedetail().add(price);
        }

        for (AdditionalServiceItem item : rs.getAdditionalServices().getAdditionalServiceItem()) {
            if (item.getCode().equalsIgnoreCase("RTCO")) {
                continue;
            } // skip agency commission
            double amountvalue = item.getAmount().doubleValue();
            if (item.isIsMandatory()) {
                String itemCurrency = item.getCurrency().equals("") ? currency : item.getCurrency();
                String amount = amountvalue == 0 ? "0" : item.getAmount().toString();
                /*               if ((!item.getCurrency().isEmpty() || item.getCurrency() != null) && !item.getCurrency().equalsIgnoreCase(currency)) {
                                  double amountconverted = PaymentService.convertCurrency(sqlSession, item.getCurrency(), currency, amountvalue);
                                  double amountround = PaymentHelper.getAmountWithTwoDecimals(amountconverted);
                                  amount = String.valueOf(amountround);
                               }*/
                QuoteDetail quoteDetail = new QuoteDetail(amount, itemCurrency, item.getDescription(),
                        item.getPaymentInfo(), item.getText(), item.isIsIncluded());
                quoteDetails.add(quoteDetail);
            }
            String type = getType(item.getAdditionalServiceType());
            if (type == null) {
                continue;
            }
            price = new net.cbtltd.shared.Price();
            price.setEntitytype(NameId.Type.Reservation.name());
            price.setEntityid(reservation.getId());
            price.setType(type);
            price.setName(NameId.trim(item.getDescription(), 24));
            price.setState(net.cbtltd.shared.Price.CREATED);
            price.setValue(amountvalue);
            price.setId(item.getCode());
            boolean mandatory = item.isIsMandatory();
            price.setQuantity(mandatory ? Double.valueOf(item.getCount()) : 0.0);
            price.setUnit(Unit.EA);
            price.setCurrency(rs.getCurrencyCode());
            price.setRule(item.getPriceRule());
            price.setDate(parse(item.getValidFrom()));
            price.setTodate(parse(item.getValidTo()));
            sqlSession.getMapper(PriceMapper.class).create(price);
            reservation.getQuotedetail().add(price);
        }
        reservation.setPrice(rack);
        reservation.setQuote(special > 0.0 ? special : total);
        reservation.setExtra(0.0);
        reservationPrice.setPrice(reservation.getPrice());
        reservationPrice.setTotal(reservation.getQuote());
        reservationPrice.setCurrency(currency);
        Double discountfactor = ReservationService.getDiscountfactor(sqlSession, reservation);
        reservation.setCost(reservation.getPrice() * discountfactor);
        reservation.setCurrency(rs.getCurrencyCode());
        Double dueNow = rs.getPrepayment().doubleValue();
        Double deposit = dueNow == null ? 0.0 : dueNow * 100 / reservation.getQuote();
        reservation.setDeposit(deposit.doubleValue());

    } else {
        throw new ServiceException(Error.reservation_api, rs.getErrors().getError().get(0).getDescription());
    }
    LOG.debug("computePrice " + reservation.getQuotedetail());
    return reservationPrice;
}

From source file:org.sakaiproject.tool.gradebook.ui.SpreadsheetUploadBean.java

/**
 * Returns TRUE if specific value imported from spreadsheet is valid
 *
 * @return false if the spreadsheet contains a invalid points possible, an invalid
 * score value, more than one column for the same gb item, more than one row for the same student
 *//* ww  w. jav a2s.  c  o  m*/
private boolean verifyImportedData(LetterGradePercentMapping lgpm) {
    if (studentRows == null || studentRows.isEmpty()) {
        return true;
    }

    if (getGradeEntryByLetter() && (lgpm == null || lgpm.getGradeMap() == null)) {
        FacesUtil.addErrorMessage(getLocalizedString("gb_setup_no_grade_entry_scale"));
        return false;
    }

    // determine the index of the "cumulative" column
    int indexOfCumColumn = -1;
    if (assignmentHeaders != null && !assignmentHeaders.isEmpty()) {
        // add one b/c assignmentHeaders does not include the username col but studentRows does
        indexOfCumColumn = assignmentHeaders.indexOf(getLocalizedString(CUMULATIVE_GRADE_STRING)) + 1;

        // we need to double check that there aren't any duplicate assignments
        // in the spreadsheet. the first column is the student name, so skip
        List<String> assignmentNames = new ArrayList<String>();
        if (assignmentHeaders.size() > 1) {
            for (int i = 1; i < assignmentHeaders.size(); i++) {
                if (i == indexOfCumColumn) {
                    continue;
                }

                String header = (String) assignmentHeaders.get(i);
                String[] parsedAssignmentName = header.split(" \\[");
                String assignmentName = parsedAssignmentName[0].trim();
                if (assignmentNames.contains(assignmentName)) {
                    FacesUtil.addErrorMessage(getLocalizedString("import_assignment_duplicate_titles",
                            new String[] { assignmentName }));
                    return false;
                }

                assignmentNames.add(assignmentName);
            }
        }
    }

    List<String> uploadedStudents = new ArrayList<String>();

    for (int row = 0; row < studentRows.size(); row++) {
        SpreadsheetRow scoreRow = (SpreadsheetRow) studentRows.get(row);
        List studentScores = scoreRow.getRowcontent();

        // verify that a student doesn't appear more than once in the ss
        if (studentScores != null) {
            String username = (String) studentScores.get(0);
            if (username != null) {
                if (uploadedStudents.contains(username)) {
                    FacesUtil.addErrorMessage(getLocalizedString("import_assignment_duplicate_student",
                            new String[] { username }));
                    return false;
                }

                uploadedStudents.add(username);
            }
        }

        // start with col 2 b/c the first two are eid and name
        if (studentScores != null && studentScores.size() > 2) {
            for (int i = 2; i < studentScores.size(); i++) {
                if (i == indexOfCumColumn)
                    continue;

                String scoreAsString = ((String) studentScores.get(i)).trim();
                if (scoreAsString != null && scoreAsString.length() > 0) {

                    if (getGradeEntryByPoints() || getGradeEntryByPercent()) {
                        Double scoreAsDouble;

                        try {
                            if (logger.isDebugEnabled())
                                logger.debug("checking if " + scoreAsString + " is a numeric value");

                            scoreAsDouble = convertStringToDouble(scoreAsString);
                            // check for negative values
                            if (scoreAsDouble.doubleValue() < 0) {
                                if (logger.isDebugEnabled())
                                    logger.debug(scoreAsString + " is not a positive value");
                                FacesUtil.addErrorMessage(getLocalizedString(IMPORT_ASSIGNMENT_NEG_VALUE));

                                return false;
                            }
                        } catch (ParseException e) {
                            if (logger.isDebugEnabled())
                                logger.debug(scoreAsString + " is not a numeric value");
                            FacesUtil.addErrorMessage(getLocalizedString(IMPORT_ASSIGNMENT_NOTSUPPORTED));

                            return false;
                        }

                    } else if (getGradeEntryByLetter()) {
                        String standardizedLetterGrade = lgpm.standardizeInputGrade(scoreAsString);
                        if (standardizedLetterGrade == null) {
                            FacesUtil.addErrorMessage(getLocalizedString("import_entire_invalid_letter"));
                            return false;
                        }
                    }
                }
            }
        }
    }

    return true;
}

From source file:net.sf.fspdfs.chartthemes.spring.GenericChartTheme.java

protected void handleCategoryPlotSettings(CategoryPlot p, JRChartPlot jrPlot) {
    Double defaultPlotLabelRotation = (Double) getDefaultValue(defaultPlotPropertiesMap,
            ChartThemesConstants.PLOT_LABEL_ROTATION);
    PlotOrientation defaultPlotOrientation = (PlotOrientation) getDefaultValue(defaultPlotPropertiesMap,
            ChartThemesConstants.PLOT_ORIENTATION);
    // Handle rotation of the category labels.
    CategoryAxis axis = p.getDomainAxis();
    boolean hasRotation = jrPlot.getLabelRotationDouble() != null || defaultPlotLabelRotation != null;
    if (hasRotation) {
        double labelRotation = jrPlot.getLabelRotationDouble() != null
                ? jrPlot.getLabelRotationDouble().doubleValue()
                : defaultPlotLabelRotation.doubleValue();

        if (labelRotation == 90) {
            axis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);
        } else if (labelRotation == -90) {
            axis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
        } else if (labelRotation < 0) {
            axis.setCategoryLabelPositions(
                    CategoryLabelPositions.createUpRotationLabelPositions((-labelRotation / 180.0) * Math.PI));
        } else if (labelRotation > 0) {
            axis.setCategoryLabelPositions(
                    CategoryLabelPositions.createDownRotationLabelPositions((labelRotation / 180.0) * Math.PI));
        }//  w w w.ja va2  s .  c o  m
    }

    if (defaultPlotOrientation != null) {
        p.setOrientation(defaultPlotOrientation);
    }
}

From source file:com.naryx.tagfusion.cfm.tag.awt.cfCHART.java

private void addSeriesDataToDataset(cfCHARTSERIESData seriesData, XYSeriesCollection dataset,
        MinMaxData minMax) {//from   www.  j av  a2s  .  co  m
    XYSeries series = new XYSeries(seriesData.getSeriesLabel());
    int num = seriesData.getNumItems();
    for (int j = 0; j < num; j++) {
        Double yValue = seriesData.getYValue(j);

        series.add(seriesData.getXValue(j), yValue);

        if (yValue.doubleValue() < minMax.minValue)
            minMax.minValue = yValue.doubleValue();
        if (yValue.doubleValue() > minMax.maxValue)
            minMax.maxValue = yValue.doubleValue();
    }
    dataset.addSeries(series);
}

From source file:org.sakaiproject.component.gradebook.GradebookServiceHibernateImpl.java

@Override
public Long addAssignment(String gradebookUid,
        org.sakaiproject.service.gradebook.shared.Assignment assignmentDefinition) {
    if (!getAuthz().isUserAbleToEditAssessments(gradebookUid)) {
        log.error("AUTHORIZATION FAILURE: User " + getUserUid() + " in gradebook " + gradebookUid
                + " attempted to add an assignment");
        throw new SecurityException("You do not have permission to perform this operation");
    }/*from  w  w w.  j ava  2s  .  co  m*/

    // Ensure that points is > zero.
    Double points = assignmentDefinition.getPoints();
    if ((points == null) || (points.doubleValue() <= 0)) {
        throw new AssignmentHasIllegalPointsException("Points must be > 0");
    }

    Gradebook gradebook = getGradebook(gradebookUid);

    //if attaching to category
    if (assignmentDefinition.getCategoryId() != null) {
        return createAssignmentForCategory(gradebook.getId(), assignmentDefinition.getCategoryId(),
                assignmentDefinition.getName(), points, assignmentDefinition.getDueDate(),
                !assignmentDefinition.isCounted(), assignmentDefinition.isReleased(),
                assignmentDefinition.isExtraCredit());
    }

    return createAssignment(gradebook.getId(), assignmentDefinition.getName(), points,
            assignmentDefinition.getDueDate(), !assignmentDefinition.isCounted(),
            assignmentDefinition.isReleased(), assignmentDefinition.isExtraCredit());
}

From source file:com.naryx.tagfusion.cfm.tag.awt.cfCHART.java

private void addSeriesDataToDataset(cfCHARTSERIESData seriesData, DefaultCategoryDataset dataset,
        MinMaxData minMax) {//w w  w . ja va 2s.co  m
    int num = seriesData.getNumItems();
    for (int j = 0; j < num; j++) {
        Double value = seriesData.getItemValue(j);

        dataset.addValue(value, seriesData.getSeriesLabel(), seriesData.getItemName(j));

        if (value.doubleValue() < minMax.minValue)
            minMax.minValue = value.doubleValue();
        if (value.doubleValue() > minMax.maxValue)
            minMax.maxValue = value.doubleValue();
    }
}

From source file:org.sakaiproject.tool.gradebook.ui.SpreadsheetUploadBean.java

/**
 * Takes the spreadsheet data imported and updates/adds to what is in the database
 *//*from  ww w.  j av a2s.  c o m*/
public String importDataAndSaveAll() {
    boolean gbUpdated = false;
    hasUnknownAssignments = false;
    externallyMaintainedImportMsg = new StringBuilder();

    LetterGradePercentMapping lgpm = new LetterGradePercentMapping();
    if (getGradeEntryByLetter()) {
        lgpm = getGradebookManager().getLetterGradePercentMapping(localGradebook);
    }

    if (logger.isDebugEnabled())
        logger.debug("importDataAll()");

    // first, verify imported data is valid
    if (!verifyImportedData(lgpm))
        return "spreadsheetVerify";

    List grAssignments = getGradebookManager().getAssignments(getGradebook().getId());
    Iterator assignIter = assignmentHeaders.iterator();

    // since the first two columns are user ids and name, skip over
    int index = 1;
    if (assignIter.hasNext())
        assignIter.next();

    while (assignIter.hasNext()) {
        String assignmentName = (String) assignIter.next();
        String pointsPossibleAsString = null;

        String[] parsedAssignmentName = assignmentName.split(" \\[");

        assignmentName = parsedAssignmentName[0].trim();
        Double pointsPossible = null;
        if (parsedAssignmentName.length > 1) {
            String[] parsedPointsPossible = parsedAssignmentName[1].split("\\]");
            if (parsedPointsPossible.length > 0) {
                pointsPossibleAsString = parsedPointsPossible[0].trim();
                try {
                    pointsPossible = convertStringToDouble(pointsPossibleAsString);
                    pointsPossible = new Double(FacesUtil.getRoundDown(pointsPossible.doubleValue(), 2));
                    if (pointsPossible <= 0)
                        pointsPossibleAsString = null;
                } catch (ParseException e) {
                    pointsPossibleAsString = null;
                }
            }
        }

        // probably last column but not sure, so continue
        if (getLocalizedString(CUMULATIVE_GRADE_STRING).equals(assignmentName)) {
            continue;
        }

        index++;

        // Get Assignment object from assignment name
        Assignment assignment = getAssignmentByName(grAssignments, assignmentName);
        List gradeRecords = new ArrayList();

        // if assignment == null, need to create a new one plus all the grade records
        // if exists, need find those that are changed and only apply those
        if (assignment == null) {

            if (pointsPossible != null) {
                // params: gradebook id, name of assignment, points possible, due date, NOT counted, is released
                assignmentId = getGradebookManager().createAssignment(getGradebookId(), assignmentName,
                        pointsPossible, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE);
                assignment = getGradebookManager().getAssignment(assignmentId);
            } else {
                // for this version, display error message saying non-match between import
                // and current gradebook assignments
                hasUnknownAssignments = true;
                unknownAssignments.add(assignmentName);

                continue;
            }

            Iterator it = studentRows.iterator();

            if (logger.isDebugEnabled())
                logger.debug("number of student rows " + studentRows.size());
            int i = 1;

            while (it.hasNext()) {
                if (logger.isDebugEnabled())
                    logger.debug("row " + i);
                SpreadsheetRow row = (SpreadsheetRow) it.next();
                List line = row.getRowcontent();

                String userid = "";
                String user = (String) line.get(0);
                try {
                    userid = ((User) rosterMap.get(user)).getUserUid();
                } catch (Exception e) {
                    if (logger.isDebugEnabled())
                        logger.debug("user " + user + "is not known to the system");
                    userid = "";
                    // checked when imported from user's system so should not happen at this point.
                }

                if (line.size() > index) {
                    String inputScore = (String) line.get(index);

                    if (inputScore != null && inputScore.trim().length() > 0) {
                        Double scoreAsDouble = null;
                        String scoreAsString = inputScore.trim();

                        AssignmentGradeRecord asnGradeRecord = new AssignmentGradeRecord(assignment, userid,
                                null);

                        // truncate input points/% to 2 decimal places
                        if (getGradeEntryByPoints() || getGradeEntryByPercent()) {
                            try {
                                scoreAsDouble = convertStringToDouble(scoreAsString);
                                scoreAsDouble = new Double(
                                        FacesUtil.getRoundDown(scoreAsDouble.doubleValue(), 2));
                                asnGradeRecord.setPercentEarned(scoreAsDouble);
                                asnGradeRecord.setPointsEarned(scoreAsDouble);
                                gradeRecords.add(asnGradeRecord);
                                if (logger.isDebugEnabled())
                                    logger.debug("user " + user + " userid " + userid + " score "
                                            + inputScore.toString());
                            } catch (ParseException pe) {
                                // this should have been caught during validation, so there is a problem
                                logger.error("ParseException encountered parsing " + scoreAsString);
                            }
                        } else if (getGradeEntryByLetter()) {
                            scoreAsString = (String) inputScore;

                            asnGradeRecord.setLetterEarned(scoreAsString.trim());
                            gradeRecords.add(asnGradeRecord);
                            if (logger.isDebugEnabled())
                                logger.debug("user " + user + " userid " + userid + " score "
                                        + inputScore.toString());
                        }
                    }
                }

                i++;
            }

            gbUpdated = true;
        } else {
            if (!assignment.getPointsPossible().equals(pointsPossible)) {
                if (assignment.isExternallyMaintained()) {
                    externallyMaintainedImportMsg
                            .append(getLocalizedString("import_assignment_externally_maintained_settings",
                                    new String[] { Validator.escapeHtml(assignment.getName()),
                                            Validator.escapeHtml(assignment.getExternalAppName()) })
                                    + "<br />");
                } else if (pointsPossible != null) {
                    assignment.setPointsPossible(pointsPossible);
                    getGradebookManager().updateAssignment(assignment);
                    gbUpdated = true;
                }
            }

            gradeRecords = gradeChanges(assignment, studentRows, index + 1, lgpm);

            if (gradeRecords.size() == 0)
                continue; // no changes to current grade record so go to next one
            else {
                gbUpdated = true;
            }
        }

        getGradebookManager().updateAssignmentGradeRecords(assignment, gradeRecords,
                getGradebook().getGrade_type());
        getGradebookBean().getEventTrackingService().postEvent("gradebook.importEntire",
                "/gradebook/" + getGradebookId() + "/" + assignment.getName() + "/" + getAuthzLevel());
    }

    // just in case previous attempt had unknown users
    hasUnknownUser = false;
    if (gbUpdated) {
        if (!hasUnknownAssignments) {
            FacesUtil.addRedirectSafeMessage(getLocalizedString(IMPORT_SUCCESS_STRING));
        } else {
            FacesUtil.addRedirectSafeMessage(getLocalizedString(IMPORT_SOME_SUCCESS_STRING));
        }
    } else if (!hasUnknownAssignments) {
        FacesUtil.addRedirectSafeMessage(getLocalizedString(IMPORT_NO_CHANGES));
    }

    this.setPageName("spreadsheetAll");
    return "spreadsheetAll";
}

From source file:org.n52.ifgicopter.spf.output.kml.KmlOutputPlugin.java

private void handleNewSensor(String id, Double lat, Double lon, Double alt, Map<String, Object> data) {
    try {/*ww  w  .j  a v a  2s .com*/
        /*
         * create new file for the sensor
         */
        String kmlFileName = getFilename(id, KmlConstants.KML_FILE_EXTENSION);
        log.info("Creating KML document " + kmlFileName);
        KmlDocument kmlDoc = KmlDocument.Factory.newInstance();
        KmlType kml = kmlDoc.addNewKml();
        this.sensorDocuments.put(id, kmlDoc);

        // <Style id="golf-balloon-style"> <BalloonStyle> <text> <![CDATA[ This is $[name] This is hole
        // $[holeNumber] The par for this hole is $[holePar] The yardage is $[holeYardage] ]]> </text>
        // </BalloonStyle> </Style>

        /*
         * add document
         */
        AbstractFeatureType abstractFeatureGroup = kml.addNewAbstractFeatureGroup();
        DocumentType document = (DocumentType) abstractFeatureGroup
                .substitute(new QName(KmlConstants.KML_NAMESPACE_URI, "Document"), DocumentType.type);
        String cleanId = XmlUtils.cleanIdentifier(id);
        document.setDescription("KML Visualisation of sensor " + id + " using cleaned identifier " + cleanId);

        document.setId("doc_" + cleanId);
        document.setName("Sensor " + id);
        document.setVisibility(true);

        /*
         * style
         */
        /*
         * TODO add styling and make editable in GUI: thicker lines, more sensor-like icon
         */
        AbstractStyleSelectorType abstractStyleSelectorGroup = document.addNewAbstractStyleSelectorGroup();
        StyleType style = (StyleType) abstractStyleSelectorGroup
                .substitute(new QName(KmlConstants.KML_NAMESPACE_URI, "Style"), StyleType.type);
        style.setId(KmlStyle.MD_ICON_STYLE);
        IconStyleType iconType = style.addNewIconStyle();
        BasicLinkType icon = iconType.addNewIcon();
        icon.setHref("md-png.png");

        /*
         * set a default view
         */
        AbstractViewType abstractViewGroup = document.addNewAbstractViewGroup();
        LookAtType lookAt = (LookAtType) abstractViewGroup
                .substitute(new QName(KmlConstants.KML_NAMESPACE_URI, "LookAt"), LookAtType.type);
        lookAt.setLatitude(lat.doubleValue());
        lookAt.setLongitude(lon.doubleValue());
        lookAt.setAltitude(alt.doubleValue());

        /*
         * add schema for extended data, see
         * https://developers.google.com/kml/documentation/kmlreference#trackexample
         */
        SchemaType schema = document.addNewSchema();
        schema.setName("DataSchema");
        schema.setId("DataSchemaId"); // schema.setId(getDataSchemaIdentifier(id));

        Set<Entry<String, Object>> dataEntries = data.entrySet();
        for (Entry<String, Object> entry : dataEntries) {
            XmlObject schemaExtension = schema.addNewSchemaExtension();
            SimpleArrayFieldType simpleArrayFieldType = (SimpleArrayFieldType) schemaExtension.substitute(
                    new QName(GxConstants.GX_NAMESPACE_URI, "SimpleArrayField"), SimpleArrayFieldType.type);
            simpleArrayFieldType.setName(entry.getKey().toLowerCase());
            simpleArrayFieldType.setType("string");
            simpleArrayFieldType.setDisplayName(entry.getKey());
        }

        /*
         * add placemark holding a track
         */
        abstractFeatureGroup = document.addNewAbstractFeatureGroup();
        PlacemarkType placemark = (PlacemarkType) abstractFeatureGroup
                .substitute(new QName(KmlConstants.KML_NAMESPACE_URI, "Placemark"), PlacemarkType.type);
        AbstractGeometryType abstractGeometryGroup = placemark.addNewAbstractGeometryGroup();
        TrackType track = (TrackType) abstractGeometryGroup
                .substitute(new QName(GxConstants.GX_NAMESPACE_URI, "Track"), TrackType.type);
        // style
        placemark.setStyleUrl("#" + KmlStyle.MD_ICON_STYLE);

        // altitudeMode
        XmlCursor cur = track.newCursor();
        cur.toNextToken();
        cur.insertElementWithText(new QName(KmlConstants.KML_NAMESPACE_URI, "altitudeMode", "kml"),
                "relativeToGround");
        cur.dispose();

        this.sensorTracks.put(id, track);

        /*
         * add SimpleArrayData for storing the values
         */
        this.sensorData.put(id, new HashMap<String, SimpleArrayDataType>());
        ExtendedDataType extendedData = track.addNewExtendedData();
        SchemaDataType schemaData = extendedData.addNewSchemaData();
        schemaData.setSchemaUrl("DataSchemaId"); // schemaData.setSchemaUrl("#" +
        // getDataSchemaIdentifier(id));
        for (Entry<String, Object> entry : dataEntries) {
            XmlObject schemaDataExtension = schemaData.addNewSchemaDataExtension();
            SimpleArrayDataType simpleArrayDataType = (SimpleArrayDataType) schemaDataExtension.substitute(
                    new QName(GxConstants.GX_NAMESPACE_URI, "SimpleArrayData"), SimpleArrayDataType.type);
            simpleArrayDataType.setName(entry.getKey());
            // no values yet, but save for later reference
            this.sensorData.get(id).put(entry.getKey(), simpleArrayDataType);
            log.debug("Added SimpleArrayData for " + entry.getKey() + " to SchemaData "
                    + schemaData.getSchemaUrl());
        }

        // save file for the sensor
        addKmlAndGxSchemaLocation(kml);
        saveDocumentInFile(kmlDoc, getFilepath(kmlFileName));

        /*
         * add new sensor file to dynamic file
         */
        abstractFeatureGroup = this.kmlFolder.addNewAbstractFeatureGroup();
        NetworkLinkType rootToDynamicNetworkLink = (NetworkLinkType) abstractFeatureGroup
                .substitute(new QName(KmlConstants.KML_NAMESPACE_URI, "NetworkLink"), NetworkLinkType.type);
        rootToDynamicNetworkLink.setName("Link to " + id);
        rootToDynamicNetworkLink.setId("link_" + id);
        LinkType rootToDynamicLink = rootToDynamicNetworkLink.addNewLink2();

        rootToDynamicLink.setHref(kmlFileName);
        rootToDynamicLink.setId("link_" + id);
        rootToDynamicLink.setRefreshMode(RefreshModeEnumType.ON_INTERVAL);
        rootToDynamicLink.setRefreshInterval(DEFAULT_REFRESH_INTERVAL);
        rootToDynamicLink.setViewRefreshMode(ViewRefreshModeEnumType.ON_STOP);
        rootToDynamicLink.setViewRefreshTime(DEFAULT_REFRESH_INTERVAL);
    } catch (Exception e) {
        log.error(e);
        return;
    }

    // save file with sensor list
    saveDocumentInFile(this.kmlDynamicRoot,
            getFilepath(getFilename(DYNAMIC_ROOT_FILENAME, KmlConstants.KML_FILE_EXTENSION)));
}

From source file:org.sakaiproject.component.gradebook.GradebookServiceHibernateImpl.java

private boolean isGradeValid(String grade, int gradeEntryType, LetterGradePercentMapping gradeMapping) {

    boolean gradeIsValid = false;

    if (grade == null || "".equals(grade)) {

        gradeIsValid = true;//from  w  w  w  .  j  a v a  2s  .c  o m

    } else {

        if (gradeEntryType == GradebookService.GRADE_TYPE_POINTS
                || gradeEntryType == GradebookService.GRADE_TYPE_PERCENTAGE) {
            try {
                Double gradeAsDouble = Double.parseDouble(grade);
                // grade must be greater than or equal to 0
                if (gradeAsDouble.doubleValue() >= 0) {
                    // check that there are no more than 2 decimal places
                    String[] splitOnDecimal = grade.split("\\.");
                    if (splitOnDecimal == null || splitOnDecimal.length < 2) {
                        gradeIsValid = true;
                    } else if (splitOnDecimal.length == 2) {
                        String decimal = splitOnDecimal[1];
                        if (decimal.length() <= 2) {
                            gradeIsValid = true;
                        }
                    }
                }
            } catch (NumberFormatException nfe) {
                if (log.isDebugEnabled())
                    log.debug("Passed grade is not a numeric value");
            }

        } else if (gradeEntryType == GradebookService.GRADE_TYPE_LETTER) {
            if (gradeMapping == null) {
                throw new IllegalArgumentException(
                        "Null mapping passed to isGradeValid for a letter grade-based gradeook");
            }

            String standardizedGrade = gradeMapping.standardizeInputGrade(grade);
            if (standardizedGrade != null) {
                gradeIsValid = true;
            }
        } else {
            throw new IllegalArgumentException("Invalid gradeEntryType passed to isGradeValid");
        }
    }

    return gradeIsValid;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.student.onlineTests.StudentTestsAction.java

public ActionForward showTestCorrection(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws FenixActionException {

    String testCode = request.getParameter("testCode");
    final DistributedTest distributedTest = FenixFramework.getDomainObject(testCode);
    if (distributedTest == null) {
        request.setAttribute("invalidTest", new Boolean(true));
        return mapping.findForward("testError");
    }/*from ww  w. ja  va2 s  .c o m*/
    final Registration registration = getRegistration(request);
    if (registration == null) {
        request.setAttribute("invalidTest", new Boolean(true));
        return mapping.findForward("testError");
    }

    List<StudentTestQuestion> studentTestQuestionList = null;
    try {
        studentTestQuestionList = ReadStudentTest.runReadStudentTestForCorrection(registration, distributedTest,
                new Boolean(false));
    } catch (InvalidArgumentsServiceException e) {
        request.setAttribute("invalidTest", new Boolean(true));
        return mapping.findForward("testError");
    } catch (NotAuthorizedException e) {
        request.setAttribute("cantShowTestCorrection", new Boolean(true));
        return mapping.findForward("testError");
    } catch (FenixServiceException e) {
        throw new FenixActionException(e);
    }

    Collections.sort(studentTestQuestionList, StudentTestQuestion.COMPARATOR_BY_TEST_QUESTION_ORDER);
    request.setAttribute("studentTestQuestionList", studentTestQuestionList);

    Double classification = new Double(0);
    for (int i = 0; i < studentTestQuestionList.size(); i++) {
        StudentTestQuestion studentTestQuestion = studentTestQuestionList.get(i);
        if (studentTestQuestion.getSubQuestionByItem().getQuestionType().getType()
                .intValue() == QuestionType.STR) {
            ResponseSTR responseSTR = new ResponseSTR();
            responseSTR.setResponsed(false);
            if (studentTestQuestion.getResponse() != null
                    && ((ResponseSTR) studentTestQuestion.getResponse()).getResponse() != null) {
                responseSTR = ((ResponseSTR) studentTestQuestion.getResponse());
            }
            request.setAttribute("question" + i, responseSTR.getResponse());
        } else if (studentTestQuestion.getSubQuestionByItem().getQuestionType().getType()
                .intValue() == QuestionType.NUM) {
            ResponseNUM responseNUM = new ResponseNUM();
            responseNUM.setResponsed(false);
            if (studentTestQuestion.getResponse() != null
                    && ((ResponseNUM) studentTestQuestion.getResponse()).getResponse() != null) {
                responseNUM = (ResponseNUM) studentTestQuestion.getResponse();
            }
            request.setAttribute("question" + i, responseNUM.getResponse());
        } else if (studentTestQuestion.getSubQuestionByItem().getQuestionType().getType()
                .intValue() == QuestionType.LID) {
            ResponseLID responseLID = new ResponseLID();
            if (studentTestQuestion.getResponse() != null
                    && ((ResponseLID) studentTestQuestion.getResponse()).getResponse() != null) {
                responseLID = (ResponseLID) studentTestQuestion.getResponse();
                if (studentTestQuestion.getSubQuestionByItem().getQuestionType().getCardinalityType().getType()
                        .intValue() == CardinalityType.SINGLE) {
                    if (((ResponseLID) studentTestQuestion.getResponse()).getResponse().length != 0) {
                        request.setAttribute("question" + i, responseLID.getResponse()[0]);
                    }
                } else {
                    request.setAttribute("question" + i, responseLID.getResponse());
                }
            } else {
                request.setAttribute("question" + i, null);
            }
        }

        if (studentTestQuestion.getTestQuestionMark() != null) {
            classification = new Double(
                    classification.doubleValue() + studentTestQuestion.getTestQuestionMark().doubleValue());
        }
    }
    final DecimalFormat df = new DecimalFormat("#0.##");
    if (classification.doubleValue() < 0) {
        classification = new Double(0);
    }
    request.setAttribute("classification", df.format(classification));
    return mapping.findForward("showTestCorrection");
}