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:de.mendelson.comm.as2.client.AS2Gui.java

/**
 * Creates new form NewJFrame//  www .j  ava 2 s .  c  o  m
 */
public AS2Gui(Splash splash, String host) {
    this.host = host;
    //Set System default look and feel
    try {
        //support the command line option -Dswing.defaultlaf=...
        if (System.getProperty("swing.defaultlaf") == null) {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
    } catch (Exception e) {
        this.logger.warning(this.getClass().getName() + ":" + e.getMessage());
    }
    //load resource bundle
    try {
        this.rb = (MecResourceBundle) ResourceBundle.getBundle(ResourceBundleAS2Gui.class.getName());
    } catch (MissingResourceException e) {
        throw new RuntimeException("Oops..resource bundle " + e.getClassName() + " not found.");
    }
    initComponents();
    this.jButtonNewVersion.setVisible(false);
    this.jPanelRefreshWarning.setVisible(false);
    //set preference values to the GUI
    this.setBounds(this.clientPreferences.getInt(PreferencesAS2.FRAME_X),
            this.clientPreferences.getInt(PreferencesAS2.FRAME_Y),
            this.clientPreferences.getInt(PreferencesAS2.FRAME_WIDTH),
            this.clientPreferences.getInt(PreferencesAS2.FRAME_HEIGHT));
    //ensure to display all messages
    this.getLogger().setLevel(Level.ALL);
    LogConsolePanel consolePanel = new LogConsolePanel(this.getLogger());
    //define the colors for the log levels
    consolePanel.setColor(Level.SEVERE, LogConsolePanel.COLOR_BROWN);
    consolePanel.setColor(Level.WARNING, LogConsolePanel.COLOR_BLUE);
    consolePanel.setColor(Level.INFO, LogConsolePanel.COLOR_BLACK);
    consolePanel.setColor(Level.CONFIG, LogConsolePanel.COLOR_DARK_GREEN);
    consolePanel.setColor(Level.FINE, LogConsolePanel.COLOR_DARK_GREEN);
    consolePanel.setColor(Level.FINER, LogConsolePanel.COLOR_DARK_GREEN);
    consolePanel.setColor(Level.FINEST, LogConsolePanel.COLOR_DARK_GREEN);
    this.jPanelServerLog.add(consolePanel);
    this.setTitle(AS2ServerVersion.getProductName() + " " + AS2ServerVersion.getVersion());
    //initialize the help system if available
    this.initializeJavaHelp();
    this.jTableMessageOverview.getSelectionModel().addListSelectionListener(this);
    this.jTableMessageOverview.getTableHeader().setReorderingAllowed(false);
    //icon columns
    TableColumn column = this.jTableMessageOverview.getColumnModel().getColumn(0);
    column.setMaxWidth(20);
    column.setResizable(false);
    column = this.jTableMessageOverview.getColumnModel().getColumn(1);
    column.setMaxWidth(20);
    column.setResizable(false);
    this.jTableMessageOverview.setDefaultRenderer(Date.class,
            new TableCellRendererDate(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)));
    //add row sorter
    RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(this.jTableMessageOverview.getModel());
    jTableMessageOverview.setRowSorter(sorter);
    sorter.addRowSorterListener(this);
    this.jPanelFilterOverview.setVisible(this.showFilterPanel);
    this.jMenuItemHelpForum.setEnabled(Desktop.isDesktopSupported());
    //destroy splash, possible login screen for the client should come up
    if (splash != null) {
        splash.destroy();
    }
    this.setButtonState();
    this.jTableMessageOverview.addMouseListener(this);
    //popup menu issues
    this.jPopupMenu.setInvoker(this.jScrollPaneMessageOverview);
    this.jPopupMenu.addPopupMenuListener(this);
    super.addMessageProcessor(this);
    //perform the connection to the server
    //warning! this works for localhost only so far
    int clientServerCommPort = this.clientPreferences.getInt(PreferencesAS2.CLIENTSERVER_COMM_PORT);
    if (splash != null) {
        splash.destroy();
    }
    this.browserLinkedPanel.cyleText(new String[] {
            "For additional EDI software to convert and process your data please contact <a href='http://www.mendelson-e-c.com'>mendelson-e-commerce GmbH</a>",
            "To buy a commercial license please visit the <a href='http://shop.mendelson-e-c.com/'>mendelson online shop</a>",
            "Most trading partners demand a trusted certificate - Order yours at the <a href='http://ca.mendelson-e-c.com'>mendelson CA</a> now!",
            "Looking for additional secure data transmission software? Try the <a href='http://oftp2.mendelson-e-c.com'>mendelson OFTP2</a> solution!",
            "You want to send EDIFACT data from your SAP system? Ask <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20SAP%20integration%20solutions'>mendelson-e-commerce GmbH</a> for a solution.",
            "You need a secure FTP solution? <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20SFTP%20solution'>Ask us</a> for the mendelson SFTP software.",
            "Convert flat files, EDIFACT, SAP IDos, VDA, inhouse formats? <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20converter%20solution'>Ask us</a> for the mendelson EDI converter.",
            "For commercial support of this software please buy a license at <a href='http://as2.mendelson-e-c.com'>the mendelson AS2</a> website.",
            "Have a look at the <a href='http://www.mendelson-e-c.com/products_mbi.php'>mendelson business integration</a> for a powerful EDI solution.",
            "The <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20RosettaNet%20solution'>mendelson RosettaNet solution</a> supports RNIF 1.1 and RNIF 2.0.",
            "The <a href='http://www.mendelson-e-c.com/products_ide.php'>mendelson converter IDE</a> is the graphical mapper for the mendelson converter.",
            "To process any XML data and convert it to EDIFACT, VDA, flat files, IDocs and inhouse formats use <a href='http://www.mendelson-e-c.com/products_converter.php'>the mendelson converter</a>.",
            "To transmit your EDI data via HTTP/S please <a href='mailto:info@mendelson.de?subject=Please%20inform%20me%20about%20your%20HTTPS%20solution'>ask us</a> for the mendelson HTTPS solution.",
            "If you have questions regarding this product please refer to the <a href='http://community.mendelson-e-c.com/'>mendelson community</a>.", });
    this.connect(new InetSocketAddress(host, clientServerCommPort), 5000);
    Runnable dailyNewsThread = new Runnable() {

        @Override
        public void run() {
            while (true) {
                long lastUpdateCheck = Long.valueOf(clientPreferences.get(PreferencesAS2.LAST_UPDATE_CHECK));
                //check only once a day even if the system is started n times a day
                if (lastUpdateCheck < (System.currentTimeMillis() - TimeUnit.HOURS.toMillis(23))) {
                    clientPreferences.put(PreferencesAS2.LAST_UPDATE_CHECK,
                            String.valueOf(System.currentTimeMillis()));
                    jButtonNewVersion.setVisible(false);
                    String version = (AS2ServerVersion.getVersion() + " " + AS2ServerVersion.getBuild())
                            .replace(' ', '+');
                    Header[] header = htmlPanel.setURL(
                            "http://www.mendelson.de/en/mecas2/client_welcome.php?version=" + version,
                            AS2ServerVersion.getProductName() + " " + AS2ServerVersion.getVersion(),
                            new File("start/client_welcome.html"));
                    if (header != null) {
                        String downloadURL = null;
                        String actualBuild = null;
                        for (Header singleHeader : header) {
                            if (singleHeader.getName().equals("x-actual-build")) {
                                actualBuild = singleHeader.getValue().trim();
                            }
                            if (singleHeader.getName().equals("x-download-url")) {
                                downloadURL = singleHeader.getValue().trim();
                            }
                        }
                        if (downloadURL != null && actualBuild != null) {
                            try {
                                int thisBuild = AS2ServerVersion.getBuildNo();
                                int availableBuild = Integer.valueOf(actualBuild);
                                if (thisBuild < availableBuild) {
                                    jButtonNewVersion.setVisible(true);
                                }
                                downloadURLNewVersion = downloadURL;
                            } catch (Exception e) {
                                //nop
                            }
                        }
                    }
                } else {
                    htmlPanel.setPage(new File("start/client_welcome.html"));
                }
                try {
                    //check once a day for new update
                    Thread.sleep(TimeUnit.DAYS.toMillis(1));
                } catch (InterruptedException e) {
                    //nop
                }
            }
        }
    };
    Executors.newSingleThreadExecutor().submit(dailyNewsThread);
    this.as2StatusBar.setConnectedHost(this.host);
}

From source file:org.robovm.eclipse.internal.AbstractLaunchConfigurationDelegate.java

@Override
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor)
        throws CoreException {

    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }//w ww . j a  v a2  s  . c  om

    monitor.beginTask(configuration.getName() + "...", 6);
    if (monitor.isCanceled()) {
        return;
    }

    try {
        monitor.subTask("Verifying launch attributes");

        String mainTypeName = getMainTypeName(configuration);
        File workingDir = getWorkingDirectory(configuration);
        String[] envp = getEnvironment(configuration);
        List<String> pgmArgs = splitArgs(getProgramArguments(configuration));
        List<String> vmArgs = splitArgs(getVMArguments(configuration));
        String[] classpath = getClasspath(configuration);
        String[] bootclasspath = getBootpath(configuration);
        IJavaProject javaProject = getJavaProject(configuration);
        int debuggerPort = findFreePort();
        boolean hasDebugPlugin = false;

        if (monitor.isCanceled()) {
            return;
        }

        // Verification done
        monitor.worked(1);

        RoboVMPlugin.consoleInfo("Building executable");

        monitor.subTask("Creating source locator");
        setDefaultSourceLocator(launch, configuration);
        monitor.worked(1);

        monitor.subTask("Creating build configuration");
        Config.Builder configBuilder;
        try {
            configBuilder = new Config.Builder();
        } catch (IOException e) {
            throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID,
                    "Launch failed. Check the RoboVM console for more information.", e));
        }
        configBuilder.logger(RoboVMPlugin.getConsoleLogger());

        File projectRoot = getJavaProject(configuration).getProject().getLocation().toFile();
        RoboVMPlugin.loadConfig(configBuilder, projectRoot, isTestConfiguration());

        Arch arch = getArch(configuration, mode);
        OS os = getOS(configuration, mode);

        configBuilder.os(os);
        configBuilder.arch(arch);

        File tmpDir = RoboVMPlugin.getBuildDir(getJavaProjectName(configuration));
        tmpDir = new File(tmpDir, configuration.getName());
        tmpDir = new File(new File(tmpDir, os.toString()), arch.toString());
        if (mainTypeName != null) {
            tmpDir = new File(tmpDir, mainTypeName);
        }

        if (ILaunchManager.DEBUG_MODE.equals(mode)) {
            configBuilder.debug(true);
            String sourcepaths = RoboVMPlugin.getSourcePaths(javaProject);
            configBuilder.addPluginArgument("debug:sourcepath=" + sourcepaths);
            configBuilder.addPluginArgument("debug:jdwpport=" + debuggerPort);
            configBuilder.addPluginArgument(
                    "debug:logdir=" + new File(projectRoot, "robovm-logs").getAbsolutePath());
            // check if we have the debug plugin
            for (Plugin plugin : configBuilder.getPlugins()) {
                if ("DebugLaunchPlugin".equals(plugin.getClass().getSimpleName())) {
                    hasDebugPlugin = true;
                }
            }
        }

        if (bootclasspath != null) {
            configBuilder.skipRuntimeLib(true);
            for (String p : bootclasspath) {
                configBuilder.addBootClasspathEntry(new File(p));
            }
        }
        for (String p : classpath) {
            configBuilder.addClasspathEntry(new File(p));
        }
        if (mainTypeName != null) {
            configBuilder.mainClass(mainTypeName);
        }
        // we need to filter those vm args that belong to plugins
        // in case of iOS run configs, we can only pass program args
        filterPluginArguments(vmArgs, configBuilder);
        filterPluginArguments(pgmArgs, configBuilder);

        configBuilder.tmpDir(tmpDir);
        configBuilder.skipInstall(true);

        Config config = null;
        AppCompiler compiler = null;
        try {
            RoboVMPlugin.consoleInfo("Cleaning output dir " + tmpDir.getAbsolutePath());
            FileUtils.deleteDirectory(tmpDir);
            tmpDir.mkdirs();

            Home home = RoboVMPlugin.getRoboVMHome();
            if (home.isDev()) {
                configBuilder.useDebugLibs(Boolean.getBoolean("robovm.useDebugLibs"));
                configBuilder.dumpIntermediates(true);
            }
            configBuilder.home(home);
            config = configure(configBuilder, configuration, mode).build();
            compiler = new AppCompiler(config);
            if (monitor.isCanceled()) {
                return;
            }
            monitor.worked(1);

            monitor.subTask("Building executable");
            AppCompilerThread thread = new AppCompilerThread(compiler, monitor);
            thread.compile();
            if (monitor.isCanceled()) {
                RoboVMPlugin.consoleInfo("Build canceled");
                return;
            }
            monitor.worked(1);
            RoboVMPlugin.consoleInfo("Build done");
        } catch (InterruptedException e) {
            RoboVMPlugin.consoleInfo("Build canceled");
            return;
        } catch (IOException e) {
            RoboVMPlugin.consoleError("Build failed");
            throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID,
                    "Build failed. Check the RoboVM console for more information.", e));
        }

        try {
            RoboVMPlugin.consoleInfo("Launching executable");
            monitor.subTask("Launching executable");
            mainTypeName = config.getMainClass();

            List<String> runArgs = new ArrayList<String>();
            runArgs.addAll(vmArgs);
            runArgs.addAll(pgmArgs);
            LaunchParameters launchParameters = config.getTarget().createLaunchParameters();
            launchParameters.setArguments(runArgs);
            launchParameters.setWorkingDirectory(workingDir);
            launchParameters.setEnvironment(envToMap(envp));
            customizeLaunchParameters(config, launchParameters, configuration, mode);
            String label = String.format("%s (%s)", mainTypeName,
                    DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(new Date()));
            // launch plugin may proxy stdout/stderr fifo, which
            // it then writes to. Need to save the original fifos
            File stdOutFifo = launchParameters.getStdoutFifo();
            File stdErrFifo = launchParameters.getStderrFifo();
            PipedInputStream pipedIn = new PipedInputStream();
            PipedOutputStream pipedOut = new PipedOutputStream(pipedIn);
            Process process = compiler.launchAsync(launchParameters, pipedIn);
            if (stdOutFifo != null || stdErrFifo != null) {
                InputStream stdoutStream = null;
                InputStream stderrStream = null;
                if (launchParameters.getStdoutFifo() != null) {
                    stdoutStream = new OpenOnReadFileInputStream(stdOutFifo);
                }
                if (launchParameters.getStderrFifo() != null) {
                    stderrStream = new OpenOnReadFileInputStream(stdErrFifo);
                }
                process = new ProcessProxy(process, pipedOut, stdoutStream, stderrStream, compiler);
            }

            IProcess iProcess = DebugPlugin.newProcess(launch, process, label);

            // setup the debugger
            if (ILaunchManager.DEBUG_MODE.equals(mode) && hasDebugPlugin) {
                VirtualMachine vm = attachToVm(monitor, debuggerPort);
                // we were canceled
                if (vm == null) {
                    process.destroy();
                    return;
                }
                if (vm instanceof VirtualMachineImpl) {
                    ((VirtualMachineImpl) vm).setRequestTimeout(DEBUGGER_REQUEST_TIMEOUT);
                }
                JDIDebugModel.newDebugTarget(launch, vm, mainTypeName + " at localhost:" + debuggerPort,
                        iProcess, true, false, true);
            }
            RoboVMPlugin.consoleInfo("Launch done");

            if (monitor.isCanceled()) {
                process.destroy();
                return;
            }
            monitor.worked(1);
        } catch (Throwable t) {
            RoboVMPlugin.consoleError("Launch failed");
            throw new CoreException(new Status(IStatus.ERROR, RoboVMPlugin.PLUGIN_ID,
                    "Launch failed. Check the RoboVM console for more information.", t));
        }

    } finally {
        monitor.done();
    }
}

From source file:org.lunarray.model.descriptor.util.DateFormatUtil.java

/**
 * Resolves the date time format.//from   w  ww.  ja  va2s  . c o m
 * 
 * @param locale
 *            The (optional) locale.
 * @return The format.
 */
private DateFormat resolveDateTimeFormat(final Locale locale) {
    DateFormat defaultValue;
    if (CheckUtil.isNull(locale)) {
        defaultValue = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
    } else {
        defaultValue = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, locale);
    }
    return this.resolve(DateFormatUtil.DEFAULT_DATE_TIME_KEY, defaultValue, locale);
}

From source file:net.lightbody.bmp.proxy.jetty.util.Resource.java

/** Get the resource list as a HTML directory listing.
 * @param base The base URL//from ww w.  ja  va2s.c om
 * @param parent True if the parent directory should be included
 * @return String of HTML
 */
public String getListHTML(String base, boolean parent) throws IOException {
    if (!isDirectory())
        return null;

    String[] ls = list();
    if (ls == null)
        return null;
    Arrays.sort(ls);

    String title = "Directory: " + URI.decodePath(base);
    title = StringUtil.replace(StringUtil.replace(title, "<", "&lt;"), ">", "&gt;");
    StringBuffer buf = new StringBuffer(4096);
    buf.append("<HTML><HEAD><TITLE>");
    buf.append(title);
    buf.append("</TITLE></HEAD><BODY>\n<H1>");
    buf.append(title);
    buf.append("</H1><TABLE BORDER=0>");

    if (parent) {
        buf.append("<TR><TD><A HREF=");
        buf.append(URI.encodePath(URI.addPaths(base, "../")));
        buf.append(">Parent Directory</A></TD><TD></TD><TD></TD></TR>\n");
    }

    DateFormat dfmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
    for (int i = 0; i < ls.length; i++) {
        String encoded = URI.encodePath(ls[i]);
        Resource item = addPath(encoded);

        buf.append("<TR><TD><A HREF=\"");

        String path = URI.addPaths(base, encoded);

        if (item.isDirectory() && !path.endsWith("/"))
            path = URI.addPaths(path, "/");
        buf.append(path);
        buf.append("\">");
        buf.append(StringUtil.replace(StringUtil.replace(ls[i], "<", "&lt;"), ">", "&gt;"));
        buf.append("&nbsp;");
        buf.append("</TD><TD ALIGN=right>");
        buf.append(item.length());
        buf.append(" bytes&nbsp;</TD><TD>");
        buf.append(dfmt.format(new Date(item.lastModified())));
        buf.append("</TD></TR>\n");
    }
    buf.append("</TABLE>\n");
    buf.append("</BODY></HTML>\n");

    return buf.toString();
}

From source file:com.sonyericsson.jenkins.plugins.bfa.CauseManagementHudsonTest.java

/**
 * Makes a modification to a {@link FailureCause} and verifies that the modification list was updated.
 * @throws Exception if something goes wrong
 */// www .j  a  va  2  s  . c  o m
public void testMakeModificationUpdatesModificationList() throws Exception {
    List<FailureCauseModification> modifications = new LinkedList<FailureCauseModification>();
    modifications.add(new FailureCauseModification("unknown", new Date(1)));
    FailureCause cause = new FailureCause(null, "SomeName", "A Description", "Some comment", null, "", null,
            modifications);
    cause.addIndication(new BuildLogIndication("."));
    PluginImpl.getInstance().getKnowledgeBase().addCause(cause);

    WebClient web = createWebClient();
    HtmlPage page = web.goTo(CauseManagement.URL_NAME);

    HtmlTable table = (HtmlTable) page.getElementById("failureCausesTable");

    HtmlAnchor firstCauseLink = (HtmlAnchor) table.getCellAt(1, 0).getFirstChild();
    HtmlPage editPage = firstCauseLink.click();

    HtmlElement modList = editPage.getElementById("modifications");
    int firstNbrOfModifications = modList.getChildNodes().size();

    editPage.getElementByName("_.comment").setTextContent("new comment");

    HtmlForm form = editPage.getFormByName("causeForm");
    submit(form);

    editPage = firstCauseLink.click();
    modList = editPage.getElementById("modifications");
    int secondNbrOfModifications = modList.getChildNodes().size();

    assertEquals(firstNbrOfModifications + 1, secondNbrOfModifications);
    assertStringContains("Latest modification date should be visible", modList.getFirstChild().asText(),
            DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
                    .format(cause.getLatestModification().getTime()));
}

From source file:com.drunkendev.confluence.plugins.attachments.PurgeAttachmentsJob.java

private void mailResultsHtml(Map<String, List<MailLogEntry>> mailEntries1, Date started, Date ended)
        throws MailException {
    String p = settingsManager.getGlobalSettings().getBaseUrl();
    String subject = "Purged old attachments";

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

    for (Map.Entry<String, List<MailLogEntry>> n : mailEntries1.entrySet()) {
        List<MailLogEntry> entries = n.getValue();

        Collections.sort(entries, new Comparator<MailLogEntry>() {
            @Override/*from  www  .j av a2  s . com*/
            public int compare(MailLogEntry o1, MailLogEntry o2) {
                Attachment a1 = o1.getAttachment();
                Attachment a2 = o2.getAttachment();

                int comp = ObjectUtils.compare(a1.getSpace().getName(), a2.getSpace().getName());
                if (comp != 0)
                    return comp;
                comp = ObjectUtils.compare(a1.getDisplayTitle(), a2.getDisplayTitle());
                if (comp != 0)
                    return comp;
                return 0;
            }
        });

        StringBuilder sb = new StringBuilder();

        sb.append(
                "<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en-US\" lang=\"en-US\">");

        sb.append("<head>");
        //sb.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />")
        sb.append("<title>").append(subject).append("</title>");
        sb.append("<style type=\"text/css\">");
        sb.append(
                "body { font-family: Helvetica, Arial, sans-serif; font-size: 10pt; width: 100%; color: #333; text-align: left; }");
        sb.append("a { color: #326ca6; text-decoration: none; }");
        sb.append("a:hover { color: #336ca6; text-decoration: underline; }");
        sb.append("a:active { color: #326ca6; }");
        sb.append("div.note { border: solid 1px #F0C000; padding: 5px; background-color: #FFFFCE; }");
        sb.append("table { border-collapse: collapse; padding: 0; border: 0 none; }");
        sb.append(
                "th, td { padding: 5px 7px; border: solid 1px #ddd; text-align: left; vertical-align: top; color: #333; margin: 0; }");
        sb.append("th { background-color: #f0f0f0 }");
        sb.append("tr.deleted td { background-color: #FFE7E7; /* border: solid 1px #DF9898; */ }");
        sb.append("</style>");
        sb.append("</head>");

        sb.append("<body>");

        sb.append("<p>");
        sb.append("This message is to inform you that the following prior");
        sb.append(" attachment versions have been removed from confluence");
        sb.append(" in order to conserve space. Current versions have not");
        sb.append(" been deleted.");
        sb.append("</p>");

        sb.append("<p>");
        sb.append("Versions deleted are listed in the 'Versions Deleted'");
        sb.append(" column. Rows shown in red have been processed, all");
        sb.append(" other rows are in report-only mode.");
        sb.append("</p>");

        sb.append("<p><strong>Started</strong>: ").append(df.format(started))
                .append(" <strong>Ended</strong>: ").append(df.format(ended)).append("</p>");

        long deleted = 0;
        long report = 0;
        for (MailLogEntry me : entries) {
            if (me.isReportOnly()) {
                report += me.getSpaceSaved();
            } else {
                deleted += me.getSpaceSaved();
            }
        }
        if (deleted > 0) {
            sb.append("<p>");
            sb.append("A total of ").append(FileSize.format(deleted)).append(" space has been reclaimed.");
            sb.append("</p>");
        }
        if (report > 0) {
            sb.append("<p>");
            sb.append("A total of ").append(FileSize.format(report))
                    .append(" can be reclaimed from those in report mode.");
            sb.append("</p>");
        }
        sb.append("<table>");

        sb.append("<thead>");
        sb.append("<tr>");
        sb.append("<th>").append("Space").append("</th>");
        sb.append("<th>").append("File Name").append("</th>");
        sb.append("<th>").append("Space Freed").append("</th>");
        //sb.append("<th>").append("Global Settings?").append("</th>");
        sb.append("<th>").append("Version").append("</th>");
        sb.append("<th>").append("Versions Deleted").append("</th>");
        sb.append("</tr>");
        sb.append("</thead>");

        sb.append("<tbody>");
        for (MailLogEntry me : entries) {
            Attachment a = me.getAttachment();

            sb.append("<tr");
            if (!me.isReportOnly()) {
                sb.append(" class=\"deleted\"");
            }
            sb.append(">");

            sb.append("<td>");
            sb.append("<a href=\"").append(p).append(a.getSpace().getUrlPath()).append("\">")
                    .append(a.getSpace().getName()).append("</a>");
            sb.append("</td>");

            sb.append("<td>");
            sb.append("<a href=\"").append(p).append(a.getContent().getAttachmentsUrlPath()).append("\">")
                    .append(a.getDisplayTitle()).append("</a>");
            sb.append("</td>");

            sb.append("<td>").append(me.getSpaceSavedPretty()).append("</td>");

            //sb.append("<td>").append(me.isGlobalSettings() ? "Yes" : "No").append("</td>");
            sb.append("<td>").append(a.getAttachmentVersion()).append("</td>");

            sb.append("<td>");
            int c = 0;
            for (Integer dl : me.getDeletedVersions()) {
                if (c++ > 0) {
                    sb.append(", ");
                }
                sb.append(dl);
            }
            sb.append("</td>");

            sb.append("</tr>");
        }
        sb.append("</tbody></table>");

        sb.append("<p>");
        sb.append("This message has been sent by the confluence mail tools");
        sb.append(" - attachment purger.");
        sb.append("</p>");

        sb.append("</body></html>");

        ConfluenceMailQueueItem mail = new ConfluenceMailQueueItem(n.getKey(), subject, sb.toString(),
                ConfluenceMailQueueItem.MIME_TYPE_HTML);
        mailQueueTaskManager.getTaskQueue("mail").addTask(mail);
        LOG.debug("Mail Sent");
    }
}

From source file:org.lilyproject.runtime.cli.LilyRuntimeCli.java

private void printStartedMessage() {
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
    String now = dateFormat.format(new Date());
    infolog.info("Lily Runtime started [" + now + "]");
}

From source file:mobisocial.bento.anyshare.util.DBHelper.java

public long storeLinkobjInDatabase(DbObj obj, Context context) {
    long localId = -1; // if replace entry, set ID
    long hash = obj.getHash();
    Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_html);
    byte[] raw = BitmapHelper.bitmapToBytes(icon);

    String feedname = obj.getFeedName();
    long parentid = 0;
    try {//  ww w .  ja v a  2s  . c om
        if (obj.getJson().has("target_relation") && obj.getJson().getString("target_relation").equals("parent")
                && obj.getJson().has("target_hash")) {
            parentid = objIdForHash(obj.getJson().getLong("target_hash"));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    DbUser usr = obj.getSender();
    String sender = "";
    if (usr != null) {
        sender = usr.getName();
    }

    long timestamp = 0;
    String title = "";
    try {
        timestamp = Long.parseLong(obj.getJson().getString("timestamp"));
        title = obj.getJson().getString("title");
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // add object
    long objId = (localId == -1) ? getNextId() : localId;
    String desc = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
            .format(new Date(timestamp));
    if (!sender.isEmpty()) {
        desc += " by " + sender;
    }

    ContentValues cv = new ContentValues();
    cv.put(ItemObject._ID, objId);
    cv.put(ItemObject.FEEDNAME, feedname);
    cv.put(ItemObject.TITLE, title);
    cv.put(ItemObject.DESC, desc);
    cv.put(ItemObject.TIMESTAMP, timestamp);
    cv.put(ItemObject.OBJHASH, hash);
    cv.put(ItemObject.PARENT_ID, parentid);

    if (raw != null) {
        cv.put(ItemObject.RAW, raw);
    }

    long newObjId = getWritableDatabase().insertOrThrow(ItemObject.TABLE, null, cv);

    return objId;
}

From source file:org.jclouds.vfs.tools.blobstore.BlobStoreShell.java

private void ls(FileSystemManager mg, FileObject wd, final String[] cmd) throws FileSystemException {
    int pos = 1;/*ww  w . ja  v  a 2s  . com*/
    final boolean recursive;
    if (cmd.length > pos && cmd[pos].equals("-R")) {
        recursive = true;
        pos++;
    } else {
        recursive = false;
    }

    final FileObject file;
    if (cmd.length > pos) {
        file = mg.resolveFile(wd, cmd[pos]);
    } else {
        file = wd;
    }

    if (file.getType() == FileType.FOLDER) {
        // List the contents
        System.out.println("Contents of " + file.getName().getFriendlyURI());
        listChildren(file, recursive, "");
    } else {
        // Stat the file
        System.out.println(file.getName());
        final FileContent content = file.getContent();
        System.out.println("Size: " + content.getSize() + " bytes.");
        final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
        final String lastMod = dateFormat.format(new Date(content.getLastModifiedTime()));
        System.out.println("Last modified: " + lastMod);
    }
}

From source file:com.facultyshowcase.app.ui.ProfessorProfileViewer.java

@Override
public void init() {
    // Make sure you call super.init() at the top of this method.
    /// See the Javadoc for #init() for more information about what it does.
    super.init();

    // Set HTML element type and class names for presentation use on this Container component.
    setHTMLElement(HTMLElement.section);
    addClassName("user-profile-viewer");
    // property_viewer is a standard class name.
    addClassName(UIUtil.PROP + "erty-viewer");
    // Add microdata for programmatic / SEO use
    /// OR use RDFa support
    /// You typically only do this in viewers - not editors.
    setAttribute("itemscope", "");
    setAttribute("itemtype", "http://schema.org/Person");
    // setAttribute allows you to set any attribute as long as it will not interfere with a component's
    /// native HTML. For example, you cannot set the "value" attribute on a Field since
    /// it uses that attribute.

    // It's a good idea to *not* mark variables final that you don't want in the scope of event listeners.
    /// Hibernate/JPA entities are a great example of this pattern. You always need to re-attach
    /// entities before using them, so we should always call getProfessorProfile() in the context
    /// of handling an event. Note: our getProfessorProfile() method re-attaches the entity.
    ProfessorProfile ProfessorProfile = getProfessorProfile();

    Name name = ProfessorProfile.getName();
    // You can use a Field for displaying non-internationalized content.
    /// It is desirable to do this since you don't need to create a LocalizedText.
    /// However, you cannot change the HTMLElement of a Field at this time,
    /// so some of the following code uses a Label which does allow
    /// specification of the HTMLElement.
    final Field slug = new Field(ProfessorProfile.getSlug(), false);
    final Field namePrefix = new Field(name.getFormOfAddress(), false);
    final Field nameGiven = new Field(name.getFirst(), false);
    final Field nameFamily = new Field(name.getLast(), false);
    final Field nameSuffix = new Field(name.getSuffix(), false);
    // Sometimes it is easier and less error prone to make a component non-visible
    /// than checking for null on each use. Use this pattern with care. You don't
    /// want to consume a lot of resource unnecessarily.
    if (StringFactory.isEmptyString(namePrefix.getText()))
        namePrefix.setVisible(false);//from  w  ww  .ja  v  a  2  s .c o  m
    if (StringFactory.isEmptyString(nameSuffix.getText()))
        nameSuffix.setVisible(false);

    // Address
    Address address = ProfessorProfile.getPostalAddress();
    // Address lines are always on their own line so we make sure they are enclosed by a block element like a DIV..
    final Label addressLine1 = new Label();
    addressLine1.setHTMLElement(HTMLElement.div).addClassName(UIUtil.PROP).addClassName(UIUtil.ADDRESS_LINE);
    final Label addressLine2 = new Label();
    addressLine2.setHTMLElement(HTMLElement.div).addClassName(UIUtil.PROP).addClassName(UIUtil.ADDRESS_LINE);
    if (address.getAddressLines().length > 0)
        addressLine1.setText(TextSources.create(address.getAddressLines()[0]));
    if (address.getAddressLines().length > 1)
        addressLine2.setText(TextSources.create(address.getAddressLines()[1]));
    final HTMLComponent city = new HTMLComponent();
    // The "prop" class name is part of the standard HTML structure. It is always a good idea to also
    /// add a specific class name like "city" in this example. Please be consistent when using class names.
    /// For example, if everyone else is using "city", please use "city" too. Don't come up with another class name
    /// that means something similar like "town" or "locality". Consistency has a big impact on
    /// the time required to style HTML as well as the ability to reuse CSS.
    city.setHTMLElement(HTMLElement.span).addClassName(UIUtil.PROP).addClassName(UIUtil.CITY);
    if (!StringFactory.isEmptyString(address.getCity())) {
        // Our microdata for the city shouldn't include the comma, so this is a bit more complicated than the other examples.
        city.setText(TextSources.create("<span item" + UIUtil.PROP + "=\"" + UIUtil.ADDRESS + "Locality\">"
                + address.getCity() + "</span><span class=\"delimiter\">,</span>"));
    } else
        city.setVisible(false);
    final Label state = new Label(TextSources.create(address.getState()));
    state.addClassName(UIUtil.PROP).addClassName(UIUtil.STATE);
    final Label postalCode = new Label(TextSources.create(address.getPostalCode()));
    postalCode.addClassName(UIUtil.PROP).addClassName(UIUtil.POSTAL_CODE);

    // Other Contact
    final Field phoneNumber = new Field(ProfessorProfile.getPhoneNumber(), false);
    final Field emailAddress = new Field(ProfessorProfile.getEmailAddress(), false);

    // Social Contact
    final URILink twitterLink = ProfessorProfile.getTwitterLink() != null
            ? new URILink(_ProfessorProfileDAO.toURI(ProfessorProfile.getTwitterLink(), null))
            : null;
    final URILink facebookLink = ProfessorProfile.getFacebookLink() != null
            ? new URILink(_ProfessorProfileDAO.toURI(ProfessorProfile.getFacebookLink(), null))
            : null;
    final URILink linkedInLink = ProfessorProfile.getLinkedInLink() != null
            ? new URILink(_ProfessorProfileDAO.toURI(ProfessorProfile.getLinkedInLink(), null))
            : null;

    // We are going to output HTML received from the outside, so we need to sanitize it first for security reasons.
    /// Sometimes you'll do this sanitation prior to persisting the data. It depends on whether or not you need to
    /// keep the original unsanitized HTML around.
    final HTMLComponent aboutMeProse = new HTMLComponent(
            UIUtil.scrubHtml(ProfessorProfile.getAboutMeProse(), Event.getRequest(), Event.getResponse()));
    Component aboutMeVideo = null;
    URL videoLink = ProfessorProfile.getAboutMeVideoLink();
    if (videoLink != null) {
        // There are several ways to link to media (Youtube video URL, Vimeo video URL, Flickr URL, internally hosted media file, etc).
        /// You can link to it.
        /// You can embed it. See http://oembed.com/ for a common protocol for doing this.
        /// If the link is to the media itself, you can create a player for it.
        /// Below is an example of creating a link to the video as well as a player.
        final URI videoLinkURI = _ProfessorProfileDAO.toURI(videoLink, null);
        URILink videoLinkComponent = new URILink(videoLinkURI, TextSources.create("My Video"));
        videoLinkComponent.setTarget("_blank");
        IMediaUtility util = MediaUtilityFactory.getUtility();
        try {
            // Check if we can parse the media and it has a stream we like.
            /// In our made up example, we're only accepting H.264 video. We don't care about the audio in this example.
            IMediaMetaData mmd;
            if (util.isEnabled() && videoLinkURI != null
                    && (mmd = util.getMetaData(videoLinkURI.toString())).getStreams().length > 0) {
                int width = 853, height = 480; // 480p default
                boolean hasVideo = false;
                for (IMediaStream stream : mmd.getStreams()) {
                    if (stream.getCodec().getType() == ICodec.Type.video
                            && "H264".equals(stream.getCodec().name())) {
                        hasVideo = true;
                        if (stream.getWidth() > 0) {
                            width = stream.getWidth();
                            height = stream.getHeight();
                        }
                        break;
                    }
                }
                if (hasVideo) {
                    Media component = new Media();
                    component.setMediaType(Media.MediaType.video);
                    component.addSource(new MediaSource(videoLinkURI));
                    component.setFallbackContent(videoLinkComponent);
                    component.setSize(new PixelMetric(width), new PixelMetric(height));
                    aboutMeVideo = component;
                }
            }
        } catch (IllegalArgumentException | RemoteException e) {
            _logger.error("Unable to get media information for " + videoLink, e);
        }
        if (aboutMeVideo == null) {
            // We could check for oEmbed support in case link was to youtube, vimeo, etc - http://oembed.com/
            // Since this is an example, we'll just output the link.
            aboutMeVideo = videoLinkComponent;
        }
    }
    ImageComponent picture = null;
    final FileEntity ProfessorProfilePicture = ProfessorProfile.getPicture();
    if (ProfessorProfilePicture != null) {
        picture = new ImageComponent(new Image(ProfessorProfilePicture));
        picture.setImageCaching(ProfessorProfilePicture.getLastModifiedTime()
                .before(new Date(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(60))));
    }

    // Professional Information

    // We are going to output HTML received from the outside, so we need to sanitize it first for security reasons.
    /// Sometimes you'll do this sanitation prior to persisting the data. It depends on whether or not you need to
    /// keep the original unsanitized HTML around.
    final HTMLComponent researchSpecialty = new HTMLComponent(
            UIUtil.scrubHtml(ProfessorProfile.getAboutMeProse(), Event.getRequest(), Event.getResponse()));

    final Field rank = ProfessorProfile.getProfessorRank() != null
            ? new Field(ObjectUtils.toString(ProfessorProfile.getProfessorRank()), false)
            : null;
    final DateFormat parser = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
    final Field dateJoined = ProfessorProfile.getDateJoined() != null
            ? new Field(parser.format(ProfessorProfile.getDateJoined()), false)
            : null;
    final Field onSabbatical = new Field(BooleanUtils.toStringYesNo(ProfessorProfile.isOnSabbatical()), false);

    // Now that we've initialized most of the content, we'll add all the components to this View
    /// using the standard HTML structure for a property viewer.
    add(of(HTMLElement.section, UIUtil.PROP + "-group " + UIUtil.NAME,
            new Label(TextSources.create("Name")).setHTMLElement(HTMLElement.h1),
            slug.setAttribute("item" + UIUtil.PROP, UIUtil.USER_ID).addClassName(UIUtil.PROP)
                    .addClassName(UIUtil.USER_ID),
            namePrefix.setAttribute("item" + UIUtil.PROP, "honorificPrefix").addClassName(UIUtil.PROP)
                    .addClassName(UIUtil.PREFIX),
            nameGiven.setAttribute("item" + UIUtil.PROP, "givenName").addClassName(UIUtil.PROP)
                    .addClassName(UIUtil.FIRST_NAME),
            nameFamily.setAttribute("item" + UIUtil.PROP, "familyName").addClassName(UIUtil.PROP)
                    .addClassName(UIUtil.LAST_NAME),
            nameSuffix.setAttribute("item" + UIUtil.PROP, "honorificSuffix").addClassName(UIUtil.PROP)
                    .addClassName(UIUtil.SUFFIX)));

    // Add wrapping DIV to group address lines if necessary.
    Component streetAddress = (!StringFactory.isEmptyString(addressLine1.getText())
            && !StringFactory.isEmptyString(addressLine2.getText())
                    ? of(HTMLElement.div, UIUtil.ADDRESS_LINES, addressLine1, addressLine2)
                    : (StringFactory.isEmptyString(addressLine1.getText()) ? addressLine2 : addressLine1)
                            .setHTMLElement(HTMLElement.div));
    streetAddress.setAttribute("item" + UIUtil.PROP, "streetAddress");
    boolean hasAddress = (!StringFactory.isEmptyString(addressLine1.getText())
            || !StringFactory.isEmptyString(addressLine2.getText())
            || !StringFactory.isEmptyString(city.getText()) || !StringFactory.isEmptyString(state.getText())
            || !StringFactory.isEmptyString(postalCode.getText()));
    boolean hasPhone = !StringFactory.isEmptyString(phoneNumber.getText());
    boolean hasEmail = !StringFactory.isEmptyString(emailAddress.getText());
    // We only want to output the enclosing HTML if we have content to display.
    if (hasAddress || hasPhone || hasEmail) {
        Container contactContainer = of(HTMLElement.section, "contact",
                new Label(TextSources.create("Contact Information")).setHTMLElement(HTMLElement.h1));
        add(contactContainer);
        if (hasAddress) {
            contactContainer.add(of(HTMLElement.div, UIUtil.PROP_GROUP + " " + UIUtil.ADDRESS,
                    // We are using an H2 here because are immediate ancestor is a DIV. If it was a SECTION,
                    /// then we would use an H1. See the ProfessorProfileViewer for a comparison.
                    new Label(TextSources.create("Address")).setHTMLElement(HTMLElement.h2), streetAddress,
                    of(HTMLElement.div, UIUtil.PLACE, city,
                            state.setAttribute("item" + UIUtil.PROP, UIUtil.ADDRESS + "Region"),
                            postalCode.setAttribute("item" + UIUtil.PROP, "postalCode")))
                                    .setAttribute("item" + UIUtil.PROP, UIUtil.ADDRESS)
                                    .setAttribute("itemscope", "")
                                    .setAttribute("itemtype", "http://schema.org/PostalAddress"));
        }
        if (hasPhone) {
            contactContainer.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.PHONE,
                    new Label(TextSources.create("Phone")).setHTMLElement(HTMLElement.h2),
                    phoneNumber.setAttribute("item" + UIUtil.PROP, "telephone")));
        }
        if (hasEmail) {
            contactContainer.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.EMAIL,
                    new Label(TextSources.create("Email")).setHTMLElement(HTMLElement.h2),
                    emailAddress.setAttribute("item" + UIUtil.PROP, UIUtil.EMAIL)));
        }
    }

    if (twitterLink != null || facebookLink != null || linkedInLink != null) {
        Container social = of(HTMLElement.section, UIUtil.SOCIAL,
                new Label(TextSources.create("Social Media Links")).setHTMLElement(HTMLElement.h1));
        add(social);
        if (twitterLink != null) {
            twitterLink.setTarget("_blank");
            twitterLink.setText(TextSources.create("Twitter Link"));
            social.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.TWITTER, TextSources.create("Twitter"),
                    twitterLink));
        }
        if (facebookLink != null) {
            facebookLink.setTarget("_blank");
            facebookLink.setText(TextSources.create("Facebook Link"));
            social.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.FACEBOOK, TextSources.create("Facebook"),
                    facebookLink));
        }
        if (linkedInLink != null) {
            linkedInLink.setTarget("_blank");
            linkedInLink.setText(TextSources.create("LinkedIn Link"));
            social.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.LINKEDIN, TextSources.create("LinkedIn"),
                    linkedInLink));
        }
    }

    final boolean hasAboutMeProse = StringFactory.isEmptyString(aboutMeProse.getText());
    if (!hasAboutMeProse || aboutMeVideo != null) {
        Container aboutMe = of(HTMLElement.section, UIUtil.ABOUT_ME,
                new Label(TextSources.create("About Me")).setHTMLElement(HTMLElement.h1));
        add(aboutMe);
        if (picture != null) {
            aboutMe.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.PICTURE, TextSources.create("Picture"),
                    picture));
        }
        if (hasAboutMeProse) {
            aboutMe.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.PROSE,
                    TextSources.create("Hobbies, Interests..."), aboutMeProse));
        }
        if (aboutMeVideo != null) {
            Label label = new Label(TextSources.create("Video")).setHTMLElement(HTMLElement.label);
            label.addClassName("vl");
            aboutMe.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.VIDEO, label, aboutMeVideo));
        }

    }

    final boolean hasResearchSpecialty = StringFactory.isEmptyString(researchSpecialty.getText());
    if (!hasResearchSpecialty || rank != null || dateJoined != null || onSabbatical != null) {
        Container professionalInformation = of(HTMLElement.section, UIUtil.PROFESSIONAL_INFORMATION,
                new Label(TextSources.create("Professional Information")).setHTMLElement(HTMLElement.h1));
        add(professionalInformation);
        if (rank != null) {
            professionalInformation.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.RANK,
                    TextSources.create("Professor Rank"), rank));
        }
        if (dateJoined != null) {
            Label label = new Label(TextSources.create("Date Joined")).setHTMLElement(HTMLElement.label);
            professionalInformation
                    .add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.DATE_JOINED, label, dateJoined));
        }
        if (onSabbatical != null) {
            Label label = new Label(TextSources.create("On Sabbatical")).setHTMLElement(HTMLElement.label);
            professionalInformation
                    .add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.ON_SABBATICAL, label, onSabbatical));
        }
        if (hasResearchSpecialty) {
            professionalInformation.add(of(HTMLElement.div, UIUtil.PROP + " " + UIUtil.PROSE,
                    TextSources.create("Research Specialty"), aboutMeProse));
        }
    }
}