Example usage for java.text DateFormat getInstance

List of usage examples for java.text DateFormat getInstance

Introduction

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

Prototype

public static final DateFormat getInstance() 

Source Link

Document

Get a default date/time formatter that uses the SHORT style for both the date and the time.

Usage

From source file:net.bobah.mail.Dupes.java

@Override
public void run() {
    final Multimap<HashCode, File> dupes = Multimaps.newListMultimap(new HashMap<HashCode, Collection<File>>(),
            new Supplier<List<File>>() {
                @Override// w w w. j a  v  a 2 s  .  com
                public List<File> get() {
                    return new LinkedList<File>();
                }
            });

    for (final File dir : dirs) {
        if (!dir.isDirectory()) {
            log.warn("{} does not exist or is not a directory, ignored", dir);
        }

        final Collection<File> files = findFiles(dir, "");
        log.info("found {} files in {}, submitting to analyzer", files.size(), dir.getAbsolutePath());

        for (final File file : files) {
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    final ExecutionContext cxt = Dupes.this.cxt.get();

                    ReadableByteChannel ch = null;
                    try {
                        cxt.sw.start();
                        // map file, take just 1 meg of data to cxt.hash and calc the function
                        // final HashCode code = Files.hash(file, hashfunc);
                        ch = Channels.newChannel(new FileInputStream(file));
                        ByteBuffer buf = ByteBuffer.wrap(cxt.buf);
                        final int len = ch.read(buf);
                        if (len == 0)
                            return;

                        final HashCode code = hashfunc.hashBytes(cxt.buf, 0, Ints.checkedCast(len));
                        synchronized (dupes) {
                            dupes.put(code, file);
                        }

                        cxt.sw.stop();
                        log.debug("{} -> {} ({}) - {} us", file, code,
                                DateFormat.getInstance().format(file.lastModified()),
                                cxt.sw.elapsed(TimeUnit.MILLISECONDS));
                    } catch (Exception e) {
                        log.debug("exception", e);
                    } finally {
                        cxt.recycle();
                        if (ch != null)
                            try {
                                ch.close();
                            } catch (IOException unused) {
                            }
                        ;
                    }
                }
            });
        }
        log.info("done submitting {} to analyzer", dir.getAbsolutePath());
    }

    try {
        shutdownExecutor(executor, log);
    } catch (InterruptedException e) {
        log.debug("exception", e);
    }

    for (Collection<File> filez : dupes.asMap().values()) {
        if (filez.size() == 1)
            continue;
        log.info("dupes found: {}", filez);
    }
}

From source file:org.prom5.analysis.performance.dottedchart.ui.MetricsPanel.java

/**
 * Displays the performance metrics of each pattern on the east side of the
 * plug-in window.//from w w  w  .  j a  v a  2 s. co  m
 * @param sortedArray int[]
 */

public void displayPerformanceMetrics() {
    String type = dcPanel.getTimeOption();
    ArrayList<DescriptiveStatistics> aList = dcModel.getTimeStatistics();
    ArrayList<String> aTitles = dcModel.getDescriptiveStatisticsTitles();

    ArrayList<String> sortedTitleList = dcModel.getSortedKeySetList();

    this.removeAll();
    this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    //add time option menu
    this.add(Box.createRigidArea(new Dimension(5, 10)));
    JPanel menuPanel = new JPanel(new BorderLayout());
    menuPanel.setPreferredSize(new Dimension(160, 45));
    menuPanel.setMaximumSize(new Dimension(180, 45));
    timeSortLabel.setAlignmentX(LEFT_ALIGNMENT);
    menuPanel.add(timeSortLabel, BorderLayout.NORTH);
    timeBox.setMaximumSize(new Dimension(160, 20));
    timeBox.setAlignmentX(LEFT_ALIGNMENT);
    menuPanel.add(Box.createRigidArea(new Dimension(5, 0)));
    menuPanel.add(timeBox, BorderLayout.CENTER);
    this.add(menuPanel);
    this.add(Box.createRigidArea(new Dimension(5, 10)));

    //for each frequency get the set of patterns that have that frequency
    //(run from high frequency to low)
    int size = 0;
    for (int i = 0; i < aList.size(); i++) {
        try {
            String key;
            DescriptiveStatistics currentDS = null;
            if (i != 0)
                key = sortedTitleList.get(i - 1);
            else {
                key = aTitles.get(0);
                currentDS = aList.get(i);
            }

            if (i > 0 && dcModel.getTypeHashMap().equals(DottedChartPanel.ST_INST)
                    && !dcModel.getInstanceTypeToKeep().contains(key))
                continue;
            size++;

            if (i > 0) {
                for (int j = 1; j < aTitles.size(); j++) {
                    if (aTitles.get(j).equals(key))
                        currentDS = aList.get(j);
                }
            }
            AbstractTableModel otm;
            //create labels that contains information about the pattern
            if (i == 0)
                otm = new OverallMetricTableModel();
            else
                otm = new OneMetricTableModel();
            DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
            dtcr.setBackground(new Color(235, 235, 235));
            JTable table = new JTable(otm);
            table.setPreferredSize(new Dimension(200, 55));
            table.setMaximumSize(new Dimension(200, 55));
            table.getColumnModel().getColumn(0).setPreferredWidth(70);
            table.getColumnModel().getColumn(0).setMaxWidth(100);
            table.getTableHeader().setFont(new Font("SansSerif", Font.PLAIN, 12));
            table.getColumnModel().getColumn(0).setCellRenderer(dtcr);
            table.setBorder(BorderFactory.createEtchedBorder());

            //place throughput times in table
            if (type.equals(DottedChartPanel.TIME_ACTUAL)) {
                if (i == 0) {
                    table.setValueAt(DateFormat.getInstance().format(dcModel.getLogBoundaryLeft()), 0, 1);
                    table.setValueAt(DateFormat.getInstance().format(dcModel.getLogBoundaryRight()), 1, 1);
                } else {
                    table.setValueAt(DateFormat.getInstance().format(dcModel.getStartDateofLogUniList(key)), 0,
                            1);
                    table.setValueAt(DateFormat.getInstance().format(dcModel.getEndDateofLogUniList(key)), 1,
                            1);
                }
                table.setValueAt(formatString(currentDS.getMean() / timeDivider, 5), 2, 1);
                table.setValueAt(formatString(currentDS.getMin() / timeDivider, 5), 3, 1);
                table.setValueAt(formatString(currentDS.getMax() / timeDivider, 5), 4, 1);
            } else if (type.equals(DottedChartPanel.TIME_RELATIVE_TIME)) {
                if (i == 0) {
                    table.setValueAt(formatDate(dcModel.getLogBoundaryLeft()), 0, 1);
                    table.setValueAt(formatDate(dcModel.getLogBoundaryRight()), 1, 1);
                } else {
                    table.setValueAt(formatDate(dcModel.getStartDateofLogUniList(key)), 0, 1);
                    table.setValueAt(formatDate(dcModel.getEndDateofLogUniList(key)), 1, 1);
                }
                table.setValueAt(formatString(currentDS.getMean() / timeDivider, 5), 2, 1);
                table.setValueAt(formatString(currentDS.getMin() / timeDivider, 5), 3, 1);
                table.setValueAt(formatString(currentDS.getMax() / timeDivider, 5), 4, 1);
            } else if (type.equals(DottedChartPanel.TIME_RELATIVE_RATIO)) {
                if (i == 0) {
                    table.setValueAt(formatRatio(dcModel.getLogBoundaryLeft()), 0, 1);
                    table.setValueAt(formatRatio(dcModel.getLogBoundaryRight()), 1, 1);
                } else {
                    table.setValueAt(formatRatio(dcModel.getStartDateofLogUniList(key)), 0, 1);
                    table.setValueAt(formatRatio(dcModel.getEndDateofLogUniList(key)), 1, 1);
                }
                table.setValueAt(formatString(currentDS.getMean() / 100, 5), 2, 1);
                table.setValueAt(formatString(currentDS.getMin() / 100, 5), 3, 1);
                table.setValueAt(formatString(currentDS.getMax() / 100, 5), 4, 1);
            } else if (type.equals(DottedChartPanel.TIME_LOGICAL)
                    || type.equals(DottedChartPanel.TIME_LOGICAL_RELATIVE)) {
                if (i == 0) {
                    table.setValueAt(formatString(dcModel.getLogBoundaryLeft().getTime(), 5), 0, 1);
                    table.setValueAt(formatString(dcModel.getLogBoundaryRight().getTime(), 5), 1, 1);
                } else {
                    table.setValueAt(formatString((dcModel.getStartDateofLogUniList(key)).getTime(), 5), 0, 1);
                    table.setValueAt(formatString((dcModel.getEndDateofLogUniList(key)).getTime(), 5), 1, 1);
                }
                table.setValueAt(formatString(currentDS.getMean(), 5), 2, 1);
                table.setValueAt(formatString(currentDS.getMin(), 5), 3, 1);
                table.setValueAt(formatString(currentDS.getMax(), 5), 4, 1);
            }

            JPanel tempPanel = new JPanel(new BorderLayout());
            table.setAlignmentX(CENTER_ALIGNMENT);
            tempPanel.setPreferredSize(new Dimension(160, 98));
            tempPanel.setMaximumSize(new Dimension(180, 98));
            tempPanel.add(table.getTableHeader(), BorderLayout.NORTH);
            tempPanel.add(table, BorderLayout.CENTER);
            JPanel tempPanel2 = new JPanel(new BorderLayout());
            JLabel patternLabel = new JLabel("Component " + key + ":");
            patternLabel.setAlignmentX(LEFT_ALIGNMENT);

            JLabel frequencyLabel = null;
            if (i == 0)
                frequencyLabel = new JLabel("# of components: " + currentDS.getN());
            else
                frequencyLabel = new JLabel("# of dots: " + dcModel.getNumberOfLogUnits(key));

            frequencyLabel.setAlignmentX(LEFT_ALIGNMENT);
            frequencyLabel.setFont(new Font("SansSerif", Font.PLAIN, 12));
            tempPanel2.add(patternLabel, BorderLayout.NORTH);
            tempPanel2.add(frequencyLabel, BorderLayout.CENTER);
            tempPanel2.add(tempPanel, BorderLayout.SOUTH);
            this.add(tempPanel2);
            this.add(Box.createRigidArea(new Dimension(5, 10)));
        } catch (NullPointerException ex) {
            //can occur when patternMap does not contain a pattern with this frequency
            size--;
        }
    }
    //make sure the pattern performance information is displayed properly
    this.setPreferredSize(new Dimension(200, 140 * (size + 1)));
    this.revalidate();
    this.repaint();

}

From source file:org.squale.squaleweb.gwt.motionchart.server.DataServiceImpl.java

/**
 * Just for debugging purposes/*www .j ava 2s. c om*/
 * 
 * @param data the data generated for the Motion Chart
 */
private void printMotionChartDataInLog(MotionChartData data) {
    if (log.isDebugEnabled()) {
        log.debug("=============================================================");
        Collection<Application> computedApps = data.getApplications();
        for (Application application : computedApps) {
            log.debug(application.getName());
            Collection<AuditValues> audits = application.getAuditValues();
            for (AuditValues auditValues : audits) {
                log.debug("\t" + DateFormat.getInstance().format(auditValues.getDate()));
                log.debug("\t\tLOC : " + auditValues.getLinesOfCode());
                log.debug("\t\tvG  : " + auditValues.getComplexity());
            }
        }
        log.debug("=============================================================");
    }
}

From source file:com.expressflow.controller.ProcessController.java

@RequestMapping(value = "/process/init")
public Process initProcess() {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    if (userService.isUserLoggedIn()) {
        Process process = new Process();
        Date now = new Date();
        process.setAccessDate(now);/*from  ww w  .  jav  a 2 s.  c  o m*/
        process.setCreationDate(now);
        process.setAccessDateView(DateFormat.getInstance().format(now));
        process.setCreationDateView(DateFormat.getInstance().format(now));
        process.setCreator(user.getEmail());
        process.setId(KeyFactory.keyToString(KeyFactory.createKey(user.getEmail(), now.getTime())));
        process.setXml("<process></process>");
        process.setExecXml("<process />");
        return process;
    } else
        return null;
}

From source file:org.processmining.analysis.performance.dottedchart.ui.MetricsPanel.java

/**
 * Displays the performance metrics of each pattern on the east side of the
 * plug-in window.//from   w ww  .  j av  a2  s . c o  m
 * 
 * @param sortedArray
 *            int[]
 */

public void displayPerformanceMetrics() {
    String type = dcPanel.getTimeOption();
    ArrayList<DescriptiveStatistics> aList = dcModel.getTimeStatistics();
    ArrayList<String> aTitles = dcModel.getDescriptiveStatisticsTitles();

    ArrayList<String> sortedTitleList = dcModel.getSortedKeySetList();

    this.removeAll();
    this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    // add time option menu
    this.add(Box.createRigidArea(new Dimension(5, 10)));
    JPanel menuPanel = new JPanel(new BorderLayout());
    menuPanel.setPreferredSize(new Dimension(160, 45));
    menuPanel.setMaximumSize(new Dimension(180, 45));
    timeSortLabel.setAlignmentX(LEFT_ALIGNMENT);
    menuPanel.add(timeSortLabel, BorderLayout.NORTH);
    timeBox.setMaximumSize(new Dimension(160, 20));
    timeBox.setAlignmentX(LEFT_ALIGNMENT);
    menuPanel.add(Box.createRigidArea(new Dimension(5, 0)));
    menuPanel.add(timeBox, BorderLayout.CENTER);
    this.add(menuPanel);
    this.add(Box.createRigidArea(new Dimension(5, 10)));

    // for each frequency get the set of patterns that have that frequency
    // (run from high frequency to low)
    int size = 0;
    for (int i = 0; i < aList.size(); i++) {
        try {
            String key;
            DescriptiveStatistics currentDS = null;
            if (i != 0)
                key = sortedTitleList.get(i - 1);
            else {
                key = aTitles.get(0);
                currentDS = aList.get(i);
            }

            if (i > 0 && dcModel.getTypeHashMap().equals(DottedChartPanel.ST_INST)
                    && !dcModel.getInstanceTypeToKeep().contains(key))
                continue;
            size++;

            if (i > 0) {
                for (int j = 1; j < aTitles.size(); j++) {
                    if (aTitles.get(j).equals(key))
                        currentDS = aList.get(j);
                }
            }
            AbstractTableModel otm;
            // create labels that contains information about the pattern
            if (i == 0)
                otm = new OverallMetricTableModel();
            else
                otm = new OneMetricTableModel();
            DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
            dtcr.setBackground(new Color(235, 235, 235));
            JTable table = new JTable(otm);
            table.setPreferredSize(new Dimension(200, 55));
            table.setMaximumSize(new Dimension(200, 55));
            table.getColumnModel().getColumn(0).setPreferredWidth(70);
            table.getColumnModel().getColumn(0).setMaxWidth(100);
            table.getTableHeader().setFont(new Font("SansSerif", Font.PLAIN, 12));
            table.getColumnModel().getColumn(0).setCellRenderer(dtcr);
            table.setBorder(BorderFactory.createEtchedBorder());

            // place throughput times in table
            if (type.equals(DottedChartPanel.TIME_ACTUAL)) {
                if (i == 0) {
                    table.setValueAt(DateFormat.getInstance().format(dcModel.getLogBoundaryLeft()), 0, 1);
                    table.setValueAt(DateFormat.getInstance().format(dcModel.getLogBoundaryRight()), 1, 1);
                } else {
                    table.setValueAt(DateFormat.getInstance().format(dcModel.getStartDateofLogUniList(key)), 0,
                            1);
                    table.setValueAt(DateFormat.getInstance().format(dcModel.getEndDateofLogUniList(key)), 1,
                            1);
                }
                table.setValueAt(formatString(currentDS.getMean() / timeDivider, 5), 2, 1);
                table.setValueAt(formatString(currentDS.getMin() / timeDivider, 5), 3, 1);
                table.setValueAt(formatString(currentDS.getMax() / timeDivider, 5), 4, 1);
            } else if (type.equals(DottedChartPanel.TIME_RELATIVE_TIME)) {
                if (i == 0) {
                    table.setValueAt(formatDate(dcModel.getLogBoundaryLeft()), 0, 1);
                    table.setValueAt(formatDate(dcModel.getLogBoundaryRight()), 1, 1);
                } else {
                    table.setValueAt(formatDate(dcModel.getStartDateofLogUniList(key)), 0, 1);
                    table.setValueAt(formatDate(dcModel.getEndDateofLogUniList(key)), 1, 1);
                }
                table.setValueAt(formatString(currentDS.getMean() / timeDivider, 5), 2, 1);
                table.setValueAt(formatString(currentDS.getMin() / timeDivider, 5), 3, 1);
                table.setValueAt(formatString(currentDS.getMax() / timeDivider, 5), 4, 1);
            } else if (type.equals(DottedChartPanel.TIME_RELATIVE_RATIO)) {
                if (i == 0) {
                    table.setValueAt(formatRatio(dcModel.getLogBoundaryLeft()), 0, 1);
                    table.setValueAt(formatRatio(dcModel.getLogBoundaryRight()), 1, 1);
                } else {
                    table.setValueAt(formatRatio(dcModel.getStartDateofLogUniList(key)), 0, 1);
                    table.setValueAt(formatRatio(dcModel.getEndDateofLogUniList(key)), 1, 1);
                }
                table.setValueAt(formatString(currentDS.getMean() / 100, 5), 2, 1);
                table.setValueAt(formatString(currentDS.getMin() / 100, 5), 3, 1);
                table.setValueAt(formatString(currentDS.getMax() / 100, 5), 4, 1);
            } else if (type.equals(DottedChartPanel.TIME_LOGICAL)
                    || type.equals(DottedChartPanel.TIME_LOGICAL_RELATIVE)) {
                if (i == 0) {
                    table.setValueAt(formatString(dcModel.getLogBoundaryLeft().getTime(), 5), 0, 1);
                    table.setValueAt(formatString(dcModel.getLogBoundaryRight().getTime(), 5), 1, 1);
                } else {
                    table.setValueAt(formatString((dcModel.getStartDateofLogUniList(key)).getTime(), 5), 0, 1);
                    table.setValueAt(formatString((dcModel.getEndDateofLogUniList(key)).getTime(), 5), 1, 1);
                }
                table.setValueAt(formatString(currentDS.getMean(), 5), 2, 1);
                table.setValueAt(formatString(currentDS.getMin(), 5), 3, 1);
                table.setValueAt(formatString(currentDS.getMax(), 5), 4, 1);
            }

            JPanel tempPanel = new JPanel(new BorderLayout());
            table.setAlignmentX(CENTER_ALIGNMENT);
            tempPanel.setPreferredSize(new Dimension(160, 98));
            tempPanel.setMaximumSize(new Dimension(180, 98));
            tempPanel.add(table.getTableHeader(), BorderLayout.NORTH);
            tempPanel.add(table, BorderLayout.CENTER);
            JPanel tempPanel2 = new JPanel(new BorderLayout());
            JLabel patternLabel = new JLabel("Component " + key + ":");
            patternLabel.setAlignmentX(LEFT_ALIGNMENT);

            JLabel frequencyLabel = null;
            if (i == 0)
                frequencyLabel = new JLabel("# of components: " + currentDS.getN());
            else
                frequencyLabel = new JLabel("# of dots: " + dcModel.getNumberOfLogUnits(key));

            frequencyLabel.setAlignmentX(LEFT_ALIGNMENT);
            frequencyLabel.setFont(new Font("SansSerif", Font.PLAIN, 12));
            tempPanel2.add(patternLabel, BorderLayout.NORTH);
            tempPanel2.add(frequencyLabel, BorderLayout.CENTER);
            tempPanel2.add(tempPanel, BorderLayout.SOUTH);
            this.add(tempPanel2);
            this.add(Box.createRigidArea(new Dimension(5, 10)));
        } catch (NullPointerException ex) {
            // can occur when patternMap does not contain a pattern with
            // this frequency
            size--;
        }
    }
    // make sure the pattern performance information is displayed properly
    this.setPreferredSize(new Dimension(200, 140 * (size + 1)));
    this.revalidate();
    this.repaint();

}

From source file:uk.ac.ox.oucs.vle.ModuleImpl.java

/**
 * SESii 16.1 Automated process for reminder emails to be sent to students
 * @param groups/*from w  w  w . j a v  a2s. c o  m*/
 */
private void modulesStarting(final List<CourseGroupDAO> groups) {

    for (CourseGroupDAO group : groups) {

        final Set<CourseComponentDAO> components = group.getComponents();
        final Set<CourseComponentDAO> componentsStarting = new HashSet<CourseComponentDAO>();

        for (CourseComponentDAO component : components) {

            if (isAboutToStart(component.getStarts())) {
                // Component is about to start
                log.info("Component is about to start [" + component.getPresentationId() + ":"
                        + DateFormat.getInstance().format(component.getStarts()) + ":" + component.getTitle()
                        + "]");
                componentsStarting.add(component);
            }
        }

        for (CourseComponentDAO component : componentsStarting) {
            for (CourseSignupDAO signup : component.getSignups()) {
                if (Status.CONFIRMED == signup.getStatus()) {
                    sendModuleStartingEmail(signup, component);
                }
            }
        }
    }
}

From source file:org.liferayhub.pc.service.impl.PowerConsoleServiceImpl.java

public String runCommand(long userId, long companyId, String mode, String command) {
    String response = "";
    Date startDate = new Date();
    if ("server".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\t\tShow this help message\n"
                    + "version\t\t Display the version of the Liferay Portal\n"
                    + "date\t\t\tDisplay the date and time of the database server\n"
                    + "uptime\t\t  Display the uptime of the portal\n" + "adduser\t\t Add a new user";
        } else if ("version".equalsIgnoreCase(command)) {
            response = ReleaseInfo.getReleaseInfo() + " running on "
                    + StringUtil.upperCaseFirstLetter(ServerDetector.getServerId());
        } else if ("date".equalsIgnoreCase(command)) {
            response = new Date().toString();
        } else if ("uptime".equalsIgnoreCase(command)) {
            response = getUptime(PortalUtil.getUptime().getTime());
        } else if (command.toLowerCase().startsWith("adduser")) {
            response = handleAddUser(userId, companyId, command);
        }//  w w w  .  j  a v a 2  s. c  o m
    } else if ("db".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\t\tShow this help message\n"
                    + "version\t\t Display the version of the database\n"
                    + "date\t\t\tDisplay the date and time of the database server\n"
                    + "<sql query>\t Display result of any SQL query";
        } else if ("date".equalsIgnoreCase(command)) {
            response = runSQLQuery("select now() \"\"");
        } else if ("version".equalsIgnoreCase(command)) {
            response = runSQLQuery(
                    "select '" + DBFactoryUtil.getDBFactory().getDB().getType() + "' as '', version() ''");
        } else
            response = runSQLQuery(command);
    } else if ("jvm".equalsIgnoreCase(mode)) {
        if ("help".equalsIgnoreCase(command)) {
            response = "Commands:\n" + "help\t\tShow this help message\n"
                    + "mem\t\t Display memory usage of the JVM\n"
                    + "osinfo\t  Display operating system info of the running JVM\n"
                    + "vminfo\t  Display VM info";
        } else if ("mem".equalsIgnoreCase(command)) {
            MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
            response = "Heap        : " + mem.getHeapMemoryUsage().toString();
            response += "\nNon Heap    : " + mem.getNonHeapMemoryUsage().toString();
            response += "\nFinalization: " + mem.getObjectPendingFinalizationCount() + " objects pending";
        } else if ("osinfo".equalsIgnoreCase(command)) {
            OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
            response = os.getName() + "[" + os.getArch() + "] " + os.getVersion() + " ("
                    + os.getAvailableProcessors() + " processors)";
            response += "\nLoad Average: " + os.getSystemLoadAverage();
        } else if ("vminfo".equalsIgnoreCase(command)) {
            RuntimeMXBean vm = ManagementFactory.getRuntimeMXBean();
            response = vm.getVmName() + " " + vm.getVmVersion() + " by " + vm.getVmVendor();
            response += "\n" + vm.getSpecName() + " " + vm.getSpecVersion() + " by " + vm.getSpecVendor();
            response += "\nStarted at: " + DateFormat.getInstance().format(new Date(vm.getStartTime()));
            response += "\nUptime    : " + getUptime(vm.getStartTime());
        } else {
            response = UNRECOGNIZED_COMMAND;
        }
    }
    // save command to database if it is not 'help'
    if (!command.startsWith("help")) {
        try {
            // add to history
            Date endDate = new Date();
            long id = CounterLocalServiceUtil.increment(CommandHistory.class.getName());
            CommandHistory history = CommandHistoryLocalServiceUtil.createCommandHistory(id);
            history.setCommand(command);
            history.setExecutionDate(startDate);
            history.setExecutionTime(endDate.getTime() - startDate.getTime());
            history.setMode(mode);
            history.setUserId(userId);
            CommandHistoryLocalServiceUtil.updateCommandHistory(history);
            // TODO: delete the oldest entry > MAX_HISTORY_SIZE
            // get the history size
            long historySize = 100;
            List<CommandHistory> historyList = CommandHistoryLocalServiceUtil
                    .findCommandHistoryByUserId(userId);
            if (historyList.size() >= historySize) {
                CommandHistoryLocalServiceUtil.deleteCommandHistory(historyList.get(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
    return response;
}

From source file:SeprozoService.UserServiceImpl.java

private String genereerSessionKey(String naam, String wachtwoord) {
    Date tijd = new Date();
    DateFormat df = DateFormat.getInstance();
    return versleutel(naam + wachtwoord + df.format(tijd));
}

From source file:de.damdi.fitness.activity.start_training.DialogFragmentAddEntry.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    LayoutInflater inflater = LayoutInflater.from(getActivity());
    final View v = inflater.inflate(R.layout.fragment_dialog_add_entry, null);

    spinner_duration = (Spinner) v.findViewById(R.id.spinner_duration);
    spinner_duration_unit = (Spinner) v.findViewById(R.id.spinner_time_unit);
    spinner_repetitions = (Spinner) v.findViewById(R.id.spinner_repetitions);
    spinner_weight = (Spinner) v.findViewById(R.id.spinner_weight);
    checkbox_duration = (CheckBox) v.findViewById(R.id.checkbox_duration);
    checkbox_weight = (CheckBox) v.findViewById(R.id.checkbox_weight);
    checkbox_repetitions = (CheckBox) v.findViewById(R.id.checkbox_repetitions);

    fillSpinners();//from   www. ja va2s .  c o m

    setSpinners();

    // show different text, if an entry is edited(not created)
    TextView tw = (TextView) v.findViewById(R.id.textview_entryaction);
    if (mState == EntryAction.EDITING_ENTRY) {
        tw.setText(getActivity().getString(R.string.edit_entry));
    } else {
        tw.setText(getActivity().getString(R.string.add_entry));
    }

    return new AlertDialog.Builder(getActivity())
            .setTitle(DateFormat.getInstance().format(mTrainingEntry.getDate())).setView(v).setCancelable(true)
            .setPositiveButton(getString(R.string.save_entry), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    List<SetParameter> setParameters = new ArrayList<SetParameter>();
                    if (checkbox_duration.isChecked()) {
                        SetParameter.Duration duration = new SetParameter.Duration(getDurationValue());
                        setParameters.add(duration);
                    }
                    if (checkbox_weight.isChecked()) {
                        SetParameter.Weight weight = new SetParameter.Weight(getWeightValue());
                        setParameters.add(weight);
                    }
                    if (checkbox_repetitions.isChecked()) {
                        SetParameter.Repetition repetition = new SetParameter.Repetition(getRepetitionValue());
                        setParameters.add(repetition);
                    }

                    // if no SetParameter has been chosen, the FSet
                    // must not be created or even has to be deleted
                    if (setParameters.isEmpty()) {
                        if (mFSet != null) {
                            // delete existing FSet
                            boolean success = mTrainingEntry.getFSetList().remove(mFSet);
                            if (!success)
                                Log.e(TAG, "Could not delete FSet:\n " + mFSet.toString()
                                        + "\n in TrainingEntry:\n " + mTrainingEntry.toDebugString());
                        } else {
                            // do nothing
                            dialog.dismiss();
                            return;
                        }
                    } else {
                        // if SetParameters have been chosen, either the old
                        // FSet has to be updated or a new FSet has to be
                        // added
                        if (mFSet == null) {
                            // add new FSet
                            mFSet = new FSet(setParameters.toArray(new SetParameter[setParameters.size()]));
                            mTrainingEntry.add(mFSet);
                        } else {
                            // replace old FSet
                            mFSet = new FSet(setParameters.toArray(new SetParameter[setParameters.size()]));
                            mTrainingEntry.getFSetList().set(mFSetPosition, mFSet);
                        }
                        mTrainingEntry.setHasBeenDone(mFSet, false);

                    }

                    FExDetailFragment fragment = (FExDetailFragment) getFragmentManager()
                            .findFragmentById(R.id.exercise_detail_container);
                    fragment.onEntryEdited(mFex);

                    dialog.dismiss();
                }
            }).setNegativeButton(getString(R.string.discard_entry), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).create();
}

From source file:org.craftercms.social.util.support.security.CrafterProfileFilter.java

/**
 *
 * @param chain//w w w.j av  a2s . c  om
 * @param httpRequest
 * @param httpResponse
 * @param tenantName
 * @param cipher
 * @param profileValues
 * @param profileToken
 * @throws IOException
 * @throws ServletException
 * @throws org.craftercms.social.exceptions.AuthenticationException
 */
private void authenticateWithCipherToken(FilterChain chain, HttpServletRequest httpRequest,
        HttpServletResponse httpResponse, String tenantName, SimpleDesCipher cipher, String[] profileValues,
        String profileToken)
        throws IOException, ServletException, org.craftercms.social.exceptions.AuthenticationException {
    // validate tenant, exception thrown for failure
    validateTenant(httpRequest.getServerName(), tenantName, profileValues[TENANT_NAME],
            profileValues[PROFILE_ID]);

    Profile userProfile = null;

    // validate the date
    Date date = null;
    try {
        date = DateFormat.getInstance().parse(profileValues[DATE]);
    } catch (ParseException e) {
        String error = "Error parsing date: '" + profileValues[DATE] + "' ";
        log.error(error + e);
        throw new org.craftercms.social.exceptions.AuthenticationException(error, e);
    }

    // if expired, we need to get refresh the user profile
    if (date.before(new Date())) {
        userProfile = profile.getUserInformation(profileToken);

    } else {

        // create user profile from cookie values
        userProfile = new Profile();
        userProfile.setId(profileValues[PROFILE_ID]);
        String[] profileRoles = profileValues[ROLES].split(",");
        userProfile.setRoles(Arrays.asList(profileRoles));
        userProfile.setTenantName(profileValues[TENANT_NAME]);

    }

    // set profile in context
    SecurityContextHolder.getContext().setAuthentication(getCrafterAuthToken(userProfile));

    // generate the encrypted token and set in response
    httpResponse.addCookie(getCipherCookie(cipher, profileToken, userProfile));

    chain.doFilter(httpRequest, httpResponse);
}