Example usage for java.awt Desktop open

List of usage examples for java.awt Desktop open

Introduction

In this page you can find the example usage for java.awt Desktop open.

Prototype

public void open(File file) throws IOException 

Source Link

Document

Launches the associated application to open the file.

Usage

From source file:org.codelibs.fess.web.IndexAction.java

@Execute(validator = true, input = "index")
public String go() throws IOException {
    Map<String, Object> doc = null;
    try {//from w  w  w.ja  va2s  .c o  m
        doc = searchService.getDocument(fieldHelper.docIdField + ":" + indexForm.docId,
                queryHelper.getResponseFields(), new String[] { fieldHelper.clickCountField });
    } catch (final Exception e) {
        logger.warn("Failed to request: " + indexForm.docId, e);
    }
    if (doc == null) {
        errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                "errors.docid_not_found", indexForm.docId);
        return "error.jsp";
    }
    final Object urlObj = doc.get(fieldHelper.urlField);
    if (urlObj == null) {
        errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                "errors.document_not_found", indexForm.docId);
        return "error.jsp";
    }
    final String url = urlObj.toString();

    if (Constants.TRUE.equals(crawlerProperties.getProperty(Constants.SEARCH_LOG_PROPERTY, Constants.TRUE))) {
        final String userSessionId = userInfoHelper.getUserCode();
        if (userSessionId != null) {
            final SearchLogHelper searchLogHelper = ComponentUtil.getSearchLogHelper();
            final ClickLog clickLog = new ClickLog();
            clickLog.setUrl(url);
            LocalDateTime now = systemHelper.getCurrentTime();
            clickLog.setRequestedTime(now);
            clickLog.setQueryRequestedTime(LocalDateTime
                    .ofInstant(Instant.ofEpochMilli(Long.parseLong(indexForm.rt)), ZoneId.systemDefault()));
            clickLog.setUserSessionId(userSessionId);
            clickLog.setDocId(indexForm.docId);
            long clickCount = 0;
            final Object count = doc.get(fieldHelper.clickCountField);
            if (count instanceof Long) {
                clickCount = ((Long) count).longValue();
            }
            clickLog.setClickCount(clickCount);
            searchLogHelper.addClickLog(clickLog);
        }
    }

    String hash;
    if (StringUtil.isNotBlank(indexForm.hash)) {
        final String value = URLUtil.decode(indexForm.hash, Constants.UTF_8);
        final StringBuilder buf = new StringBuilder(value.length() + 100);
        for (final char c : value.toCharArray()) {
            if (CharUtil.isUrlChar(c) || c == ' ') {
                buf.append(c);
            } else {
                try {
                    buf.append(URLEncoder.encode(String.valueOf(c), Constants.UTF_8));
                } catch (final UnsupportedEncodingException e) {
                    // NOP
                }
            }
        }
        hash = buf.toString();
    } else {
        hash = StringUtil.EMPTY;
    }

    if (isFileSystemPath(url)) {
        if (Constants.TRUE
                .equals(crawlerProperties.getProperty(Constants.SEARCH_FILE_PROXY_PROPERTY, Constants.TRUE))) {
            final CrawlingConfigHelper crawlingConfigHelper = ComponentUtil.getCrawlingConfigHelper();
            try {
                crawlingConfigHelper.writeContent(doc);
                return null;
            } catch (final Exception e) {
                logger.error("Failed to load: " + doc, e);
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.not_load_from_server", url);
                return "error.jsp";
            }
        } else if (Constants.TRUE
                .equals(crawlerProperties.getProperty(Constants.SEARCH_DESKTOP_PROPERTY, Constants.FALSE))) {
            final String path = url.replaceFirst("file:/+", "//");
            final File file = new File(path);
            if (!file.exists()) {
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.not_found_on_file_system", url);
                return "error.jsp";
            }
            final Desktop desktop = Desktop.getDesktop();
            try {
                desktop.open(file);
            } catch (final Exception e) {
                errorMessage = MessageResourcesUtil.getMessage(RequestUtil.getRequest().getLocale(),
                        "errors.could_not_open_on_system", url);
                logger.warn("Could not open " + path, e);
                return "error.jsp";
            }

            ResponseUtil.getResponse().setStatus(HttpServletResponse.SC_NO_CONTENT);
            return null;
        } else {
            ResponseUtil.getResponse().sendRedirect(url + hash);
        }
    } else {
        ResponseUtil.getResponse().sendRedirect(url + hash);
    }
    return null;
}

From source file:org.domainmath.gui.MainFrame.java

private void openscript(File file) {
    try {//from  w  w w. j  a  va  2  s .  c om
        Desktop desktop = Desktop.getDesktop();
        desktop.open(file);
    } catch (Exception ioe) {
        JOptionPane.showMessageDialog(null, file.getAbsolutePath() + " doesn't exist");
    }
}

From source file:org.geopublishing.atlasStyler.swing.AtlasStylerSaveAsLayerToSLDAction.java

@Override
public void actionPerformed(ActionEvent e) {

    boolean backup = false;

    File startWithFile = new File(System.getProperty("user.home"), styledLayer.getTitle().toString() + ".sld");

    if (styledLayer.getSldFile() != null)
        startWithFile = styledLayer.getSldFile();

    File exportFile = AsSwingUtil.chooseFileSave(owner, startWithFile,
            ASUtil.R("StyledLayerSLD.ChooseFileLocationDialog.Title"),
            new FileExtensionFilter(ASUtil.FILTER_SLD));

    if (exportFile == null)
        return;/*from  w  ww  .java2s  .c  o m*/

    if (!(exportFile.getName().toLowerCase().endsWith(".sld")
            || exportFile.getName().toLowerCase().endsWith(".xml"))) {
        exportFile = new File(exportFile.getParentFile(), exportFile.getName() + ".sld");
    }

    styledLayer.setSldFile(exportFile);

    if (styledLayer.getSldFile().exists()) {
        try {
            FileUtils.copyFile(styledLayer.getSldFile(),
                    IOUtil.changeFileExt(styledLayer.getSldFile(), "sld.bak"));
            backup = true;
        } catch (IOException e1) {
            LOGGER.warn("could not create a backup of the existing .sld", e1);
            return;
        }
    }

    try {
        StylingUtil.saveStyleToSld(styledLayer.getStyle(), styledLayer.getSldFile());
        StylingUtil.saveStyleToSld(styledLayer.getStyle(),
                ASUtil.changeToOptimizedFilename(styledLayer.getSldFile()), true,
                getOptimizedTitle(styledLayer));

        Object[] options = { "OK", ASUtil.R("AtlasStylerSaveLayerToSLD.OpenFile"),
                ASUtil.R("AtlasStylerSaveLayerToSLD.OpenProductive") };
        int dialogValue = 0;

        if (backup) {
            dialogValue = JOptionPane.showOptionDialog(owner,
                    ASUtil.R("AtlasStylerGUI.saveToSLDFileSuccessAndBackedUp",
                            IOUtil.escapePath(styledLayer.getSldFile())),
                    "", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
        } else {
            dialogValue = JOptionPane.showOptionDialog(owner,
                    ASUtil.R("AtlasStylerGUI.saveToSLDFileSuccess",
                            IOUtil.escapePath(styledLayer.getSldFile())),
                    "", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
        }
        if (dialogValue == JOptionPane.NO_OPTION) {
            Desktop desktop = Desktop.getDesktop();
            desktop.open(styledLayer.getSldFile());
        }
        if (dialogValue == JOptionPane.CANCEL_OPTION) {
            Desktop desktop = Desktop.getDesktop();
            desktop.open(ASUtil.changeToOptimizedFilename(styledLayer.getSldFile()));
        }

        List<Exception> es = StylingUtil.validateSld(new FileInputStream(styledLayer.getSldFile()));
        if (es.size() > 0) {
            ExceptionDialog.show(owner,
                    new IllegalStateException(ASUtil.R("AtlasStylerExport.WarningSLDNotValid",
                            IOUtil.escapePath(styledLayer.getSldFile())), es.get(0)));
        }

    } catch (Exception e1) {
        LOGGER.error("saveStyleToSLD", e1);
        ExceptionDialog.show(owner, e1);
        return;
    }
}

From source file:org.geopublishing.atlasStyler.swing.AtlasStylerSaveLayerToSLDAction.java

@Override
public void actionPerformed(ActionEvent e) {

    boolean backup = false;

    if (styledLayer.getSldFile().exists()) {

        // if (StylingUtil.isStyleDifferent(styledLayer.getStyle(),
        // styledLayer.getSldFile())){
        // return;
        // }//  ww w. ja  v  a 2  s.  c  o  m

        try {
            FileUtils.copyFile(styledLayer.getSldFile(),
                    IOUtil.changeFileExt(styledLayer.getSldFile(), "sld.bak"));
            backup = true;
        } catch (IOException e1) {
            LOGGER.warn("could not create a backup of the existing .sld", e1);
            return;
        }
    }

    try {
        StylingUtil.saveStyleToSld(styledLayer.getStyle(), styledLayer.getSldFile());
        StylingUtil.saveStyleToSld(styledLayer.getStyle(),
                ASUtil.changeToOptimizedFilename(styledLayer.getSldFile()), true,
                "AtlasStyler " + ReleaseUtil.getVersionInfo(AtlasStyler.class) + ", Layer:"
                        + styledLayer.getTitle() + ", Export-Mode: PRODUCTION");

        Object[] options = { "OK", ASUtil.R("AtlasStylerSaveLayerToSLD.OpenFile"),
                ASUtil.R("AtlasStylerSaveLayerToSLD.OpenProductive") };
        int dialogValue = 0;
        if (backup) {
            dialogValue = JOptionPane.showOptionDialog(owner,
                    ASUtil.R("AtlasStylerGUI.saveToSLDFileSuccessAndBackedUp",
                            IOUtil.escapePath(styledLayer.getSldFile())),
                    "", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
        } else {
            dialogValue = JOptionPane.showOptionDialog(owner,
                    ASUtil.R("AtlasStylerGUI.saveToSLDFileSuccess",
                            IOUtil.escapePath(styledLayer.getSldFile())),
                    "", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
        }
        if (dialogValue == JOptionPane.NO_OPTION) {
            Desktop desktop = Desktop.getDesktop();
            desktop.open(styledLayer.getSldFile());
        }
        if (dialogValue == JOptionPane.CANCEL_OPTION) {
            Desktop desktop = Desktop.getDesktop();
            desktop.open(ASUtil.changeToOptimizedFilename(styledLayer.getSldFile()));
        }
        List<Exception> es = StylingUtil.validateSld(new FileInputStream(styledLayer.getSldFile()));
        if (es.size() > 0) {
            ExceptionDialog.show(owner,
                    new IllegalStateException(ASUtil.R("AtlasStylerExport.WarningSLDNotValid",
                            IOUtil.escapePath(styledLayer.getSldFile())), es.get(0)));
        }

    } catch (Exception e1) {
        LOGGER.error("saveStyleToSLD", e1);
        ExceptionDialog.show(owner, e1);
        return;
    }
}

From source file:org.interreg.docexplore.authoring.AuthoringMenu.java

public AuthoringMenu(final AuthoringToolFrame authoringTool) {
    this.tool = authoringTool;

    this.recent = new LinkedList<String>();
    readRecent();/*from  ww  w  .  ja  va  2s .c o m*/
    this.file = new JMenu(XMLResourceBundle.getBundledString("generalMenuFile"));
    add(file);

    newItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuNew")) {
        public void actionPerformed(ActionEvent arg0) {
            newFile();
        }
    });
    loadItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuLoad")) {
        public void actionPerformed(ActionEvent arg0) {
            load();
        }
    });
    saveItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuSave")) {
        public void actionPerformed(ActionEvent arg0) {
            save();
        }
    });
    saveAsItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuSaveAs")) {
        public void actionPerformed(ActionEvent arg0) {
            saveAs();
        }
    });
    exportItem = new JMenuItem(
            new AbstractAction(XMLResourceBundle.getBundledString("generalMenuExport") + "...") {
                public void actionPerformed(ActionEvent arg0) {
                    GuiUtils.blockUntilComplete(new ProgressRunnable() {
                        public void run() {
                            try {
                                authoringTool.readerExporter.doExport(authoringTool.editor.link);
                            } catch (Exception ex) {
                                ErrorHandler.defaultHandler.submit(ex);
                            }
                        }

                        public float getProgress() {
                            return (float) authoringTool.readerExporter.progress[0];
                        }
                    }, authoringTool.editor);
                }
            });
    webExportItem = new JMenuItem(
            new AbstractAction(XMLResourceBundle.getBundledString("generalMenuWebExport") + "...") {
                public void actionPerformed(ActionEvent arg0) {
                    GuiUtils.blockUntilComplete(new ProgressRunnable() {
                        public void run() {
                            try {
                                authoringTool.webExporter.doExport(authoringTool.editor.link);
                            } catch (Exception ex) {
                                ErrorHandler.defaultHandler.submit(ex);
                            }
                        }

                        public float getProgress() {
                            return (authoringTool.webExporter.copyComplete ? .5f : 0f)
                                    + (float) (.5 * authoringTool.webExporter.progress[0]);
                        }
                    }, authoringTool.editor);
                }
            });
    //      webExportItem = new JMenuItem(new AbstractAction("Web export") {public void actionPerformed(ActionEvent arg0)
    //      {
    //         GuiUtils.blockUntilComplete(new Runnable() {public void run()
    //         {
    //            try 
    //            {
    //               new WebStaticExporter().doExport(authoringTool.editor.link.getBook(authoringTool.editor.link.getLink().getAllBookIds().get(0)));
    //            }
    //            catch (Exception ex) {ErrorHandler.defaultHandler.submit(ex);}
    //         }}, authoringTool.editor);
    //      }});
    //      webExportItem.setEnabled(false);
    quitItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuQuit")) {
        public void actionPerformed(ActionEvent arg0) {
            authoringTool.quit();
        }
    });
    buildFileMenu();

    JMenu edit = new JMenu(XMLResourceBundle.getBundledString("generalMenuEdit"));
    this.undoItem = new JMenuItem();
    undoItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                authoringTool.historyManager.undo();
            } catch (Exception ex) {
                ErrorHandler.defaultHandler.submit(ex);
            }
        }
    });
    edit.add(undoItem);
    this.redoItem = new JMenuItem();
    redoItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                authoringTool.historyManager.redo();
            } catch (Exception ex) {
                ErrorHandler.defaultHandler.submit(ex);
            }
        }
    });
    edit.add(redoItem);
    JMenuItem viewHistory = new JMenuItem(XMLResourceBundle.getBundledString("generalMenuEditViewHistory"));
    viewHistory.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            authoringTool.historyDialog.setVisible(true);
        }
    });
    edit.add(viewHistory);

    edit.addSeparator();

    edit.add(new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("fixChars")) {
        public void actionPerformed(ActionEvent arg0) {
            Object res = JOptionPane.showInputDialog(tool, XMLResourceBundle.getBundledString("fixCharsMsg"),
                    XMLResourceBundle.getBundledString("fixChars"), JOptionPane.QUESTION_MESSAGE, null,
                    new Object[] { XMLResourceBundle.getBundledString("fixCharsWin"),
                            XMLResourceBundle.getBundledString("fixCharsMac") },
                    XMLResourceBundle.getBundledString("fixCharsWin"));
            if (res == null)
                return;
            try {
                convertPresentation(tool.defaultFile,
                        res.equals(XMLResourceBundle.getBundledString("fixCharsWin")) ? "ISO-8859-1"
                                : "x-MacRoman");
            } catch (Exception e) {
                ErrorHandler.defaultHandler.submit(e);
            }
            try {
                tool.editor.reset();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }));

    //TODO: remove!
    //      edit.add(new JMenuItem(new AbstractAction("hack!")
    //      {
    //         public void actionPerformed(ActionEvent e) {try
    //         {
    //            BookEditorView be = null;
    //            for (ExplorerView view : tool.editor.views)
    //               if (view instanceof BookEditorView)
    //                  be = (BookEditorView)view;
    //            Book book = be.curBook;
    //            int lastPage = book.getLastPageNumber();
    //            for (int pageNum = 1;pageNum <= lastPage;pageNum++)
    //            {
    //               Page page = book.getPage(pageNum);
    //               Set<Region> regions = page.getRegions();
    //               if (regions.size() > 2)
    //               {
    //                  Region highest = null;
    //                  int max = -1;
    //                  for (Region region : regions)
    //                     for (Point point : region.getOutline())
    //                        if (max < 0 || point.y < max)
    //                           {max = point.y; highest = region;}
    //                  Region middle = null;
    //                  max = -1;
    //                  for (Region region : regions)
    //                     if (region != highest)
    //                        for (Point point : region.getOutline())
    //                           if (max < 0 || point.y < max)
    //                              {max = point.y; middle = region;}
    //                  if (regions.size() > 3)
    //                  {
    //                     max = -1;
    //                     Region newMiddle = null;
    //                     for (Region region : regions)
    //                        if (region != highest && region != middle)
    //                           for (Point point : region.getOutline())
    //                              if (max < 0 || point.y < max)
    //                                 {max = point.y; newMiddle = region;}
    //                     middle = newMiddle;
    //                  }
    //                  MetaDataKey display = book.getLink().getKey("display", "");
    //                  for (Map.Entry<MetaDataKey, List<MetaData>> entry : highest.getMetaData().entrySet())
    //                     for (MetaData md : entry.getValue())
    //                        if (md.getType().equals(MetaData.textType))
    //                        {
    //                           String val = "<b>"+md.getString()+"</b>\n";
    //                           for (Map.Entry<MetaDataKey, List<MetaData>> entry2 : middle.getMetaData().entrySet())
    //                              for (MetaData md2 : entry2.getValue())
    //                                 if (md2.getType().equals(MetaData.textType) && TextElement.getStyle(md, tool.styleManager) == TextElement.getStyle(md2, tool.styleManager))
    //                                    val = val+"\n"+md2.getString();
    //                           md.setString(val);
    //                        }
    //                  boolean hasImage = false;
    //                  for (Map.Entry<MetaDataKey, List<MetaData>> entry2 : middle.getMetaData().entrySet())
    //                     for (MetaData md2 : entry2.getValue())
    //                        if (md2.getType().equals(MetaData.imageType))
    //                        {
    //                           MetaData imageMd = new MetaData(book.getLink(), display, md2.getType(), md2.getValue());
    //                           if (!hasImage)
    //                              BookImporter.insert(imageMd, highest, 0);
    //                           else BookImporter.insert(imageMd, highest, BookImporter.getHighestRank(highest)+1);
    //                           hasImage = true;
    //                        }
    //                  page.removeRegion(middle);
    //               }
    //            }
    //         }
    //         catch (Exception ex) {ex.printStackTrace();}System.out.println("done");}
    //      }));
    //      edit.add(new JMenuItem(new AbstractAction("hack!")
    //      {
    //         public void actionPerformed(ActionEvent e) {try
    //         {
    //            BookEditorView be = null;
    //            for (ExplorerView view : tool.editor.views)
    //               if (view instanceof BookEditorView)
    //                  be = (BookEditorView)view;
    //            Book book = be.curBook;
    //            int lastPage = book.getLastPageNumber();
    //            MetaDataKey display = book.getLink().getKey("display", "");
    //            for (int pageNum = 1;pageNum <= lastPage;pageNum++)
    //            {
    //               Page page = book.getPage(pageNum);
    //               Set<Region> regions = page.getRegions();
    //               for (Region region : regions)
    //               {
    //                  List<MetaData> mds = region.getMetaDataListForKey(display);
    //                     for (MetaData md : mds)
    //                        if (md.getType().equals(MetaData.textType))
    //                        {
    //                           String val = md.getString().trim();
    //                           if (!val.startsWith("<i>") || !val.endsWith("</i>"))
    //                              continue;
    //                           TextElement.getStyleMD(md).setString("4");
    //                           md.setString(val.substring(3, val.length()-4));
    //                           System.out.println(md.getString());
    //                        }
    //               }
    //            }
    //         }
    //         catch (Exception ex) {ex.printStackTrace();}System.out.println("done");}
    //      }));
    //      edit.add(new JMenuItem(new AbstractAction("hack!")
    //      {
    //         public void actionPerformed(ActionEvent e) {try
    //         {
    //            BookEditorView be = null;
    //            for (ExplorerView view : tool.editor.views)
    //               if (view instanceof BookEditorView)
    //                  be = (BookEditorView)view;
    //            Book book = be.curBook;
    //            int lastPage = book.getLastPageNumber();
    //            MetaDataKey display = book.getLink().getKey("display", "");
    //            for (int pageNum = 1;pageNum <= lastPage;pageNum++)
    //            {
    //               Page page = book.getPage(pageNum);
    //               Set<Region> regions = page.getRegions();
    //               for (Region region : regions)
    //               {
    //                  int max = BookImporter.getHighestRank(region);
    //                  for (int i=0;i<max;i++)
    //                  {
    //                     MetaData md1 = BookImporter.getAtRank(region, i);
    //                     if (md1 == null || !md1.getType().equals(MetaData.textType))
    //                        continue;
    //                     MetaData style1 = TextElement.getStyleMD(md1);
    //                     if (!style1.getString().equals("0"))
    //                        continue;
    //                     MetaData md2 = BookImporter.getAtRank(region, i+1);
    //                     if (md2 == null || !md2.getType().equals(MetaData.textType))
    //                        continue;
    //                     MetaData style2 = TextElement.getStyleMD(md2);
    //                     if (!style2.getString().equals("1"))
    //                        continue;
    //                     BookImporter.setRank(md1, i+1);
    //                     BookImporter.setRank(md2, i);
    //                     i++;
    //                  }
    //               }
    //            }
    //         }
    //         catch (Exception ex) {ex.printStackTrace();}System.out.println("done");}
    //      }));
    //      edit.add(new JMenuItem(new AbstractAction("hack!")
    //      {
    //         public void actionPerformed(ActionEvent e) {try
    //         {
    //            BookEditorView be = null;
    //            for (ExplorerView view : tool.editor.views)
    //               if (view instanceof BookEditorView)
    //                  be = (BookEditorView)view;
    //            Book book = be.curBook;
    //            MetaDataKey mini = book.getLink().getOrCreateKey("mini", "");
    //            MetaDataKey dim = book.getLink().getOrCreateKey("dimension", "");
    //            int lastPage = book.getLastPageNumber();
    //            for (int pageNum = 1;pageNum <= lastPage;pageNum++)
    //            {
    //               Page page = book.getPage(pageNum);
    //               List<MetaData> mds = page.getMetaDataListForKey(mini);
    //               if (mds != null)
    //                  for (MetaData md : mds)
    //                     page.removeMetaData(md);
    //               mds = page.getMetaDataListForKey(dim);
    //               if (mds != null)
    //                  for (MetaData md : mds)
    //                     page.removeMetaData(md);
    //               DocExploreDataLink.getImageDimension(page, true);
    //               DocExploreDataLink.getImageMini(page, false);
    //            }
    //         }
    //         catch (Exception ex) {ex.printStackTrace();}System.out.println("done");}
    //      }));

    add(edit);

    JMenu view = new JMenu(XMLResourceBundle.getBundledString("generalMenuView"));
    add(view);

    JMenuItem styles = new JMenuItem(XMLResourceBundle.getBundledString("styleEdit") + "...",
            ImageUtils.getIcon("pencil-24x24.png"));
    styles.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            authoringTool.styleManager.styleDialog.setVisible(true);
        }
    });
    view.add(styles);

    helpToggle = new JCheckBoxMenuItem(
            new AbstractAction(XMLResourceBundle.getBundledString("viewHelpToggle")) {
                public void actionPerformed(ActionEvent arg0) {
                    authoringTool.displayHelp = helpToggle.isSelected();
                    authoringTool.repaint();
                }
            });
    helpToggle.setSelected(tool.startup.showHelp);
    view.add(helpToggle);

    JMenu helpMenu = new JMenu(XMLResourceBundle.getString("management-lrb", "generalMenuHelp"));
    if (Desktop.isDesktopSupported()) {
        final Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN)) {
            helpMenu.add(new AbstractAction(
                    XMLResourceBundle.getString("management-lrb", "generalMenuHelpContents")) {
                public void actionPerformed(ActionEvent e) {
                    try {
                        File doc = new File(DocExploreTool.getExecutableDir(), "MMT documentation.htm");
                        desktop.open(doc);
                    } catch (Exception ex) {
                        ErrorHandler.defaultHandler.submit(ex, true);
                    }
                }
            });
            helpMenu.add(new AbstractAction(
                    XMLResourceBundle.getString("management-lrb", "generalMenuHelpWebsite")) {
                public void actionPerformed(ActionEvent e) {
                    try {
                        File link = new File(DocExploreTool.getExecutableDir(), "website.url");
                        desktop.open(link);
                    } catch (Exception ex) {
                        ErrorHandler.defaultHandler.submit(ex, true);
                    }
                }
            });
        }
    }
    helpMenu.add(new AbstractAction(XMLResourceBundle.getString("management-lrb", "generalMenuHelpAbout")) {
        public void actionPerformed(ActionEvent e) {
            final JDialog splash = new JDialog(tool, true);
            splash.setLayout(new BorderLayout());
            SplashScreen screen = new SplashScreen("logoAT.png");
            splash.add(screen, BorderLayout.NORTH);
            screen.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseReleased(MouseEvent e) {
                    splash.setVisible(false);
                }
            });
            splash.setUndecorated(true);
            screen.setText(
                    "<html>DocExplore 2009-2014" + "<br/>Released under the CeCILL v2.1 license" + "</html>");
            splash.pack();
            splash.setAlwaysOnTop(true);
            GuiUtils.centerOnScreen(splash);
            splash.setVisible(true);
        }
    });
    add(helpMenu);

    historyChanged(authoringTool.historyManager);
    authoringTool.historyManager.addHistoryListener(this);
}

From source file:org.jdal.system.SystemUtils.java

public static void open(byte[] data, String extension) {
    if (data != null && Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        File file;/*w  w w .j a  v a2  s. c o  m*/
        try {
            file = File.createTempFile("tmp", "." + extension);
            file.deleteOnExit();
            FileUtils.writeByteArrayToFile(file, data);
            desktop.open(file);
        } catch (IOException e) {
            String message = "No ha sido posible abrir el fichero";
            JOptionPane.showMessageDialog(null, message, "Error de datos", JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:org.jdal.util.processor.JasperReportFileProcessor.java

public static void main(String[] args) {
    try {/*from  w  w w  .ja  v a2 s. com*/
        JasperReport report = JasperCompileManager
                .compileReport("/home/jose/Projects/telmma/Documents/Code/testParameters.jrxml");

        System.out.println("Query en el jasper: " + report.getQuery().getText());
        for (JRParameter param : report.getParameters()) {
            if (!param.isSystemDefined())
                System.out.println(param.getName());
        }
        Map<String, Object> parameters = new HashMap<String, Object>();
        // TEST
        parameters.put("NombreCiudad", "Huelva");

        JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, new JREmptyDataSource());
        byte[] reportBin = JasperExportManager.exportReportToPdf(jasperPrint);

        if (Desktop.isDesktopSupported()) {
            Desktop desktop = Desktop.getDesktop();
            File outputFile;
            try {
                outputFile = File.createTempFile("simple_report", ".pdf");
                //outputFile.deleteOnExit();
                // Create the file with the raw data provided by the file processor 
                FileUtils.writeByteArrayToFile(outputFile, reportBin);

                System.out.println("OutputFile -> " + outputFile.getName() + " " + outputFile.getTotalSpace());

                desktop.open(outputFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.pmedv.blackboard.dialogs.DatasheetDialog.java

@Override
protected void initializeComponents() {

    sheetProvider = AppContext.getContext().getBean(DataSheetProvider.class);

    sheetPanel = new DatasheetPanel();
    busyPanel = new JBusyComponent<DatasheetPanel>(sheetPanel);

    setSize(new Dimension(900, 650));
    getContentPanel().add(busyPanel);//  w ww.java 2s . c  om

    SwingWorker<ArrayList<DatasheetBean>, Void> w = new SwingWorker<ArrayList<DatasheetBean>, Void>() {

        @Override
        protected ArrayList<DatasheetBean> doInBackground() throws Exception {
            busyPanel.setBusy(true);
            sheetProvider.loadSheets();
            return sheetProvider.getDatasheetList().getDatasheets();
        }

        @Override
        protected void done() {
            log.info("Done loading sheets.");
            try {
                model = new DataSheetTableModel(get());
                sheetPanel.getDatasheetTable().setModel(model);
            } catch (Exception e) {
                e.printStackTrace();
            }
            busyPanel.setBusy(false);
            sheetPanel.transferFocus();
        }
    };

    getOkButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
        }
    });
    getCancelButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            result = OPTION_CANCEL;
            setVisible(false);
        }
    });

    sheetPanel.getDatasheetTable().addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {

                int modelIndex = sheetPanel.getDatasheetTable()
                        .convertRowIndexToModel(sheetPanel.getDatasheetTable().getSelectedRow());
                DatasheetBean sheet = model.getDatasheetBeans().get(modelIndex);

                if (Desktop.isDesktopSupported()) {
                    Desktop desktop = Desktop.getDesktop();
                    try {
                        desktop.open(new File(sheet.getLocation()));
                    } catch (Exception e1) {
                        ErrorUtils.showErrorDialog(e1);
                    }
                }
            }
        }
    });

    sheetPanel.getAddSheetButton().setAction(AppContext.getContext().getBean(AddDatasheetCommand.class));
    sheetPanel.getRemoveSheetButton().setAction(AppContext.getContext().getBean(RemoveDatasheetCommand.class));
    sheetPanel.getImportFolderButton()
            .setAction(AppContext.getContext().getBean(ImportDatasheetFolderCommand.class));

    // create filter for sheets
    DataSheetFilter filter = new DataSheetFilter(sheetPanel.getDatasheetTable());
    BindingGroup filterGroup = new BindingGroup();

    // bind filter JTextBox's text attribute to part tables filterString attribute
    filterGroup.addBinding(Bindings.createAutoBinding(READ, sheetPanel.getFilterPanel().getFilterTextField(),
            BeanProperty.create("text"), filter, BeanProperty.create("filterString")));
    filterGroup.bind();
    w.execute();

}

From source file:output.ExcelM3Upgrad.java

public boolean save() {
    dialStatus();/*from  w ww .j  a v  a  2s  .c  o m*/
    try {
        if (workbook instanceof HSSFWorkbook) {
            if (!filepath.endsWith("xls")) {
                filepath += ".xls";
            }
        } else if (workbook instanceof XSSFWorkbook) {
            if (!filepath.endsWith("xlsx")) {
                filepath += ".xlsx";
            }
        }
        busyDial.setText("Sauvegarde du fichier " + filepath);
        FileOutputStream out = new FileOutputStream(new File(filepath));
        workbook.write(out);
        out.close();
        if (endFile) {
            Object[] options = { i18n.Language.getLabel(140), i18n.Language.getLabel(23),
                    i18n.Language.getLabel(130) };
            int n = JOptionPane.showOptionDialog(busyDial, i18n.Language.getLabel(213), "Excel",
                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

            if (n == 0) {
                busyDial.setText(i18n.Language.getLabel(214) + "...");
                Desktop dt = Desktop.getDesktop();
                dt.open(new File(filepath));
            } else if (n == 1) {
                try {
                    busyDial.setText(i18n.Language.getLabel(215) + "...");
                    GmailTLS mail = new GmailTLS();
                    Message msg = mail.writeMail("j.chaut@3kles-consulting.com", "M3Upgrader",
                            "Rsultat de M3Upgrader");
                    msg = mail.addAttachment(msg, new File(filepath));
                    busyDial.setText(i18n.Language.getLabel(216) + "...");
                    mail.sendMail(msg);
                } catch (MessagingException ex) {
                    Ressource.logger.error(ex.getLocalizedMessage(), ex);
                }
            }
            in.close();
        }
    } catch (IOException e) {
        error(e.getMessage());
        return false;
    }
    return true;
}

From source file:plugin.notes.gui.JIcon.java

/**
 *  Launches a file into the appropriate program for the OS we are running on
 *///from   w w  w.  ja  v  a2s.c  o m
private void launchFile() {
    if (PCGFile.isPCGenCharacterOrPartyFile(launch)) {
        plugin.loadRecognizedFileType(launch);
    } else {
        boolean opened = false;

        // Use desktop if available
        if (Desktop.isDesktopSupported()) {
            Desktop d = Desktop.getDesktop();
            if (d.isSupported(Desktop.Action.OPEN)) {
                try {
                    d.open(launch);
                    opened = true;
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        if (!opened) {
            if (SystemUtils.IS_OS_UNIX) {
                String openCmd = SystemUtils.IS_OS_MAC_OSX ? "/usr/bin/open" : "xdg-open";
                String filePath = launch.getAbsolutePath();
                String[] args = { openCmd, filePath };
                Logging.debugPrintLocalised("Runtime.getRuntime().exec: [{0}] [{1}]", args[0], args[1]);

                try {
                    Runtime.getRuntime().exec(args);
                } catch (IOException e) {
                    Logging.errorPrint(e.getMessage(), e);
                }
            } else if (SystemUtils.IS_OS_WINDOWS) {
                try {
                    String start = ("rundll32 url.dll,FileProtocolHandler file://" + launch.getAbsoluteFile());
                    Runtime.getRuntime().exec(start);
                } catch (Exception e) {
                    Logging.errorPrint(e.getMessage(), e);
                }
            }
        }
    }
}