Example usage for java.math BigDecimal doubleValue

List of usage examples for java.math BigDecimal doubleValue

Introduction

In this page you can find the example usage for java.math BigDecimal doubleValue.

Prototype

@Override
public double doubleValue() 

Source Link

Document

Converts this BigDecimal to a double .

Usage

From source file:com.salesmanager.core.module.impl.integration.payment.PaypalTransactionImpl.java

/** This can be invoked after a sale transaction **/
//public GatewayTransactionVO refundTransaction(MerchantStore store,
//      Order order, BigDecimal amnt) throws TransactionException {

public GatewayTransactionVO refundTransaction(IntegrationKeys keys, IntegrationProperties properties,
        MerchantStore store, Order order, GatewayTransactionVO trx, Customer customer,
        CoreModuleService serviceDefinition, BigDecimal amnt) throws TransactionException {
    // TODO Auto-generated method stub

    try {//from ww  w  . j a v  a2s. c  om

        /*
         * '------------------------------------ ' The currencyCodeType and
         * paymentType ' are set to the selections made on the Integration
         * Assistant '------------------------------------
         */

        if (serviceDefinition == null) {
            // throw new
            // Exception("Central integration services not configured for "
            // + PaymentConstants.PAYMENT_LINKPOINTNAME + " and country id "
            // + origincountryid);
            log.error("Central integration services not configured for " + PaymentConstants.PAYMENT_PAYPALNAME
                    + " and country id " + store.getCountry());
            TransactionException te = new TransactionException(
                    "Central integration services not configured for " + PaymentConstants.PAYMENT_PAYPALNAME
                            + " and country id " + store.getCountry());
            te.setErrorcode("01");
            throw te;
        }

        String transactionId = trx.getTransactionID();

        if (transactionId == null) {
            throw new TransactionException("capture Paypal authorizationId is null in GatewayTransaction");
        }

        String amount = CurrencyUtil.displayFormatedAmountNoCurrency(amnt, Constants.CURRENCY_CODE_USD);

        // InetAddress addr = InetAddress.getLocalHost();

        // Get IP Address
        // byte[] ipAddr = addr.getAddress();

        // String ip = new String(ipAddr);

        // REQUEST
        // requiredSecurityParameters]&METHOD=RefundTransaction&AUTHORIZATIONID=
        // &AMT=99.12&REFUNDTYPE=Full|Partial

        // IPN
        // String ipnUrl = ReferenceUtil.buildSecureServerUrl() +
        // (String)conf.getString("core.salesmanager.checkout.paypalIpn");

        String refundType = "Full";
        boolean partial = false;
        if (amnt.doubleValue() < order.getTotal().doubleValue()) {
            partial = true;
        }
        if (partial) {
            refundType = "Partial";
        }

        // String nvpstr = "&TRANSACTIONID=" + transactionId +
        // "&REFUNDTYPE=" + refundType + "&IPADDRESS=" + ip.toString();
        String nvpstr = "&TRANSACTIONID=" + transactionId + "&REFUNDTYPE=" + refundType + "&CURRENCYCODE="
                + order.getCurrency() + "&IPADDRESS=";

        if (amnt.floatValue() < order.getTotal().floatValue()) {
            partial = true;
        }

        if (partial) {
            nvpstr = nvpstr + "&AMT=" + amount + "&NOTE=Partial refund";
        }

        Map nvp = httpcall(properties, serviceDefinition, "RefundTransaction", nvpstr);
        String strAck = nvp.get("ACK").toString();
        if (strAck != null && strAck.equalsIgnoreCase("Success")) {

            /**
             * RESPONSE
             * [successResponseFields]&AUTHORIZATIONID=
             * &TRANSACTIONID
             * =&PARENTTRANSACTIONID=
             * &RECEIPTID
             * =&TRANSACTIONTYPE=express-checkout
             * &PAYMENTTYPE=instant&ORDERTIME=2006-08-15T17:31:38Z&AMT=99.12
             * &CURRENCYCODE=USD&FEEAMT=3.29&TAXAMT=0.00&PAYMENTSTATUS=
             * Completed &PENDINGREASON=None&REASONCODE=None
             **/

            String responseTransactionId = (String) nvp.get("REFUNDTRANSACTIONID");
            String responseAuthorizationId = (String) nvp.get("REFUNDTRANSACTIONID");

            try {

                Iterator it = nvp.keySet().iterator();
                StringBuffer valueBuffer = new StringBuffer();
                while (it.hasNext()) {
                    String key = (String) it.next();
                    valueBuffer.append("[").append(key).append("=").append((String) nvp.get(key)).append("]");
                }

                MerchantPaymentGatewayTrx gtrx = new MerchantPaymentGatewayTrx();
                gtrx.setMerchantId(order.getMerchantId());
                gtrx.setCustomerid(order.getCustomerId());
                gtrx.setOrderId(order.getOrderId());
                gtrx.setAmount(amnt);
                gtrx.setMerchantPaymentGwMethod(order.getPaymentModuleCode());
                gtrx.setMerchantPaymentGwRespcode(strAck);
                gtrx.setMerchantPaymentGwOrderid(responseAuthorizationId);// AUTHORIZATIONID
                gtrx.setMerchantPaymentGwTrxid(responseTransactionId);// TRANSACTIONID
                gtrx.setMerchantPaymentGwAuthtype(String.valueOf(PaymentConstants.REFUND));
                gtrx.setMerchantPaymentGwSession("");

                // String cryptedvalue =
                // EncryptionUtil.encrypt(EncryptionUtil.generatekey(String.valueOf(order.getMerchantId())),
                // nvpstr);
                gtrx.setMerchantPaymentGwSent(nvpstr);
                gtrx.setMerchantPaymentGwReceived(valueBuffer.toString());
                gtrx.setDateAdded(new Date(new Date().getTime()));

                PaymentService pservice = (PaymentService) ServiceFactory
                        .getService(ServiceFactory.PaymentService);
                pservice.saveMerchantPaymentGatewayTrx(gtrx);

                GatewayTransactionVO returnVo = new GatewayTransactionVO();
                returnVo.setAmount(order.getTotal());
                returnVo.setCreditcard("");
                returnVo.setCreditcardtransaction(false);
                returnVo.setExpirydate("");
                returnVo.setInternalGatewayOrderId(responseTransactionId);
                returnVo.setTransactionDetails(gtrx);
                returnVo.setOrderID(String.valueOf(order.getOrderId()));
                returnVo.setTransactionID(responseTransactionId);

                returnVo.setTransactionMessage((String) nvp.get("RESPONSE"));

                return returnVo;

                // insert an off system gateway transaction
                // for IPN usage

                // OffsystemPendingOrder pending = new
                // OffsystemPendingOrder();
                // pending.setOrderId(order.getOrderId());
                // pending.setTransactionId(payerID);
                // pending.setPayerEmail(order.getCustomerEmailAddress());
                // pservice.saveOrUpdateOffsystemPendingOrder(pending,
                // order);

            } catch (Exception e) {
                TransactionException te = new TransactionException(
                        "Can't persist MerchantPaymentGatewayTrx internal id (orderid)" + order.getOrderId(),
                        e);
                te.setErrorcode("01");
                throw te;
            }

        } else {

            String ErrorCode = nvp.get("L_ERRORCODE0").toString();
            String ErrorShortMsg = nvp.get("L_SHORTMESSAGE0").toString();
            String ErrorLongMsg = nvp.get("L_LONGMESSAGE0").toString();
            String ErrorSeverityCode = nvp.get("L_SEVERITYCODE0").toString();

            TransactionException te = new TransactionException("Paypal transaction refused " + ErrorLongMsg);
            te.setErrorType(ErrorConstants.PAYMENT_TRANSACTION_ERROR);
            LogMerchantUtil.log(order.getMerchantId(),
                    "Paypal transaction error code[" + ErrorCode + "] " + ErrorLongMsg);
            if (ErrorCode.equals("10415")) {// transaction already submited
                te = new TransactionException("Paypal transaction refused " + ErrorLongMsg);
                te.setErrorType(ErrorConstants.PAYMENT_DUPLICATE_TRANSACTION);
            }

            throw te;
        }

    } catch (Exception e) {
        if (e instanceof TransactionException) {
            throw (TransactionException) e;
        }
        throw new TransactionException(e);
    }

}

From source file:com.viettel.logistic.wms.dao.StockGoodsSerialStripDAO.java

public Double getAmountInStockGoodsTotal(ChangePositionDTO changePositionDTO) {
    StringBuilder sql = new StringBuilder();
    sql.append("       SELECT   sum(a.quantity) ");
    sql.append("       FROM   wms_owner.stock_goods_serial_strip a");
    sql.append("       WHERE       a.goods_id = ? ");
    sql.append("            AND a.owner_type = ? ");
    sql.append("            AND a.owner_id = ? ");
    sql.append("            AND a.cust_id = ? ");
    sql.append("            AND a.cell_code = ? ");
    sql.append("            AND a.status = '1' ");
    List lstParams = new ArrayList<>();
    lstParams.add(changePositionDTO.getGoodsId());
    lstParams.add(changePositionDTO.getOwnerType());
    lstParams.add(changePositionDTO.getStockId());
    lstParams.add(changePositionDTO.getCustomerId());
    lstParams.add(changePositionDTO.getCellCodeOld());
    if (!DataUtil.isStringNullOrEmpty(changePositionDTO.getBarcode())) {
        sql.append("            AND a.barcode = ? ");
        lstParams.add(changePositionDTO.getBarcode());
    }//from   w  w w.j  a  v  a2s.  c o  m
    SQLQuery query = getSession().createSQLQuery(sql.toString());
    for (int idx = 0; idx < lstParams.size(); idx++) {
        query.setParameter(idx, lstParams.get(idx));
    }
    List listResult = query.list();
    BigDecimal result;
    if (listResult != null && listResult.size() > 0) {
        result = (BigDecimal) listResult.get(0);
        return result.doubleValue();
    }
    return 0D;
}

From source file:com.wasteofplastic.acidisland.commands.IslandCmd.java

private void resetMoney(Player player) {
    if (!Settings.useEconomy) {
        return;/*www .jav a2s  .  co m*/
    }
    // Set player's balance in acid island to the starting balance
    try {
        // plugin.getLogger().info("DEBUG: " + player.getName() + " " +
        // Settings.general_worldName);
        if (VaultHelper.econ == null) {
            // plugin.getLogger().warning("DEBUG: econ is null!");
            VaultHelper.setupEconomy();
        }
        Double playerBalance = VaultHelper.econ.getBalance(player, Settings.worldName);
        // plugin.getLogger().info("DEBUG: playerbalance = " +
        // playerBalance);
        // Round the balance to 2 decimal places and slightly down to
        // avoid issues when withdrawing the amount later
        BigDecimal bd = new BigDecimal(playerBalance);
        bd = bd.setScale(2, RoundingMode.HALF_DOWN);
        playerBalance = bd.doubleValue();
        // plugin.getLogger().info("DEBUG: playerbalance after rounding = "
        // + playerBalance);
        if (playerBalance != Settings.startingMoney) {
            if (playerBalance > Settings.startingMoney) {
                Double difference = playerBalance - Settings.startingMoney;
                EconomyResponse response = VaultHelper.econ.withdrawPlayer(player, Settings.worldName,
                        difference);
                // plugin.getLogger().info("DEBUG: withdrawn");
                if (response.transactionSuccess()) {
                    plugin.getLogger()
                            .info("FYI:" + player.getName() + " had " + VaultHelper.econ.format(playerBalance)
                                    + " when they typed /island and it was set to " + Settings.startingMoney);
                } else {
                    plugin.getLogger().warning("Problem trying to withdraw " + playerBalance + " from "
                            + player.getName() + "'s account when they typed /island!");
                    plugin.getLogger().warning("Error from economy was: " + response.errorMessage);
                }
            } else {
                Double difference = Settings.startingMoney - playerBalance;
                EconomyResponse response = VaultHelper.econ.depositPlayer(player, Settings.worldName,
                        difference);
                if (response.transactionSuccess()) {
                    plugin.getLogger()
                            .info("FYI:" + player.getName() + " had " + VaultHelper.econ.format(playerBalance)
                                    + " when they typed /island and it was set to " + Settings.startingMoney);
                } else {
                    plugin.getLogger().warning("Problem trying to deposit " + playerBalance + " from "
                            + player.getName() + "'s account when they typed /island!");
                    plugin.getLogger().warning("Error from economy was: " + response.errorMessage);
                }

            }
        }
    } catch (final Exception e) {
        plugin.getLogger()
                .severe("Error trying to zero " + player.getName() + "'s account when they typed /island!");
        plugin.getLogger().severe(e.getMessage());
    }

}

From source file:controller.ChartAndGraphServlet.java

/**
 * Creates the appropriate chart for the patient history page or the
 * statistics page. Line charts are created to display a longitudinal view
 * of patient results on the history page. The statistics page includes pie
 * charts, bar charts, histograms, and box and whisker charts.
 *
 * @param request servlet request/*from w  ww . j  ava  2 s.c  o m*/
 * @param response servlet response
 * @throws IOException
 */
public void getChart(HttpServletRequest request, HttpServletResponse response) throws IOException {
    HttpSession session = request.getSession();
    response.setContentType("image/png");
    OutputStream outputStream = response.getOutputStream();
    final int widthIncreaseThreshold = 18;
    final int incrementalIncreaseThreshold = 22;
    final int incrementalIncreaseInPixels = 45;
    final int treatmentClassUnknownIndex = 6;
    int width = 640;
    int height = 450;
    int bigWidth = 780;
    ReferenceContainer rc = (ReferenceContainer) session.getServletContext().getAttribute("references");
    HealthyTargetReference htr = rc.getHealthyTargets();
    String action = request.getParameter("action");

    switch (action) {
    case "a1c": {
        ArrayList<A1cResult> a1cHistory = (ArrayList<A1cResult>) session
                .getAttribute(SessionObjectUtility.A1C_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = a1cHistory.size() - 1; i > -1; i--) {
            dataset.addValue(a1cHistory.get(i).getValue(), "A1C", a1cHistory.get(i).getDate());
        }
        /* remove reference */
        session.setAttribute(SessionObjectUtility.A1C_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("A1C History", "dates", "A1C", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getA1c().getUpperBound();
        BigDecimal lower = htr.getA1c().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (a1cHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (a1cHistory.size() > incrementalIncreaseThreshold) {
            int increments = a1cHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "psa": {
        ArrayList<ContinuousResult> psaHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.PSA_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = psaHistory.size() - 1; i > -1; i--) {
            dataset.addValue(psaHistory.get(i).getValue(), "PSA", psaHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.PSA_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("PSA History", "dates", "PSA", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getPsa().getUpperBound();
        BigDecimal lower = htr.getPsa().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (psaHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (psaHistory.size() > incrementalIncreaseThreshold) {
            int increments = psaHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "alt": {
        ArrayList<ContinuousResult> altHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.ALT_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = altHistory.size() - 1; i > -1; i--) {
            dataset.addValue(altHistory.get(i).getValue(), "ALT", altHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.ALT_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("ALT History", "dates", "ALT", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getAlt().getUpperBound();
        BigDecimal lower = htr.getAlt().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (altHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (altHistory.size() > incrementalIncreaseThreshold) {
            int increments = altHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "ast": {
        ArrayList<ContinuousResult> astHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.AST_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = astHistory.size() - 1; i > -1; i--) {
            dataset.addValue(astHistory.get(i).getValue(), "AST", astHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.AST_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("AST History", "dates", "AST", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getAst().getUpperBound();
        BigDecimal lower = htr.getAst().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (astHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (astHistory.size() > incrementalIncreaseThreshold) {
            int increments = astHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "bp": {
        ArrayList<BloodPressureResult> bpHistory = (ArrayList<BloodPressureResult>) session
                .getAttribute(SessionObjectUtility.BP_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = bpHistory.size() - 1; i > -1; i--) {
            dataset.addValue(bpHistory.get(i).getSystolicValue(), "systolic", bpHistory.get(i).getDate());
            dataset.addValue(bpHistory.get(i).getDiastolicValue(), "diastolic", bpHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.BP_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Blood Pressure History", "dates", "blood pressure",
                dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upperSystole = htr.getBloodPressureSystole().getUpperBound();
        BigDecimal upperDiastole = htr.getBloodPressureDiastole().getUpperBound();
        if (upperSystole != null) {
            ValueMarker marker = new ValueMarker(upperSystole.doubleValue());
            marker.setPaint(Color.MAGENTA);
            plot.addRangeMarker(marker);
        }
        if (upperDiastole != null) {
            ValueMarker marker = new ValueMarker(upperDiastole.doubleValue());
            marker.setPaint(Color.BLUE);
            plot.addRangeMarker(marker);
        }

        if (bpHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (bpHistory.size() > incrementalIncreaseThreshold) {
            int increments = bpHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "bmi": {
        ArrayList<ContinuousResult> bmiHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.BMI_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = bmiHistory.size() - 1; i > -1; i--) {
            dataset.addValue(bmiHistory.get(i).getValue(), "BMI", bmiHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.BMI_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("BMI History", "dates", "BMI", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getBmi().getUpperBound();
        BigDecimal lower = htr.getBmi().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (bmiHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (bmiHistory.size() > incrementalIncreaseThreshold) {
            int increments = bmiHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "creatinine": {
        ArrayList<ContinuousResult> creatinineHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.CREATININE_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = creatinineHistory.size() - 1; i > -1; i--) {
            dataset.addValue(creatinineHistory.get(i).getValue(), "creatinine",
                    creatinineHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.CREATININE_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Creatinine History", "dates", "creatinine", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getCreatinine().getUpperBound();
        BigDecimal lower = htr.getCreatinine().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (creatinineHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (creatinineHistory.size() > incrementalIncreaseThreshold) {
            int increments = creatinineHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "egfr": {
        ArrayList<ContinuousResult> egfrHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.EGFR_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = egfrHistory.size() - 1; i > -1; i--) {
            dataset.addValue(egfrHistory.get(i).getValue(), "eGFR", egfrHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.EGFR_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("eGFR History", "dates", "eGFR", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getEgfr().getUpperBound();
        BigDecimal lower = htr.getEgfr().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (egfrHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (egfrHistory.size() > incrementalIncreaseThreshold) {
            int increments = egfrHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "glucose": {
        ArrayList<ContinuousResult> glucoseHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.GLUCOSE_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = glucoseHistory.size() - 1; i > -1; i--) {
            dataset.addValue(glucoseHistory.get(i).getValue(), "glucose", glucoseHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.GLUCOSE_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Glucose History", "dates", "glucose", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getGlucoseAc().getUpperBound();
        BigDecimal lower = htr.getGlucoseAc().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (glucoseHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (glucoseHistory.size() > incrementalIncreaseThreshold) {
            int increments = glucoseHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "hdl": {
        ArrayList<ContinuousResult> hdlHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.HDL_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = hdlHistory.size() - 1; i > -1; i--) {
            dataset.addValue(hdlHistory.get(i).getValue(), "HDL", hdlHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.HDL_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /*get the chart */
        JFreeChart chart = ChartFactory.createLineChart("HDL History", "dates", "HDL", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upperFemale = htr.getHdlFemale().getUpperBound();
        BigDecimal lowerFemale = htr.getHdlFemale().getLowerBound();
        BigDecimal upperMale = htr.getHdlMale().getUpperBound();
        BigDecimal lowerMale = htr.getHdlMale().getLowerBound();
        if (upperFemale != null) {
            ValueMarker marker = new ValueMarker(upperFemale.doubleValue());
            marker.setPaint(Color.MAGENTA);
            plot.addRangeMarker(marker);
        }
        if (lowerFemale != null) {
            ValueMarker marker = new ValueMarker(lowerFemale.doubleValue());
            marker.setPaint(Color.MAGENTA);
            plot.addRangeMarker(marker);
        }
        if (upperMale != null) {
            ValueMarker marker = new ValueMarker(upperMale.doubleValue());
            marker.setPaint(Color.BLUE);
            plot.addRangeMarker(marker);
        }
        if (lowerMale != null) {
            ValueMarker marker = new ValueMarker(lowerMale.doubleValue());
            marker.setPaint(Color.BLUE);
            plot.addRangeMarker(marker);
        }

        if (hdlHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (hdlHistory.size() > incrementalIncreaseThreshold) {
            int increments = hdlHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "ldl": {
        ArrayList<LdlResult> ldlHistory = (ArrayList<LdlResult>) session
                .getAttribute(SessionObjectUtility.LDL_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = ldlHistory.size() - 1; i > -1; i--) {
            dataset.addValue(ldlHistory.get(i).getValue(), "LDL", ldlHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.LDL_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("LDL History", "dates", "LDL", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getLdl().getUpperBound();
        BigDecimal lower = htr.getLdl().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (ldlHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (ldlHistory.size() > incrementalIncreaseThreshold) {
            int increments = ldlHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "compliance": {
        ArrayList<ContinuousResult> complianceHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.COMPLIANCE_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = complianceHistory.size() - 1; i > -1; i--) {
            dataset.addValue(complianceHistory.get(i).getValue(), "compliance",
                    complianceHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.COMPLIANCE_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Compliance History", "dates", "compliance", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        if (complianceHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (complianceHistory.size() > incrementalIncreaseThreshold) {
            int increments = complianceHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "physicalActivity": {
        ArrayList<DiscreteResult> physicalActivityHistory = (ArrayList<DiscreteResult>) session
                .getAttribute(SessionObjectUtility.PHYSICAL_ACTIVITY_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = physicalActivityHistory.size() - 1; i > -1; i--) {
            dataset.addValue(physicalActivityHistory.get(i).getValue(), "physical activity",
                    physicalActivityHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.PHYSICAL_ACTIVITY_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Physical Activity History", "dates", "min per wk",
                dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getPhysicalActivity().getUpperBound();
        BigDecimal lower = htr.getPhysicalActivity().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (physicalActivityHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (physicalActivityHistory.size() > incrementalIncreaseThreshold) {
            int increments = physicalActivityHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "psychological": {
        ArrayList<PsychologicalScreeningResult> psychologicalHistory = (ArrayList<PsychologicalScreeningResult>) session
                .getAttribute(SessionObjectUtility.PSYCHOLOGICAL_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = psychologicalHistory.size() - 1; i > -1; i--) {
            dataset.addValue(psychologicalHistory.get(i).getScore(), "PHQ9 score",
                    psychologicalHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.PSYCHOLOGICAL_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Psychological Screening History", "dates", "score",
                dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        if (psychologicalHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (psychologicalHistory.size() > incrementalIncreaseThreshold) {
            int increments = psychologicalHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "t4": {
        ArrayList<ContinuousResult> t4History = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.T4_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = t4History.size() - 1; i > -1; i--) {
            dataset.addValue(t4History.get(i).getValue(), "T4", t4History.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.T4_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("T4 History", "dates", "T4", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getT4().getUpperBound();
        BigDecimal lower = htr.getT4().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (t4History.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (t4History.size() > incrementalIncreaseThreshold) {
            int increments = t4History.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "triglycerides": {
        ArrayList<ContinuousResult> triglyceridesHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.TRIGLYCERIDES_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = triglyceridesHistory.size() - 1; i > -1; i--) {
            dataset.addValue(triglyceridesHistory.get(i).getValue(), "triglycerides",
                    triglyceridesHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.TRIGLYCERIDES_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Triglycerides History", "dates", "triglycerides",
                dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getTriglycerides().getUpperBound();
        BigDecimal lower = htr.getTriglycerides().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (triglyceridesHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (triglyceridesHistory.size() > incrementalIncreaseThreshold) {
            int increments = triglyceridesHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "tsh": {
        ArrayList<TshResult> tshHistory = (ArrayList<TshResult>) session
                .getAttribute(SessionObjectUtility.TSH_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = tshHistory.size() - 1; i > -1; i--) {
            dataset.addValue(tshHistory.get(i).getValue(), "TSH", tshHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.TSH_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("TSH History", "dates", "TSH", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getTsh().getUpperBound();
        BigDecimal lower = htr.getTsh().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (tshHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (tshHistory.size() > incrementalIncreaseThreshold) {
            int increments = tshHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "uacr": {
        ArrayList<ContinuousResult> uacrHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.UACR_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = uacrHistory.size() - 1; i > -1; i--) {
            dataset.addValue(uacrHistory.get(i).getValue(), "UACR", uacrHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.UACR_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("UACR History", "dates", "UACR", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upper = htr.getUacr().getUpperBound();
        BigDecimal lower = htr.getUacr().getLowerBound();
        if (upper != null) {
            ValueMarker marker = new ValueMarker(upper.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }
        if (lower != null) {
            ValueMarker marker = new ValueMarker(lower.doubleValue());
            marker.setPaint(Color.YELLOW);
            plot.addRangeMarker(marker);
        }

        if (uacrHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (uacrHistory.size() > incrementalIncreaseThreshold) {
            int increments = uacrHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "waist": {
        ArrayList<ContinuousResult> waistHistory = (ArrayList<ContinuousResult>) session
                .getAttribute(SessionObjectUtility.WAIST_GRAPH_POINTS);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        /* add the data */
        for (int i = waistHistory.size() - 1; i > -1; i--) {
            dataset.addValue(waistHistory.get(i).getValue(), "waist", waistHistory.get(i).getDate());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.WAIST_GRAPH_POINTS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createLineChart("Waist History", "dates", "waist", dataset,
                PlotOrientation.VERTICAL, legend, tooltips, urls);

        /* angle the x-axis labels */
        CategoryPlot plot = chart.getCategoryPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        /* show the healthy target boundaries */
        BigDecimal upperFemale = htr.getWaistFemale().getUpperBound();
        BigDecimal lowerFemale = htr.getWaistFemale().getLowerBound();
        BigDecimal upperMale = htr.getWaistMale().getUpperBound();
        BigDecimal lowerMale = htr.getWaistMale().getLowerBound();
        if (upperFemale != null) {
            ValueMarker marker = new ValueMarker(upperFemale.doubleValue());
            marker.setPaint(Color.MAGENTA);
            plot.addRangeMarker(marker);
        }
        if (lowerFemale != null) {
            ValueMarker marker = new ValueMarker(lowerFemale.doubleValue());
            marker.setPaint(Color.MAGENTA);
            plot.addRangeMarker(marker);
        }
        if (upperMale != null) {
            ValueMarker marker = new ValueMarker(upperMale.doubleValue());
            marker.setPaint(Color.BLUE);
            plot.addRangeMarker(marker);
        }
        if (lowerMale != null) {
            ValueMarker marker = new ValueMarker(lowerMale.doubleValue());
            marker.setPaint(Color.BLUE);
            plot.addRangeMarker(marker);
        }

        if (waistHistory.size() > widthIncreaseThreshold) {
            width = bigWidth;
        }
        if (waistHistory.size() > incrementalIncreaseThreshold) {
            int increments = waistHistory.size() % incrementalIncreaseThreshold;
            for (int i = 0; i < increments; i++) {
                width += incrementalIncreaseInPixels;
            }
        }
        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "agedemographics": {
        DemographicData demographicData = (DemographicData) session
                .getAttribute(SessionObjectUtility.AGE_DEMOGRAPHICS_GRAPH_DATA);
        HistogramDataset dataset = new HistogramDataset();
        ArrayList<Integer> ages = demographicData.getAges();
        if (ages.size() > 0) {
            double[] vector = new double[ages.size()];

            for (int i = 0; i < vector.length; i++) {
                vector[i] = ages.get(i);
            }

            /* add the data */
            dataset.addSeries("number of patients", vector, 10);

            /* remove reference */
            session.setAttribute(SessionObjectUtility.AGE_DEMOGRAPHICS_GRAPH_DATA, null);

            boolean legend = true;
            boolean tooltips = false;
            boolean urls = false;

            /* get the chart */
            JFreeChart chart = ChartFactory.createHistogram("Age Distribution", "age", "number of patients",
                    dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

            chart.setBorderPaint(Color.GREEN);
            chart.setBorderStroke(new BasicStroke(5.0f));
            chart.setBorderVisible(true);

            XYPlot plot = chart.getXYPlot();

            final XYBarRenderer renderer = (XYBarRenderer) plot.getRenderer();

            /* creating a shadow */
            renderer.setShadowXOffset(4.0);
            renderer.setShadowYOffset(1.5);
            renderer.setShadowVisible(true);

            ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }
        break;
    }
    case "genderdemographics": {
        DemographicData demographicData = (DemographicData) session
                .getAttribute(SessionObjectUtility.GENDER_DEMOGRAPHICS_GRAPH_DATA);
        DefaultPieDataset dataset = new DefaultPieDataset();

        /* add the data */
        dataset.setValue("female", demographicData.getPercentFemale());
        dataset.setValue("male", demographicData.getPercentMale());

        /* remove reference */
        session.setAttribute(SessionObjectUtility.GENDER_DEMOGRAPHICS_GRAPH_DATA, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createPieChart3D("Gender", dataset, legend, tooltips, urls);

        final PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setStartAngle(90);
        plot.setForegroundAlpha(0.60f);
        plot.setInteriorGap(0.02);

        PieSectionLabelGenerator labels = new StandardPieSectionLabelGenerator("{0}: ({2})",
                new DecimalFormat("0"), new DecimalFormat("0%"));
        plot.setLabelGenerator(labels);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "racedemographics": {
        DemographicData demographicData = (DemographicData) session
                .getAttribute(SessionObjectUtility.RACE_DEMOGRAPHICS_GRAPH_DATA);
        DefaultPieDataset dataset = new DefaultPieDataset();

        /* add the data */
        dataset.setValue("White", demographicData.getPercentWhite());
        dataset.setValue("African American", demographicData.getPercentAfricanAmerican());
        dataset.setValue("Asian/Pacific Islander", demographicData.getPercentAsian());
        dataset.setValue("American Indian/Alaska Native", demographicData.getPercentIndian());
        dataset.setValue("Hispanic", demographicData.getPercentHispanic());
        dataset.setValue("Middle Eastern", demographicData.getPercentMiddleEastern());
        dataset.setValue("Other", demographicData.getPercentOther());

        /* remove reference */
        session.setAttribute(SessionObjectUtility.RACE_DEMOGRAPHICS_GRAPH_DATA, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createPieChart3D("Race", dataset, legend, tooltips, urls);

        final PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setStartAngle(90);
        plot.setForegroundAlpha(0.60f);
        plot.setInteriorGap(0.02);

        PieSectionLabelGenerator labels = new StandardPieSectionLabelGenerator("{0}: ({2})",
                new DecimalFormat("0"), new DecimalFormat("0%"));
        plot.setLabelGenerator(labels);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "lasta1c": {
        Stats glycemicStats = (Stats) session.getAttribute(SessionObjectUtility.LAST_A1C_DATA);
        HistogramDataset dataset = new HistogramDataset();
        ArrayList<CategoricalValue> lastA1cValues = new ArrayList<>();

        if (glycemicStats.getGroups() != null) {
            int i;
            for (i = 0; i < glycemicStats.getGroups().size(); i++) {
                if (glycemicStats.getGroups().get(i) != null) {
                    lastA1cValues.addAll(glycemicStats.getGroups().get(i));
                }
            }
        }
        if (lastA1cValues.size() > 0) {
            double[] vector = new double[lastA1cValues.size()];

            for (int i = 0; i < vector.length; i++) {
                vector[i] = lastA1cValues.get(i).getValue().doubleValue();
            }

            /* add the data */
            dataset.addSeries("number of patients", vector, 15);

            /* remove reference */
            session.setAttribute(SessionObjectUtility.LAST_A1C_DATA, null);

            boolean legend = true;
            boolean tooltips = false;
            boolean urls = false;

            /* get the chart */
            JFreeChart chart = ChartFactory.createHistogram("Most Recent A1C Values", "last A1C(%)",
                    "number of patients", dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

            chart.setBorderPaint(Color.GREEN);
            chart.setBorderStroke(new BasicStroke(5.0f));
            chart.setBorderVisible(true);

            XYPlot plot = chart.getXYPlot();

            final XYBarRenderer renderer = (XYBarRenderer) plot.getRenderer();

            /* creating a shadow */
            renderer.setShadowXOffset(4.0);
            renderer.setShadowYOffset(1.5);
            renderer.setShadowVisible(true);

            ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }
        break;
    }
    case "lasta1cbyclassattendance": {
        final int topGroupIndex = 4;
        Stats glycemicStats = (Stats) session.getAttribute(SessionObjectUtility.LAST_A1C_BY_CLASS_DATA);

        DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

        if (glycemicStats.getGroups() != null) {
            for (int i = 0; i < glycemicStats.getGroups().size(); i++) {
                if ((glycemicStats.getGroups().get(i) != null)
                        && (!glycemicStats.getGroups().get(i).isEmpty())) {
                    List values = new ArrayList();
                    for (CategoricalValue cv : glycemicStats.getGroups().get(i)) {
                        values.add(cv.getValue());
                    }
                    if (i == topGroupIndex) {
                        dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values),
                                "last A1C(%)", "5 or more");
                    } else {
                        dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values),
                                "last A1C(%)", i + 1);
                    }
                }
            }
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.LAST_A1C_BY_CLASS_DATA, null);

        CategoryAxis domainAxis = new CategoryAxis("number of classes attended");
        NumberAxis rangeAxis = new NumberAxis("last A1C(%)");
        BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
        CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
        JFreeChart chart = new JFreeChart("Most Recent A1C by Classes Attended", plot);
        renderer.setMeanVisible(false);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "lastbmimales": {
        Stats bmiMalesStats = (Stats) session.getAttribute(SessionObjectUtility.LAST_BMI_MALES_DATA);
        HistogramDataset dataset = new HistogramDataset();
        ArrayList<CategoricalValue> lastBmiMalesValues = new ArrayList<>();
        if ((bmiMalesStats.getGroups() != null) && (!bmiMalesStats.getGroups().isEmpty())) {
            for (int i = 0; i < bmiMalesStats.getGroups().size(); i++) {
                if (bmiMalesStats.getGroups().get(i) != null) {
                    lastBmiMalesValues.addAll(bmiMalesStats.getGroups().get(i));
                }
            }
        }
        if (lastBmiMalesValues.size() > 0) {
            double[] vector = new double[lastBmiMalesValues.size()];

            for (int i = 0; i < vector.length; i++) {
                vector[i] = lastBmiMalesValues.get(i).getValue().doubleValue();
            }

            /* add the data */
            dataset.addSeries("number of patients", vector, 15);

            /* remove reference */
            session.setAttribute(SessionObjectUtility.LAST_BMI_MALES_DATA, null);

            boolean legend = true;
            boolean tooltips = false;
            boolean urls = false;

            /* get the chart */
            JFreeChart chart = ChartFactory.createHistogram("Most Recent BMI Values for Males", "last BMI",
                    "number of patients", dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

            chart.setBorderPaint(Color.GREEN);
            chart.setBorderStroke(new BasicStroke(5.0f));
            chart.setBorderVisible(true);

            XYPlot plot = chart.getXYPlot();

            final XYBarRenderer renderer = (XYBarRenderer) plot.getRenderer();

            /* creating a shadow */
            renderer.setShadowXOffset(4.0);
            renderer.setShadowYOffset(1.5);
            renderer.setShadowVisible(true);

            ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }
        break;
    }
    case "lastbmifemales": {
        Stats bmiFemalesStats = (Stats) session.getAttribute(SessionObjectUtility.LAST_BMI_FEMALES_DATA);
        HistogramDataset dataset = new HistogramDataset();
        ArrayList<CategoricalValue> lastBmiFemalesValues = new ArrayList<>();
        if ((bmiFemalesStats.getGroups() != null) && (!bmiFemalesStats.getGroups().isEmpty())) {
            for (int i = 0; i < bmiFemalesStats.getGroups().size(); i++) {
                if (bmiFemalesStats.getGroups().get(i) != null) {
                    lastBmiFemalesValues.addAll(bmiFemalesStats.getGroups().get(i));
                }
            }
        }
        if (lastBmiFemalesValues.size() > 0) {
            double[] vector = new double[lastBmiFemalesValues.size()];

            for (int i = 0; i < vector.length; i++) {
                vector[i] = lastBmiFemalesValues.get(i).getValue().doubleValue();
            }

            /* add the data */
            dataset.addSeries("number of patients", vector, 15);

            /* remove reference */
            session.setAttribute(SessionObjectUtility.LAST_BMI_FEMALES_DATA, null);

            boolean legend = true;
            boolean tooltips = false;
            boolean urls = false;

            /* get the chart */
            JFreeChart chart = ChartFactory.createHistogram("Most Recent BMI Values for Females", "last BMI",
                    "number of patients", dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

            chart.setBorderPaint(Color.GREEN);
            chart.setBorderStroke(new BasicStroke(5.0f));
            chart.setBorderVisible(true);

            XYPlot plot = chart.getXYPlot();

            final XYBarRenderer renderer = (XYBarRenderer) plot.getRenderer();

            /* creating a shadow */
            renderer.setShadowXOffset(4.0);
            renderer.setShadowYOffset(1.5);
            renderer.setShadowVisible(true);

            ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        }
        break;
    }
    case "lastbmimalesbyclassattendance": {
        final int topGroupIndex = 4;
        Stats bmiMalesStats = (Stats) session.getAttribute(SessionObjectUtility.LAST_BMI_MALES_BY_CLASS_DATA);

        DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

        if (bmiMalesStats.getGroups() != null) {
            for (int i = 0; i < bmiMalesStats.getGroups().size(); i++) {
                if ((bmiMalesStats.getGroups().get(i) != null)
                        && (!bmiMalesStats.getGroups().get(i).isEmpty())) {
                    List values = new ArrayList();
                    for (CategoricalValue cv : bmiMalesStats.getGroups().get(i)) {
                        values.add(cv.getValue());
                    }
                    if (i == topGroupIndex) {
                        dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values),
                                "last BMI (males)", "5 or more");
                    } else {
                        dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values),
                                "last BMI (males)", i + 1);
                    }
                }
            }
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.LAST_BMI_MALES_BY_CLASS_DATA, null);

        CategoryAxis domainAxis = new CategoryAxis("number of classes attended");
        NumberAxis rangeAxis = new NumberAxis("last BMI (males)");
        BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
        CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
        JFreeChart chart = new JFreeChart("Most Recent BMI for Males by Classes Attended", plot);
        renderer.setMeanVisible(false);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "lastbmifemalesbyclassattendance": {
        final int topGroupIndex = 4;
        Stats bmiFemalesStats = (Stats) session
                .getAttribute(SessionObjectUtility.LAST_BMI_FEMALES_BY_CLASS_DATA);

        DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

        if (bmiFemalesStats.getGroups() != null) {
            for (int i = 0; i < bmiFemalesStats.getGroups().size(); i++) {
                if ((bmiFemalesStats.getGroups().get(i) != null)
                        && (!bmiFemalesStats.getGroups().get(i).isEmpty())) {
                    List values = new ArrayList();
                    for (CategoricalValue cv : bmiFemalesStats.getGroups().get(i)) {
                        values.add(cv.getValue());
                    }
                    if (i == topGroupIndex) {
                        dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values),
                                "last BMI (females)", "5 or more");
                    } else {
                        dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values),
                                "last BMI (females)", i + 1);
                    }
                }
            }
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.LAST_BMI_FEMALES_BY_CLASS_DATA, null);

        CategoryAxis domainAxis = new CategoryAxis("number of classes attended");
        NumberAxis rangeAxis = new NumberAxis("last BMI (females)");
        BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
        CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
        JFreeChart chart = new JFreeChart("Most Recent BMI for Females by Classes Attended", plot);
        renderer.setMeanVisible(false);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "lasta1cbytreatment": {
        final int firstIndex = 0;
        Stats glycemicStats = (Stats) session.getAttribute(SessionObjectUtility.LAST_A1C_BY_TREATMENT);

        DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

        if (glycemicStats.getGroups() != null) {
            for (int i = 0; i < glycemicStats.getGroups().size(); i++) {
                if ((glycemicStats.getGroups().get(i) != null)
                        && (!glycemicStats.getGroups().get(i).isEmpty())) {
                    String category = glycemicStats.getGroups().get(i).get(firstIndex) != null
                            ? glycemicStats.getGroups().get(i).get(firstIndex).getCategory()
                            : "";
                    List values = new ArrayList();
                    for (CategoricalValue cv : glycemicStats.getGroups().get(i)) {
                        values.add(cv.getValue());
                    }
                    dataset.add(BoxAndWhiskerCalculator.calculateBoxAndWhiskerStatistics(values), "last A1C(%)",
                            category);
                }
            }
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.LAST_A1C_BY_TREATMENT, null);

        CategoryAxis domainAxis = new CategoryAxis("treatment class");
        NumberAxis rangeAxis = new NumberAxis("last A1C(%)");
        BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
        CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
        JFreeChart chart = new JFreeChart("Most Recent A1C by Treatment Class", plot);
        renderer.setMeanVisible(false);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "treatmentclasscounts": {
        int treatmentClassCountsIndex = 1;

        Stats treatmentData = (Stats) session.getAttribute(SessionObjectUtility.CLASS_COUNTS_TREATMENT_STATS);
        DefaultPieDataset dataset = new DefaultPieDataset();

        /* add the treatment data to the dataset */
        for (int i = 0; i < treatmentClassUnknownIndex + 1; i++) {
            dataset.setValue(treatmentData.getGroups().get(treatmentClassCountsIndex).get(i).getCategory(),
                    treatmentData.getGroups().get(treatmentClassCountsIndex).get(i).getValue());
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.CLASS_COUNTS_TREATMENT_STATS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        /* get the chart */
        JFreeChart chart = ChartFactory.createPieChart3D("Treatment Class", dataset, legend, tooltips, urls);

        final PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setStartAngle(90);
        plot.setForegroundAlpha(0.60f);
        plot.setInteriorGap(0.02);

        PieSectionLabelGenerator labels = new StandardPieSectionLabelGenerator("{0}: {1} ({2})",
                new DecimalFormat("0"), new DecimalFormat("0%"));
        plot.setLabelGenerator(labels);

        chart.setBorderPaint(Color.GREEN);
        chart.setBorderStroke(new BasicStroke(5.0f));
        chart.setBorderVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
        break;
    }
    case "treatmentgenderclasscounts": {
        int maleClassCountsIndex = 2;
        int femaleClassCountsIndex = 3;

        Stats treatmentData = (Stats) session
                .getAttribute(SessionObjectUtility.GENDER_CLASS_COUNTS_TREATMENT_STATS);
        final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        HashMap<Integer, String> genderMap = new HashMap<>();
        genderMap.put(maleClassCountsIndex, "Male");
        genderMap.put(femaleClassCountsIndex, "Female");

        /* load data for males and females into the dataset */
        for (int i = femaleClassCountsIndex; i > maleClassCountsIndex - 1; i--) {
            for (int j = 0; j < treatmentClassUnknownIndex + 1; j++) {
                dataset.addValue(treatmentData.getGroups().get(i).get(j).getValue(), genderMap.get(i),
                        treatmentData.getGroups().get(i).get(j).getCategory());
            }
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.GENDER_CLASS_COUNTS_TREATMENT_STATS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        JFreeChart barChart = ChartFactory.createBarChart("Treatment Class by Gender", "Treatment Class",
                "Number of Patients", dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

        barChart.setBorderPaint(Color.GREEN);
        barChart.setBorderStroke(new BasicStroke(5.0f));
        barChart.setBorderVisible(true);

        CategoryPlot plot = barChart.getCategoryPlot();

        final BarRenderer renderer = (BarRenderer) plot.getRenderer();

        /* creating a shadow */
        renderer.setShadowXOffset(4.0);
        renderer.setShadowYOffset(1.5);
        renderer.setShadowVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, barChart, width, height);

        break;
    }
    case "treatmentraceclasscounts": {
        int whiteClassCountsIndex = 4;
        int africanAmericanClassCountsIndex = 5;
        int asianPacificIslanderClassCountsIndex = 6;
        int americanIndianAlaskaNativeClassCountsIndex = 7;
        int hispanicClassCountsIndex = 8;
        int middleEasternClassCountsIndex = 9;
        int otherClassCountsIndex = 10;

        Stats treatmentData = (Stats) session
                .getAttribute(SessionObjectUtility.RACE_CLASS_COUNTS_TREATMENT_STATS);
        final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        HashMap<Integer, String> raceMap = new HashMap<>();
        raceMap.put(whiteClassCountsIndex, "White");
        raceMap.put(africanAmericanClassCountsIndex, "African American");
        raceMap.put(asianPacificIslanderClassCountsIndex, "Asian/Pacific Islander");
        raceMap.put(americanIndianAlaskaNativeClassCountsIndex, "American Indian/Alaska Native");
        raceMap.put(hispanicClassCountsIndex, "Hispanic");
        raceMap.put(middleEasternClassCountsIndex, "Middle Eastern");
        raceMap.put(otherClassCountsIndex, "Other");

        /* load data for each race into the dataset */
        for (int i = whiteClassCountsIndex; i < otherClassCountsIndex + 1; i++) {
            for (int j = 0; j < treatmentClassUnknownIndex + 1; j++) {
                dataset.addValue(treatmentData.getGroups().get(i).get(j).getValue(), raceMap.get(i),
                        treatmentData.getGroups().get(i).get(j).getCategory());
            }
        }

        /* remove reference */
        session.setAttribute(SessionObjectUtility.RACE_CLASS_COUNTS_TREATMENT_STATS, null);

        boolean legend = true;
        boolean tooltips = false;
        boolean urls = false;

        JFreeChart barChart = ChartFactory.createStackedBarChart("Treatment Class by Race", "Treatment Class",
                "Number of Patients", dataset, PlotOrientation.VERTICAL, legend, tooltips, urls);

        barChart.setBorderPaint(Color.GREEN);
        barChart.setBorderStroke(new BasicStroke(5.0f));
        barChart.setBorderVisible(true);

        CategoryPlot plot = barChart.getCategoryPlot();

        final BarRenderer renderer = (BarRenderer) plot.getRenderer();

        /* creating a shadow */
        renderer.setShadowXOffset(4.0);
        renderer.setShadowYOffset(1.5);
        renderer.setShadowVisible(true);

        ChartUtilities.writeChartAsPNG(outputStream, barChart, width, height);

        break;
    }
    default:
        break;
    }
}

From source file:com.visionet.platform.cooperation.service.OrderService.java

/**
 * ?/*  w  ww .java2  s.  c o m*/
 *
 * @param orderNo
 * @param partnerOrderNo
 * @param invoiceTitle
 * @param invoiceContent
 * @param address
 * @param postCode
 * @param addressee
 * @param phone
 * @param amount
 * @param sign
 * @param channel
 * @author fangren
 */
public void postInvoice(String orderNo, String partnerOrderNo, String invoiceTitle, String invoiceContent,
        String address, String postCode, String addressee, String phone, BigDecimal amount, String sign,
        String channel) {
    if (StringUtils.isEmpty(orderNo)) {
        throw new BizException("???");
    }
    if (StringUtils.isEmpty(partnerOrderNo)) {
        throw new BizException("????");
    }
    ThirdPartyOrder tpo = thirdPartyOrderMapper.selectByOrderIdAndPartnerOrderNo(orderNo, partnerOrderNo);
    if (tpo == null) {
        throw new BizException("?????");
    }

    Order order = orderMapper.selectByPrimaryKey(orderNo);
    if (order == null) {
        throw new BizException("??");
    }
    if (StringUtils.isEmpty(phone)) {
        throw new BizException("??");
    }
    if (StringUtils.isEmpty(address)) {
        throw new BizException("??");
    }
    if (StringUtils.isEmpty(invoiceTitle)) {
        throw new BizException("??");
    }
    // Customer customer = customerMapper.selectByPrimaryKey(phone);
    // Double invoiceBalance = customer.getInvoiceBalance();
    // Double invailInvoice = invoiceBalance - moneySum;
    // if (invailInvoice < 0) {
    // throw new BizException("????");
    // }
    // customer.setInvoiceBalance(invailInvoice);
    // customerMapper.updateByPrimaryKeySelective(customer);

    if (order.getIsInvoice() != 0) {
        throw new BizException("??");
    }
    // -----------?----------
    OrderInvoice orderInvoice = new OrderInvoice();
    orderInvoice.setNumber(1);// 
    orderInvoice.setAmount(amount.doubleValue());// ??
    orderInvoice.setOrderId(orderNo);// ?id,
    orderInvoice.setPhone(phone);// ?
    orderInvoice.setTotalAmount(amount.doubleValue());// ?
    orderInvoice.setReceiver(addressee);// 
    orderInvoice.setCompanyName(invoiceTitle);// ???
    orderInvoice.setApplyDate(new Date());
    orderInvoice.setReceiverPhone(phone);
    orderInvoice.setReceiverAddress(address);
    orderInvoice.setInvoiceType(1);//0:?1??
    orderInvoice.setStatus(1);// 
    orderInvoice.setArea(order.getCity());// 
    orderInvoice.setZipCode(postCode);// 
    orderInvoice.setInvoiceDescription(invoiceContent);// ??
    Integer num = orderInvoiceMapper.insertSelective(orderInvoice);
    if (num != 1) {
        throw new BizException("");
    }
    // -----------??----------

    // ????
    order.setIsInvoice(1);// ?0   ; 1 
    order.setUpdateDate(new Date());
    int j = orderMapper.updateByPrimaryKeySelective(order);
    if (j != 1) {
        throw new BizException("???");
    }
}

From source file:com.icebreak.p2p.trade.impl.TradeServiceImpl.java

public CalculateLoanCostResult getInterestByRole(List<DivsionRuleRole> list,
        CalculateLoanCostOrder loanCostOrder) {
    CalculateLoanCostResult loanCostResult = new CalculateLoanCostResult();
    double loanInterest = 0;
    double investorInterest = 0;
    String[] roleName = new String[list.size()];
    double[] divisionRule = new double[list.size()];
    int i = 0;/*from w ww  .j  a  v  a2s.c  o m*/
    for (DivsionRuleRole d : list) {
        BigDecimal bg = new BigDecimal(d.getRule() * 100);
        loanInterest += bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        if (SysUserRoleEnum.INVESTOR.getValue() == d.getRoleId()) {
            investorInterest += bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        Role role = roleDao.getByRoleId(d.getRoleId());
        roleName[i] = role.getName();
        divisionRule[i] = d.getRule();
        i++;
    }
    if (sysFunctionConfigService.isTradeFeeCharge()) {
        if (loanCostOrder.getLoanAmount() != null && loanCostOrder.getLoanAmount().greaterThan(Money.zero())
                && loanCostOrder.getTimeLimitUnit() != null && loanCostOrder.getTimeLimit() > 0) {
            Money tradeChargeAmount = loanCostOrder.getLoanAmount().multiply(new BigDecimal(0.002));
            BigDecimal rate = new BigDecimal(0);
            if (loanCostOrder.getTimeLimitUnit() == LoanPeriodUnitEnum.LOAN_BY_DAY) {
                rate = tradeChargeAmount.multiply(new BigDecimal(360)).getAmount()
                        .divide(new BigDecimal(loanCostOrder.getTimeLimit()), BigDecimal.ROUND_HALF_UP)
                        .divide(loanCostOrder.getLoanAmount().getAmount(), 3, BigDecimal.ROUND_HALF_UP);
            } else if (loanCostOrder.getTimeLimitUnit() == LoanPeriodUnitEnum.LOAN_BY_YEAR) {
                rate = tradeChargeAmount.getAmount()
                        .divide(new BigDecimal(loanCostOrder.getTimeLimit()), BigDecimal.ROUND_HALF_UP)
                        .divide(loanCostOrder.getLoanAmount().getAmount(), 3, BigDecimal.ROUND_HALF_UP);
            } else {
                rate = tradeChargeAmount.multiply(new BigDecimal(12)).getAmount()
                        .divide(new BigDecimal(loanCostOrder.getTimeLimit()), BigDecimal.ROUND_HALF_UP)
                        .divide(loanCostOrder.getLoanAmount().getAmount(), 3, BigDecimal.ROUND_HALF_UP);
            }
            loanCostResult.setTradeChargeAmount(tradeChargeAmount);
            loanCostResult.setTradeChargeRate(rate.doubleValue() * 100);
        }
    }
    loanCostResult.setDivisionRule(divisionRule);
    loanCostResult.setRoleName(roleName);
    loanCostResult.setSuccess(true);
    loanCostResult.setLoanInterest(loanInterest);
    loanCostResult.setInvestorInterest(investorInterest);
    return loanCostResult;
}

From source file:com.gollahalli.web.WebViewer.java

public void webReturnFortnightly() {
    Calculate calculate = new Calculate();

    double yearsTextMonth1 = yearsTextMonth / 2;
    // monthly payments output
    double weeklyOutputForFortnightly = calculate.fixedRateMortgageFortnightly(loanAmountText, yearsTextMonth1,
            interestText);//from   w ww  .  j a v a  2 s .  co m
    // total interest paid
    BigDecimal bd2 = new BigDecimal((weeklyOutputForFortnightly * yearsTextMonth1) - loanAmountText).setScale(2,
            RoundingMode.HALF_DOWN);
    System.out.println(weeklyOutputForFortnightly);
    System.out.println(bd2);

    double[][] monthlyChartYearly = calculate.fixedRateMortgageWeeklyChart(loanAmountText, interestText,
            yearsTextMonth);

    String[] property = propertyReader();

    double[][] newFortnightly = new double[5][(int) yearsTextMonth];
    newFortnightly[0][0] = monthlyChartYearly[2][0];
    newFortnightly[1][0] = monthlyChartYearly[1][0];
    newFortnightly[2][0] = monthlyChartYearly[3][0];
    for (int i = 1; i < yearsTextMonth; i++) {
        monthlyChartYearly = calculate.fixedRateMortgageWeeklyChart(monthlyChartYearly[3][0], interestText,
                yearsTextMonth - i);
        newFortnightly[0][i] = monthlyChartYearly[2][0];
        newFortnightly[1][i] = monthlyChartYearly[1][0];
        newFortnightly[2][i] = monthlyChartYearly[3][0];
    }

    String html = "";
    int someNumber = 1;

    double yearlyPrincipal = 0.0;
    double yearlyInterest = 0.0;
    double yearlyBalance = loanAmountText;
    for (int i = 0; i < newFortnightly[0].length; i++) {
        if (i % 2 == 0 && i != 0) {
            html += "<tr><td>" + String.valueOf(someNumber++) + "</td>" + "<td class=\"text-center\">"
                    + currencyMaker(
                            String.valueOf(new BigDecimal(yearlyPrincipal).setScale(2, RoundingMode.HALF_DOWN)))
                    + "</td>" + "<td class=\"text-center\">"
                    + currencyMaker(
                            String.valueOf(new BigDecimal(yearlyInterest).setScale(2, RoundingMode.HALF_DOWN)))
                    + "</td>" + "<td class=\"text-right\">"
                    + currencyMaker(
                            String.valueOf(new BigDecimal(yearlyBalance).setScale(2, RoundingMode.HALF_DOWN)))
                    + "</td></tr>";
            yearlyPrincipal = 0;
            yearlyInterest = 0;
        }
        yearlyPrincipal += newFortnightly[0][i];
        yearlyInterest += newFortnightly[1][i];
        yearlyBalance -= newFortnightly[0][i];
        if (i == newFortnightly[0].length - 1 && i != 0) {
            html += "<tr><td>" + String.valueOf(someNumber++) + "</td>" + "<td class=\"text-center\">"
                    + currencyMaker(
                            String.valueOf(new BigDecimal(yearlyPrincipal).setScale(2, RoundingMode.HALF_DOWN)))
                    + "</td>" + "<td class=\"text-center\">"
                    + currencyMaker(
                            String.valueOf(new BigDecimal(yearlyInterest).setScale(2, RoundingMode.HALF_DOWN)))
                    + "</td>" + "<td class=\"text-right\">"
                    + currencyMaker(
                            String.valueOf(new BigDecimal(yearlyBalance).setScale(2, RoundingMode.HALF_DOWN)))
                    + "</td></tr>";

        }

    }

    general.templateMaker(WordUtils.capitalize(property[0]), WordUtils.capitalize(this.custName),
            WordUtils.capitalize(this.custAddress), general.getDate(), currencyMaker(loanAmount), years, months,
            " type of payment", currencyMaker(String.valueOf(weeklyOutputForFortnightly)),
            currencyMaker(String.valueOf(bd2.doubleValue())),
            currencyMaker(String.valueOf(bd2.doubleValue() + loanAmountText)), "type of time", html,
            property[5], WordUtils.capitalize(property[1]), WordUtils.capitalize(property[2]), property[3],
            property[4]);

}

From source file:com.lp.server.lieferschein.ejbfac.LieferscheinFacBean.java

/**
 * Bei einem auftragbezogenen Lieferschein ist es moeglich, all jene offenen
 * oder teilerledigten Auftragpositionen innerhalb einer Transaktion zu
 * uebernehmen, die keine Benutzerinteraktion benoetigen. <br>
 * Es gilt://  ww w.  j  a v  a  2 s.  com
 * <ul>
 * <li>Handeingabepositionen werden uebernommen.
 * <li>Nicht Serien- oder Chargennummertragende Artikelpositionen werden mit
 * jener Menge uebernommen, die auf Lager liegt.
 * <li>Artikelpositionen mit Seriennummer werden nicht uebernommen.
 * <li>Artikelpositionen mit Chargennummer werden mit jener Menge
 * uebernommen, die auf Lager liegt, wenn es genau eine Charge gibt.
 * </ul>
 * Die restlichen Positionen koennen nicht automatisch uebernommen werden.
 * 
 * @param iIdLieferscheinI
 *            PK des Lieferscheins
 * @param auftragIIdI
 *            Integer
 * @param theClientDto
 *            String der aktuelle Benutzer
 * @throws EJBExceptionLP
 *             Ausnahme
 */
public void uebernimmAlleOffenenAuftragpositionenOhneBenutzerinteraktion(Integer iIdLieferscheinI,
        Integer auftragIIdI, TheClientDto theClientDto) throws EJBExceptionLP {
    checkLieferscheinIId(iIdLieferscheinI);
    try {
        LieferscheinDto lieferscheinDto = lieferscheinFindByPrimaryKey(iIdLieferscheinI, theClientDto);
        AuftragpositionDto[] aAuftragpositionDto = getAuftragpositionFac()
                .auftragpositionFindByAuftrag(auftragIIdI);

        boolean bEsGibtNochPositiveOffene = false;
        if (getMandantFac().darfAnwenderAufZusatzfunktionZugreifen(MandantFac.ZUSATZFUNKTION_VERLEIH,
                theClientDto)) {
            for (int i = 0; i < aAuftragpositionDto.length; i++) {
                if (!AuftragServiceFac.AUFTRAGPOSITIONSTATUS_ERLEDIGT
                        .equals(aAuftragpositionDto[i].getAuftragpositionstatusCNr())) {
                    if (aAuftragpositionDto[i].getNMenge() != null
                            && aAuftragpositionDto[i].getNMenge().doubleValue() > 0) {
                        bEsGibtNochPositiveOffene = true;
                    }
                }
            }
        }

        for (int i = 0; i < aAuftragpositionDto.length; i++) {
            if (!AuftragServiceFac.AUFTRAGPOSITIONSTATUS_ERLEDIGT
                    .equals(aAuftragpositionDto[i].getAuftragpositionstatusCNr())) {
                // IMS 2129
                if (aAuftragpositionDto[i].getNMenge() != null) {

                    // wenn es noch positive offene gibt, dann duerfen dei
                    // negativen noch nicht geliert werden

                    if (aAuftragpositionDto[i].getNMenge().doubleValue() < 0 && bEsGibtNochPositiveOffene) {
                        continue;
                    }

                    // dieses Flag legt fest, ob eine Lieferscheinposition
                    // fuer die aktuelle
                    // Auftragposition angleget oder aktualisiert werden
                    // soll
                    boolean bLieferscheinpositionErzeugen = false;

                    // die Menge, mit der eine neue Lieferscheinposition
                    // angelegt oder eine
                    // bestehende Lieferscheinposition aktualisiert werden
                    // soll
                    BigDecimal nMengeFuerLieferscheinposition = null;

                    // die Serien- oder Chargennummer, die bei der Abbuchung
                    // verwendet werden soll
                    String cSerienchargennummer = null;

                    if (aAuftragpositionDto[i].getPositionsartCNr()
                            .equals(AuftragServiceFac.AUFTRAGPOSITIONART_HANDEINGABE)) {
                        bLieferscheinpositionErzeugen = true;
                        nMengeFuerLieferscheinposition = aAuftragpositionDto[i].getNOffeneMenge();
                    } else if (aAuftragpositionDto[i].getPositionsartCNr()
                            .equals(AuftragServiceFac.AUFTRAGPOSITIONART_IDENT)) {
                        ArtikelDto artikelDto = getArtikelFac()
                                .artikelFindByPrimaryKey(aAuftragpositionDto[i].getArtikelIId(), theClientDto);

                        // nicht lagerbewirtschaftete Artikel werden mit der
                        // vollen offenen Menge uebernommen
                        if (!Helper.short2boolean(artikelDto.getBLagerbewirtschaftet())) {
                            bLieferscheinpositionErzeugen = true;
                            nMengeFuerLieferscheinposition = aAuftragpositionDto[i].getNOffeneMenge();
                        } else {
                            if (Helper.short2boolean(artikelDto.getBSeriennrtragend())) {
                                // seriennummerbehaftete Artikel koennen
                                // nicht automatisch uebernommen werden
                            } else if (Helper.short2boolean(artikelDto.getBChargennrtragend())) {
                                // chargennummernbehaftete Artikel koennen
                                // nur uebernommen werden, wenn
                                // es nur eine Charge gibt und mit der
                                // Menge, die in dieser Charge
                                // vorhanden ist
                                SeriennrChargennrAufLagerDto[] alleChargennummern = getLagerFac()
                                        .getAllSerienChargennrAufLager(artikelDto.getIId(),
                                                lieferscheinDto.getLagerIId(), theClientDto, true, false);
                                if (alleChargennummern != null && alleChargennummern.length == 1) {
                                    BigDecimal nLagerstd = alleChargennummern[0].getNMenge();
                                    cSerienchargennummer = alleChargennummern[0].getCSeriennrChargennr();
                                    // ist ausreichend auf Lager?
                                    if (nLagerstd.compareTo(aAuftragpositionDto[i].getNOffeneMenge()) >= 0) {
                                        bLieferscheinpositionErzeugen = true;
                                        nMengeFuerLieferscheinposition = aAuftragpositionDto[i]
                                                .getNOffeneMenge();
                                    }
                                    // nicht genug auf Lager, aber es kann
                                    // zumindest ein Teil abgebucht werden.
                                    else if (nLagerstd.compareTo(new BigDecimal(0)) > 0) {
                                        bLieferscheinpositionErzeugen = true;
                                        nMengeFuerLieferscheinposition = nLagerstd;
                                    }
                                }
                            } else {
                                // bei lagerbewirtschafteten Artikeln muss
                                // die Menge auf Lager
                                // beruecksichtigt werden
                                BigDecimal nMengeAufLager = getLagerFac().getMengeAufLager(artikelDto.getIId(),
                                        lieferscheinDto.getLagerIId(), null, theClientDto);

                                if (nMengeAufLager.doubleValue() >= aAuftragpositionDto[i].getNOffeneMenge()
                                        .doubleValue()) {
                                    bLieferscheinpositionErzeugen = true;
                                    nMengeFuerLieferscheinposition = aAuftragpositionDto[i].getNOffeneMenge();
                                } else if (nMengeAufLager.doubleValue() > 0
                                        && nMengeAufLager.doubleValue() < aAuftragpositionDto[i]
                                                .getNOffeneMenge().doubleValue()) {
                                    bLieferscheinpositionErzeugen = true;
                                    nMengeFuerLieferscheinposition = nMengeAufLager;
                                }
                            }
                        }
                    }

                    if (bLieferscheinpositionErzeugen && nMengeFuerLieferscheinposition != null) {
                        LieferscheinpositionDto lieferscheinpositionBisherDto = getLieferscheinpositionByLieferscheinAuftragposition(
                                iIdLieferscheinI, aAuftragpositionDto[i].getIId());

                        if (lieferscheinpositionBisherDto == null) {
                            LieferscheinpositionDto lieferscheinpositionDto = aAuftragpositionDto[i]
                                    .cloneAsLieferscheinpositionDto();

                            if (aAuftragpositionDto[i].getPositioniIdArtikelset() != null) {

                                LieferscheinpositionDto[] lPositionDtos = null;
                                Query query = em.createNamedQuery("LieferscheinpositionfindByAuftragposition");
                                query.setParameter(1, aAuftragpositionDto[i].getPositioniIdArtikelset());
                                Collection<?> cl = query.getResultList();
                                lPositionDtos = assembleLieferscheinpositionDtos(cl);

                                for (int j = 0; j < lPositionDtos.length; j++) {
                                    if (lPositionDtos[j].getLieferscheinIId().equals(iIdLieferscheinI)) {
                                        lieferscheinpositionDto
                                                .setPositioniIdArtikelset(lPositionDtos[j].getIId());
                                        break;
                                    }
                                }

                            }

                            lieferscheinpositionDto.setLieferscheinIId(iIdLieferscheinI);
                            lieferscheinpositionDto.setNMenge(nMengeFuerLieferscheinposition);
                            lieferscheinpositionDto.setSeriennrChargennrMitMenge(
                                    SeriennrChargennrMitMengeDto.erstelleDtoAusEinerChargennummer(
                                            cSerienchargennummer, nMengeFuerLieferscheinposition));
                            lieferscheinpositionDto.setISort(null);
                            getLieferscheinpositionFac().createLieferscheinposition(lieferscheinpositionDto,
                                    false, theClientDto);
                        } else {
                            lieferscheinpositionBisherDto.setNMenge(nMengeFuerLieferscheinposition);

                            if (aAuftragpositionDto[i].getPositionsartCNr()
                                    .equals(AuftragServiceFac.AUFTRAGPOSITIONART_IDENT)) {
                                ArtikelDto artikelDto = getArtikelFac().artikelFindByPrimaryKey(
                                        aAuftragpositionDto[i].getArtikelIId(), theClientDto);

                                if (Helper.short2boolean(artikelDto.getBSeriennrtragend())
                                        || Helper.short2boolean(artikelDto.getBChargennrtragend())) {
                                    lieferscheinpositionBisherDto.setSeriennrChargennrMitMenge(
                                            SeriennrChargennrMitMengeDto.erstelleDtoAusEinerChargennummer(
                                                    cSerienchargennummer, nMengeFuerLieferscheinposition));
                                } else {
                                    lieferscheinpositionBisherDto.setSeriennrChargennrMitMenge(null);
                                }

                            }

                            getLieferscheinpositionFac().updateLieferscheinpositionSichtAuftrag(
                                    lieferscheinpositionBisherDto, theClientDto);
                        }
                    }
                } else {
                    LieferscheinpositionDto lieferscheinpositionDto = aAuftragpositionDto[i]
                            .cloneAsLieferscheinpositionDto();
                    lieferscheinpositionDto.setLieferscheinIId(iIdLieferscheinI);
                    lieferscheinpositionDto.setISort(null);
                    getLieferscheinpositionFac().createLieferscheinposition(lieferscheinpositionDto, false,
                            theClientDto);
                }
            }
        }
    } catch (RemoteException ex) {
        throwEJBExceptionLPRespectOld(ex);
    }
}

From source file:it.govpay.core.business.Rendicontazioni.java

public String downloadRendicontazioni(boolean deep) throws GovPayException {
    boolean errori = false;
    List<String> response = new ArrayList<String>();
    try {//from   ww w.  j ava  2 s. c  o  m
        GpThreadLocal.get().log("rendicontazioni.acquisizione");
        DominiBD dominiBD = new DominiBD(this);

        StazioniBD stazioniBD = new StazioniBD(this);
        List<Stazione> lstStazioni = stazioniBD.getStazioni();

        PspBD pspBD = new PspBD(this);
        List<Psp> lstPsp = pspBD.getPsp();
        closeConnection();

        for (Stazione stazione : lstStazioni) {

            List<TipoIdRendicontazione> flussiDaAcquisire = new ArrayList<TipoIdRendicontazione>();

            setupConnection(GpThreadLocal.get().getTransactionId());
            Intermediario intermediario = stazione.getIntermediario(this);
            NodoClient client = new NodoClient(intermediario, this);
            closeConnection();

            if (deep) {
                DominioFilter filter = dominiBD.newFilter();
                filter.setCodStazione(stazione.getCodStazione());
                List<Dominio> lstDomini = dominiBD.findAll(filter);

                for (Dominio dominio : lstDomini) {
                    List<String> sids = new ArrayList<String>();
                    for (Psp psp : lstPsp) {
                        if (sids.contains(psp.getCodPsp()))
                            continue;
                        sids.add(psp.getCodPsp());
                        log.debug("Acquisizione dei flussi di rendicontazione dal psp [" + psp.getCodPsp()
                                + "] per il dominio [" + dominio.getCodDominio() + "] in corso.");
                        flussiDaAcquisire.addAll(chiediListaFr(client, psp, stazione, dominio));
                    }
                }
            } else {
                log.debug("Acquisizione dei flussi di rendicontazione per la stazione ["
                        + stazione.getCodStazione() + "] in corso.");
                flussiDaAcquisire.addAll(chiediListaFr(client, null, stazione, null));
            }

            // Scarto i flussi gia acquisiti
            setupConnection(GpThreadLocal.get().getTransactionId());

            FrBD frBD = new FrBD(this);
            for (TipoIdRendicontazione idRendicontazione : flussiDaAcquisire) {
                if (frBD.exists(idRendicontazione.getIdentificativoFlusso()))
                    flussiDaAcquisire.remove(idRendicontazione);
            }
            closeConnection();

            for (TipoIdRendicontazione idRendicontazione : flussiDaAcquisire) {
                log.debug("Acquisizione flusso di rendicontazione "
                        + idRendicontazione.getIdentificativoFlusso());
                boolean hasFrAnomalia = false;
                String idTransaction2 = null;
                try {
                    idTransaction2 = GpThreadLocal.get().openTransaction();
                    GpThreadLocal.get().getContext().getRequest()
                            .addGenericProperty(new Property("codStazione", stazione.getCodStazione()));
                    GpThreadLocal.get().getContext().getRequest().addGenericProperty(
                            new Property("idFlusso", idRendicontazione.getIdentificativoFlusso()));
                    GpThreadLocal.get().setupNodoClient(stazione.getCodStazione(), null,
                            Azione.nodoChiediFlussoRendicontazione);
                    NodoChiediFlussoRendicontazione richiestaFlusso = new NodoChiediFlussoRendicontazione();
                    richiestaFlusso.setIdentificativoIntermediarioPA(
                            stazione.getIntermediario(this).getCodIntermediario());
                    richiestaFlusso.setIdentificativoStazioneIntermediarioPA(stazione.getCodStazione());
                    richiestaFlusso.setPassword(stazione.getPassword());
                    richiestaFlusso.setIdentificativoFlusso(idRendicontazione.getIdentificativoFlusso());

                    NodoChiediFlussoRendicontazioneRisposta risposta;
                    try {
                        risposta = client.nodoChiediFlussoRendicontazione(richiestaFlusso,
                                stazione.getIntermediario(this).getDenominazione());
                    } catch (Exception e) {
                        // Errore nella richiesta. Loggo e continuo con il prossimo flusso
                        response.add(idRendicontazione.getIdentificativoFlusso()
                                + "#Richiesta al nodo fallita: " + e + ".");
                        log.error("Richiesta flusso  rendicontazione ["
                                + idRendicontazione.getIdentificativoFlusso() + "] fallita: " + e);
                        GpThreadLocal.get().log("rendicontazioni.acquisizioneFlussoFail", e.getMessage());
                        errori = true;
                        continue;
                    }

                    if (risposta.getFault() != null) {
                        // Errore nella richiesta. Loggo e continuo con il prossimo flusso
                        response.add(idRendicontazione.getIdentificativoFlusso()
                                + "#Richiesta al nodo fallita: " + risposta.getFault().getFaultCode() + " "
                                + risposta.getFault().getFaultString() + ".");
                        log.error("Richiesta flusso rendicontazione ["
                                + idRendicontazione.getIdentificativoFlusso() + "] fallita: "
                                + risposta.getFault().getFaultCode() + " "
                                + risposta.getFault().getFaultString());
                        GpThreadLocal.get().log("rendicontazioni.acquisizioneFlussoKo",
                                risposta.getFault().getFaultCode(), risposta.getFault().getFaultString(),
                                risposta.getFault().getDescription());
                    } else {
                        byte[] tracciato = null;
                        try {
                            ByteArrayOutputStream output = new ByteArrayOutputStream();
                            DataHandler dh = risposta.getXmlRendicontazione();
                            dh.writeTo(output);
                            tracciato = output.toByteArray();
                        } catch (IOException e) {
                            response.add(idRendicontazione.getIdentificativoFlusso()
                                    + "#Lettura del flusso fallita: " + e + ".");
                            log.error("Errore durante la lettura del flusso di rendicontazione", e);
                            GpThreadLocal.get().log("rendicontazioni.acquisizioneFlussoFail",
                                    "Lettura del flusso fallita: " + e);
                            errori = true;
                            continue;
                        }

                        CtFlussoRiversamento flussoRendicontazione = null;
                        try {
                            flussoRendicontazione = JaxbUtils.toFR(tracciato);
                        } catch (Exception e) {
                            response.add(idRendicontazione.getIdentificativoFlusso()
                                    + "#Parsing del flusso fallita: " + e + ".");
                            log.error("Errore durante il parsing del flusso di rendicontazione", e);
                            GpThreadLocal.get().log("rendicontazioni.acquisizioneFlussoFail",
                                    "Errore durante il parsing del flusso di rendicontazione: " + e);
                            errori = true;
                            continue;
                        }

                        log.info("Ricevuto flusso rendicontazione per "
                                + flussoRendicontazione.getDatiSingoliPagamenti().size()
                                + " singoli pagamenti");

                        setupConnection(GpThreadLocal.get().getTransactionId());

                        GpThreadLocal.get().log("rendicontazioni.acquisizioneFlusso");
                        GpThreadLocal.get().getContext().getRequest().addGenericProperty(new Property("trn",
                                flussoRendicontazione.getIdentificativoUnivocoRegolamento()));

                        Fr fr = new Fr();
                        fr.setCodBicRiversamento(flussoRendicontazione.getCodiceBicBancaDiRiversamento());
                        fr.setCodFlusso(idRendicontazione.getIdentificativoFlusso());
                        fr.setIur(flussoRendicontazione.getIdentificativoUnivocoRegolamento());
                        fr.setDataAcquisizione(new Date());
                        fr.setDataFlusso(flussoRendicontazione.getDataOraFlusso());
                        fr.setDataRegolamento(flussoRendicontazione.getDataRegolamento());
                        fr.setNumeroPagamenti(flussoRendicontazione.getNumeroTotalePagamenti().longValue());
                        fr.setImportoTotalePagamenti(flussoRendicontazione.getImportoTotalePagamenti());

                        fr.setXml(tracciato);

                        String codPsp = null, codDominio = null;
                        try {
                            codPsp = idRendicontazione.getIdentificativoFlusso().substring(10,
                                    idRendicontazione.getIdentificativoFlusso().indexOf("-", 10));
                            fr.setCodPsp(codPsp);
                            log.debug("Identificativo PSP estratto dall'identificativo flusso: " + codPsp);
                            AnagraficaManager.getPsp(this, codPsp);
                            GpThreadLocal.get().getContext().getRequest()
                                    .addGenericProperty(new Property("codPsp", codPsp));
                        } catch (Exception e) {
                            GpThreadLocal.get().log("rendicontazioni.acquisizioneFlussoPspNonCensito",
                                    codPsp == null ? "null" : codPsp);
                            GpThreadLocal.get().getContext().getRequest().addGenericProperty(
                                    new Property("codPsp", codPsp == null ? "null" : codPsp));
                            fr.addAnomalia("007108", "L'identificativo PSP [" + codPsp
                                    + "] ricavato dal codice flusso non riferisce un PSP censito");
                        }

                        Dominio dominio = null;
                        try {
                            codDominio = flussoRendicontazione.getIstitutoRicevente()
                                    .getIdentificativoUnivocoRicevente().getCodiceIdentificativoUnivoco();
                            fr.setCodDominio(codDominio);
                            GpThreadLocal.get().getContext().getRequest()
                                    .addGenericProperty(new Property("codDominio", codDominio));
                            dominio = AnagraficaManager.getDominio(this, codDominio);
                        } catch (Exception e) {
                            if (codDominio == null) {
                                codDominio = "????";
                                GpThreadLocal.get().getContext().getRequest()
                                        .addGenericProperty(new Property("codDominio", "null"));
                            }
                            GpThreadLocal.get().log("rendicontazioni.acquisizioneFlussoDominioNonCensito");
                            fr.addAnomalia("007109", "L'indentificativo ricevente [" + codDominio
                                    + "] del flusso non riferisce un Dominio censito");
                        }

                        BigDecimal totaleImportiRendicontati = BigDecimal.ZERO;

                        PagamentiBD pagamentiBD = new PagamentiBD(this);
                        VersamentiBD versamentiBD = new VersamentiBD(this);
                        IuvBD iuvBD = new IuvBD(this);
                        for (CtDatiSingoliPagamenti dsp : flussoRendicontazione.getDatiSingoliPagamenti()) {

                            String iur = dsp.getIdentificativoUnivocoRiscossione();
                            String iuv = dsp.getIdentificativoUnivocoVersamento();
                            BigDecimal importoRendicontato = dsp.getSingoloImportoPagato();

                            log.debug("Rendicontato (Esito " + dsp.getCodiceEsitoSingoloPagamento()
                                    + ") per un importo di (" + dsp.getSingoloImportoPagato()
                                    + ") [CodDominio: " + codDominio + "] [Iuv: "
                                    + dsp.getIdentificativoUnivocoVersamento() + "][Iur: " + iur + "]");

                            it.govpay.bd.model.Rendicontazione rendicontazione = new it.govpay.bd.model.Rendicontazione();

                            // Gestisco un codice esito non supportato
                            try {
                                rendicontazione.setEsito(
                                        EsitoRendicontazione.toEnum(dsp.getCodiceEsitoSingoloPagamento()));
                            } catch (Exception e) {
                                GpThreadLocal.get().log("rendicontazioni.esitoSconosciuto", iuv, iur,
                                        dsp.getCodiceEsitoSingoloPagamento() == null ? "null"
                                                : dsp.getCodiceEsitoSingoloPagamento());
                                rendicontazione.addAnomalia("007110", "Codice esito ["
                                        + dsp.getCodiceEsitoSingoloPagamento() + "] sconosciuto");
                            }

                            rendicontazione.setData(dsp.getDataEsitoSingoloPagamento());
                            rendicontazione.setIur(dsp.getIdentificativoUnivocoRiscossione());
                            rendicontazione.setIuv(dsp.getIdentificativoUnivocoVersamento());
                            rendicontazione.setImporto(dsp.getSingoloImportoPagato());

                            totaleImportiRendicontati = totaleImportiRendicontati.add(importoRendicontato);

                            // Cerco il pagamento riferito
                            it.govpay.bd.model.Pagamento pagamento = null;
                            try {
                                pagamento = pagamentiBD.getPagamento(codDominio, iuv, iur);

                                // Pagamento trovato. Faccio i controlli semantici
                                rendicontazione.setIdPagamento(pagamento.getId());

                                // Verifico l'importo
                                if (rendicontazione.getEsito().equals(EsitoRendicontazione.REVOCATO)) {
                                    if (pagamento.getImportoRevocato()
                                            .compareTo(importoRendicontato.abs()) != 0) {
                                        GpThreadLocal.get().log("rendicontazioni.importoStornoErrato", iuv,
                                                iur);
                                        log.info("Revoca [Dominio:" + codDominio + " Iuv:" + iuv + " Iur: "
                                                + iur + "] rendicontato con errore: l'importo rendicontato ["
                                                + importoRendicontato.doubleValue()
                                                + "] non corrisponde a quanto stornato ["
                                                + pagamento.getImportoRevocato().doubleValue() + "]");
                                        rendicontazione.addAnomalia("007112",
                                                "L'importo rendicontato [" + importoRendicontato.doubleValue()
                                                        + "] non corrisponde a quanto stornato ["
                                                        + pagamento.getImportoRevocato().doubleValue() + "]");
                                    }

                                    // Verifico che il pagamento non sia gia' rendicontato
                                    if (pagamento.isPagamentoRendicontato(this)) {
                                        GpThreadLocal.get().log("rendicontazioni.giaStornato", iuv, iur);
                                        log.info("Pagamento [Dominio:" + codDominio + " Iuv:" + iuv + " Iur: "
                                                + iur
                                                + "] rendicontato con errore: storno gia' rendicontato da altri flussi");
                                        rendicontazione.addAnomalia("007113",
                                                "Lo storno riferito dalla rendicontazione risulta gia' rendicontato da altri flussi");
                                    }

                                } else {
                                    if (pagamento.getImportoPagato().compareTo(importoRendicontato) != 0) {
                                        GpThreadLocal.get().log("rendicontazioni.importoErrato", iuv, iur);
                                        log.info("Pagamento [Dominio:" + codDominio + " Iuv:" + iuv + " Iur: "
                                                + iur + "] rendicontato con errore: l'importo rendicontato ["
                                                + importoRendicontato.doubleValue()
                                                + "] non corrisponde a quanto pagato ["
                                                + pagamento.getImportoPagato().doubleValue() + "]");
                                        rendicontazione.addAnomalia("007104",
                                                "L'importo rendicontato [" + importoRendicontato.doubleValue()
                                                        + "] non corrisponde a quanto pagato ["
                                                        + pagamento.getImportoPagato().doubleValue() + "]");
                                    }

                                    // Verifico che il pagamento non sia gia' rendicontato
                                    if (pagamento.isPagamentoRendicontato(this)) {
                                        GpThreadLocal.get().log("rendicontazioni.giaRendicontato", iuv, iur);
                                        log.info("Pagamento [Dominio:" + codDominio + " Iuv:" + iuv + " Iur: "
                                                + iur
                                                + "] rendicontato con errore: pagamento gia' rendicontato da altri flussi");
                                        rendicontazione.addAnomalia("007103",
                                                "Il pagamento riferito dalla rendicontazione risulta gia' rendicontato da altri flussi");
                                    }
                                }

                            } catch (NotFoundException e) {
                                // Pagamento non trovato. Devo capire se ce' un errore.

                                // Controllo che sia per uno IUV generato da noi
                                if (!isInterno(dominio, iuv)) {
                                    rendicontazione.setStato(StatoRendicontazione.ALTRO_INTERMEDIARIO);
                                    continue;
                                }

                                // Controllo se e' un pagamento senza RPT
                                if (rendicontazione.getEsito()
                                        .equals(EsitoRendicontazione.ESEGUITO_SENZA_RPT)) {

                                    //Recupero il versamento, internamente o dall'applicazione esterna
                                    it.govpay.bd.model.Versamento versamento = null;
                                    String erroreVerifica = null;
                                    String codApplicazione = null;
                                    try {
                                        try {
                                            it.govpay.model.Iuv iuvModel = iuvBD.getIuv(dominio.getId(), iuv);
                                            versamento = versamentiBD.getVersamento(
                                                    iuvModel.getIdApplicazione(),
                                                    iuvModel.getCodVersamentoEnte());
                                        } catch (NotFoundException nfe) {
                                            codApplicazione = it.govpay.bd.GovpayConfig.getInstance()
                                                    .getDefaultCustomIuvGenerator().getCodApplicazione(dominio,
                                                            iuv, dominio.getApplicazioneDefault(this));
                                            if (codApplicazione == null) {
                                                response.add(idRendicontazione.getIdentificativoFlusso()
                                                        + "#Acquisizione flusso fallita. Impossibile individuare l'applicativo gestore del versamento per acquisirne i dati [Dominio:"
                                                        + codDominio + " Iuv:" + iuv + "].");
                                                log.error(
                                                        "Errore durante il processamento del flusso di Rendicontazione [Flusso:"
                                                                + idRendicontazione.getIdentificativoFlusso()
                                                                + "]: Impossibile individuare l'applicativo gestore del versamento per acquisirne i dati [Dominio:"
                                                                + codDominio + " Iuv:" + iuv
                                                                + "]. Flusso non acquisito.");
                                                GpThreadLocal.get().log("rendicontazioni.acquisizioneFlussoKo",
                                                        idRendicontazione.getIdentificativoFlusso(),
                                                        "Impossibile individuare l'applicativo gestore del versamento per acquisirne i dati [Dominio:"
                                                                + codDominio + " Iuv:" + iuv
                                                                + "].  Flusso non acquisito.");
                                                throw new GovPayException(EsitoOperazione.INTERNAL,
                                                        "Impossibile individuare l'applicativo gestore del versamento per acquisirne i dati [Dominio:"
                                                                + codDominio + " Iuv:" + iuv
                                                                + "].  Flusso non acquisito.");
                                            }
                                            versamento = VersamentoUtils.acquisisciVersamento(
                                                    AnagraficaManager.getApplicazione(this, codApplicazione),
                                                    null, null, null, codDominio, iuv, this);
                                        }
                                    } catch (VersamentoScadutoException e1) {
                                        erroreVerifica = "Versamento non acquisito dall'applicazione gestrice perche' SCADUTO.";
                                    } catch (VersamentoAnnullatoException e1) {
                                        erroreVerifica = "Versamento non acquisito dall'applicazione gestrice perche' ANNULLATO.";
                                    } catch (VersamentoDuplicatoException e1) {
                                        erroreVerifica = "Versamento non acquisito dall'applicazione gestrice perche' DUPLICATO.";
                                    } catch (VersamentoSconosciutoException e1) {
                                        erroreVerifica = "Versamento non acquisito dall'applicazione gestrice perche' SCONOSCIUTO.";
                                    } catch (ClientException ce) {
                                        response.add(idRendicontazione.getIdentificativoFlusso()
                                                + "#Acquisizione flusso fallita. Riscontrato errore nell'acquisizione del versamento dall'applicazione gestrice [Transazione: "
                                                + idTransaction2 + "].");
                                        log.error(
                                                "Errore durante il processamento del flusso di Rendicontazione [Flusso:"
                                                        + idRendicontazione.getIdentificativoFlusso()
                                                        + "]: impossibile acquisire i dati del versamento [Dominio:"
                                                        + codDominio + " Iuv:" + iuv
                                                        + "]. Flusso non acquisito.");
                                        GpThreadLocal.get().log("rendicontazioni.acquisizioneFlussoKo",
                                                idRendicontazione.getIdentificativoFlusso(),
                                                "Impossibile acquisire i dati di un versamento dall'applicativo gestore [Applicazione:"
                                                        + codApplicazione + " Dominio:" + codDominio + " Iuv:"
                                                        + iuv + "].  Flusso non acquisito.");
                                        throw new GovPayException(ce);
                                    }

                                    if (versamento == null) {
                                        // non ho trovato il versamento 
                                        GpThreadLocal.get().log("rendicontazioni.senzaRptNoVersamento", iuv,
                                                iur);
                                        log.info("Pagamento [Dominio:" + codDominio + " Iuv:" + iuv + " Iur: "
                                                + iur
                                                + "] rendicontato con errore: Pagamento senza RPT di versamento sconosciuto.");
                                        rendicontazione.addAnomalia("007111",
                                                "Il versamento risulta sconosciuto: " + erroreVerifica);
                                        continue;
                                    } else {

                                        if (versamento.getSingoliVersamenti(this).size() != 1) {
                                            // Un pagamento senza rpt DEVE riferire un pagamento tipo 3 con un solo singolo versamento
                                            GpThreadLocal.get().log(
                                                    "rendicontazioni.senzaRptVersamentoMalformato", iuv, iur);
                                            log.info("Pagamento [Dominio:" + codDominio + " Iuv:" + iuv
                                                    + " Iur: " + iur
                                                    + "] rendicontato con errore: Pagamento senza RPT di versamento sconosciuto.");
                                            rendicontazione.addAnomalia("007114",
                                                    "Il versamento presenta piu' singoli versamenti");
                                            continue;
                                        }

                                        // Trovato versamento. Creo il pagamento senza rpt 
                                        pagamento = new it.govpay.bd.model.Pagamento();
                                        pagamento.setCodDominio(codDominio);
                                        pagamento.setDataAcquisizione(rendicontazione.getData());
                                        pagamento.setDataPagamento(rendicontazione.getData());
                                        pagamento.setImportoPagato(rendicontazione.getImporto());
                                        pagamento.setIur(rendicontazione.getIur());
                                        pagamento.setIuv(rendicontazione.getIuv());
                                        pagamento.setCodDominio(fr.getCodDominio());
                                        pagamento.setSingoloVersamento(
                                                versamento.getSingoliVersamenti(this).get(0));

                                        rendicontazione.setPagamento(pagamento);
                                        rendicontazione.setPagamentoDaCreare(true);
                                        continue;
                                    }
                                }

                                GpThreadLocal.get().log("rendicontazioni.noPagamento", iuv, iur);
                                log.info("Pagamento [Dominio:" + codDominio + " Iuv:" + iuv + " Iur: " + iur
                                        + "] rendicontato con errore: il pagamento non risulta presente in base dati.");
                                rendicontazione.addAnomalia("007101",
                                        "Il pagamento riferito dalla rendicontazione non risulta presente in base dati.");
                                continue;
                            } catch (MultipleResultException e) {
                                // Individuati piu' pagamenti riferiti dalla rendicontazione
                                GpThreadLocal.get().log("rendicontazioni.poliPagamento", iuv, iur);
                                log.info("Pagamento rendicontato duplicato: [CodDominio: " + codDominio
                                        + "] [Iuv: " + iuv + "] [Iur: " + iur + "]");
                                rendicontazione.addAnomalia("007102",
                                        "La rendicontazione riferisce piu di un pagamento gestito.");
                            } finally {
                                if (!StatoRendicontazione.ALTRO_INTERMEDIARIO.equals(rendicontazione.getStato())
                                        && rendicontazione.getAnomalie().isEmpty()) {
                                    rendicontazione.setStato(StatoRendicontazione.OK);
                                } else if (!StatoRendicontazione.ALTRO_INTERMEDIARIO
                                        .equals(rendicontazione.getStato())
                                        && !rendicontazione.getAnomalie().isEmpty()) {
                                    rendicontazione.setStato(StatoRendicontazione.ANOMALA);
                                    hasFrAnomalia = true;
                                }
                                fr.addRendicontazione(rendicontazione);
                            }
                        }

                        // Singole rendicontazioni elaborate.
                        // Controlli di quadratura generali

                        if (totaleImportiRendicontati
                                .compareTo(flussoRendicontazione.getImportoTotalePagamenti()) != 0) {
                            GpThreadLocal.get().log("rendicontazioni.importoTotaleErrato");
                            log.info("La somma degli importi rendicontati [" + totaleImportiRendicontati
                                    + "] non corrisponde al totale indicato nella testata del flusso ["
                                    + flussoRendicontazione.getImportoTotalePagamenti() + "]");
                            fr.addAnomalia("007106",
                                    "La somma degli importi rendicontati [" + totaleImportiRendicontati
                                            + "] non corrisponde al totale indicato nella testata del flusso ["
                                            + flussoRendicontazione.getImportoTotalePagamenti() + "]");
                        }

                        try {
                            if (flussoRendicontazione.getDatiSingoliPagamenti().size() != flussoRendicontazione
                                    .getNumeroTotalePagamenti().longValueExact()) {
                                GpThreadLocal.get().log("rendicontazioni.numeroRendicontazioniErrato");
                                log.info("Il numero di pagamenti rendicontati ["
                                        + flussoRendicontazione.getDatiSingoliPagamenti().size()
                                        + "] non corrisponde al totale indicato nella testata del flusso ["
                                        + flussoRendicontazione.getNumeroTotalePagamenti().longValueExact()
                                        + "]");
                                fr.addAnomalia("007107", "Il numero di pagamenti rendicontati ["
                                        + flussoRendicontazione.getDatiSingoliPagamenti().size()
                                        + "] non corrisponde al totale indicato nella testata del flusso ["
                                        + flussoRendicontazione.getNumeroTotalePagamenti().longValueExact()
                                        + "]");
                            }
                        } catch (Exception e) {
                            GpThreadLocal.get().log("rendicontazioni.numeroRendicontazioniErrato");
                            log.info("Il numero di pagamenti rendicontati ["
                                    + flussoRendicontazione.getDatiSingoliPagamenti().size()
                                    + "] non corrisponde al totale indicato nella testata del flusso [????]");
                            fr.addAnomalia("007107", "Il numero di pagamenti rendicontati ["
                                    + flussoRendicontazione.getDatiSingoliPagamenti().size()
                                    + "] non corrisponde al totale indicato nella testata del flusso [????]");
                        }

                        // Decido lo stato del FR
                        if (fr.getAnomalie().isEmpty()) {
                            fr.setStato(StatoFr.ACCETTATA);
                        } else {
                            fr.setStato(StatoFr.ANOMALA);
                            hasFrAnomalia = true;
                        }

                        // Procedo al salvataggio
                        RendicontazioniBD rendicontazioniBD = new RendicontazioniBD(this);

                        // Tutte le operazioni di salvataggio devono essere in transazione.
                        setAutoCommit(false);
                        frBD.insertFr(fr);
                        for (Rendicontazione r : fr.getRendicontazioni(this)) {
                            r.setIdFr(fr.getId());

                            // controllo se c'e' un pagamento da creare relativo alla rendicontazione
                            // deve anche essere creato il pagamento.
                            if (r.isPagamentoDaCreare()) {
                                pagamentiBD.insertPagamento(r.getPagamento(this));
                                r.setIdPagamento(r.getPagamento(this).getId());
                            }
                            rendicontazioniBD.insert(r);
                        }
                        this.commit();
                        if (!hasFrAnomalia) {
                            log.info("Flusso di rendicontazione acquisito senza anomalie.");
                            GpThreadLocal.get().log("rendicontazioni.acquisizioneFlussoOk");
                        } else {
                            log.info("Flusso di rendicontazione acquisito con anomalie.");
                            GpThreadLocal.get().log("rendicontazioni.acquisizioneFlussoOkAnomalia");
                        }
                    }
                } catch (GovPayException ce) {
                    log.error("Flusso di rendicontazione non acquisito", ce);
                    errori = true;
                } finally {
                    GpThreadLocal.get().closeTransaction(idTransaction2);
                }
            }
        }
    } catch (Exception e) {
        GpThreadLocal.get().log("rendicontazioni.acquisizioneFlussiFail", e.getMessage());
        throw new GovPayException(e);
    } finally {
        try {
            if (isClosed())
                setupConnection(GpThreadLocal.get().getTransactionId());
        } catch (Exception e) {
            log.error("Errore nel ripristino della connessione", e);
        }
    }

    GpThreadLocal.get().log("rendicontazioni.acquisizioneOk");

    String rspTxt = "";
    if (errori)
        rspTxt = "WARNING#Processo di acquisizione completato parzialmente: uno o piu' flussi non sono stati acquisiti.|";
    else
        rspTxt = "OK#Processo di acquisizione completato con successo|";

    if (response.isEmpty()) {
        return rspTxt + "Processo di acquisizione completato con successo. #Nessun flusso acquisito.";
    } else {
        return rspTxt + StringUtils.join(response, "|");
    }
}

From source file:com.selfsoft.business.service.impl.TbFixEntrustServiceImpl.java

private List<TbMaintianVo> composePart(List<TbMaintianVo> maintianvos) {

    List<TbMaintianVo> maintianvosTemp = new ArrayList<TbMaintianVo>();

    List<TbMaintianVo> maintianvosAdd = new ArrayList<TbMaintianVo>();

    if (maintianvos.size() > 0) {

        for (int i = 0; i < maintianvos.size(); i++) {

            boolean flag = false;

            if (maintianvosTemp.size() == 0) {

                maintianvosTemp.add(maintianvos.get(i));

            } else {

                if (maintianvosTemp.size() > 1) {

                    int l = 0;

                    for (TbMaintianVo _tbMaintianVo : maintianvosTemp) {

                        if (_tbMaintianVo.getPartId().equals(maintianvos.get(i).getPartId())
                                && _tbMaintianVo.getIsFree().equals(maintianvos.get(i).getIsFree())) {

                            // maintianvosTemp.set(l, maintianvos.get(i));

                            flag = true;

                            break;

                        }//from w  w  w.  j a  v a  2 s  .  c om

                        l++;

                    }

                }

            }

            if (flag) {

                continue;

            } else {

                maintianvosTemp.add(maintianvos.get(i));

            }

            TbMaintianVo temp = maintianvos.get(i);

            BigDecimal d1 = new BigDecimal(temp.getPartQuantity());

            BigDecimal d2 = new BigDecimal(temp.getTotal());

            for (int j = i + 1; j < maintianvos.size(); j++) {

                if (temp.getPartId().equals(maintianvos.get(j).getPartId())
                        && temp.getIsFree().equals(maintianvos.get(j).getIsFree())) {

                    temp.setPrice(maintianvos.get(j).getPrice());

                    d1 = d1.add(new BigDecimal(maintianvos.get(j).getPartQuantity()));

                    d2 = d2.add(new BigDecimal(maintianvos.get(j).getTotal()));

                }

            }

            temp.setPartQuantity(d1.doubleValue());

            temp.setTotal(d2.doubleValue());

            if (!temp.getIsFree().equals(1D) || !temp.getPartQuantity().equals(0d)) {

                /*
                 * temp.setPrice(new BigDecimal(temp.getTotal()).divide(new
                 * BigDecimal(temp.getPartQuantity()),2,
                 * BigDecimal.ROUND_HALF_UP).setScale(2,
                 * BigDecimal.ROUND_HALF_UP).doubleValue());
                 */

                maintianvosAdd.add(temp);

            }

        }

    }

    return maintianvosAdd;
}