Example usage for java.text DateFormat getDateTimeInstance

List of usage examples for java.text DateFormat getDateTimeInstance

Introduction

In this page you can find the example usage for java.text DateFormat getDateTimeInstance.

Prototype

public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle) 

Source Link

Document

Gets the date/time formatter with the given date and time formatting styles for the default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

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);//  w  w w  .j  av  a 2 s  . c  o  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.methodize.nntprss.admin.AdminServlet.java

private void cmdShowCurrentChannels(HttpServletResponse response) throws ServletException, IOException {

    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);

    Writer writer = response.getWriter();
    writeHeader(writer, TAB_VIEW_CHANNELS);

    writeCheckboxSelector(writer, "checkAllChannels", "chl", "channels");

    writer.write("<form name='channels' action='/?action=channelaction' method='POST'>");
    writer.write("<table class='tableborder' border='0'>");
    writer.write("<tr><th colspan='5' class='tableHead'>Channels</td></th>");
    //      writer.write("<tr><th class='subHead'><input type='checkbox' name='change' onClick='checkAllChannels(this);'></th><th class='subHead'>Newsgroup Name</th><th class='subHead'>RSS URL</th><th class='subHead'>Last Polled</th></tr>");
    writer.write(/*from  ww  w  .  j  av  a2 s  .c om*/
            "<tr><th class='subHead'><input type='checkbox' name='change' onClick='checkAllChannels(this);'></th><th class='subHead'>Newsgroup Name</th><th class='subHead'>&nbsp;</th><th class='subHead'>Feed URL</th><th class='subHead'>Last Polled</th></tr>");

    ChannelManager channelManager = (ChannelManager) getServletContext()
            .getAttribute(AdminServer.SERVLET_CTX_RSS_MANAGER);
    NNTPServer nntpServer = (NNTPServer) getServletContext().getAttribute(AdminServer.SERVLET_CTX_NNTP_SERVER);

    Iterator channelIter = channelManager.channels();
    String newsPrefix = getNewsURLPrefix(nntpServer);

    while (channelIter.hasNext()) {
        Channel channel = (Channel) channelIter.next();
        writer.write("<tr><td class='row1'><input type='checkbox' name='chl"
                + HTMLHelper.escapeString(channel.getName()) + "'></td>");

        // Truncate displayed URL...
        String url = channel.getUrl();
        if (url.length() > 32) {
            url = url.substring(0, 32) + "...";
        }

        String lastPolled;
        if (channel.getLastPolled() != null) {
            lastPolled = df.format(channel.getLastPolled());
        } else {
            lastPolled = "Awaiting poll";
        }

        String parser = (channel.isParseAtAllCost() ? "*" : "");

        switch (channel.getStatus()) {
        case Channel.STATUS_INVALID_CONTENT:
        case Channel.STATUS_NOT_FOUND:
        case Channel.STATUS_UNKNOWN_HOST:
        case Channel.STATUS_NO_ROUTE_TO_HOST:
        case Channel.STATUS_PROXY_AUTHENTICATION_REQUIRED:
        case Channel.STATUS_USER_AUTHENTICATION_REQUIRED:
            writer.write("<td class='chlerror' bgcolor='#FF0000'>" + parser
                    + "<a class='row' title='Channel configuration' href='/?action=show&name="
                    + URLEncoder.encode(channel.getName()) + "'><font color='#FFFFFF'>" + channel.getName()
                    + "</font></a></td>");
            writer.write(
                    "<td class='chlerror' bgcolor='#FF0000'><a class='row' title='Read this channel in your default newsreader' href='"
                            + newsPrefix + HTMLHelper.escapeString(channel.getName())
                            + "'><font color='#FFFFFF'>[Read]</font></a></td>");
            writer.write(
                    "<td class='chlerror' bgcolor='#FF0000'><font color='#FFFFFF'>" + url + "</font></td>");
            writer.write("<td class='chlerror' bgcolor='#FF0000'><font color='#FFFFFF'>" + lastPolled
                    + "</font></td></tr>");
            break;
        case Channel.STATUS_SOCKET_EXCEPTION:
        case Channel.STATUS_CONNECTION_TIMEOUT:
            writer.write("<td class='chlwarning' bgcolor='#FFFF00'>" + parser
                    + "<a class='row' title='Channel configuration' href='/?action=show&name="
                    + URLEncoder.encode(channel.getName()) + "'><font color='#000000'>" + channel.getName()
                    + "</font></a></td>");
            writer.write(
                    "<td class='chlwarning' bgcolor='#FFFF00'><a class='row' title='Read this channel in your default newsreader' href='"
                            + newsPrefix + HTMLHelper.escapeString(channel.getName()) + "'>[Read]</a></td>");
            writer.write(
                    "<td class='chlwarning' bgcolor='#FFFF00'><font color='#000000'>" + url + "</font></td>");
            writer.write("<td class='chlwarning' bgcolor='#FFFF00'><font color='#000000'>" + lastPolled
                    + "</font></td></tr>");
            break;
        default:
            if (channel.isEnabled()) {
                writer.write("<td class='row1'>" + parser
                        + "<a class='row' title='Channel configuration' href='/?action=show&name="
                        + URLEncoder.encode(channel.getName()) + "'>" + channel.getName() + "</a></td>");
                writer.write(
                        "<td class='row1'><a class='row' title='Read this channel in your default newsreader' href='"
                                + newsPrefix + HTMLHelper.escapeString(channel.getName())
                                + "'>[Read]</a></td>");

                writer.write("<td class='row1'>" + url + "</td>");
                writer.write("<td class='row1'>" + lastPolled + "</td></tr>");
            } else {
                writer.write("<td class='chldisabled' bgcolor='#CCCCCC'>" + parser
                        + "<a class='row' title='Channel configuration' href='/?action=show&name="
                        + URLEncoder.encode(channel.getName()) + "'>" + channel.getName() + "</a></td>");
                writer.write(
                        "<td class='chldisabled'><a class='row' title='Read this channel in your default newsreader' href='"
                                + newsPrefix + HTMLHelper.escapeString(channel.getName())
                                + "'>[Read]</a></td>");
                writer.write("<td class='chldisabled' bgcolor='#CCCCCC'>" + url + "</td>");
                writer.write("<td class='chldisabled' bgcolor='#CCCCCC'>" + lastPolled + "</td></tr>");
            }
        }
    }

    writer.write("<tr><td class='row2' colspan='5'>");
    writer.write(
            "<input type='submit' onClick='return confirm(\"Are you sure you want to delete these channels?\");' name='delete' value='Delete Selected Channels'>&nbsp;&nbsp;"
                    + "<input type='submit' onClick='return confirm(\"Are you sure you want to repoll these channels?\");' name='repoll' value='Repoll Selected Channels'>"
                    + "</td></tr>");

    writer.write("</table><font size='-1'>[* = Channel configured for Parse-At-All-Cost parser]</font><p>");
    writer.write("</form><p>");
    writeFooter(writer);
    writer.flush();

}

From source file:op.care.reports.PnlReport.java

private JPanel getMenu(final NReport nreport) {

    JPanel pnlMenu = new JPanel(new VerticalLayout());

    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        /***//from   ww w  .  j a  v a  2 s  . c o m
         *      _____    _ _ _
         *     | ____|__| (_) |_
         *     |  _| / _` | | __|
         *     | |__| (_| | | |_
         *     |_____\__,_|_|\__|
         *
         */
        final JButton btnEdit = GUITools.createHyperlinkButton("nursingrecords.reports.btnEdit.tooltip",
                SYSConst.icon22edit3, null);
        btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEdit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgReport(nreport.clone(), new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {

                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                final NReport newReport = em.merge((NReport) o);
                                NReport oldReport = em.merge(nreport);
                                em.lock(oldReport, LockModeType.OPTIMISTIC);
                                newReport.setReplacementFor(oldReport);

                                for (SYSNR2FILE oldAssignment : oldReport.getAttachedFilesConnections()) {
                                    em.remove(oldAssignment);
                                }
                                oldReport.getAttachedFilesConnections().clear();
                                for (SYSNR2PROCESS oldAssignment : oldReport.getAttachedQProcessConnections()) {
                                    em.remove(oldAssignment);
                                }
                                oldReport.getAttachedQProcessConnections().clear();

                                oldReport.setEditedBy(em.merge(OPDE.getLogin().getUser()));
                                oldReport.setEditDate(new Date());
                                oldReport.setReplacedBy(newReport);

                                em.getTransaction().commit();

                                final String keyNewDay = DateFormat.getDateInstance()
                                        .format(newReport.getPit());
                                final String keyOldDay = DateFormat.getDateInstance()
                                        .format(oldReport.getPit());

                                synchronized (contentmap) {
                                    contentmap.remove(keyNewDay);
                                    contentmap.remove(keyOldDay);
                                }
                                synchronized (linemap) {
                                    linemap.remove(oldReport);
                                }

                                synchronized (valuecache) {
                                    valuecache.get(keyOldDay).remove(nreport);
                                    valuecache.get(keyOldDay).add(oldReport);
                                    Collections.sort(valuecache.get(keyOldDay));

                                    if (valuecache.containsKey(keyNewDay)) {
                                        valuecache.get(keyNewDay).add(newReport);
                                        Collections.sort(valuecache.get(keyNewDay));
                                    }
                                }

                                synchronized (listUsedCommontags) {
                                    boolean reloadSearch = false;
                                    for (Commontags ctag : newReport.getCommontags()) {
                                        if (!listUsedCommontags.contains(ctag)) {
                                            listUsedCommontags.add(ctag);
                                            reloadSearch = true;
                                        }
                                    }
                                    if (reloadSearch) {
                                        prepareSearchArea();
                                    }
                                }

                                if (minmax.isAfter(new DateTime(newReport.getPit()))) {
                                    minmax.setStart(new DateTime(newReport.getPit()));
                                }

                                if (minmax.isBefore(new DateTime(newReport.getPit()))) {
                                    minmax.setEnd(new DateTime(newReport.getPit()));
                                }

                                createCP4Day(new LocalDate(oldReport.getPit()));
                                createCP4Day(new LocalDate(newReport.getPit()));

                                buildPanel();
                                GUITools.scroll2show(jspReports, cpMap.get(keyNewDay), cpsReports,
                                        new Closure() {
                                            @Override
                                            public void execute(Object o) {
                                                GUITools.flashBackground(linemap.get(newReport), 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();
                                } else {
                                    reloadDisplay(true);
                                }
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                        }
                    }
                });
            }
        });
        btnEdit.setEnabled(NReportTools.isChangeable(nreport));
        pnlMenu.add(btnEdit);
        /***
         *      ____       _      _
         *     |  _ \  ___| | ___| |_ ___
         *     | | | |/ _ \ |/ _ \ __/ _ \
         *     | |_| |  __/ |  __/ ||  __/
         *     |____/ \___|_|\___|\__\___|
         *
         */
        final JButton btnDelete = GUITools.createHyperlinkButton("nursingrecords.reports.btnDelete.tooltip",
                SYSConst.icon22delete, null);
        btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnDelete.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(
                                        nreport.getPit())
                                + "</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();
                                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                        final NReport delReport = em.merge(nreport);
                                        em.lock(delReport, LockModeType.OPTIMISTIC);
                                        delReport.setDeletedBy(em.merge(OPDE.getLogin().getUser()));
                                        for (SYSNR2FILE oldAssignment : delReport
                                                .getAttachedFilesConnections()) {
                                            em.remove(oldAssignment);
                                        }
                                        delReport.getAttachedFilesConnections().clear();
                                        for (SYSNR2PROCESS oldAssignment : delReport
                                                .getAttachedQProcessConnections()) {
                                            em.remove(oldAssignment);
                                        }
                                        delReport.getAttachedQProcessConnections().clear();
                                        em.getTransaction().commit();

                                        final String keyDay = DateFormat.getDateInstance()
                                                .format(delReport.getPit());

                                        synchronized (contentmap) {
                                            contentmap.remove(keyDay);
                                        }
                                        synchronized (linemap) {
                                            linemap.remove(delReport);
                                        }

                                        synchronized (valuecache) {
                                            valuecache.get(keyDay).remove(nreport);
                                            valuecache.get(keyDay).add(delReport);
                                            Collections.sort(valuecache.get(keyDay));
                                        }

                                        createCP4Day(new LocalDate(delReport.getPit()));

                                        buildPanel();
                                        if (tbShowReplaced.isSelected()) {
                                            GUITools.flashBackground(linemap.get(delReport), 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();
                                        } else {
                                            reloadDisplay(true);
                                        }
                                    } catch (Exception e) {
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }

                                }
                            }
                        });
            }
        });
        btnDelete.setEnabled(NReportTools.isChangeable(nreport));
        pnlMenu.add(btnDelete);

        /***
         *      _     _       _____  _    ____
         *     | |__ | |_ _ _|_   _|/ \  / ___|___
         *     | '_ \| __| '_ \| | / _ \| |  _/ __|
         *     | |_) | |_| | | | |/ ___ \ |_| \__ \
         *     |_.__/ \__|_| |_|_/_/   \_\____|___/
         *
         */
        final JButton btnTAGs = GUITools.createHyperlinkButton("misc.msg.editTags", SYSConst.icon22tagPurple,
                null);
        btnTAGs.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnTAGs.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                final JidePopup popup = new JidePopup();

                final JPanel pnl = new JPanel(new BorderLayout(5, 5));
                final PnlCommonTags pnlCommonTags = new PnlCommonTags(nreport.getCommontags(), true, 3);
                pnl.add(new JScrollPane(pnlCommonTags), BorderLayout.CENTER);
                JButton btnApply = new JButton(SYSConst.icon22apply);
                pnl.add(btnApply, BorderLayout.SOUTH);
                btnApply.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        EntityManager em = OPDE.createEM();
                        try {
                            em.getTransaction().begin();
                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            final NReport myReport = em.merge(nreport);
                            em.lock(myReport, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            myReport.getCommontags().clear();
                            for (Commontags commontag : pnlCommonTags.getListSelectedTags()) {
                                myReport.getCommontags().add(em.merge(commontag));
                            }

                            em.getTransaction().commit();

                            final String keyNewDay = DateFormat.getDateInstance().format(myReport.getPit());

                            synchronized (contentmap) {
                                contentmap.remove(keyNewDay);
                            }
                            synchronized (linemap) {
                                linemap.remove(nreport);
                            }

                            synchronized (valuecache) {
                                valuecache.get(keyNewDay).remove(nreport);
                                valuecache.get(keyNewDay).add(myReport);
                                Collections.sort(valuecache.get(keyNewDay));
                            }

                            synchronized (listUsedCommontags) {
                                boolean reloadSearch = false;
                                for (Commontags ctag : myReport.getCommontags()) {
                                    if (!listUsedCommontags.contains(ctag)) {
                                        listUsedCommontags.add(ctag);
                                        reloadSearch = true;
                                    }
                                }
                                if (reloadSearch) {
                                    prepareSearchArea();
                                }
                            }

                            createCP4Day(new LocalDate(myReport.getPit()));

                            buildPanel();
                            GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2);
                        } catch (OptimisticLockException ole) {
                            OPDE.warn(ole);
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            } else {
                                reloadDisplay(true);
                            }
                        } catch (Exception e) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }
                    }
                });

                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.setOwner(btnTAGs);
                popup.removeExcludedComponent(btnTAGs);
                pnl.setPreferredSize(new Dimension(350, 150));
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

                GUITools.showPopup(popup, SwingConstants.WEST);

            }
        });
        btnTAGs.setEnabled(NReportTools.isChangeable(nreport) && NReportTools.isMine(nreport));
        pnlMenu.add(btnTAGs);

        /***
         *      _     _         __  __ _             _
         *     | |__ | |_ _ __ |  \/  (_)_ __  _   _| |_ ___  ___
         *     | '_ \| __| '_ \| |\/| | | '_ \| | | | __/ _ \/ __|
         *     | |_) | |_| | | | |  | | | | | | |_| | ||  __/\__ \
         *     |_.__/ \__|_| |_|_|  |_|_|_| |_|\__,_|\__\___||___/
         *
         */
        final JButton btnMinutes = GUITools.createHyperlinkButton("nursingrecords.reports.btnminutes.tooltip",
                SYSConst.icon22clock, null);
        btnMinutes.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnMinutes.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {

                final JPopupMenu menu = SYSCalendar.getMinutesMenu(
                        new int[] { 1, 2, 3, 4, 5, 10, 15, 20, 30, 45, 60, 120, 240, 360 }, new Closure() {
                            @Override
                            public void execute(Object o) {
                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();

                                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                    NReport myReport = em.merge(nreport);
                                    em.lock(myReport, LockModeType.OPTIMISTIC);

                                    myReport.setMinutes((Integer) o);
                                    myReport.setEditDate(new Date());

                                    em.getTransaction().commit();

                                    final String keyNewDay = DateFormat.getDateInstance()
                                            .format(myReport.getPit());

                                    synchronized (contentmap) {
                                        contentmap.remove(keyNewDay);
                                    }
                                    synchronized (linemap) {
                                        linemap.remove(nreport);
                                    }

                                    synchronized (valuecache) {
                                        valuecache.get(keyNewDay).remove(nreport);
                                        valuecache.get(keyNewDay).add(myReport);
                                        Collections.sort(valuecache.get(keyNewDay));
                                    }

                                    createCP4Day(new LocalDate(myReport.getPit()));

                                    buildPanel();
                                    GUITools.flashBackground(linemap.get(myReport), 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();
                                    } else {
                                        reloadDisplay(true);
                                    }
                                } catch (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }
                            }
                        });

                menu.show(btnMinutes, 0, btnMinutes.getHeight());
            }
        });
        btnMinutes.setEnabled(!nreport.isObsolete() && NReportTools.isMine(nreport));
        pnlMenu.add(btnMinutes);

        pnlMenu.add(new JSeparator());

        /***
         *      _     _         _____ _ _
         *     | |__ | |_ _ __ |  ___(_) | ___  ___
         *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
         *     | |_) | |_| | | |  _| | | |  __/\__ \
         *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
         *
         */
        final JButton btnFiles = GUITools.createHyperlinkButton("misc.btnfiles.tooltip", SYSConst.icon22attach,
                null);
        btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnFiles.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                Closure fileHandleClosure = nreport.isObsolete() ? null : new Closure() {
                    @Override
                    public void execute(Object o) {
                        EntityManager em = OPDE.createEM();
                        final NReport myReport = em.find(NReport.class, nreport.getID());
                        em.close();

                        final String keyNewDay = DateFormat.getDateInstance().format(myReport.getPit());

                        synchronized (contentmap) {
                            contentmap.remove(keyNewDay);
                        }
                        synchronized (linemap) {
                            linemap.remove(nreport);
                        }

                        synchronized (valuecache) {
                            valuecache.get(keyNewDay).remove(nreport);
                            valuecache.get(keyNewDay).add(myReport);
                            Collections.sort(valuecache.get(keyNewDay));
                        }

                        createCP4Day(new LocalDate(myReport.getPit()));

                        buildPanel();
                        GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2);
                    }
                };
                new DlgFiles(nreport, fileHandleClosure);
            }
        });
        btnFiles.setEnabled(OPDE.isFTPworking());
        pnlMenu.add(btnFiles);

        /***
         *      _     _         ____
         *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
         *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
         *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
         *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
         *
         */
        final JButton btnProcess = GUITools.createHyperlinkButton("misc.btnprocess.tooltip",
                SYSConst.icon22link, null);
        btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnProcess.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgProcessAssign(nreport, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o == null) {
                            return;
                        }
                        Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

                        ArrayList<QProcess> assigned = result.getFirst();
                        ArrayList<QProcess> unassigned = result.getSecond();

                        EntityManager em = OPDE.createEM();

                        try {
                            em.getTransaction().begin();

                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            NReport myReport = em.merge(nreport);
                            em.lock(myReport, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            ArrayList<SYSNR2PROCESS> attached = new ArrayList<SYSNR2PROCESS>(
                                    myReport.getAttachedQProcessConnections());
                            for (SYSNR2PROCESS linkObject : attached) {
                                if (unassigned.contains(linkObject.getQProcess())) {
                                    linkObject.getQProcess().getAttachedNReportConnections().remove(linkObject);
                                    linkObject.getNReport().getAttachedQProcessConnections().remove(linkObject);
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                    + nreport.getTitle() + " ID: " + nreport.getID(),
                                            PReportTools.PREPORT_TYPE_REMOVE_ELEMENT,
                                            linkObject.getQProcess()));
                                    em.remove(linkObject);
                                }
                            }
                            attached.clear();

                            for (QProcess qProcess : assigned) {
                                java.util.List<QProcessElement> listElements = qProcess.getElements();
                                if (!listElements.contains(myReport)) {
                                    QProcess myQProcess = em.merge(qProcess);
                                    SYSNR2PROCESS myLinkObject = em
                                            .merge(new SYSNR2PROCESS(myQProcess, myReport));
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                    + nreport.getTitle() + " ID: " + nreport.getID(),
                                            PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                    qProcess.getAttachedNReportConnections().add(myLinkObject);
                                    myReport.getAttachedQProcessConnections().add(myLinkObject);
                                }
                            }

                            em.getTransaction().commit();

                            final String keyNewDay = DateFormat.getDateInstance().format(myReport.getPit());

                            synchronized (contentmap) {
                                contentmap.remove(keyNewDay);
                            }
                            synchronized (linemap) {
                                linemap.remove(nreport);
                            }

                            synchronized (valuecache) {
                                valuecache.get(keyNewDay).remove(nreport);
                                valuecache.get(keyNewDay).add(myReport);
                                Collections.sort(valuecache.get(keyNewDay));
                            }

                            createCP4Day(new LocalDate(myReport.getPit()));

                            buildPanel();
                            GUITools.flashBackground(linemap.get(myReport), 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();
                            } else {
                                reloadDisplay(true);
                            }
                        } catch (RollbackException 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();
                        }

                    }
                });
            }
        });
        pnlMenu.add(btnProcess);

    }
    return pnlMenu;
}

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

private CategoryPlot getCategoryPlot(List<cfCHARTSERIESData> series, String xAxisTitle, String yAxisTitle,
        String labelFormat, boolean bShowMarkers, int markerSize, boolean bShow3D, String tipStyle,
        String drillDownUrl, int xOffset, int yOffset, int yAxisUnits, String seriesPlacement,
        boolean bSortXAxis, int height, String[] yAxisSymbols, int gridLines) throws cfmRunTimeException {
    // Create a category plot
    CategoryPlot plot = new CategoryPlot();

    // Set the domain axis (the x-axis)
    org.jfree.chart.axis.CategoryAxis categoryAxis;
    if (bShow3D)/*from   www  . j a va 2s.c o m*/
        categoryAxis = new CategoryAxis3D(xAxisTitle);
    else
        categoryAxis = new CategoryAxis(xAxisTitle);
    plot.setDomainAxis(categoryAxis);

    // Set the range axis (the y-axis)
    ValueAxis valueAxis;
    DateFormat dateFormat = null;
    NumberFormat numberFormat = null;

    // Ignore a label format of date if the y-axis is using symbols
    if (labelFormat.equals("date") && (yAxisSymbols == null)) {
        valueAxis = new DateAxis(yAxisTitle);
        dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        ((DateAxis) valueAxis).setDateFormatOverride(dateFormat);
    } else {
        if (yAxisSymbols != null) {
            valueAxis = new SymbolAxis(yAxisTitle, yAxisSymbols);
            ((SymbolAxis) valueAxis).setGridBandsVisible(false);
            ((SymbolAxis) valueAxis).setAutoRangeStickyZero(true);
        } else if (bShow3D) {
            valueAxis = new NumberAxis3D(yAxisTitle);
        } else {
            valueAxis = new NumberAxis(yAxisTitle);
        }

        if (labelFormat.equals("currency")) {
            ((NumberAxis) valueAxis).setNumberFormatOverride(NumberFormat.getCurrencyInstance());
            numberFormat = NumberFormat.getCurrencyInstance();
        } else if (labelFormat.equals("percent")) {
            numberFormat = NumberFormat.getPercentInstance();
            numberFormat.setMaximumFractionDigits(3); // without this change .11443
                                                      // would be displayed as 11%
                                                      // instead of 11.443%
            ((NumberAxis) valueAxis).setNumberFormatOverride(numberFormat);
        } else {
            numberFormat = NumberFormat.getInstance();
        }

        if (yAxisUnits != 0)
            ((NumberAxis) valueAxis).setTickUnit(new NumberTickUnit(yAxisUnits));
    }
    plot.setRangeAxis(valueAxis);

    // Add a dataset and renderer for each series
    int barChartDatasetIndex = -1;
    int hBarChartDatasetIndex = -1;
    int num = 0;
    MinMaxData minMax = new MinMaxData();
    for (int i = 0; i < series.size(); i++) {
        cfCHARTSERIESData seriesData = series.get(i);

        // If the sortXAxis attribute was set to "yes" then sort the data.
        // NOTE: this attribute is only used with category charts.
        if (bSortXAxis)
            seriesData.sort();

        DefaultCategoryDataset dataset;
        if ((barChartDatasetIndex != -1) && (seriesData.getType().equals("bar"))) {
            dataset = (DefaultCategoryDataset) plot.getDataset(barChartDatasetIndex);

            addSeriesDataToDataset(seriesData, dataset, minMax);

            // Set the paint style for this series
            setPaintStyle(seriesData.getPaintStyle(), plot.getRenderer(barChartDatasetIndex),
                    dataset.getRowCount() - 1, height);

            // Add the color list for this series to the custom color renderer
            CustomColorRenderer cr = (CustomColorRenderer) plot.getRenderer(barChartDatasetIndex);
            cr.addColors(getColorList(seriesData));

            continue;
        } else if ((hBarChartDatasetIndex != -1) && (seriesData.getType().equals("horizontalbar"))) {
            dataset = (DefaultCategoryDataset) plot.getDataset(hBarChartDatasetIndex);

            addSeriesDataToDataset(seriesData, dataset, minMax);

            // Set the paint style for this series
            setPaintStyle(seriesData.getPaintStyle(), plot.getRenderer(hBarChartDatasetIndex),
                    dataset.getRowCount() - 1, height);

            // Add the color list for this series to the custom color renderer
            CustomColorRenderer cr = (CustomColorRenderer) plot.getRenderer(hBarChartDatasetIndex);
            cr.addColors(getColorList(seriesData));

            continue;
        } else {
            dataset = new DefaultCategoryDataset();

            addSeriesDataToDataset(seriesData, dataset, minMax);
        }

        plot.setDataset(num, dataset);

        AbstractCategoryItemRenderer renderer = null;
        if (seriesData.getType().equals("bar")) {
            plot.setOrientation(PlotOrientation.VERTICAL);
            renderer = getBarRenderer(seriesPlacement, bShow3D, xOffset, yOffset, getColorList(seriesData));
            ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
                    TextAnchor.BOTTOM_CENTER);
            renderer.setPositiveItemLabelPosition(position1);
            ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6,
                    TextAnchor.TOP_CENTER);
            renderer.setNegativeItemLabelPosition(position2);
            ((BarRenderer) renderer).setItemMargin(0.0); // The margin between items
                                                         // in the same category
            categoryAxis.setCategoryMargin(0.2); // The margin between each category

            barChartDatasetIndex = num;
        } else if (seriesData.getType().equals("horizontalbar")) {
            plot.setOrientation(PlotOrientation.HORIZONTAL);
            plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
            renderer = getBarRenderer(seriesPlacement, bShow3D, xOffset, yOffset, getColorList(seriesData));
            if (bShow3D) {
                // change rendering order to ensure that bar overlapping is the
                // right way around
                plot.setRowRenderingOrder(org.jfree.util.SortOrder.DESCENDING);
                plot.setColumnRenderingOrder(org.jfree.util.SortOrder.DESCENDING);
            }
            ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3,
                    TextAnchor.CENTER_LEFT);
            renderer.setPositiveItemLabelPosition(position1);
            ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE9,
                    TextAnchor.CENTER_RIGHT);
            renderer.setNegativeItemLabelPosition(position2);
            ((BarRenderer) renderer).setItemMargin(0.0); // The margin between items
                                                         // in the same category
            categoryAxis.setCategoryMargin(0.2); // The margin between each category

            hBarChartDatasetIndex = num;
        } else if (seriesData.getType().equals("line")) {
            if (bShow3D) {
                renderer = new LineRenderer3D();
                ((LineRenderer3D) renderer).setXOffset(xOffset);
                ((LineRenderer3D) renderer).setYOffset(yOffset);
            } else {
                renderer = new LineAndShapeRenderer(true, false);
            }

            // Enable/Disable displaying of markers
            ((LineAndShapeRenderer) renderer).setShapesVisible(bShowMarkers);

            // Set the shape of the markers based on the markerSize value
            ((LineAndShapeRenderer) renderer).setShape(getMarker(seriesData.getMarkerStyle(), markerSize));
        } else if (seriesData.getType().equals("area")) {
            if (seriesPlacement.equals("stacked"))
                renderer = new StackedAreaRenderer(); // this doesn't work for some
                                                      // reason
            else
                renderer = new AreaRenderer();

            // Truncate the first and last values to match CFMX 7
            ((AreaRenderer) renderer).setEndType(AreaRendererEndType.TRUNCATE);

            categoryAxis.setCategoryMargin(0.0);
        } else if (seriesData.getType().equals("step")) {
            renderer = new CategoryStepRenderer(true);
        } else if (seriesData.getType().equals("scatter")) {
            renderer = new LineAndShapeRenderer(false, true);

            // Set the shape of the markers based on the markerSize value
            ((LineAndShapeRenderer) renderer).setShape(getMarker(seriesData.getMarkerStyle(), markerSize));
        }

        if (!tipStyle.equals("none")) {
            if (dateFormat != null)
                renderer.setBaseToolTipGenerator(
                        new StandardCategoryToolTipGenerator("({0}, {1}) = {2}", dateFormat));
            else
                renderer.setBaseToolTipGenerator(
                        new StandardCategoryToolTipGenerator("({0}, {1}) = {2}", numberFormat));
        }

        if (drillDownUrl != null) {
            if (dateFormat != null)
                renderer.setBaseItemURLGenerator(
                        new com.newatlanta.bluedragon.CategoryURLGenerator(drillDownUrl, dateFormat));
            else
                renderer.setBaseItemURLGenerator(
                        new com.newatlanta.bluedragon.CategoryURLGenerator(drillDownUrl, numberFormat));
        }

        if (seriesData.getSeriesColor() != null)
            renderer.setSeriesPaint(0, convertStringToColor(seriesData.getSeriesColor()));

        String dataLabelStyle = seriesData.getDataLabelStyle();
        if (labelFormat.equals("date")) {
            if (dataLabelStyle.equals("none")) {
                renderer.setItemLabelsVisible(false);
            } else {
                setCategoryItemLabelsData(renderer, seriesData);
                if (dataLabelStyle.equals("value"))
                    renderer.setItemLabelGenerator(
                            new CategoryItemLabelGenerator("{2}", dateFormat, yAxisSymbols));
                else if (dataLabelStyle.equals("rowlabel"))
                    renderer.setItemLabelGenerator(
                            new CategoryItemLabelGenerator("{0}", dateFormat, yAxisSymbols));
                else if (dataLabelStyle.equals("columnlabel"))
                    renderer.setItemLabelGenerator(
                            new CategoryItemLabelGenerator("{1}", dateFormat, yAxisSymbols));
                else if (dataLabelStyle.equals("pattern"))
                    renderer.setItemLabelGenerator(
                            new CategoryItemLabelGenerator("{1} {2}", dateFormat, yAxisSymbols));
                else
                    renderer.setItemLabelGenerator(
                            new CategoryItemLabelGenerator(dataLabelStyle, dateFormat, yAxisSymbols));
            }
        } else {
            if (dataLabelStyle.equals("none")) {
                renderer.setItemLabelsVisible(false);
            } else {
                setCategoryItemLabelsData(renderer, seriesData);
                if (dataLabelStyle.equals("value"))
                    renderer.setItemLabelGenerator(
                            new CategoryItemLabelGenerator("{2}", numberFormat, yAxisSymbols));
                else if (dataLabelStyle.equals("rowlabel"))
                    renderer.setItemLabelGenerator(
                            new CategoryItemLabelGenerator("{0}", numberFormat, yAxisSymbols));
                else if (dataLabelStyle.equals("columnlabel"))
                    renderer.setItemLabelGenerator(
                            new CategoryItemLabelGenerator("{1}", numberFormat, yAxisSymbols));
                else if (dataLabelStyle.equals("pattern"))
                    renderer.setItemLabelGenerator(
                            new CategoryItemLabelGenerator("{1} {2} ({3} of {4})", numberFormat, yAxisSymbols));
                else
                    renderer.setItemLabelGenerator(
                            new CategoryItemLabelGenerator(dataLabelStyle, numberFormat, yAxisSymbols));
            }
        }

        // Add the renderer to the plot.
        // NOTE: this must be done before the setPaintStyle() call so the
        // DrawingSupplier object
        // will be set up properly for the generation of default colors.
        plot.setRenderer(num, renderer);

        // Set the paint style for this series (series 0)
        if (seriesData.getType().equals("bar") || seriesData.getType().equals("horizontalbar")
                || seriesData.getType().equals("area"))
            setPaintStyle(seriesData.getPaintStyle(), renderer, 0, height);

        num++;
    }

    // If gridLines was specified then we need to calculate the yAxisUnits
    if ((gridLines != -1) && (valueAxis instanceof NumberAxis)) {
        // Calculate the yAxisUnits we need to use to create the number of
        // gridLines
        yAxisUnits = calculateYAxisUnits(gridLines, minMax);

        // Set the yAxisUnits
        ((NumberAxis) valueAxis).setTickUnit(new NumberTickUnit(yAxisUnits));
    }

    return plot;
}

From source file:es.caib.seycon.ng.servei.XarxaServiceImpl.java

@Override
protected Maquina handleRegisterDynamicIP(String nomMaquina, String ip, String serialNumber)
        throws es.caib.seycon.ng.exception.UnknownHostException, UnknownNetworkException {
    boolean anyChange = false;
    // First. Test if this IP belongs to anybody else
    MaquinaEntity old = getMaquinaEntityDao().findByAdreca(ip);
    MaquinaEntity maquina = null;// w w  w. ja  v a 2 s.c  om
    if (old != null) {
        if (serialNumber.equals(old.getSerialNumber())) {
            maquina = old;
            // Coincide serial number 
            if (!nomMaquina.equals(maquina.getNom())) {
                // Host name changed
                // Check if already exists such a name
                old = getMaquinaEntityDao().findByNom(nomMaquina);
                if (old != null) {
                    old.setDeleted(true);
                    getMaquinaEntityDao().update(old);
                }
                maquina.setNom(nomMaquina);
                anyChange = true;
            }
        } else {
            if (old.getDeleted().booleanValue() || old.getDynamicIP().booleanValue()) {
                old.setAdreca(null);
                old.setXarxa(null);
                getMaquinaEntityDao().update(old);
            } else {
                log.warn(String.format(Messages.getString("XarxaServiceImpl.HostsCollisionMessage"), //$NON-NLS-1$
                        nomMaquina, nomMaquina, ip, serialNumber));
                throw new UnknownHostException(
                        String.format(Messages.getString("XarxaServiceImpl.IPAssignedMessage"), //$NON-NLS-1$
                                ip, old.getNom()));
            }
        }
    }
    // Second. Test if this name belongs to anybody else
    if (maquina == null) {
        // Found a host with no serial number => Bind it
        old = getMaquinaEntityDao().findByNom(nomMaquina);
        if (old == null) {
            // Nothing to do
        } else if (old.getSerialNumber() == null && old.getDynamicIP().booleanValue()) {
            // Replace unused host
            maquina = old;
            maquina.setSerialNumber(serialNumber);
            maquina.setAdreca(ip);
            maquina.setLastSeen(new Date());
            getMaquinaEntityDao().update(maquina);
        } else if (serialNumber.equals(old.getSerialNumber())) {
            // Found host entry
            maquina = old;
        } else if (old.getDynamicIP().booleanValue()) {
            // Autodelete
            old.setDeleted(true);
            getMaquinaEntityDao().update(old);
        } else {
            log.warn(String.format(Messages.getString("XarxaServiceImpl.HostsCollisionMessage"), //$NON-NLS-1$
                    nomMaquina, nomMaquina, ip, serialNumber));
            throw new UnknownHostException(nomMaquina);
        }
    }
    // Third. Test if this serial is already used (with another name)
    if (maquina == null) {
        maquina = getMaquinaEntityDao().findBySerialNumber(serialNumber);
        if (maquina != null && !nomMaquina.equals(maquina.getNom())) {
            anyChange = true;
            maquina.setNom(nomMaquina);
        }
    }

    if (maquina == null) {
        try {
            InetAddress addr = InetAddress.getByName(ip);
            XarxaEntity x = guessNetwork(addr.getAddress());
            if (x == null) {
                String msg = String.format(Messages.getString("XarxaServiceImpl.RequestUnmanagedIP"), //$NON-NLS-1$
                        nomMaquina, ip);
                log.warn(msg);
                throw new UnknownNetworkException(msg);
            }
            maquina = getMaquinaEntityDao().newMaquinaEntity();
            maquina.setAdreca(ip);
            maquina.setCorreu("N"); //$NON-NLS-1$
            maquina.setDeleted(false);
            DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
            maquina.setDescripcio(Messages.getString("XarxaServiceImpl.AutocreatedMessage") + //$NON-NLS-1$
                    " " + // $NON-NLS-1$ //$NON-NLS-1$
                    df.format(new Date())); //$NON-NLS-1$
            maquina.setDynamicIP(new Boolean(true));
            maquina.setNom(nomMaquina);
            maquina.setOfimatica("N"); //$NON-NLS-1$
            maquina.setSerialNumber(serialNumber);
            maquina.setServidorImpressores("N"); //$NON-NLS-1$
            maquina.setOperatingSystem(getOsTypeEntityDao().findOSTypeByName("ALT")); //$NON-NLS-1$
            maquina.setXarxa(x);
            getMaquinaEntityDao().create(maquina);
        } catch (java.net.UnknownHostException e) {
            String msg = String.format(Messages.getString("XarxaServiceImpl.RequestUnmanagedIP"), nomMaquina, //$NON-NLS-1$
                    "??"); //$NON-NLS-1$ 
            log.warn(msg);
            throw new UnknownNetworkException(msg);
        }
    }

    if (!ip.equals(maquina.getAdreca()) || maquina.getXarxa() == null
            || !Boolean.FALSE.equals(maquina.getDeleted())) {
        try {
            InetAddress addr = InetAddress.getByName(ip);
            XarxaEntity x = guessNetwork(addr.getAddress());
            if (x != null) {
                if (x.isDchpSupport()) {
                    anyChange = true;
                    maquina.setDeleted(Boolean.FALSE);
                    maquina.setAdreca(ip);
                    maquina.setXarxa(x);
                } else {
                    throw new UnknownNetworkException(
                            String.format(Messages.getString("XarxaServiceImpl.RequestWithoutDHCP"), //$NON-NLS-1$
                                    nomMaquina, ip, x.getCodi()));
                }
            } else {
                throw new UnknownNetworkException(String
                        .format(Messages.getString("XarxaServiceImpl.RequestUnmanagedIP"), nomMaquina, ip)); //$NON-NLS-1$
            }
        } catch (java.net.UnknownHostException e) {
            String msg = String.format(Messages.getString("XarxaServiceImpl.RequestUnmanagedIP"), nomMaquina, //$NON-NLS-1$
                    "??"); //$NON-NLS-1$ 
            log.warn(msg);
            throw new UnknownNetworkException(msg);
        }
    }
    if (anyChange || maquina.getLastSeen() == null
            || System.currentTimeMillis() - maquina.getLastSeen().getTime() > 8 * 60L * 60L * 1000L) // each 8 hours update last seen
    {
        maquina.setLastSeen(new Date());
        getMaquinaEntityDao().update(maquina);
    }

    return getMaquinaEntityDao().toMaquina(maquina);
}

From source file:org.etudes.mneme.impl.SubmissionServiceImpl.java

/**
 * Returns the text of an assessment evaluation notification sample with dates filled in
 * @param assmt Assessment object/*from w w w  .j  a  v a  2 s  .c  om*/
 * @return Evaluation notification sample
 */
public String getEvalNotificationSample(Assessment assmt) {
    StringBuilder contents = new StringBuilder();
    BufferedReader input = null;
    String message = null;
    InputStream inputStream = null;

    try {
        inputStream = AttachmentServiceImpl.class.getClassLoader().getResourceAsStream("evalnotif.html");

        input = new BufferedReader(new InputStreamReader(inputStream));

        String line = null;

        while ((line = input.readLine()) != null) {
            contents.append(line);
        }

        message = contents.toString();

        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        if (assmt != null) {
            Date finalDate;
            if (assmt.getDates().getAcceptUntilDate() != null)
                finalDate = assmt.getDates().getAcceptUntilDate();
            else
                finalDate = assmt.getDates().getDueDate();
            if (assmt.getDates().getOpenDate() != null && finalDate != null) {
                message = message.replace("date.info",
                        "It opens on " + dateFormat.format(assmt.getDates().getOpenDate()) + " and closes on "
                                + dateFormat.format(finalDate) + ".");
            } else {
                if (assmt.getDates().getOpenDate() != null && finalDate == null)
                    message = message.replace("date.info",
                            "It opens on " + dateFormat.format(assmt.getDates().getOpenDate()) + ".");
                if (assmt.getDates().getOpenDate() == null && finalDate != null)
                    message = message.replace("date.info",
                            "It closes on " + dateFormat.format(finalDate) + ".");
                if (assmt.getDates().getOpenDate() == null && finalDate == null)
                    message = message.replace("date.info", " ");
            }
        }
    } catch (Exception e) {
        M_log.warn("Error in getEvalNotificationSample", e);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }

        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {

            }
        }
    }
    return message;
}

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

private XYPlot getXYPlot(List<cfCHARTSERIESData> series, String xAxisTitle, String yAxisTitle,
        String labelFormat, boolean bShowMarkers, int markerSize, boolean bShow3D, String tipStyle,
        String drillDownUrl, int xOffset, int yOffset, int yAxisUnits, String seriesPlacement, int height,
        int gridLines) throws cfmRunTimeException {
    // Create an XY plot
    XYPlot plot = new XYPlot();
    ValueAxis domainAxis;/*from www .  j a v a  2 s .c o m*/

    if (series.get(0).getSeriesDataType() == cfCHARTSERIESData.XY_NUMERIC_SERIES) {
        if (bShow3D)
            domainAxis = new NumberAxis3D(xAxisTitle);
        else
            domainAxis = new NumberAxis(xAxisTitle);
    } else {
        domainAxis = new DateAxis(xAxisTitle);
    }
    plot.setDomainAxis(domainAxis);

    ValueAxis valueAxis;
    DateFormat dateFormat = null;
    NumberFormat numberFormat = null;
    if (labelFormat.equals("date")) {
        valueAxis = new DateAxis(yAxisTitle);
        dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        ((DateAxis) valueAxis).setDateFormatOverride(dateFormat);
    } else {
        if (bShow3D)
            valueAxis = new NumberAxis3D(yAxisTitle);
        else
            valueAxis = new NumberAxis(yAxisTitle);
        if (labelFormat.equals("currency")) {
            ((NumberAxis) valueAxis).setNumberFormatOverride(NumberFormat.getCurrencyInstance());
            numberFormat = NumberFormat.getCurrencyInstance();
        } else if (labelFormat.equals("percent")) {
            numberFormat = NumberFormat.getPercentInstance();
            numberFormat.setMaximumFractionDigits(3); // without this change .11443
                                                      // would be displayed as 11%
                                                      // instead of 11.443%
            ((NumberAxis) valueAxis).setNumberFormatOverride(numberFormat);
        } else {
            numberFormat = NumberFormat.getInstance();
        }

        if (yAxisUnits != 0)
            ((NumberAxis) valueAxis).setTickUnit(new NumberTickUnit(yAxisUnits));
    }
    plot.setRangeAxis(valueAxis);

    // Add a dataset and renderer for each series
    int barChartDatasetIndex = -1;
    int hBarChartDatasetIndex = -1;
    int num = 0;
    MinMaxData minMax = new MinMaxData();
    for (int i = 0; i < series.size(); i++) {
        cfCHARTSERIESData seriesData = series.get(i);
        XYSeriesCollection dataset;
        if ((barChartDatasetIndex != -1) && (seriesData.getType().equals("bar"))) {
            dataset = (XYSeriesCollection) plot.getDataset(barChartDatasetIndex);

            addSeriesDataToDataset(seriesData, dataset, minMax);

            // Set the paint style for this series
            setPaintStyle(seriesData.getPaintStyle(), plot.getRenderer(barChartDatasetIndex),
                    dataset.getSeriesCount() - 1, height);

            // Add the color list for this series to the custom color renderer
            CustomColorRenderer cr = (CustomColorRenderer) plot.getRenderer(barChartDatasetIndex);
            cr.addColors(getColorList(seriesData));

            continue;
        } else if ((hBarChartDatasetIndex != -1) && (seriesData.getType().equals("horizontalbar"))) {
            dataset = (XYSeriesCollection) plot.getDataset(hBarChartDatasetIndex);

            addSeriesDataToDataset(seriesData, dataset, minMax);

            // Set the paint style for this series
            setPaintStyle(seriesData.getPaintStyle(), plot.getRenderer(hBarChartDatasetIndex),
                    dataset.getSeriesCount() - 1, height);

            // Add the color list for this series to the custom color renderer
            CustomColorRenderer cr = (CustomColorRenderer) plot.getRenderer(hBarChartDatasetIndex);
            cr.addColors(getColorList(seriesData));

            continue;
        } else {
            dataset = new XYSeriesCollection();

            addSeriesDataToDataset(seriesData, dataset, minMax);
        }

        plot.setDataset(num, dataset);

        XYItemRenderer renderer = null;
        if (seriesData.getType().equals("bar")) {
            plot.setOrientation(PlotOrientation.VERTICAL);
            renderer = getXYBarRenderer(seriesPlacement, bShow3D, xOffset, yOffset, getColorList(seriesData));
            ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
                    TextAnchor.BOTTOM_CENTER);
            renderer.setPositiveItemLabelPosition(position1);
            ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6,
                    TextAnchor.TOP_CENTER);
            renderer.setNegativeItemLabelPosition(position2);
            ((XYBarRenderer) renderer).setMargin(0.2); // The margin between each
                                                       // category

            barChartDatasetIndex = num;
        } else if (seriesData.getType().equals("horizontalbar")) {
            plot.setOrientation(PlotOrientation.HORIZONTAL);
            plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
            renderer = getXYBarRenderer(seriesPlacement, bShow3D, xOffset, yOffset, getColorList(seriesData));
            ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3,
                    TextAnchor.CENTER_LEFT);
            renderer.setPositiveItemLabelPosition(position1);
            ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE9,
                    TextAnchor.CENTER_RIGHT);
            renderer.setNegativeItemLabelPosition(position2);
            ((XYBarRenderer) renderer).setMargin(0.2); // The margin between each
                                                       // category

            hBarChartDatasetIndex = num;
        } else if (seriesData.getType().equals("line")) {
            renderer = new XYLineAndShapeRenderer(true, false);

            // Enable/Disable displaying of markers
            ((XYLineAndShapeRenderer) renderer).setShapesVisible(bShowMarkers);

            // Set the shape of the markers based on the markerSize value
            ((XYLineAndShapeRenderer) renderer).setShape(getMarker(seriesData.getMarkerStyle(), markerSize));
        } else if (seriesData.getType().equals("area")) {
            renderer = new CustomXYAreaRenderer();
        } else if (seriesData.getType().equals("step")) {
            renderer = new CustomXYStepRenderer();
        } else if (seriesData.getType().equals("scatter")) {
            renderer = new XYLineAndShapeRenderer(false, true);

            // Set the shape of the markers based on the markerSize value
            ((XYLineAndShapeRenderer) renderer).setShape(getMarker(seriesData.getMarkerStyle(), markerSize));
        }

        if (!tipStyle.equals("none")) {
            if (series.get(0).getSeriesDataType() == cfCHARTSERIESData.XY_DATE_SERIES) {
                renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator("{0}: {1}",
                        DateFormat.getInstance(), DateFormat.getInstance()));
            } else {
                if (dateFormat != null)
                    renderer.setBaseToolTipGenerator(
                            new StandardXYToolTipGenerator("{0}: {2}", dateFormat, dateFormat));
                else
                    renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator("{0}: ({1}, {2})",
                            numberFormat, NumberFormat.getInstance()));
            }
        }

        if (drillDownUrl != null) {
            if (dateFormat != null)
                renderer.setURLGenerator(
                        new com.newatlanta.bluedragon.XYURLGenerator(drillDownUrl, dateFormat));
            else
                renderer.setURLGenerator(
                        new com.newatlanta.bluedragon.XYURLGenerator(drillDownUrl, numberFormat));
        }

        if (seriesData.getSeriesColor() != null)
            renderer.setSeriesPaint(0, convertStringToColor(seriesData.getSeriesColor()));

        String dataLabelStyle = seriesData.getDataLabelStyle();
        if (labelFormat.equals("date")) {
            if (dataLabelStyle.equals("none")) {
                renderer.setItemLabelsVisible(false);
            } else {
                setXYItemLabelsData(renderer, seriesData);
                if (dataLabelStyle.equals("value"))
                    renderer.setItemLabelGenerator(
                            new StandardXYItemLabelGenerator("{2}", dateFormat, dateFormat));
                else if (dataLabelStyle.equals("rowlabel"))
                    renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator("{0}",
                            NumberFormat.getInstance(), NumberFormat.getInstance()));
                else if (dataLabelStyle.equals("columnlabel"))
                    renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator("{1}",
                            NumberFormat.getInstance(), NumberFormat.getInstance()));
                else if (dataLabelStyle.equals("pattern"))
                    renderer.setItemLabelGenerator(new XYItemLabelGenerator("{2}", dateFormat, dateFormat));
                else
                    renderer.setItemLabelGenerator(
                            new XYItemLabelGenerator(dataLabelStyle, dateFormat, dateFormat));
            }
        } else {
            if (dataLabelStyle.equals("none")) {
                renderer.setItemLabelsVisible(false);
            } else {
                setXYItemLabelsData(renderer, seriesData);
                if (dataLabelStyle.equals("value")) {

                    renderer.setItemLabelGenerator(
                            new StandardXYItemLabelGenerator("{2}", numberFormat, numberFormat));

                } else if (dataLabelStyle.equals("rowlabel")) {

                    renderer.setItemLabelGenerator(
                            new StandardXYItemLabelGenerator("{0}", numberFormat, numberFormat));

                } else if (dataLabelStyle.equals("columnlabel")) {

                    if (series.get(0).getSeriesDataType() == cfCHARTSERIESData.XY_DATE_SERIES) {
                        renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator("{1}",
                                SimpleDateFormat.getInstance(), NumberFormat.getInstance()));
                    } else {
                        renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator("{1}",
                                NumberFormat.getInstance(), NumberFormat.getInstance()));
                    }

                } else if (dataLabelStyle.equals("pattern")) {

                    if (series.get(0).getSeriesDataType() == cfCHARTSERIESData.XY_DATE_SERIES) {
                        renderer.setItemLabelGenerator(new XYItemLabelGenerator("{1} {2} ({3} of {4})",
                                SimpleDateFormat.getInstance(), numberFormat));
                    } else {
                        renderer.setItemLabelGenerator(new XYItemLabelGenerator("{1} {2} ({3} of {4})",
                                NumberFormat.getInstance(), numberFormat));
                    }

                } else {
                    renderer.setItemLabelGenerator(
                            new XYItemLabelGenerator(dataLabelStyle, NumberFormat.getInstance(), numberFormat));
                }
            }
        }

        // Add the renderer to the plot.
        // NOTE: this must be done before the setPaintStyle() call so the
        // DrawingSupplier object
        // will be set up properly for the generation of default colors.
        plot.setRenderer(num, renderer);

        // Set the paint style for this series (series 0)
        if (seriesData.getType().equals("bar") || seriesData.getType().equals("horizontalbar")
                || seriesData.getType().equals("area"))
            setPaintStyle(seriesData.getPaintStyle(), renderer, 0, height);

        num++;
    }

    // If gridLines was specified then we need to calculate the yAxisUnits
    if ((gridLines != -1) && (valueAxis instanceof NumberAxis)) {
        // Calculate the yAxisUnits we need to use to create the number of
        // gridLines
        yAxisUnits = calculateYAxisUnits(gridLines, minMax);

        // Set the yAxisUnits
        ((NumberAxis) valueAxis).setTickUnit(new NumberTickUnit(yAxisUnits));
    }

    return plot;
}

From source file:net.sf.fspdfs.chartthemes.simple.SimpleChartTheme.java

protected void setAxisTickLabels(Axis axis, JRFont tickLabelFont, Paint tickLabelColor, String tickLabelMask,
        AxisSettings axisSettings) {//from  www .j a  va2 s .c o m
    boolean axisTickLabelsVisible = axisSettings.getTickLabelsVisible() == null
            || axisSettings.getTickLabelsVisible().booleanValue();//FIXMETHEME axis visibility should be dealt with above;

    axis.setTickLabelsVisible(axisTickLabelsVisible);

    if (axisTickLabelsVisible) {
        JRBaseFont font = new JRBaseFont();
        JRFontUtil.copyNonNullOwnProperties(axisSettings.getTickLabelFont(), font);
        JRFontUtil.copyNonNullOwnProperties(tickLabelFont, font);
        font = new JRBaseFont(getChart(), font);
        axis.setTickLabelFont(JRFontUtil.getAwtFont(font, getLocale()));

        RectangleInsets tickLabelInsets = axisSettings.getTickLabelInsets();
        if (tickLabelInsets != null) {
            axis.setTickLabelInsets(tickLabelInsets);
        }

        Paint tickLabelPaint = tickLabelColor != null ? tickLabelColor
                : axisSettings.getTickLabelPaint() != null ? axisSettings.getTickLabelPaint().getPaint() : null;

        if (tickLabelPaint != null) {
            axis.setTickLabelPaint(tickLabelPaint);
        }

        TimeZone timeZone = getChartContext().getTimeZone();
        if (axis instanceof DateAxis && timeZone != null) {
            // used when no mask is set
            ((DateAxis) axis).setTimeZone(timeZone);
        }

        if (tickLabelMask != null) {
            if (axis instanceof NumberAxis) {
                NumberFormat fmt = NumberFormat.getInstance();
                if (fmt instanceof DecimalFormat)
                    ((DecimalFormat) fmt).applyPattern(tickLabelMask);
                ((NumberAxis) axis).setNumberFormatOverride(fmt);
            } else if (axis instanceof DateAxis) {
                DateFormat fmt;
                if (tickLabelMask.equals("SHORT") || tickLabelMask.equals("DateFormat.SHORT"))
                    fmt = DateFormat.getDateInstance(DateFormat.SHORT);
                else if (tickLabelMask.equals("MEDIUM") || tickLabelMask.equals("DateFormat.MEDIUM"))
                    fmt = DateFormat.getDateInstance(DateFormat.MEDIUM);
                else if (tickLabelMask.equals("LONG") || tickLabelMask.equals("DateFormat.LONG"))
                    fmt = DateFormat.getDateInstance(DateFormat.LONG);
                else if (tickLabelMask.equals("FULL") || tickLabelMask.equals("DateFormat.FULL"))
                    fmt = DateFormat.getDateInstance(DateFormat.FULL);
                else
                    fmt = new SimpleDateFormat(tickLabelMask);

                // FIXME fmt cannot be null
                if (fmt != null) {
                    if (timeZone != null) {
                        fmt.setTimeZone(timeZone);
                    }

                    ((DateAxis) axis).setDateFormatOverride(fmt);
                } else
                    ((DateAxis) axis).setDateFormatOverride(
                            DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT));
            }
            // ignore mask for other axis types.
        }
    }
}

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

protected void setAxisTickLabels(Axis axis, JRFont tickLabelFont, Paint tickLabelColor, String tickLabelMask,
        Integer baseFontSize) {/*from   w w w .ja v  a 2s  .  co  m*/
    Boolean defaultAxisTickLabelsVisible = (Boolean) getDefaultValue(defaultAxisPropertiesMap,
            ChartThemesConstants.AXIS_TICK_LABELS_VISIBLE);
    if (defaultAxisTickLabelsVisible != null && defaultAxisTickLabelsVisible.booleanValue()) {
        Font themeTickLabelFont = getFont(
                (JRFont) getDefaultValue(defaultAxisPropertiesMap, ChartThemesConstants.AXIS_TICK_LABEL_FONT),
                tickLabelFont, baseFontSize);
        axis.setTickLabelFont(themeTickLabelFont);

        RectangleInsets defaultTickLabelInsets = (RectangleInsets) getDefaultValue(defaultAxisPropertiesMap,
                ChartThemesConstants.AXIS_TICK_LABEL_INSETS);
        if (defaultTickLabelInsets != null) {
            axis.setTickLabelInsets(defaultTickLabelInsets);
        }
        Paint tickLabelPaint = tickLabelColor != null ? tickLabelColor
                : (Paint) getDefaultValue(defaultAxisPropertiesMap, ChartThemesConstants.AXIS_TICK_LABEL_PAINT);
        if (tickLabelPaint != null) {
            axis.setTickLabelPaint(tickLabelPaint);
        }

        TimeZone timeZone = getChartContext().getTimeZone();
        if (axis instanceof DateAxis && timeZone != null) {
            // used when no mask is set
            ((DateAxis) axis).setTimeZone(timeZone);
        }

        if (tickLabelMask != null) {
            if (axis instanceof NumberAxis) {
                NumberFormat fmt = NumberFormat.getInstance();
                if (fmt instanceof DecimalFormat)
                    ((DecimalFormat) fmt).applyPattern(tickLabelMask);
                ((NumberAxis) axis).setNumberFormatOverride(fmt);
            } else if (axis instanceof DateAxis) {
                DateFormat fmt;
                if (tickLabelMask.equals("SHORT") || tickLabelMask.equals("DateFormat.SHORT"))
                    fmt = DateFormat.getDateInstance(DateFormat.SHORT);
                else if (tickLabelMask.equals("MEDIUM") || tickLabelMask.equals("DateFormat.MEDIUM"))
                    fmt = DateFormat.getDateInstance(DateFormat.MEDIUM);
                else if (tickLabelMask.equals("LONG") || tickLabelMask.equals("DateFormat.LONG"))
                    fmt = DateFormat.getDateInstance(DateFormat.LONG);
                else if (tickLabelMask.equals("FULL") || tickLabelMask.equals("DateFormat.FULL"))
                    fmt = DateFormat.getDateInstance(DateFormat.FULL);
                else
                    fmt = new SimpleDateFormat(tickLabelMask);

                // FIXME fmt cannot be null
                if (fmt != null) {
                    if (timeZone != null) {
                        fmt.setTimeZone(timeZone);
                    }

                    ((DateAxis) axis).setDateFormatOverride(fmt);
                } else
                    ((DateAxis) axis).setDateFormatOverride(
                            DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT));
            }
            // ignore mask for other axis types.
        }
    }
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

private void showThreadPreviewDialog(final int position) {
    final List<PresentationItemModel> items = new ArrayList<>();
    final int bgShadowResource = ThemeUtils.getThemeResId(activity.getTheme(), R.attr.dialogBackgroundShadow);
    final int bgColor = ThemeUtils.getThemeColor(activity.getTheme(), R.attr.activityRootBackground,
            Color.BLACK);/*w  w w .j  av a2s.  co m*/
    final View tmpV = new View(activity);
    final Dialog tmpDlg = new Dialog(activity);
    tmpDlg.getWindow().setBackgroundDrawableResource(bgShadowResource);
    tmpDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
    tmpDlg.setCanceledOnTouchOutside(true);
    tmpDlg.setContentView(tmpV);
    tmpDlg.show();
    Runnable next = new Runnable() {
        @Override
        public void run() {
            final int dlgWidth = tmpV.getWidth();
            tmpDlg.hide();
            tmpDlg.cancel();
            final Dialog dialog = new Dialog(activity);

            if (presentationModel.source != null && presentationModel.source.threads != null
                    && presentationModel.source.threads.length > position
                    && presentationModel.source.threads[position].posts != null
                    && presentationModel.source.threads[position].posts.length > 0) {

                final String threadNumber = presentationModel.source.threads[position].posts[0].number;

                ClickableURLSpan.URLSpanClickListener spanClickListener = new ClickableURLSpan.URLSpanClickListener() {
                    @Override
                    public void onClick(View v, ClickableURLSpan span, String url, String referer) {
                        if (url.startsWith("#")) {
                            try {
                                UrlPageModel threadPageModel = new UrlPageModel();
                                threadPageModel.chanName = chan.getChanName();
                                threadPageModel.type = UrlPageModel.TYPE_THREADPAGE;
                                threadPageModel.boardName = tabModel.pageModel.boardName;
                                threadPageModel.threadNumber = threadNumber;
                                url = chan.buildUrl(threadPageModel) + url;
                                dialog.dismiss();
                                UrlHandler.open(chan.fixRelativeUrl(url), activity);
                            } catch (Exception e) {
                                Logger.e(TAG, e);
                            }
                        } else {
                            dialog.dismiss();
                            UrlHandler.open(chan.fixRelativeUrl(url), activity);
                        }
                    }
                };

                AndroidDateFormat.initPattern();
                String datePattern = AndroidDateFormat.getPattern();
                DateFormat dateFormat = datePattern == null
                        ? DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
                        : new SimpleDateFormat(datePattern, Locale.US);
                dateFormat.setTimeZone(settings.isLocalTime() ? TimeZone.getDefault()
                        : TimeZone.getTimeZone(presentationModel.source.boardModel.timeZoneId));

                int postsCount = presentationModel.source.threads[position].postsCount;
                boolean showIndex = presentationModel.source.threads[position].posts.length <= postsCount;
                int curPostIndex = postsCount - presentationModel.source.threads[position].posts.length + 1;

                boolean openSpoilers = settings.openSpoilers();

                for (int i = 0; i < presentationModel.source.threads[position].posts.length; ++i) {
                    PresentationItemModel model = new PresentationItemModel(
                            presentationModel.source.threads[position].posts[i], chan.getChanName(),
                            presentationModel.source.pageModel.boardName,
                            presentationModel.source.pageModel.threadNumber, dateFormat, spanClickListener,
                            imageGetter, ThemeUtils.ThemeColors.getInstance(activity.getTheme()), openSpoilers,
                            floatingModels, null);
                    model.buildSpannedHeader(showIndex ? (i == 0 ? 1 : ++curPostIndex) : -1,
                            presentationModel.source.boardModel.bumpLimit,
                            presentationModel.source.boardModel.defaultUserName, null, false);
                    items.add(model);
                }
            } else {
                items.add(presentationModel.presentationList.get(position));
            }
            ListView dlgList = new ListView(activity);
            dlgList.setAdapter(new ArrayAdapter<PresentationItemModel>(activity, 0, items) {
                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    View view = adapter.getView(position, convertView, parent, dlgWidth, getItem(position));
                    view.setBackgroundColor(bgColor);
                    return view;
                }
            });
            dialog.getWindow().setBackgroundDrawableResource(bgShadowResource);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCanceledOnTouchOutside(true);
            dialog.setContentView(dlgList);
            dialog.show();
            dialogs.add(dialog);
        }
    };
    if (tmpV.getWidth() != 0) {
        next.run();
    } else {
        AppearanceUtils.callWhenLoaded(tmpDlg.getWindow().getDecorView(), next);
    }
}