Example usage for org.joda.time Duration getMillis

List of usage examples for org.joda.time Duration getMillis

Introduction

In this page you can find the example usage for org.joda.time Duration getMillis.

Prototype

public long getMillis() 

Source Link

Document

Gets the length of this duration in milliseconds.

Usage

From source file:rcrr.reversi.Clock.java

License:Open Source License

/**
 * Returns a String representing the clock.
 * The format is mm:ss corresponding to the given time in milliseconds, where:
 *  - mm is the amount of minutes/* ww  w  .j  a  v a  2  s.c  o  m*/
 *  - ss is the amount of seconds
 *
 * @param  duration time in milliseconds
 * @return          a formatted {@code String} with minutes and seconds
 */
private static String timeString(final Duration duration) {
    final long durationAsMilliseconds = duration.getMillis();
    final long durationAsSeconds = durationAsMilliseconds / DateTimeConstants.MILLIS_PER_SECOND;
    final long minutes = durationAsSeconds / DateTimeConstants.SECONDS_PER_MINUTE;
    final long seconds = durationAsSeconds - (minutes * DateTimeConstants.SECONDS_PER_MINUTE);
    return TIME_FORMATTER.format(minutes) + ":" + TIME_FORMATTER.format(seconds);
}

From source file:sg.atom.utils.execution.ScheduledExecutors.java

License:Apache License

/**
 * Run callable repeatedly with the given delay between calls, until it
 * returns Signal.STOP. Exceptions are caught and logged as errors.
 *//*from  w w w .j  a v  a2  s  .  com*/
public static void scheduleWithFixedDelay(final ScheduledExecutorService exec, final Duration initialDelay,
        final Duration delay, final Callable<Signal> callable) {
    log.debug("Scheduling repeatedly: %s with delay %s", callable, delay);
    exec.schedule(new Runnable() {
        @Override
        public void run() {
            try {
                log.debug("Running %s (delay %s)", callable, delay);
                if (callable.call() == Signal.REPEAT) {
                    log.debug("Rescheduling %s (delay %s)", callable, delay);
                    exec.schedule(this, delay.getMillis(), TimeUnit.MILLISECONDS);
                } else {
                    log.debug("Stopped rescheduling %s (delay %s)", callable, delay);
                }
            } catch (Throwable e) {
                log.error("Uncaught exception.");
            }
        }
    }, initialDelay.getMillis(), TimeUnit.MILLISECONDS);
}

From source file:sg.atom.utils.execution.ScheduledExecutors.java

License:Apache License

public static void scheduleAtFixedRate(final ScheduledExecutorService exec, final Duration initialDelay,
        final Duration rate, final Callable<Signal> callable) {
    log.debug("Scheduling periodically: %s with period %s", callable, rate);
    exec.schedule(new Runnable() {
        private volatile Signal prevSignal = null;

        @Override//  w  w  w.  j a  v  a  2 s  .  c o m
        public void run() {
            if (prevSignal == null || prevSignal == Signal.REPEAT) {
                exec.schedule(this, rate.getMillis(), TimeUnit.MILLISECONDS);
            }

            try {
                log.debug("Running %s (period %s)", callable, rate);
                prevSignal = callable.call();
            } catch (Throwable e) {
                log.error("Uncaught exception.");
            }
        }
    }, initialDelay.getMillis(), TimeUnit.MILLISECONDS);
}

From source file:sk.linhard.openair.eventmodel.util.Util.java

License:Open Source License

public static String formatDuration(Duration duration) {
    if (duration == null) {
        return null;
    }// w  ww .  j av a2s  .c  om
    long miliseconds = duration.getMillis();
    long hours = miliseconds / MILIS_IN_HOUR;
    long mins = (miliseconds % MILIS_IN_HOUR) / MILIS_IN_MIN;
    StringBuffer theSB = new StringBuffer();
    theSB.append(hours);
    theSB.append(":");
    if (mins < 10) {
        theSB.append("0");
    }
    theSB.append(mins);
    return theSB.toString();
}

From source file:sql.fredy.sqltools.SqlMonitor.java

License:Open Source License

@Override
public void run() {
    /**//from ww  w  .java 2s .  com
     * if it is a query send it to the table, otherwise execute the command
     * and display the result of the command in the status tab
     */
    busyCursor();

    String queryText = "";
    String fullQueryText;

    JPanel lastPanel = new JPanel();
    JPanel statusPanel = new JPanel();

    statusPanel.setLayout(new GridBagLayout());

    boolean bError = false;

    //get query   
    if (query.getSelectionStart() == query.getSelectionEnd()) {
        fullQueryText = query.getText();
    } else {
        fullQueryText = query.getSelectedText();
    }

    if (fullQueryText == "" | fullQueryText == null) {
        defaultCursor();
        return;
    }

    //initialise based on Preferences
    int count = tabbedPane.getTabCount();

    if (!retainTabs) {
        tabIndex = 0;
        for (int i = (count - 1); i > 0; i--) {
            tabbedPane.remove(i);
        }
    } else {
        int stat = tabbedPane.indexOfTab("Status");
        if (stat > -1) {
            tabbedPane.remove(stat);
        }
    }

    if (!retainStatus) {
        response.setText("");
    }

    //parse query strings & iterate throught them
    StringTokenizer fqt = new StringTokenizer(fullQueryText, sqlSeparators);

    // write query to history
    queryHistory.write(getDatabase(), fullQueryText);

    while (fqt.hasMoreTokens()) {

        queryText = fqt.nextToken().trim();
        if (queryText.length() > 0) {

            //response.append(queryText + "\n");
            appendToPane(queryText + "\n", Color.BLACK);

            logger.log(Level.FINE, "executing Query on " + getDatabase());

            /*
             if ((!isComment(queryText))) {
             queryHistory.write(getDatabase(), queryText);  // this writes every single query to the history
             }
             */
            SqlTab tabPanel = new SqlTextArea();

            if (queryText.toLowerCase().startsWith("select") | queryText.toLowerCase().startsWith("set")
                    | queryText.toLowerCase().startsWith("show") | queryText.toLowerCase().startsWith("desc")
                    | queryText.toLowerCase().startsWith("declare")
                    | queryText.toLowerCase().startsWith("values") | queryText.toLowerCase().startsWith("with")
                    | queryText.toLowerCase().startsWith("sp_") | queryText.toLowerCase().startsWith("exec")) {

                if (resultType != TABLE) {
                    tabPanel = new SqlTextArea(getCon(), queryText);
                } else {
                    tabPanel = new SqlPanel(getCon(), queryText);
                }

                if (tabPanel.getSQLError() != null) {
                    //response.append(tabPanel.getSQLError() + "\n\n");
                    appendToPane(tabPanel.getSQLError() + "\n\n", Color.RED);
                    tk.beep();
                    bError = true;
                } else {
                    tabIndex++;
                    JPanel resultPanel = new JPanel();
                    resultPanel.setLayout(new BorderLayout());
                    resultPanel.add(BorderLayout.CENTER, (JPanel) tabPanel);
                    JPanel resultStatusPanel = new JPanel();
                    resultStatusPanel.setLayout(new FlowLayout());
                    resultStatusPanel.setBackground(Color.WHITE);
                    resultStatusPanel.setForeground(Color.LIGHT_GRAY);
                    resultStatusPanel.setFont(resultStatusPanel.getFont().deriveFont(10f));

                    JLabel statusLabel = new JLabel(
                            tabPanel.getNumRows() + " rows returned " + tabPanel.getStatusLine());
                    statusLabel.setFont(statusLabel.getFont().deriveFont(10f));
                    resultStatusPanel.add(statusLabel);
                    resultPanel.add(BorderLayout.SOUTH, resultStatusPanel);

                    //tabbedPane.addTab("Results " + tabIndex, null, (JPanel) tabPanel, queryText);
                    tabbedPane.addTab("Results " + tabIndex, null, (JPanel) resultPanel, queryText);
                    fitSize(tabbedPane.getSize(), tabPanel);
                    //response.append(tabPanel.getNumRows() + " rows returned in Results " + tabIndex + "\n\n");
                    appendToPane(tabPanel.getNumRows() + " rows returned in Results " + tabIndex + "\n\n",
                            Color.BLUE);
                    //lastPanel = (JPanel) tabPanel;
                    lastPanel = (JPanel) resultPanel;
                }
            } else {
                getCon();
                if (con.getError() != null) {
                    tk.beep();
                } else {
                    DateTime startTime = new DateTime();
                    try {
                        DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

                        int records = con.stmt.executeUpdate(queryText);
                        DateTime endTime = new DateTime();
                        Duration dur = new Duration(startTime, endTime);
                        //response.append(Integer.toString(records) + " rows affected in " + dur.getMillis()+ " ms\n\n");
                        appendToPane(
                                Integer.toString(records) + " rows affected in " + dur.getMillis() + " ms\n\n",
                                Color.BLUE);

                        lastPanel = statusPanel;
                    } catch (Exception excpt) {
                        //response.append(excpt.toString());
                        appendToPane(excpt.toString(), Color.RED);
                        DateTime endTime = new DateTime();
                        Duration dur = new Duration(startTime, endTime);
                        //response.append("\n in " + dur.getMillis() + " ms");
                        appendToPane("\nin " + dur.getMillis() + " ms", Color.BLUE);
                        tk.beep();
                        bError = true;
                    }
                }
                con.close();
            }
        }
    }

    GridBagConstraints gbc;
    Insets insets = new Insets(1, 1, 1, 1);
    gbc = new GridBagConstraints();
    gbc.insets = insets;

    gbc.anchor = GridBagConstraints.CENTER;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    gbc.gridx = 0;
    gbc.gridy = 0;
    statusPanel.add(new JScrollPane(response), gbc);

    tabbedPane.add("Status", statusPanel);

    tabbedPane.repaint();

    if (bError) {
        lastPanel = statusPanel;
    }
    try {
        tabbedPane.setSelectedComponent(lastPanel);
        defaultCursor();
    } catch (Exception anException) {
        if (!anException.toString()
                .equalsIgnoreCase("java.lang.IllegalArgumentException: component not found in tabbed pane")) {
            //response.append(anException.toString());
            appendToPane(anException.toString(), Color.RED);
            tk.beep();
            bError = true;
        }
        defaultCursor();
    }

}

From source file:sql.fredy.sqltools.SqlPanel.java

License:Open Source License

private void init() {
    this.setLayout(new GridBagLayout());

    DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTimeFormatter dtf1 = DateTimeFormat.forPattern("HH:mm:ss.sss");
    SimpleDateFormat sdt = new SimpleDateFormat("HH:mm:ss.sss");
    DateTime startTime = new DateTime();

    //JDBCAdapter dt = new JDBCAdapter(getCon());
    dt = new JdbcTable(getCon());
    dt.setStandalone(false);// w w  w.  ja  v  a  2s  . c  o m

    if (dt.executeQuery(getQuery())) {

        DateTime endTime = new DateTime();

        rsmd = dt.getMetaData();

        createFieldList();

        try {
            iRows = dt.getNumRows();
        } catch (Exception e) {
            iRows = 0;
        }
        SQLError = dt.getSQLError();
        tableView = new JTable(dt) {
            public TableCellRenderer getCellRenderer(int row, int column) {
                if (dt.getColumnType(column) == java.sql.Types.TIMESTAMP) {
                    return new JdbcTableTimestampRenderer();
                }
                if (dt.getColumnType(column) == java.sql.Types.TIMESTAMP_WITH_TIMEZONE) {
                    return new JdbcTableTimestampRenderer();
                }
                if (dt.getColumnType(column) == java.sql.Types.DATE) {
                    return new JdbcTableDateRenderer();
                }
                if (dt.getColumnType(column) == java.sql.Types.TIME) {
                    return new JdbcTableTimeRenderer();
                }
                if (dt.getColumnType(column) == java.sql.Types.TIME_WITH_TIMEZONE) {
                    return new JdbcTableTimeRenderer();
                }

                if (dt.getColumnType(column) == java.sql.Types.INTEGER) {
                    return new JdbcTableIntegerRenderer();
                }
                if (dt.getColumnType(column) == java.sql.Types.BIGINT) {
                    return new JdbcTableIntegerRenderer();
                }
                if (dt.getColumnType(column) == java.sql.Types.SMALLINT) {
                    return new JdbcTableIntegerRenderer();
                }
                if (dt.getColumnType(column) == java.sql.Types.TINYINT) {
                    return new JdbcTableIntegerRenderer();
                }
                if (dt.getColumnType(column) == java.sql.Types.DECIMAL) {
                    return new JdbcTableNumberRenderer();
                }
                if (dt.getColumnType(column) == java.sql.Types.DOUBLE) {
                    return new JdbcTableNumberRenderer();
                }
                if (dt.getColumnType(column) == java.sql.Types.FLOAT) {
                    return new JdbcTableNumberRenderer();
                }
                if (dt.getColumnType(column) == java.sql.Types.NUMERIC) {
                    return new JdbcTableNumberRenderer();
                }

                return super.getCellRenderer(row, column);

            }
        };

        tableView.getTableHeader().setReorderingAllowed(false);
        //tableView.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        //tableView.setAutoCreateRowSorter(true);

        tableView.setRowSorter(dt.getRowSorter());

        tableView.setColumnSelectionAllowed(true);
        tableView.setCellSelectionEnabled(true);
        //tableView.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        //tableView.getSelectionModel().addListSelectionListener(new SharedListSelectionHandler());
        listSelectionModel = tableView.getSelectionModel();

        listSelectionModel.setValueIsAdjusting(true);

        listSelectionModel.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        listSelectionModel.addListSelectionListener(this);
        tableView.setSelectionModel(listSelectionModel);

        scrollpane = new JScrollPane(tableView);

        GridBagConstraints gbc;
        Insets insets = new Insets(1, 1, 1, 1);
        gbc = new GridBagConstraints();
        gbc.insets = insets;

        gbc.anchor = GridBagConstraints.CENTER;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.gridx = 0;
        gbc.gridy = 0;

        this.add(scrollpane, gbc);
        //this.add(scrollpane, BorderLayout.CENTER);        

        Duration dur = new Duration(startTime, endTime);

        long millis = dur.getMillis();
        String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
                TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));

        if (millis <= 10000) {
            hms = Long.toString(millis) + "ms";
        }

        setStatusLine(" in " + hms + " |  " + startTime.toString(dtf) + " --> " + endTime.toString(dtf));

        mouseThings();

        this.add(popUpMenu());

        /**
         * This is the stupid try to get an idea of automatically set the
         * preferred size of a table-column by taking the metadata of a
         * query. It is based on the value of getColumnDisplaySize() what
         * and then I take the alphabet to get an average wide... the
         * sentence 'thequickbrownfoxjumpsoverthelazydog' contains all
         * letters of the alphabet. As a next try, we can add numbers in
         * between the single words. but... in the end, it is just
         * statistics
         */
        /*
        if (rsmd
            != null) {
        int i = 0;
        try {
            for (i = 0; i < rsmd.getColumnCount(); i++) {
                TableColumn column = null;
                column = tableView.getColumnModel().getColumn(i);
                int wi = rsmd.getColumnDisplaySize(i + 1);
                
                //logger.log(Level.INFO, "Column-Name: {0} mit bevorzugter Breite von {1} Zeichen", new Object[]{rsmd.getColumnLabel(i + 1), wi});
                // we display max.  Chars initially
                if (wi > 50) {
                    wi = 50;
                }
                
                Font font = tableView.getFont();
                FontMetrics metrics = Toolkit.getDefaultToolkit().getFontMetrics(font);
                
                String sizer = "the0quick1brown2fox3jumps4over5the6lazy7dog8the9quick0brown1fox2jumps3over4the5lazy6dog7the8quick9brown0fox1jumps2over3the4lazy5dog"; // 80 Char (or so....)                 
                
                int textwidth = metrics.stringWidth(sizer.substring(0, wi));
                column.setPreferredWidth(textwidth);
            }
                
        } catch (SQLException sqlex) {
            logger.log(Level.WARNING, "Error while fixing JTable-preferred width: {0}", sqlex.getMessage());
            logger.log(Level.INFO, "SQL Status : {0}", sqlex.getSQLState());
            logger.log(Level.INFO, "SQL Error : {0}", sqlex.getErrorCode());
        } catch (Exception excp) {
            logger.log(Level.WARNING, "Error while fixing JTable-preferred width: {0} at position {1}", new Object[]{excp.getMessage(), i});
            //excp.printStackTrace();
        }
        }
         */
    } else {
        setSQLError(dt.getSQLError());
    }
}

From source file:sql.fredy.sqltools.SqlText.java

License:Open Source License

private void execQuery(String query) {
    try {/*from  w w  w.  j a  v a 2  s .c om*/
        DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.sss");
        DateTime startTime = new DateTime();
        ResultSet rs = stmt.executeQuery(query);
        ResultSetMetaData rsmd = rs.getMetaData();
        DateTime endTime = new DateTime();

        Duration dur = new Duration(startTime, endTime);

        long millis = dur.getMillis();
        String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
                TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));

        if (millis <= 10000) {
            hms = Long.toString(millis) + "ms";
        }
        setStatusLine("Query started " + startTime.toString(dtf) + " Query ended " + endTime.toString(dtf)
                + " Execution Time " + hms);

        SqlResults s = new SqlResults(rs, rsmd, rsmd.getColumnCount());
        s.loadText(TextArea);
    } catch (SQLException e) {
        e.printStackTrace();

    }
}

From source file:sql.fredy.sqltools.SqlTextArea.java

License:Open Source License

private void execQuery(String query) {
    try {//  w w w . j  a va 2s  .c  om
        DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.sss");
        DateTime startTime = new DateTime();
        ResultSet rs = con.stmt.executeQuery(query);
        ResultSetMetaData rsmd = rs.getMetaData();
        DateTime endTime = new DateTime();
        Duration dur = new Duration(startTime, endTime);

        long millis = dur.getMillis();
        String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
                TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));

        if (millis <= 10000) {
            hms = Long.toString(millis) + "ms";
        }
        setStatusLine("Query started " + startTime.toString(dtf) + " Query ended " + endTime.toString(dtf)
                + " Execution Time " + hms);

        SqlResults s = new SqlResults(rs, rsmd, rsmd.getColumnCount());
        s.loadText(TextArea);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

From source file:ua.com.fielden.platform.example.swing.egi.displayonly.UninstrumentalEntityEGIExample.java

@Override
protected void exposeUi(final String[] args, final SplashController splashController) throws Exception {
    final EntityGridInspector<ExampleEntity> exampleEntityGridInspector = new EntityGridInspector<ExampleEntity>(
            exampleEntityTableModel) {/*from   w w  w  .ja va  2s  . co m*/

        private static final long serialVersionUID = -582615854538245301L;

        @Override
        protected void paintComponent(final Graphics g) {
            final Date before = new Date();
            super.paintComponent(g);
            final Date after = new Date();
            final Duration duration = new Duration(before.getTime(), after.getTime());
            System.out.println(duration.getMillis());
        }
    };

    final JPanel topPanel = new JPanel(new MigLayout("fill", "[:800:]", "[]0[]"));

    topPanel.add(new JLabel("Example entity not enhnaced example"), "growx, wrap");
    topPanel.add(new JScrollPane(exampleEntityGridInspector), "grow");
    SimpleLauncher.show("Entity Grid Inspector Not Enhanced Example With Example Entity", topPanel);
}

From source file:ua.com.fielden.platform.example.swing.egi.performance.EgiWithExampleEntityExample.java

@Override
protected void exposeUi(final String[] args, final SplashController splashController) throws Exception {
    final EntityGridInspector<ExampleEntity> exampleEntityGridInspector = new EntityGridInspector<ExampleEntity>(
            exampleEntityTableModel) {/*from   w ww . ja v  a2  s.c o m*/

        private static final long serialVersionUID = -582615854538245301L;

        @Override
        protected void paintComponent(final Graphics g) {
            final Date before = new Date();
            super.paintComponent(g);
            final Date after = new Date();
            final Duration duration = new Duration(before.getTime(), after.getTime());
            System.out.println(duration.getMillis());
        }
    };

    final JPanel topPanel = new JPanel(new MigLayout("fill", "[:800:]", "[]0[]"));

    topPanel.add(new JLabel("Example entity perforamce example"), "growx, wrap");
    topPanel.add(new JScrollPane(exampleEntityGridInspector), "grow");
    SimpleLauncher.show("Entity Grid Inspector Performance Example With Example Entity", topPanel);
}