Example usage for java.math BigDecimal ONE

List of usage examples for java.math BigDecimal ONE

Introduction

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

Prototype

BigDecimal ONE

To view the source code for java.math BigDecimal ONE.

Click Source Link

Document

The value 1, with a scale of 0.

Usage

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The inverse trigonometric tangent./* w ww . j  a va  2  s. com*/
 *
 * @param x the argument.
 * @return the principal value of arctan(x) in radians in the range -pi/2 to +pi/2.
 */
static public BigDecimal atan(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return atan(x.negate()).negate();

    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else if (x.doubleValue() > 0.7 && x.doubleValue() < 3.0) {
        /* Abramowitz-Stegun 4.4.34 convergence acceleration
         * 2*arctan(x) = arctan(2x/(1-x^2)) = arctan(y). x=(sqrt(1+y^2)-1)/y
         * This maps 0<=y<=3 to 0<=x<=0.73 roughly. Temporarily with 2 protectionist digits.
         */
        BigDecimal y = scalePrec(x, 2);
        BigDecimal newx = divideRound(hypot(1, y).subtract(BigDecimal.ONE), y);
        /* intermediate result with too optimistic error estimate*/
        BigDecimal resul = multiplyRound(atan(newx), 2);
        /* absolute error in the result is errx/(1+x^2), where errx = half of the ulp. */

        double eps = x.ulp().doubleValue() / (2.0 * Math.hypot(1.0, x.doubleValue()));
        MathContext mc = new MathContext(err2prec(resul.doubleValue(), eps));

        return resul.round(mc);

    } else if (x.doubleValue() < 0.71) {
        /* Taylor expansion around x=0; Abramowitz-Stegun 4.4.42 */
        final BigDecimal xhighpr = scalePrec(x, 2);
        final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr).negate();
        BigDecimal resul = xhighpr.plus();
        /* signed x^(2i+1) */
        BigDecimal xpowi = xhighpr;
        /* absolute error in the result is errx/(1+x^2), where errx = half of the ulp.
         */

        double eps = x.ulp().doubleValue() / (2.0 * Math.hypot(1.0, x.doubleValue()));

        for (int i = 1;; i++) {
            xpowi = multiplyRound(xpowi, xhighprSq);
            BigDecimal c = divideRound(xpowi, 2 * i + 1);
            resul = resul.add(c);

            if (Math.abs(c.doubleValue()) < 0.1 * eps) {
                break;
            }

        }
        MathContext mc = new MathContext(err2prec(resul.doubleValue(), eps));

        return resul.round(mc);

    } else {
        /* Taylor expansion around x=infinity; Abramowitz-Stegun 4.4.42 */
        /* absolute error in the result is errx/(1+x^2), where errx = half of the ulp.
         */
        double eps = x.ulp().doubleValue() / (2.0 * Math.hypot(1.0, x.doubleValue()));
        /* start with the term pi/2; gather its precision relative to the expected result
         */
        MathContext mc = new MathContext(2 + err2prec(3.1416, eps));
        BigDecimal onepi = pi(mc);
        BigDecimal resul = onepi.divide(new BigDecimal(2));
        final BigDecimal xhighpr = divideRound(-1, scalePrec(x, 2));
        final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr).negate();
        /* signed x^(2i+1) */
        BigDecimal xpowi = xhighpr;

        for (int i = 0;; i++) {
            BigDecimal c = divideRound(xpowi, 2 * i + 1);
            resul = resul.add(c);

            if (Math.abs(c.doubleValue()) < 0.1 * eps) {
                break;
            }
            xpowi = multiplyRound(xpowi, xhighprSq);

        }
        mc = new MathContext(err2prec(resul.doubleValue(), eps));

        return resul.round(mc);

    }
}

From source file:org.apache.pig.test.TestBuiltin.java

@Test
public void testAVGIntermediate() throws Exception {
    String[] avgTypes = { "AVGIntermediate", "DoubleAvgIntermediate", "LongAvgIntermediate",
            "IntAvgIntermediate", "FloatAvgIntermediate", "BigDecimalAvgIntermediate",
            "BigIntegerAvgIntermediate" };
    for (int k = 0; k < avgTypes.length; k++) {
        EvalFunc<?> avg = evalFuncMap.get(avgTypes[k]);
        String inputType = getInputType(avgTypes[k]);
        Tuple tup = inputMap.get(inputType);
        // The tuple we got above has a bag with input
        // values. Input to the Intermediate.exec() however comes
        // from the map which would put each value and a count of
        // 1 in a tuple and send it down. So lets create a bag with
        // tuples that have two fields - the value and a count 1.
        DataBag bag = (DataBag) tup.get(0);
        DataBag bg = bagFactory.newDefaultBag();
        for (Tuple t : bag) {
            Tuple newTuple = tupleFactory.newTuple(2);
            newTuple.set(0, t.get(0));/*  ww  w . j  a v a2 s .  c om*/
            if (inputType == "BigDecimal") {
                newTuple.set(1, BigDecimal.ONE);
            } else if (inputType == "BigInteger") {
                newTuple.set(1, BigInteger.ONE);
            } else {
                newTuple.set(1, new Long(1));
            }
            bg.add(newTuple);
        }
        Tuple intermediateInput = tupleFactory.newTuple();
        intermediateInput.append(bg);

        Object output = avg.exec(intermediateInput);

        if (inputType == "Long" || inputType == "Integer" || inputType == "IntegerAsLong") {
            Long l = (Long) ((Tuple) output).get(0);
            String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k])
                    + " ( (output) " + l + " == " + getExpected(avgTypes[k]) + " (expected) )]";
            assertEquals(msg, getExpected(avgTypes[k]), l);
        } else if (inputType == "BigDecimal") {
            BigDecimal f1 = (BigDecimal) ((Tuple) output).get(0);
            String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k])
                    + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]";
            assertEquals(msg, ((BigDecimal) getExpected(avgTypes[k])).toPlainString(), f1.toPlainString());
        } else if (inputType == "BigInteger") {
            BigInteger f1 = (BigInteger) ((Tuple) output).get(0);
            String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k])
                    + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]";
            assertEquals(msg, ((BigInteger) getExpected(avgTypes[k])).toString(), f1.toString());
        } else {
            Double f1 = (Double) ((Tuple) output).get(0);
            String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k])
                    + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]";
            assertEquals(msg, (Double) getExpected(avgTypes[k]), f1, 0.00001);
        }
        if (inputType == "BigDecimal") {
            BigDecimal f2 = (BigDecimal) ((Tuple) output).get(1);
            assertEquals("[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 4",
                    "4", f2.toPlainString());

        } else if (inputType == "BigInteger") {
            BigInteger f2 = (BigInteger) ((Tuple) output).get(1);
            assertEquals("[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 4",
                    "4", f2.toString());

        } else {
            Long f2 = (Long) ((Tuple) output).get(1);
            assertEquals(
                    "[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 11", 11,
                    f2.longValue());
        }
    }
}

From source file:pe.gob.mef.gescon.web.ui.BaseLegalMB.java

public String toEdit() {
    try {//from  w  ww  .j  a  va2  s . co m
        this.cleanAttributes();
        int index = Integer.parseInt((String) JSFUtils.getRequestParameter("index"));
        if (!CollectionUtils.isEmpty(this.getFilteredListaBaseLegal())) {
            this.setSelectedBaseLegal(this.getFilteredListaBaseLegal().get(index));
        } else {
            this.setSelectedBaseLegal(this.getListaBaseLegal().get(index));
        }
        CategoriaService categoriaService = (CategoriaService) ServiceFinder.findBean("CategoriaService");
        this.setSelectedCategoria(
                categoriaService.getCategoriaById(this.getSelectedBaseLegal().getNcategoriaid()));
        index = this.getSelectedBaseLegal().getVnumero().indexOf("-");
        this.setTiporangoId(this.getSelectedBaseLegal().getNtiporangoid());
        this.setRangoId(this.getSelectedBaseLegal().getNrangoid());
        this.setTipoNorma(this.getSelectedBaseLegal().getVnumero().substring(0, index).trim());
        this.setNumeroNorma(this.getSelectedBaseLegal().getVnumero().substring(index + 1).trim());
        this.setChkGobNacional(this.getSelectedBaseLegal().getNgobnacional().equals(BigDecimal.ONE));
        this.setChkGobRegional(this.getSelectedBaseLegal().getNgobregional().equals(BigDecimal.ONE));
        this.setChkGobLocal(this.getSelectedBaseLegal().getNgoblocal().equals(BigDecimal.ONE));
        this.setChkMancomunidades(this.getSelectedBaseLegal().getNmancomunidades().equals(BigDecimal.ONE));
        this.setChkDestacado(this.getSelectedBaseLegal().getNdestacado().equals(BigDecimal.ONE));
        this.setCodigoWiki(this.getSelectedBaseLegal().getNcodigowiki());
        ConocimientoService conocimientoService = (ConocimientoService) ServiceFinder
                .findBean("ConocimientoService");
        this.setSelectedWiki(conocimientoService.getConocimientoById(this.getCodigoWiki()));
        RangoService rangoService = (RangoService) ServiceFinder.findBean("RangoService");
        this.setListaRangos(
                new Items(rangoService.getRangosActivosByTipo(this.getSelectedBaseLegal().getNtiporangoid()),
                        null, "nrangoid", "vnombre").getItems());
        BaseLegalService service = (BaseLegalService) ServiceFinder.findBean("BaseLegalService");
        this.setListaSource(
                service.getTbaselegalesNotLinkedById(this.getSelectedBaseLegal().getNbaselegalid()));
        this.setListaTarget(service.getTbaselegalesLinkedById(this.getSelectedBaseLegal().getNbaselegalid()));
        this.setPickList(new DualListModel<BaseLegal>(this.getListaSource(), this.getListaTarget()));
        this.setFilteredListaBaseLegal(new ArrayList());
        this.setUploadFile(null);
        this.setFile(null);
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }
    return "/pages/baselegal/editar?faces-redirect=true";
}

From source file:op.care.med.inventory.PnlInventory.java

private JPanel createContentPanel4(final MedStock stock) {
    //        final String key = stock.getID() + ".xstock";

    //        if (!contentmap.containsKey(key)) {

    final JPanel pnlTX = new JPanel(new VerticalLayout());
    //            pnlTX.setLayout(new BoxLayout(pnlTX, BoxLayout.PAGE_AXIS));

    pnlTX.setOpaque(true);//from   w ww  . j  a  va  2 s  .co m
    //        pnlTX.setBackground(Color.white);
    synchronized (lstInventories) {
        pnlTX.setBackground(getColor(SYSConst.light2, lstInventories.indexOf(stock.getInventory()) % 2 != 0));
    }

    /***
     *         _       _     _ _______  __
     *        / \   __| | __| |_   _\ \/ /
     *       / _ \ / _` |/ _` | | |  \  /
     *      / ___ \ (_| | (_| | | |  /  \
     *     /_/   \_\__,_|\__,_| |_| /_/\_\
     *
     */
    JideButton btnAddTX = GUITools.createHyperlinkButton("nursingrecords.inventory.newmedstocktx",
            SYSConst.icon22add, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    new DlgTX(new MedStockTransaction(stock, BigDecimal.ONE,
                            MedStockTransactionTools.STATE_EDIT_MANUAL), new Closure() {
                                @Override
                                public void execute(Object o) {
                                    if (o != null) {
                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();

                                            final MedStockTransaction myTX = (MedStockTransaction) em.merge(o);
                                            MedStock myStock = em.merge(stock);
                                            em.lock(myStock, LockModeType.OPTIMISTIC);
                                            em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);
                                            em.lock(em.merge(myTX.getStock().getInventory().getResident()),
                                                    LockModeType.OPTIMISTIC);
                                            em.getTransaction().commit();

                                            createCP4(myStock.getInventory());

                                            buildPanel();
                                        } catch (OptimisticLockException ole) {
                                            OPDE.warn(ole);
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                                OPDE.getMainframe().emptyFrame();
                                                OPDE.getMainframe().afterLogin();
                                            }
                                            OPDE.getDisplayManager()
                                                    .addSubMessage(DisplayManager.getLockMessage());
                                        } catch (Exception e) {
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            OPDE.fatal(e);
                                        } finally {
                                            em.close();
                                        }
                                    }
                                }
                            });
                }
            });
    btnAddTX.setEnabled(!stock.isClosed());
    pnlTX.add(btnAddTX);

    /***
     *      ____  _                           _ _   _______  __
     *     / ___|| |__   _____      __   __ _| | | |_   _\ \/ /___
     *     \___ \| '_ \ / _ \ \ /\ / /  / _` | | |   | |  \  // __|
     *      ___) | | | | (_) \ V  V /  | (_| | | |   | |  /  \\__ \
     *     |____/|_| |_|\___/ \_/\_/    \__,_|_|_|   |_| /_/\_\___/
     *
     */
    OPDE.getMainframe().setBlocked(true);
    OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));

    SwingWorker worker = new SwingWorker() {

        @Override
        protected Object doInBackground() throws Exception {
            int progress = 0;

            List<MedStockTransaction> listTX = MedStockTransactionTools.getAll(stock);
            OPDE.getDisplayManager().setProgressBarMessage(
                    new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, listTX.size()));

            BigDecimal rowsum = MedStockTools.getSum(stock);
            //                BigDecimal rowsum = MedStockTools.getSum(stock);
            //                Collections.sort(stock.getStockTransaction());
            for (final MedStockTransaction tx : listTX) {
                progress++;
                OPDE.getDisplayManager().setProgressBarMessage(
                        new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, listTX.size()));
                String title = "<html><table border=\"0\">" + "<tr>" + "<td width=\"130\" align=\"left\">"
                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT)
                                .format(tx.getPit())
                        + "<br/>[" + tx.getID() + "]" + "</td>" + "<td width=\"200\" align=\"center\">"
                        + SYSTools.catchNull(tx.getText(), "--") + "</td>" +

                        "<td width=\"100\" align=\"right\">"
                        + NumberFormat.getNumberInstance().format(tx.getAmount()) + "</td>" +

                        "<td width=\"100\" align=\"right\">"
                        + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "<font color=\"red\">" : "")
                        + NumberFormat.getNumberInstance().format(rowsum)
                        + (rowsum.compareTo(BigDecimal.ZERO) < 0 ? "</font>" : "") + "</td>" +

                        (stock.getTradeForm().isWeightControlled() ? "<td width=\"100\" align=\"right\">"
                                + NumberFormat.getNumberInstance().format(tx.getWeight()) + "g" + "</td>" : "")
                        +

                        "<td width=\"100\" align=\"left\">" + SYSTools.anonymizeUser(tx.getUser().getUID())
                        + "</td>" + "</tr>" + "</table>" +

                        "</font></html>";

                rowsum = rowsum.subtract(tx.getAmount());

                final DefaultCPTitle pnlTitle = new DefaultCPTitle(title, null);

                //                pnlTitle.getLeft().addMouseListener();

                if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, "nursingrecords.inventory")) {
                    /***
                     *      ____       _ _______  __
                     *     |  _ \  ___| |_   _\ \/ /
                     *     | | | |/ _ \ | | |  \  /
                     *     | |_| |  __/ | | |  /  \
                     *     |____/ \___|_| |_| /_/\_\
                     *
                     */
                    final JButton btnDelTX = new JButton(SYSConst.icon22delete);
                    btnDelTX.setPressedIcon(SYSConst.icon22deletePressed);
                    btnDelTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                    btnDelTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    btnDelTX.setContentAreaFilled(false);
                    btnDelTX.setBorder(null);
                    btnDelTX.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btndelete.tooltip"));
                    btnDelTX.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/><i>"
                                    + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT)
                                            .format(tx.getPit())
                                    + "&nbsp;" + tx.getUser().getUID() + "</i><br/>"
                                    + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete,
                                    new Closure() {
                                        @Override
                                        public void execute(Object answer) {
                                            if (answer.equals(JOptionPane.YES_OPTION)) {
                                                EntityManager em = OPDE.createEM();
                                                try {
                                                    em.getTransaction().begin();

                                                    MedStockTransaction myTX = em.merge(tx);
                                                    MedStock myStock = em.merge(stock);
                                                    em.lock(em.merge(
                                                            myTX.getStock().getInventory().getResident()),
                                                            LockModeType.OPTIMISTIC);
                                                    em.lock(myStock, LockModeType.OPTIMISTIC);
                                                    em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);
                                                    em.remove(myTX);
                                                    //                                                myStock.getStockTransaction().remove(myTX);
                                                    em.getTransaction().commit();

                                                    //                                                synchronized (lstInventories) {
                                                    //                                                    int indexInventory = lstInventories.indexOf(stock.getInventory());
                                                    //                                                    int indexStock = lstInventories.get(indexInventory).getMedStocks().indexOf(stock);
                                                    //                                                    lstInventories.get(indexInventory).getMedStocks().remove(stock);
                                                    //                                                    lstInventories.get(indexInventory).getMedStocks().add(indexStock, myStock);
                                                    //                                                }

                                                    //                                                synchronized (linemap) {
                                                    //                                                    linemap.remove(myTX);
                                                    //                                                }

                                                    createCP4(myStock.getInventory());

                                                    buildPanel();
                                                } catch (OptimisticLockException ole) {
                                                    OPDE.warn(ole);
                                                    if (em.getTransaction().isActive()) {
                                                        em.getTransaction().rollback();
                                                    }
                                                    if (ole.getMessage()
                                                            .indexOf("Class> entity.info.Resident") > -1) {
                                                        OPDE.getMainframe().emptyFrame();
                                                        OPDE.getMainframe().afterLogin();
                                                    }
                                                    OPDE.getDisplayManager()
                                                            .addSubMessage(DisplayManager.getLockMessage());
                                                } catch (Exception e) {
                                                    if (em.getTransaction().isActive()) {
                                                        em.getTransaction().rollback();
                                                    }
                                                    OPDE.fatal(e);
                                                } finally {
                                                    em.close();
                                                }
                                            }
                                        }
                                    });

                        }
                    });
                    btnDelTX.setEnabled(
                            !stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT
                                    || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL));
                    pnlTitle.getRight().add(btnDelTX);
                }

                /***
                 *      _   _           _         _______  __
                 *     | | | |_ __   __| | ___   |_   _\ \/ /
                 *     | | | | '_ \ / _` |/ _ \    | |  \  /
                 *     | |_| | | | | (_| | (_) |   | |  /  \
                 *      \___/|_| |_|\__,_|\___/    |_| /_/\_\
                 *
                 */
                final JButton btnUndoTX = new JButton(SYSConst.icon22undo);
                btnUndoTX.setPressedIcon(SYSConst.icon22Pressed);
                btnUndoTX.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnUndoTX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnUndoTX.setContentAreaFilled(false);
                btnUndoTX.setBorder(null);
                btnUndoTX.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btnUndoTX.tooltip"));
                btnUndoTX.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        new DlgYesNo(
                                SYSTools.xx("misc.questions.undo1") + "<br/><i>"
                                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT)
                                                .format(tx.getPit())
                                        + "&nbsp;" + tx.getUser().getUID() + "</i><br/>"
                                        + SYSTools.xx("misc.questions.undo2"),
                                SYSConst.icon48undo, new Closure() {
                                    @Override
                                    public void execute(Object answer) {
                                        if (answer.equals(JOptionPane.YES_OPTION)) {
                                            EntityManager em = OPDE.createEM();
                                            try {
                                                em.getTransaction().begin();
                                                MedStock myStock = em.merge(stock);
                                                final MedStockTransaction myOldTX = em.merge(tx);

                                                myOldTX.setState(MedStockTransactionTools.STATE_CANCELLED);
                                                final MedStockTransaction myNewTX = em
                                                        .merge(new MedStockTransaction(myStock,
                                                                myOldTX.getAmount().negate(),
                                                                MedStockTransactionTools.STATE_CANCEL_REC));
                                                myOldTX.setText(SYSTools.xx("misc.msg.reversedBy") + ": "
                                                        + DateFormat
                                                                .getDateTimeInstance(DateFormat.DEFAULT,
                                                                        DateFormat.SHORT)
                                                                .format(myNewTX.getPit()));
                                                myNewTX.setText(SYSTools.xx("misc.msg.reversalFor") + ": "
                                                        + DateFormat
                                                                .getDateTimeInstance(DateFormat.DEFAULT,
                                                                        DateFormat.SHORT)
                                                                .format(myOldTX.getPit()));

                                                //                                            myStock.getStockTransaction().add(myNewTX);
                                                //                                            myStock.getStockTransaction().remove(tx);
                                                //                                            myStock.getStockTransaction().add(myOldTX);

                                                em.lock(em
                                                        .merge(myNewTX.getStock().getInventory().getResident()),
                                                        LockModeType.OPTIMISTIC);
                                                em.lock(myStock, LockModeType.OPTIMISTIC);
                                                em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);

                                                em.getTransaction().commit();

                                                //                                            synchronized (lstInventories) {
                                                //                                                int indexInventory = lstInventories.indexOf(stock.getInventory());
                                                //                                                int indexStock = lstInventories.get(indexInventory).getMedStocks().indexOf(stock);
                                                //                                                lstInventories.get(indexInventory).getMedStocks().remove(stock);
                                                //                                                lstInventories.get(indexInventory).getMedStocks().add(indexStock, myStock);
                                                //                                            }

                                                //                                            synchronized (linemap) {
                                                //                                                linemap.remove(tx);
                                                //                                            }
                                                createCP4(myStock.getInventory());
                                                buildPanel();
                                                //                                            SwingUtilities.invokeLater(new Runnable() {
                                                //                                                @Override
                                                //                                                public void run() {
                                                //                                                    synchronized (linemap) {
                                                //                                                        GUITools.flashBackground(linemap.get(myOldTX), Color.RED, 2);
                                                //                                                        GUITools.flashBackground(linemap.get(myNewTX), Color.YELLOW, 2);
                                                //                                                    }
                                                //                                                }
                                                //                                            });
                                            } catch (OptimisticLockException ole) {
                                                OPDE.warn(ole);
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                if (ole.getMessage()
                                                        .indexOf("Class> entity.info.Resident") > -1) {
                                                    OPDE.getMainframe().emptyFrame();
                                                    OPDE.getMainframe().afterLogin();
                                                }
                                                OPDE.getDisplayManager()
                                                        .addSubMessage(DisplayManager.getLockMessage());
                                            } catch (Exception e) {
                                                if (em.getTransaction().isActive()) {
                                                    em.getTransaction().rollback();
                                                }
                                                OPDE.fatal(e);
                                            } finally {
                                                em.close();
                                            }
                                        }
                                    }
                                });

                    }
                });
                btnUndoTX.setEnabled(!stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT
                        || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL));
                pnlTitle.getRight().add(btnUndoTX);

                if (stock.getTradeForm().isWeightControlled() && OPDE.getAppInfo()
                        .isAllowedTo(InternalClassACL.MANAGER, "nursingrecords.inventory")) {
                    /***
                     *               _ __        __   _       _     _
                     *      ___  ___| |\ \      / /__(_) __ _| |__ | |_
                     *     / __|/ _ \ __\ \ /\ / / _ \ |/ _` | '_ \| __|
                     *     \__ \  __/ |_ \ V  V /  __/ | (_| | | | | |_
                     *     |___/\___|\__| \_/\_/ \___|_|\__, |_| |_|\__|
                     *                                  |___/
                     */
                    final JButton btnSetWeight = new JButton(SYSConst.icon22scales);
                    btnSetWeight.setPressedIcon(SYSConst.icon22Pressed);
                    btnSetWeight.setAlignmentX(Component.RIGHT_ALIGNMENT);
                    btnSetWeight.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    btnSetWeight.setContentAreaFilled(false);
                    btnSetWeight.setBorder(null);
                    btnSetWeight.setToolTipText(SYSTools.xx("nursingrecords.inventory.tx.btnUndoTX.tooltip"));
                    btnSetWeight.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {

                            BigDecimal weight;
                            new DlgYesNo(SYSConst.icon48scales, new Closure() {
                                @Override
                                public void execute(Object o) {
                                    if (!SYSTools.catchNull(o).isEmpty()) {
                                        BigDecimal weight = (BigDecimal) o;

                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();
                                            MedStock myStock = em.merge(stock);
                                            final MedStockTransaction myTX = em.merge(tx);
                                            em.lock(myTX, LockModeType.OPTIMISTIC);
                                            myTX.setWeight(weight);
                                            em.lock(myStock, LockModeType.OPTIMISTIC);
                                            em.lock(myStock.getInventory(), LockModeType.OPTIMISTIC);

                                            em.getTransaction().commit();

                                            createCP4(myStock.getInventory());
                                            buildPanel();
                                        } catch (OptimisticLockException ole) {
                                            OPDE.warn(ole);
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                                OPDE.getMainframe().emptyFrame();
                                                OPDE.getMainframe().afterLogin();
                                            }
                                            OPDE.getDisplayManager()
                                                    .addSubMessage(DisplayManager.getLockMessage());
                                        } catch (Exception e) {
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            OPDE.fatal(e);
                                        } finally {
                                            em.close();
                                        }
                                    }
                                }
                            }, "nursingrecords.bhp.weight",
                                    NumberFormat.getNumberInstance().format(tx.getWeight()),
                                    new Validator<BigDecimal>() {
                                        @Override
                                        public boolean isValid(String value) {
                                            BigDecimal bd = parse(value);
                                            return bd != null && bd.compareTo(BigDecimal.ZERO) > 0;

                                        }

                                        @Override
                                        public BigDecimal parse(String text) {
                                            return SYSTools.parseDecimal(text);
                                        }
                                    });

                        }
                    });
                    btnSetWeight.setEnabled(
                            !stock.isClosed() && (tx.getState() == MedStockTransactionTools.STATE_DEBIT
                                    || tx.getState() == MedStockTransactionTools.STATE_CREDIT
                                    || tx.getState() == MedStockTransactionTools.STATE_EDIT_MANUAL));
                    pnlTitle.getRight().add(btnSetWeight);
                }

                pnlTX.add(pnlTitle.getMain());
            }

            return null;
        }

        @Override
        protected void done() {
            OPDE.getDisplayManager().setProgressBarMessage(null);
            OPDE.getMainframe().setBlocked(false);
        }
    };
    worker.execute();

    return pnlTX;
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The hyperbolic cosine.//from w w w.  j  a  va 2  s . c o  m
 *
 * @param x The argument.
 * @return The cosh(x) = (exp(x)+exp(-x))/2 .
 */
static public BigDecimal cosh(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return cos(x.negate());
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ONE;
    } else {
        if (x.doubleValue() > 1.5) {
            /* cosh^2(x) = 1+ sinh^2(x).
             */
            return hypot(1, sinh(x));

        } else {
            BigDecimal xhighpr = scalePrec(x, 2);
            /* Simple Taylor expansion, sum_{0=1..infinity} x^(2i)/(2i)! */
            BigDecimal resul = BigDecimal.ONE;
            /* x^i */
            BigDecimal xpowi = BigDecimal.ONE;
            /* 2i factorial */
            BigInteger ifac = BigInteger.ONE;
            /* The absolute error in the result is the error in x^2/2 which is x times the error in x.
             */

            double xUlpDbl = 0.5 * x.ulp().doubleValue() * x.doubleValue();
            /* The error in the result is set by the error in x^2/2 itself, xUlpDbl.
             * We need at most k terms to push x^(2k)/(2k)! below this value.
             * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl);
             */

            int k = (int) (Math.log(xUlpDbl) / Math.log(x.doubleValue())) / 2;
            /* The individual terms are all smaller than 1, so an estimate of 1.0 for
             * the absolute value will give a safe relative error estimate for the indivdual terms
             */
            MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / k));

            for (int i = 1;; i++) {
                /* TBD: at which precision will 2*i-1 or 2*i overflow?
                 */
                ifac = ifac.multiply(new BigInteger("" + (2 * i - 1)));
                ifac = ifac.multiply(new BigInteger("" + (2 * i)));
                xpowi = xpowi.multiply(xhighpr).multiply(xhighpr);
                BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay);
                resul = resul.add(corr);

                if (corr.abs().doubleValue() < 0.5 * xUlpDbl) {
                    break;
                }

            } /* The error in the result is governed by the error in x itself.
              */
            MathContext mc = new MathContext(err2prec(resul.doubleValue(), xUlpDbl));

            return resul.round(mc);

        }
    }
}

From source file:org.egov.restapi.util.ValidationUtil.java

public Boolean paymentAmountHasDecimals(final BigDecimal amount) {
    return amount.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == 0 ? false : true;
}

From source file:org.kuali.kfs.module.purap.service.impl.PurapAccountingServiceImpl.java

/**
 * @see org.kuali.kfs.module.purap.service.PurapAccountingService#convertMoneyToPercent(org.kuali.kfs.module.purap.document.PaymentRequestDocument)
 *///from   ww  w . ja  v  a  2  s.c o m
@Override
public void convertMoneyToPercent(PaymentRequestDocument pr) {
    LOG.debug("convertMoneyToPercent() started");

    int itemNbr = 0;

    for (Iterator<PaymentRequestItem> iter = pr.getItems().iterator(); iter.hasNext();) {
        PaymentRequestItem item = iter.next();

        itemNbr++;
        String identifier = item.getItemIdentifierString();

        if (item.getTotalAmount() != null && item.getTotalAmount().isNonZero()) {
            int numOfAccounts = item.getSourceAccountingLines().size();
            BigDecimal percentTotal = BigDecimal.ZERO;
            BigDecimal percentTotalRoundUp = BigDecimal.ZERO;
            KualiDecimal accountTotal = KualiDecimal.ZERO;
            int accountIdentifier = 0;

            for (Iterator<PurApAccountingLine> iterator = item.getSourceAccountingLines().iterator(); iterator
                    .hasNext();) {
                accountIdentifier++;
                PaymentRequestAccount account = (PaymentRequestAccount) iterator.next();

                // account.getAmount returns the wrong value for trade in source accounting lines...
                KualiDecimal accountAmount = KualiDecimal.ZERO;
                if (ObjectUtils.isNotNull(account.getAmount())) {
                    accountAmount = account.getAmount();
                }

                BigDecimal tmpPercent = BigDecimal.ZERO;
                KualiDecimal extendedPrice = item.getTotalAmount();
                tmpPercent = accountAmount.bigDecimalValue().divide(extendedPrice.bigDecimalValue(),
                        PurapConstants.CREDITMEMO_PRORATION_SCALE.intValue(), KualiDecimal.ROUND_BEHAVIOR);

                if (accountIdentifier == numOfAccounts) {
                    // if on last account, calculate the percent by subtracting current percent total from 1
                    tmpPercent = BigDecimal.ONE.subtract(percentTotal);
                }

                // test that the above amount is correct, if so just check that the total of all these matches the item total
                BigDecimal calcAmountBd = tmpPercent.multiply(extendedPrice.bigDecimalValue());
                calcAmountBd = calcAmountBd.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR);
                KualiDecimal calcAmount = new KualiDecimal(calcAmountBd);
                if (calcAmount.compareTo(accountAmount) != 0) {
                    // rounding error
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("convertMoneyToPercent() Rounding error on " + account);
                    }
                    String param1 = identifier + "." + accountIdentifier;
                    String param2 = calcAmount.bigDecimalValue().subtract(accountAmount.bigDecimalValue())
                            .toString();
                    GlobalVariables.getMessageMap().putError(item.getItemIdentifierString(),
                            PurapKeyConstants.ERROR_ITEM_ACCOUNTING_ROUNDING, param1, param2);
                    account.setAmount(calcAmount);
                }

                // update percent
                if (LOG.isDebugEnabled()) {
                    LOG.debug("convertMoneyToPercent() updating percent to " + tmpPercent);
                }
                account.setAccountLinePercent(tmpPercent.multiply(new BigDecimal(100)));
                // handle 33.33% issue
                if (accountIdentifier == numOfAccounts) {
                    account.setAccountLinePercent(new BigDecimal(100).subtract(percentTotalRoundUp));
                }

                // check total based on adjusted amount
                accountTotal = accountTotal.add(calcAmount);
                percentTotal = percentTotal.add(tmpPercent);
                percentTotalRoundUp = percentTotalRoundUp.add(account.getAccountLinePercent());
            }
        }
    }
}

From source file:pe.gob.mef.gescon.web.ui.PendienteMB.java

public String toEditPendiente(int caso) {
    String pagina = null;/*from   w  ww  .  j a  v  a 2  s. c  o  m*/
    try {
        this.setAlertaFlag("false");

        LoginMB mb = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
        PreguntaService service = (PreguntaService) ServiceFinder.findBean("PreguntaService");
        AsignacionService serviceasig = (AsignacionService) ServiceFinder.findBean("AsignacionService");

        int perfil_actual = Integer
                .parseInt(service.obtenerPerfilxUsuario(mb.getUser().getNusuarioid()).toString());
        int user_actual = Integer.parseInt(mb.getUser().getNusuarioid().toString());
        int user_creacion;
        int index = Integer.parseInt((String) JSFUtils.getRequestParameter("index"));

        if (caso == 1) {
            if (CollectionUtils.isEmpty(mb.getFilteredListaNotificacionesAsignadas())) {
                mb.setSelectedNotification(mb.getListaNotificacionesAsignadas().get(index));
            } else {
                mb.setSelectedNotification(mb.getFilteredListaNotificacionesAsignadas().get(index));
            }
        } else {
            if (caso == 2) {
                if (CollectionUtils.isEmpty(mb.getFilteredListaNotificacionesRecibidas())) {
                    mb.setSelectedNotification(mb.getListaNotificacionesRecibidas().get(index));
                } else {
                    mb.setSelectedNotification(mb.getFilteredListaNotificacionesRecibidas().get(index));
                }
            } else {
                if (CollectionUtils.isEmpty(mb.getFilteredListaNotificacionesAlerta())) {
                    mb.setSelectedNotification(mb.getListaNotificacionesAlerta().get(index));
                } else {
                    mb.setSelectedNotification(mb.getFilteredListaNotificacionesAlerta().get(index));
                }
            }
        }

        Integer tipo = mb.getSelectedNotification().getIdTipoConocimiento().intValue();
        Integer id = mb.getSelectedNotification().getIdconocimiento().intValue();
        switch (tipo) {
        case 1: {
            int situacion;
            BaseLegalService servicebl = (BaseLegalService) ServiceFinder.findBean("BaseLegalService");
            this.setSelectedBaseLegal(servicebl.getBaselegalById(BigDecimal.valueOf(id)));
            cat_antigua = this.getSelectedBaseLegal().getNcategoriaid();
            ArchivoService aservice = (ArchivoService) ServiceFinder.findBean("ArchivoService");
            this.selectedBaseLegal.setArchivo(aservice.getArchivoByBaseLegal(this.getSelectedBaseLegal()));
            index = this.getSelectedBaseLegal().getVnumero().indexOf("-");
            this.setTipoNorma(this.getSelectedBaseLegal().getVnumero().substring(0, index).trim());
            this.setNumeroNorma(this.getSelectedBaseLegal().getVnumero().substring(index + 1).trim());
            this.setChkGobNacional(this.getSelectedBaseLegal().getNgobnacional().equals(BigDecimal.ONE));
            this.setChkGobRegional(this.getSelectedBaseLegal().getNgobregional().equals(BigDecimal.ONE));
            this.setChkGobLocal(this.getSelectedBaseLegal().getNgoblocal().equals(BigDecimal.ONE));
            this.setChkMancomunidades(this.getSelectedBaseLegal().getNmancomunidades().equals(BigDecimal.ONE));
            this.setChkDestacado(BigDecimal.ONE.equals(this.getSelectedBaseLegal().getNdestacado()));
            CategoriaService categoriaService = (CategoriaService) ServiceFinder.findBean("CategoriaService");
            this.setSelectedCategoria(
                    categoriaService.getCategoriaById(this.getSelectedBaseLegal().getNcategoriaid()));
            this.setListaSource(
                    servicebl.getTbaselegalesNotLinkedById(this.getSelectedBaseLegal().getNbaselegalid()));
            this.setListaTarget(
                    servicebl.getTbaselegalesLinkedById(this.getSelectedBaseLegal().getNbaselegalid()));
            this.setPickList(new DualListModel<BaseLegal>(this.getListaSource(), this.getListaTarget()));
            setListaAsignacion(servicebl.obtenerBaseLegalxAsig(this.getSelectedBaseLegal().getNbaselegalid(),
                    mb.getUser().getNusuarioid(), Constante.BASELEGAL));
            setSelectedAsignacion(getListaAsignacion().get(0));

            user_creacion = Integer.parseInt(serviceasig
                    .getUserCreacionByBaseLegal(this.getSelectedBaseLegal().getNbaselegalid()).toString());

            if (user_creacion == user_actual) {
                this.setfButtonEspe("true");
                this.setfButton("false");
                this.setfButtonUM("false");
                this.setfButtonMod("false");
                this.setfButtonModPub("false");
            } else {
                if (perfil_actual == Constante.MODERADOR) {
                    this.setfButtonEspe("false");
                    this.setfButton("false");
                    this.setfButtonUM("false");
                    this.setfButtonMod("true");
                    this.setfButtonModPub("false");
                }
            }

            if (StringUtils.isBlank(this.getSelectedBaseLegal().getVmsjmoderador())) {
                this.fSInfMod = "false";
            } else {
                this.fSInfMod = "true";
            }
            if (StringUtils.isBlank(this.getSelectedBaseLegal().getVmsjusuariocreacion())) {
                this.fMsjUsu1 = "false";
            } else {
                this.fMsjUsu1 = "true";
            }

            this.getSelectedAsignacion().setDfecharecepcion(new Date());
            serviceasig.saveOrUpdate(this.getSelectedAsignacion());

            pagina = "/pages/Pendientes/moderarBaseLegal?faces-redirect=true";

            break;
        }
        case 2: {
            int situacion;
            this.setSelectedPregunta(service.getPreguntaById(BigDecimal.valueOf(id)));
            cat_antigua = this.getSelectedPregunta().getNcategoriaid();
            this.setEntidad(service.getNomEntidadbyIdEntidad(this.getSelectedPregunta().getNentidadid()));
            this.setChkDestacado(BigDecimal.ONE.equals(this.getSelectedPregunta().getNdestacado()));
            setListaAsignacion(service.obtenerPreguntaxAsig(this.getSelectedPregunta().getNpreguntaid(),
                    mb.getUser().getNusuarioid(), Constante.PREGUNTAS));
            setFlistaPregunta(service.obtenerPreguntas(this.getSelectedPregunta().getNpreguntaid(),
                    mb.getUser().getNusuarioid(), Constante.PREGUNTAS));

            String ruta0 = this.pathpr + this.getSelectedPregunta().getNpreguntaid().toString() + "/"
                    + BigDecimal.ZERO.toString() + "/";
            this.getSelectedPregunta().setVrespuesta(GcmFileUtils.readStringFromFileServer(ruta0, "html.txt"));

            this.setListaSourceVinculos(new ArrayList<Consulta>());
            this.setListaTargetVinculos(new ArrayList<Consulta>());
            this.setPickListPregunta(
                    new DualListModel<Consulta>(this.getListaSourceVinculos(), this.getListaTargetVinculos()));

            HashMap filters = new HashMap();
            filters.put("ntipoconocimientoid", Constante.BASELEGAL);
            filters.put("npreguntaid", this.getSelectedPregunta().getNpreguntaid());
            this.setListaTargetVinculosBL(service.getConcimientosVinculados(filters));

            filters.put("ntipoconocimientoid", Constante.PREGUNTAS);
            filters.put("npreguntaid", this.getSelectedPregunta().getNpreguntaid());
            this.setListaTargetVinculosPR(service.getConcimientosVinculados(filters));

            filters.put("ntipoconocimientoid", Constante.WIKI);
            filters.put("npreguntaid", this.getSelectedPregunta().getNpreguntaid());
            this.setListaTargetVinculosWK(service.getConcimientosVinculados(filters));

            filters.put("ntipoconocimientoid", Constante.CONTENIDO);
            filters.put("npreguntaid", this.getSelectedPregunta().getNpreguntaid());
            this.setListaTargetVinculosCT(service.getConcimientosVinculados(filters));

            filters.put("ntipoconocimientoid", Constante.BUENAPRACTICA);
            filters.put("npreguntaid", this.getSelectedPregunta().getNpreguntaid());
            this.setListaTargetVinculosBP(service.getConcimientosVinculados(filters));

            filters.put("ntipoconocimientoid", Constante.OPORTUNIDADMEJORA);
            filters.put("npreguntaid", this.getSelectedPregunta().getNpreguntaid());
            this.setListaTargetVinculosOM(service.getConcimientosVinculados(filters));

            this.setListaTargetVinculosConocimiento(new ArrayList<Consulta>());

            if (!CollectionUtils.isEmpty(this.getListaTargetVinculosBL())) {
                this.getListaTargetVinculosConocimiento().addAll(this.getListaTargetVinculosBL());
            }
            if (!CollectionUtils.isEmpty(this.getListaTargetVinculosBP())) {
                this.getListaTargetVinculosConocimiento().addAll(this.getListaTargetVinculosBP());
            }
            if (!CollectionUtils.isEmpty(this.getListaTargetVinculosCT())) {
                this.getListaTargetVinculosConocimiento().addAll(this.getListaTargetVinculosCT());
            }
            if (!CollectionUtils.isEmpty(this.getListaTargetVinculosOM())) {
                this.getListaTargetVinculosConocimiento().addAll(this.getListaTargetVinculosOM());
            }
            if (!CollectionUtils.isEmpty(this.getListaTargetVinculosWK())) {
                this.getListaTargetVinculosConocimiento().addAll(this.getListaTargetVinculosWK());
            }

            situacion = Integer.parseInt(this.getSelectedPregunta().getNsituacionid().toString());

            if (getListaAsignacion().isEmpty() || getFlistaPregunta().isEmpty()) {
                this.setfButton("false");
                this.setfButtonUM("false");
                this.setfButtonEspe("false");
                this.setfButtonMod("false");
                this.setfButtonModPub("false");
            } else {
                setSelectedAsignacion(getListaAsignacion().get(0));

                getSelectedAsignacion().setDfecharecepcion(new Date());
                serviceasig.saveOrUpdate(getSelectedAsignacion());
                perfil_actual = Integer
                        .parseInt(service.obtenerPerfilxUsuario(mb.getUser().getNusuarioid()).toString());
                if (perfil_actual == Constante.ESPECIALISTA) {
                    this.setfButtonEspe("true");
                    this.setfButton("false");
                    this.setfButtonUM("false");
                    this.setfButtonMod("false");
                    this.setfButtonModPub("false");
                } else {
                    if (perfil_actual == Constante.MODERADOR) {
                        this.setfButtonEspe("false");
                        this.setfButton("false");
                        this.setfButtonUM("false");
                        if (StringUtils.isBlank(this.getSelectedPregunta().getVrespuesta())) {
                            this.setfButtonMod("true");
                            this.setfButtonModPub("false");
                        } else {
                            this.setfButtonMod("false");
                            this.setfButtonModPub("true");
                        }
                    } else {
                        if (situacion == 1) {
                            if (StringUtils.isBlank(this.getSelectedPregunta().getVmsjmoderador())) {
                                this.setfButtonUM("false");
                            } else {
                                this.setfButtonUM("true");
                            }
                        } else {
                            if (StringUtils.isBlank(this.getSelectedPregunta().getVmsjespecialista())) {
                                this.setfButton("false");
                            } else {
                                this.setfButton("true");
                            }
                        }
                        this.setfButtonEspe("false");
                        this.setfButtonMod("false");
                        this.setfButtonModPub("false");
                    }
                }
            }
            if (situacion == 1) {
                if (StringUtils.isBlank(this.getSelectedPregunta().getVmsjmoderador())) {
                    this.fSInfMod = "false";
                } else {
                    this.fSInfMod = "true";
                }
                if (StringUtils.isBlank(this.getSelectedPregunta().getVmsjusuario1())) {
                    this.fMsjUsu1 = "false";
                } else {
                    this.fMsjUsu1 = "true";
                }
                this.fSInfEspe = "false";
                this.fMsjUsu2 = "false";
            }
            if (situacion == 2 || situacion == 3 || situacion == 4) {
                if (StringUtils.isBlank(this.getSelectedPregunta().getVmsjespecialista())) {
                    this.fSInfEspe = "false";
                } else {
                    this.fSInfEspe = "true";
                }
                if (StringUtils.isBlank(this.getSelectedPregunta().getVmsjusuario2())) {
                    this.fMsjUsu2 = "false";
                } else {
                    this.fMsjUsu2 = "true";
                }
                this.fSInfMod = "false";
                this.fMsjUsu1 = "false";
            }

            this.getSelectedAsignacion().setDfecharecepcion(new Date());
            serviceasig.saveOrUpdate(this.getSelectedAsignacion());

            if (situacion == 1) {
                pagina = "/pages/Pendientes/moderarPregunta?faces-redirect=true";
            }

            if (situacion == 2 || situacion == 3) {
                pagina = "/pages/Pendientes/responderPregunta?faces-redirect=true";
            }

            if (situacion == 5) {
                pagina = "/pages/Pendientes/publicarPregunta?faces-redirect=true";
            }

            break;
        }
        case 3: {
            int situacion;
            WikiService servicewk = (WikiService) ServiceFinder.findBean("WikiService");
            this.setSelectedWiki(servicewk.getWikiById(BigDecimal.valueOf(tipo), BigDecimal.valueOf(id)));
            cat_antigua = this.getSelectedWiki().getNcategoriaid();
            CategoriaService categoriaService = (CategoriaService) ServiceFinder.findBean("CategoriaService");
            this.setSelectedCategoria(
                    categoriaService.getCategoriaById(this.getSelectedWiki().getNcategoriaid()));
            this.setChkDestacado(BigDecimal.ONE.equals(this.getSelectedWiki().getNdestacado()));
            this.setDescripcionHtml(
                    GcmFileUtils.readStringFromFileServer(this.getSelectedWiki().getVruta(), "html.txt"));
            SeccionService seccionService = (SeccionService) ServiceFinder.findBean("SeccionService");
            this.setListaSeccion(
                    seccionService.getSeccionesByConocimiento(this.getSelectedWiki().getNconocimientoid()));
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(this.getListaSeccion())) {
                for (Seccion seccion : this.getListaSeccion()) {
                    seccion.setDetalleHtml(
                            GcmFileUtils.readStringFromFileServer(seccion.getVruta(), "html.txt"));
                }
            }
            setListaAsignacion(servicewk.obtenerWikixAsig(this.getSelectedWiki().getNconocimientoid(),
                    mb.getUser().getNusuarioid(), Constante.WIKI));
            setSelectedAsignacion(getListaAsignacion().get(0));

            this.setListaSourceVinculos(new ArrayList<Consulta>());
            this.setListaTargetVinculos(new ArrayList<Consulta>());
            this.setPickListWiki(
                    new DualListModel<Consulta>(this.getListaSourceVinculos(), this.getListaTargetVinculos()));

            this.listaTargetVinculosBL = new ArrayList<Consulta>();
            this.listaTargetVinculosPR = new ArrayList<Consulta>();
            this.listaTargetVinculosWK = new ArrayList<Consulta>();
            this.listaTargetVinculosCT = new ArrayList<Consulta>();
            this.listaTargetVinculosBP = new ArrayList<Consulta>();
            this.listaTargetVinculosOM = new ArrayList<Consulta>();

            ConocimientoService conocimientoService = (ConocimientoService) ServiceFinder
                    .findBean("ConocimientoService");
            HashMap map = new HashMap();
            map.put("nconocimientoid", this.getSelectedWiki().getNconocimientoid().toString());
            map.put("flag", true);
            map.put("ntipoconocimientoid", Constante.BASELEGAL.toString());
            this.setListaTargetVinculosBL(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.PREGUNTAS.toString());
            this.setListaTargetVinculosPR(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.BUENAPRACTICA.toString());
            this.setListaTargetVinculosBP(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.CONTENIDO.toString());
            this.setListaTargetVinculosCT(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.OPORTUNIDADMEJORA.toString());
            this.setListaTargetVinculosOM(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.WIKI.toString());
            situacion = Integer.parseInt(this.getSelectedWiki().getNsituacionid().toString());

            user_creacion = Integer.parseInt(
                    serviceasig.getUserCreacionByContenido(this.getSelectedWiki().getNtipoconocimientoid(),
                            this.getSelectedWiki().getNconocimientoid()).toString());

            if (user_creacion == user_actual) {
                this.setfButtonEspe("true");
                this.setfButton("false");
                this.setfButtonUM("false");
                this.setfButtonMod("false");
                this.setfButtonModPub("false");
            } else {
                if (perfil_actual == Constante.MODERADOR) {
                    this.setfButtonEspe("false");
                    this.setfButton("false");
                    this.setfButtonUM("false");
                    this.setfButtonMod("true");
                    this.setfButtonModPub("false");
                }
            }

            if (StringUtils.isBlank(this.getSelectedWiki().getVmsjsolicita())) {
                this.fSInfMod = "false";
            } else {
                this.fSInfMod = "true";
            }
            if (StringUtils.isBlank(this.getSelectedWiki().getVmsjrespuesta())) {
                this.fMsjUsu1 = "false";
            } else {
                this.fMsjUsu1 = "true";
            }

            this.getSelectedAsignacion().setDfecharecepcion(new Date());
            serviceasig.saveOrUpdate(this.getSelectedAsignacion());

            if (situacion == 1) {
                pagina = "/pages/Pendientes/moderarWiki?faces-redirect=true";
            }
            break;
        }
        case 4: {
            int situacion;
            ContenidoService servicect = (ContenidoService) ServiceFinder.findBean("ContenidoService");
            this.setSelectedContenido(
                    servicect.getContenidoById(BigDecimal.valueOf(tipo), BigDecimal.valueOf(id)));
            cat_antigua = this.getSelectedContenido().getNcategoriaid();
            CategoriaService categoriaService = (CategoriaService) ServiceFinder.findBean("CategoriaService");
            this.setSelectedCategoria(
                    categoriaService.getCategoriaById(this.getSelectedContenido().getNcategoriaid()));
            this.setChkDestacado(BigDecimal.ONE.equals(this.getSelectedContenido().getNdestacado()));
            this.setContenidoHtml(
                    GcmFileUtils.readStringFromFileServer(this.getSelectedContenido().getVruta(), "html.txt"));
            ArchivoConocimientoService archivoservice = (ArchivoConocimientoService) ServiceFinder
                    .findBean("ArchivoConocimientoService");
            this.setListaArchivos(
                    archivoservice.getArchivosByConocimiento(this.getSelectedContenido().getNconocimientoid()));
            setListaAsignacion(servicect.obtenerContenidoxAsig(this.getSelectedContenido().getNconocimientoid(),
                    mb.getUser().getNusuarioid(), Constante.CONTENIDO));
            setSelectedAsignacion(getListaAsignacion().get(0));

            this.setListaSourceVinculos(new ArrayList<Consulta>());
            this.setListaTargetVinculos(new ArrayList<Consulta>());
            this.setPickListContenido(
                    new DualListModel<Consulta>(this.getListaSourceVinculos(), this.getListaTargetVinculos()));

            this.listaTargetVinculosBL = new ArrayList<Consulta>();
            this.listaTargetVinculosPR = new ArrayList<Consulta>();
            this.listaTargetVinculosWK = new ArrayList<Consulta>();
            this.listaTargetVinculosCT = new ArrayList<Consulta>();
            this.listaTargetVinculosBP = new ArrayList<Consulta>();
            this.listaTargetVinculosOM = new ArrayList<Consulta>();

            HashMap filters = new HashMap();
            filters.put("ntipoconocimientoid", BigDecimal.valueOf(Long.parseLong("1")));
            filters.put("nconocimientoid", this.getSelectedContenido().getNconocimientoid());
            this.getListaTargetVinculosBL().addAll(servicect.getConcimientosVinculados(filters));

            filters.put("ntipoconocimientoid", BigDecimal.valueOf(Long.parseLong("2")));
            filters.put("nconocimientoid", this.getSelectedContenido().getNconocimientoid());
            this.getListaTargetVinculosPR().addAll(servicect.getConcimientosVinculados(filters));

            filters.put("ntipoconocimientoid", BigDecimal.valueOf(Long.parseLong("3")));
            filters.put("nconocimientoid", this.getSelectedContenido().getNconocimientoid());
            this.getListaTargetVinculosWK().addAll(servicect.getConcimientosVinculados(filters));

            filters.put("ntipoconocimientoid", BigDecimal.valueOf(Long.parseLong("4")));
            filters.put("nconocimientoid", this.getSelectedContenido().getNconocimientoid());
            this.getListaTargetVinculosCT().addAll(servicect.getConcimientosVinculados(filters));

            filters.put("ntipoconocimientoid", BigDecimal.valueOf(Long.parseLong("5")));
            filters.put("nconocimientoid", this.getSelectedContenido().getNconocimientoid());
            this.getListaTargetVinculosBP().addAll(servicect.getConcimientosVinculados(filters));

            filters.put("ntipoconocimientoid", BigDecimal.valueOf(Long.parseLong("6")));
            filters.put("nconocimientoid", this.getSelectedContenido().getNconocimientoid());
            this.getListaTargetVinculosOM().addAll(servicect.getConcimientosVinculados(filters));
            situacion = Integer.parseInt(this.getSelectedContenido().getNsituacionid().toString());
            user_creacion = Integer.parseInt(
                    serviceasig.getUserCreacionByContenido(this.getSelectedContenido().getNtipoconocimientoid(),
                            this.getSelectedContenido().getNconocimientoid()).toString());

            if (user_creacion == user_actual) {
                this.setfButtonEspe("true");
                this.setfButton("false");
                this.setfButtonUM("false");
                this.setfButtonMod("false");
                this.setfButtonModPub("false");
            } else {
                if (perfil_actual == Constante.MODERADOR) {
                    this.setfButtonEspe("false");
                    this.setfButton("false");
                    this.setfButtonUM("false");
                    this.setfButtonMod("true");
                    this.setfButtonModPub("false");
                }
            }

            if (StringUtils.isBlank(this.getSelectedContenido().getVmsjsolicita())) {
                this.fSInfMod = "false";
            } else {
                this.fSInfMod = "true";
            }
            if (StringUtils.isBlank(this.getSelectedContenido().getVmsjrespuesta())) {
                this.fMsjUsu1 = "false";
            } else {
                this.fMsjUsu1 = "true";
            }

            this.getSelectedAsignacion().setDfecharecepcion(new Date());
            serviceasig.saveOrUpdate(this.getSelectedAsignacion());

            if (situacion == 1) {
                pagina = "/pages/Pendientes/moderarContenido?faces-redirect=true";
            }
            break;
        }
        case 5: {
            int situacion;
            ConocimientoService servicebp = (ConocimientoService) ServiceFinder.findBean("ConocimientoService");
            this.setSelectedBpractica(
                    servicebp.getBpracticaById(BigDecimal.valueOf(tipo), BigDecimal.valueOf(id)));
            cat_antigua = this.getSelectedBpractica().getNcategoriaid();
            CategoriaService categoriaService = (CategoriaService) ServiceFinder.findBean("CategoriaService");
            this.setSelectedCategoria(
                    categoriaService.getCategoriaById(this.getSelectedBpractica().getNcategoriaid()));
            this.setChkDestacado(BigDecimal.ONE.equals(this.getSelectedBpractica().getNdestacado()));
            this.setDescripcionHtml(
                    GcmFileUtils.readStringFromFileServer(this.getSelectedBpractica().getVruta(), "html.txt"));
            SeccionService seccionService = (SeccionService) ServiceFinder.findBean("SeccionService");
            this.setListaSeccion(seccionService
                    .getSeccionesByConocimiento(this.getSelectedBpractica().getNconocimientoid()));
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(this.getListaSeccion())) {
                for (Seccion seccion : this.getListaSeccion()) {
                    seccion.setDetalleHtml(
                            GcmFileUtils.readStringFromFileServer(seccion.getVruta(), "html.txt"));
                }
            }
            setListaAsignacion(servicebp.obtenerBpracticaxAsig(this.getSelectedBpractica().getNconocimientoid(),
                    mb.getUser().getNusuarioid(), Constante.BUENAPRACTICA));
            setSelectedAsignacion(getListaAsignacion().get(0));

            this.setListaSourceVinculos(new ArrayList<Consulta>());
            this.setListaTargetVinculos(new ArrayList<Consulta>());
            this.setPickListBpractica(
                    new DualListModel<Consulta>(this.getListaSourceVinculos(), this.getListaTargetVinculos()));

            this.listaTargetVinculosBL = new ArrayList<Consulta>();
            this.listaTargetVinculosPR = new ArrayList<Consulta>();
            this.listaTargetVinculosWK = new ArrayList<Consulta>();
            this.listaTargetVinculosCT = new ArrayList<Consulta>();
            this.listaTargetVinculosBP = new ArrayList<Consulta>();
            this.listaTargetVinculosOM = new ArrayList<Consulta>();

            ConocimientoService conocimientoService = (ConocimientoService) ServiceFinder
                    .findBean("ConocimientoService");
            HashMap map = new HashMap();
            map.put("nconocimientoid", this.getSelectedBpractica().getNconocimientoid().toString());
            map.put("flag", true);
            map.put("ntipoconocimientoid", Constante.BASELEGAL.toString());
            this.setListaTargetVinculosBL(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.PREGUNTAS.toString());
            this.setListaTargetVinculosPR(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.BUENAPRACTICA.toString());
            this.setListaTargetVinculosBP(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.CONTENIDO.toString());
            this.setListaTargetVinculosCT(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.OPORTUNIDADMEJORA.toString());
            this.setListaTargetVinculosOM(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.WIKI.toString());
            situacion = Integer.parseInt(this.getSelectedBpractica().getNsituacionid().toString());

            user_creacion = Integer.parseInt(
                    serviceasig.getUserCreacionByContenido(this.getSelectedBpractica().getNtipoconocimientoid(),
                            this.getSelectedBpractica().getNconocimientoid()).toString());

            if (user_creacion == user_actual) {
                this.setfButtonEspe("true");
                this.setfButton("false");
                this.setfButtonUM("false");
                this.setfButtonMod("false");
                this.setfButtonModPub("false");
            } else {
                if (perfil_actual == Constante.MODERADOR) {
                    this.setfButtonEspe("false");
                    this.setfButton("false");
                    this.setfButtonUM("false");
                    this.setfButtonMod("true");
                    this.setfButtonModPub("false");
                }
            }

            if (StringUtils.isBlank(this.getSelectedBpractica().getVmsjsolicita())) {
                this.fSInfMod = "false";
            } else {
                this.fSInfMod = "true";
            }
            if (StringUtils.isBlank(this.getSelectedBpractica().getVmsjrespuesta())) {
                this.fMsjUsu1 = "false";
            } else {
                this.fMsjUsu1 = "true";
            }

            this.getSelectedAsignacion().setDfecharecepcion(new Date());
            serviceasig.saveOrUpdate(this.getSelectedAsignacion());

            if (situacion == 1) {
                pagina = "/pages/Pendientes/moderarBpracticas?faces-redirect=true";
            }
            break;
        }
        case 6: {
            int situacion;
            ConocimientoService servicebp = (ConocimientoService) ServiceFinder.findBean("ConocimientoService");
            this.setSelectedOmejora(servicebp.getOmejoraById(BigDecimal.valueOf(tipo), BigDecimal.valueOf(id)));
            cat_antigua = this.getSelectedOmejora().getNcategoriaid();
            CategoriaService categoriaService = (CategoriaService) ServiceFinder.findBean("CategoriaService");
            this.setSelectedCategoria(
                    categoriaService.getCategoriaById(this.getSelectedOmejora().getNcategoriaid()));
            this.setChkDestacado(BigDecimal.ONE.equals(this.getSelectedOmejora().getNdestacado()));
            this.setContenidoHtml(
                    GcmFileUtils.readStringFromFileServer(this.getSelectedOmejora().getVruta(), "html.txt"));
            SeccionService seccionService = (SeccionService) ServiceFinder.findBean("SeccionService");
            this.setListaSeccion(
                    seccionService.getSeccionesByConocimiento(this.getSelectedOmejora().getNconocimientoid()));
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(this.getListaSeccion())) {
                for (Seccion seccion : this.getListaSeccion()) {
                    seccion.setDetalleHtml(
                            GcmFileUtils.readStringFromFileServer(seccion.getVruta(), "html.txt"));
                }
            }
            setListaAsignacion(servicebp.obtenerOmejoraxAsig(this.getSelectedOmejora().getNconocimientoid(),
                    mb.getUser().getNusuarioid(), Constante.OPORTUNIDADMEJORA));
            setSelectedAsignacion(getListaAsignacion().get(0));

            this.setListaSourceVinculos(new ArrayList<Consulta>());
            this.setListaTargetVinculos(new ArrayList<Consulta>());
            this.setPickListOmejora(
                    new DualListModel<Consulta>(this.getListaSourceVinculos(), this.getListaTargetVinculos()));

            this.listaTargetVinculosBL = new ArrayList<Consulta>();
            this.listaTargetVinculosPR = new ArrayList<Consulta>();
            this.listaTargetVinculosWK = new ArrayList<Consulta>();
            this.listaTargetVinculosCT = new ArrayList<Consulta>();
            this.listaTargetVinculosBP = new ArrayList<Consulta>();
            this.listaTargetVinculosOM = new ArrayList<Consulta>();

            ConocimientoService conocimientoService = (ConocimientoService) ServiceFinder
                    .findBean("ConocimientoService");
            HashMap map = new HashMap();
            map.put("nconocimientoid", this.getSelectedOmejora().getNconocimientoid().toString());
            map.put("flag", true);
            map.put("ntipoconocimientoid", Constante.BASELEGAL.toString());
            this.setListaTargetVinculosBL(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.PREGUNTAS.toString());
            this.setListaTargetVinculosPR(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.BUENAPRACTICA.toString());
            this.setListaTargetVinculosBP(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.CONTENIDO.toString());
            this.setListaTargetVinculosCT(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.OPORTUNIDADMEJORA.toString());
            this.setListaTargetVinculosOM(conocimientoService.getConcimientosVinculados(map));
            map.put("ntipoconocimientoid", Constante.WIKI.toString());
            situacion = Integer.parseInt(this.getSelectedOmejora().getNsituacionid().toString());
            user_creacion = Integer.parseInt(
                    serviceasig.getUserCreacionByContenido(this.getSelectedOmejora().getNtipoconocimientoid(),
                            this.getSelectedOmejora().getNconocimientoid()).toString());

            if (user_creacion == user_actual) {
                this.setfButtonEspe("true");
                this.setfButton("false");
                this.setfButtonUM("false");
                this.setfButtonMod("false");
                this.setfButtonModPub("false");
            } else {
                if (perfil_actual == Constante.MODERADOR) {
                    this.setfButtonEspe("false");
                    this.setfButton("false");
                    this.setfButtonUM("false");
                    this.setfButtonMod("true");
                    this.setfButtonModPub("false");
                }
            }

            if (StringUtils.isBlank(this.getSelectedOmejora().getVmsjsolicita())) {
                this.fSInfMod = "false";
            } else {
                this.fSInfMod = "true";
            }
            if (StringUtils.isBlank(this.getSelectedOmejora().getVmsjrespuesta())) {
                this.fMsjUsu1 = "false";
            } else {
                this.fMsjUsu1 = "true";
            }

            this.getSelectedAsignacion().setDfecharecepcion(new Date());
            serviceasig.saveOrUpdate(this.getSelectedAsignacion());

            if (situacion == Integer.parseInt(Constante.SITUACION_POR_VERIFICAR)) {
                pagina = "/pages/Pendientes/moderarOmejora?faces-redirect=true";
            } else if (situacion == Integer.parseInt(Constante.SITUACION_VERIFICADO)) {
                pagina = "/pages/Pendientes/analizarOmejora?faces-redirect=true";
            } else if (situacion == Integer.parseInt(Constante.SITUACION_APROBADO)) {
                pagina = "/pages/Pendientes/implementarOmejora?faces-redirect=true";
            } else if (situacion == Integer.parseInt(Constante.SITUACION_IMPLEMENTADO)) {
                pagina = "/pages/Pendientes/resumenOmejora?faces-redirect=true";
            }
            break;
        }
        }
        mb.refreshNotifications();
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }
    return pagina;
}

From source file:org.yes.cart.web.service.rest.CustomerController.java

private List<ProductSearchResultRO> viewRecentlyViewedInternal() {

    final ShoppingCart cart = cartMixin.getCurrentCart();
    final long shopId = cartMixin.getCurrentShopId();

    final List<String> productIds = cart.getShoppingContext().getLatestViewedSkus();

    final List<ProductSearchResultDTO> viewedProducts = productServiceFacade.getListProducts(productIds, -1L,
            ShopCodeContext.getShopId());

    final List<ProductSearchResultRO> rvRo = new ArrayList<ProductSearchResultRO>();

    final Pair<String, Boolean> symbol = currencySymbolService.getCurrencySymbol(cart.getCurrencyCode());

    for (final ProductSearchResultDTO viewedProduct : viewedProducts) {

        final ProductSearchResultRO rv = mappingMixin.map(viewedProduct, ProductSearchResultRO.class,
                ProductSearchResultDTO.class);

        final ProductAvailabilityModel skuPam = productServiceFacade.getProductAvailability(viewedProduct,
                shopId);//from  ww  w.  jav  a  2 s .c om
        final ProductAvailabilityModelRO amRo = mappingMixin.map(skuPam, ProductAvailabilityModelRO.class,
                ProductAvailabilityModel.class);
        rv.setProductAvailabilityModel(amRo);

        final SkuPrice price = productServiceFacade.getSkuPrice(null, skuPam.getFirstAvailableSkuCode(),
                BigDecimal.ONE, cart.getCurrencyCode(), shopId);

        final SkuPriceRO priceRo = mappingMixin.map(price, SkuPriceRO.class, SkuPrice.class);
        priceRo.setSymbol(symbol.getFirst());
        priceRo.setSymbolPosition(symbol.getSecond() != null && symbol.getSecond() ? "after" : "before");

        rv.setPrice(priceRo);

        rvRo.add(rv);

    }

    return rvRo;

}

From source file:org.openbravo.erpCommon.ad_forms.AcctServer.java

public static BigDecimal getConvertionRate(String CurFrom_ID, String CurTo_ID, String ConvDate, String RateType,
        String client, String org, ConnectionProvider conn) {
    if (CurFrom_ID.equals(CurTo_ID))
        return BigDecimal.ONE;
    AcctServerData[] data = null;//  w ww .j  a va 2 s.c o  m
    try {
        if (ConvDate != null && ConvDate.equals(""))
            ConvDate = DateTimeData.today(conn);
        // ConvDate IN DATE
        if (RateType == null || RateType.equals(""))
            RateType = "S";
        data = AcctServerData.currencyConvertionRate(conn, CurFrom_ID, CurTo_ID, ConvDate, RateType, client,
                org);
    } catch (ServletException e) {
        log4j.warn(e);
        e.printStackTrace();
    }
    if (data == null || data.length == 0) {
        log4j.error("No conversion ratio");
        return BigDecimal.ZERO;
    } else {
        if (log4j.isDebugEnabled())
            log4j.debug("getConvertionRate - rate:" + data[0].converted);
        return new BigDecimal(data[0].converted);
    }
}