Example usage for java.awt Desktop getDesktop

List of usage examples for java.awt Desktop getDesktop

Introduction

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

Prototype

public static synchronized Desktop getDesktop() 

Source Link

Document

Returns the Desktop instance of the current desktop context.

Usage

From source file:com.diversityarrays.kdxplore.field.FieldViewDialog.java

public FieldViewDialog(Window owner, String title, SampleGroupChoice sgcSamples, Trial trial,
        SampleGroupChoice sgcNewMedia, KDSmartDatabase db) throws IOException {
    super(owner, title, ModalityType.MODELESS);

    advanceRetreatControls = Box.createHorizontalBox();
    advanceRetreatControls.add(new JButton(retreatAction));
    advanceRetreatControls.add(new JButton(advanceAction));

    autoAdvanceControls = Box.createHorizontalBox();
    autoAdvanceControls.add(new JButton(autoAdvanceAction));

    autoAdvanceOption.addActionListener(new ActionListener() {
        @Override//from  w  w  w .  j a  v  a 2  s .com
        public void actionPerformed(ActionEvent e) {
            updateMovementControls();
        }
    });

    this.database = db;
    this.sampleGroupChoiceForSamples = sgcSamples;
    this.sampleGroupChoiceForNewMedia = sgcNewMedia;

    NumberSpinner fontSpinner = new NumberSpinner(new SpinnerNumberModel(), "0.00");

    this.fieldViewPanel = FieldViewPanel.create(database, trial, SeparatorVisibilityOption.VISIBLE, null,
            Box.createHorizontalGlue(), new JButton(showInfoAction), Box.createHorizontalGlue(),
            new JLabel("Font Size:"), fontSpinner, Box.createHorizontalGlue(), advanceRetreatControls,
            autoAdvanceOption, autoAdvanceControls);

    initialiseAction(advanceAction, "ic_object_advance_black.png", "Auto-Advance");

    this.xyProvider = fieldViewPanel.getXYprovider();
    this.traitMap = fieldViewPanel.getTraitMap();

    fieldLayoutTable = fieldViewPanel.getFieldLayoutTable();

    JScrollPane scrollPane = fieldViewPanel.getFieldTableScrollPane();
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    fieldLayoutTable.setTransferHandler(flth);
    fieldLayoutTable.setDropMode(DropMode.ON);

    fieldLayoutTable.addMouseListener(new MouseAdapter() {
        JPopupMenu popupMenu;

        @Override
        public void mouseClicked(MouseEvent e) {
            if (!SwingUtilities.isRightMouseButton(e) || 1 != e.getClickCount()) {
                return;
            }
            Point pt = e.getPoint();
            int row = fieldLayoutTable.rowAtPoint(pt);
            if (row >= 0) {
                int col = fieldLayoutTable.columnAtPoint(pt);
                if (col >= 0) {
                    Plot plot = fieldViewPanel.getPlotAt(col, row);
                    if (plot != null) {
                        if (popupMenu == null) {
                            popupMenu = new JPopupMenu("View Attachments");
                        }
                        popupMenu.removeAll();

                        Set<File> set = plot.getMediaFiles();
                        if (Check.isEmpty(set)) {
                            popupMenu.add(new JMenuItem("No Attachments available"));
                        } else {
                            for (File file : set) {
                                Action a = new AbstractAction(file.getName()) {
                                    @Override
                                    public void actionPerformed(ActionEvent e) {
                                        try {
                                            Desktop.getDesktop().browse(file.toURI());
                                        } catch (IOException e1) {
                                            MsgBox.warn(FieldViewDialog.this, e1, file.getName());
                                        }
                                    }
                                };
                                popupMenu.add(new JMenuItem(a));
                            }
                        }
                        popupMenu.show(fieldLayoutTable, pt.x, pt.y);
                    }
                }
            }
        }

    });
    Font font = fieldLayoutTable.getFont();
    float fontSize = font.getSize2D();

    fontSizeModel = new SpinnerNumberModel(fontSize, fontSize, 50.0, 1.0);
    fontSpinner.setModel(fontSizeModel);
    fontSizeModel.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            float fsize = fontSizeModel.getNumber().floatValue();
            System.out.println("Using fontSize=" + fsize);
            Font font = fieldLayoutTable.getFont().deriveFont(fsize);
            fieldLayoutTable.setFont(font);
            FontMetrics fm = fieldLayoutTable.getFontMetrics(font);
            int lineHeight = fm.getMaxAscent() + fm.getMaxDescent();
            fieldLayoutTable.setRowHeight(4 * lineHeight);

            //                GuiUtil.initialiseTableColumnWidths(fieldLayoutTable, false);

            fieldLayoutTable.repaint();
        }
    });

    fieldLayoutTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    fieldLayoutTable.setResizable(true, true);
    fieldLayoutTable.getTableColumnResizer().setResizeAllColumns(true);

    advanceAction.setEnabled(false);
    fieldLayoutTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                handlePlotSelection();
            }
        }
    });
    TableColumnModel columnModel = fieldLayoutTable.getColumnModel();
    columnModel.addColumnModelListener(new TableColumnModelListener() {
        @Override
        public void columnSelectionChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                handlePlotSelection();
            }
        }

        @Override
        public void columnRemoved(TableColumnModelEvent e) {
        }

        @Override
        public void columnMoved(TableColumnModelEvent e) {
        }

        @Override
        public void columnMarginChanged(ChangeEvent e) {
        }

        @Override
        public void columnAdded(TableColumnModelEvent e) {
        }
    });

    PropertyChangeListener listener = new PropertyChangeListener() {
        // Use a timer and redisplay other columns when delay is GT 100 ms

        Timer timer = new Timer(true);
        TimerTask timerTask;
        long lastActive;
        boolean busy = false;
        private int eventColumnWidth;
        private TableColumn eventColumn;

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (busy) {
                return;
            }

            if (evt.getSource() instanceof TableColumn && "width".equals(evt.getPropertyName())) {

                eventColumn = (TableColumn) evt.getSource();
                eventColumnWidth = eventColumn.getWidth();

                lastActive = System.currentTimeMillis();
                if (timerTask == null) {
                    timerTask = new TimerTask() {
                        @Override
                        public void run() {
                            if (System.currentTimeMillis() - lastActive > 200) {
                                timerTask.cancel();
                                timerTask = null;

                                busy = true;
                                try {
                                    for (Enumeration<TableColumn> en = columnModel.getColumns(); en
                                            .hasMoreElements();) {
                                        TableColumn tc = en.nextElement();
                                        if (tc != eventColumn) {
                                            tc.setWidth(eventColumnWidth);
                                        }
                                    }
                                } finally {
                                    busy = false;
                                }
                            }
                        }
                    };
                    timer.scheduleAtFixedRate(timerTask, 100, 150);
                }
            }
        }
    };
    for (Enumeration<TableColumn> en = columnModel.getColumns(); en.hasMoreElements();) {
        TableColumn tc = en.nextElement();
        tc.addPropertyChangeListener(listener);
    }

    Map<Integer, Plot> plotById = new HashMap<>();
    for (Plot plot : fieldViewPanel.getFieldLayout()) {
        plotById.put(plot.getPlotId(), plot);
    }

    TrialItemVisitor<Sample> sampleVisitor = new TrialItemVisitor<Sample>() {
        @Override
        public void setExpectedItemCount(int count) {
        }

        @Override
        public boolean consumeItem(Sample sample) throws IOException {

            Plot plot = plotById.get(sample.getPlotId());
            if (plot == null) {
                throw new IOException("Missing plot for plotId=" + sample.getPlotId() + " sampleIdent="
                        + Util.createUniqueSampleKey(sample));
            }
            plot.addSample(sample);

            SampleCounts counts = countsByTraitId.get(sample.getTraitId());
            if (counts == null) {
                counts = new SampleCounts();
                countsByTraitId.put(sample.getTraitId(), counts);
            }
            if (sample.hasBeenScored()) {
                ++counts.scored;
            } else {
                ++counts.unscored;
            }
            return true;
        }
    };
    database.visitSamplesForTrial(sampleGroupChoiceForSamples, trial.getTrialId(),
            SampleOrder.ALL_BY_PLOT_ID_THEN_TRAIT_ID_THEN_INSTANCE_NUMBER_ORDER_THEN_SPECIMEN_NUMBER,
            sampleVisitor);

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    this.trial = trial;

    KDClientUtils.initAction(ImageId.SETTINGS_24, showInfoAction, "Trial Summary");

    Action clear = new AbstractAction("Clear") {
        @Override
        public void actionPerformed(ActionEvent e) {
            infoTextArea.setText("");
        }
    };
    JPanel bottom = new JPanel(new BorderLayout());
    bottom.add(GuiUtil.createLabelSeparator("Plot Details", new JButton(clear)), BorderLayout.NORTH);
    bottom.add(new JScrollPane(infoTextArea), BorderLayout.CENTER);
    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, fieldViewPanel,
            new JScrollPane(infoTextArea));
    splitPane.setResizeWeight(0.0);
    splitPane.setOneTouchExpandable(true);

    setContentPane(splitPane);

    updateMovementControls();
    pack();
}

From source file:se.trixon.toolbox.photokml.PhotoKmlTopComponent.java

private void viewButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewButtonActionPerformed
    new Thread(() -> {
        try {//from w ww . ja v a2s  . c  om
            Desktop.getDesktop().open(mDestination);
        } catch (IOException | IllegalArgumentException ex) {
            Message.error(Dict.FILE_NOT_FOUND_TITLE.getString(),
                    String.format(Dict.FILE_NOT_FOUND_MESSAGE.getString(), mDestination.getAbsolutePath()));
        } catch (Exception ex) {
            Message.error(Dict.ERROR.getString(), ex.getLocalizedMessage());
        }
    }).start();
}

From source file:org.wandora.application.tools.server.HTTPServerTool.java

@Override
public void execute(Wandora wandora, Context context) throws TopicMapException {

    if ((mode & CONFIGURE) != 0) {

        WandoraModulesServer server = wandora.getHTTPServer();

        String u = null; //s.getLoginUser();
        String p = null; //s.getLoginPassword();
        if (u == null)
            u = "";
        if (p == null)
            p = "";

        String[] logLevels = { "trace", "debug", "info", "warn", "error", "fatal", "none" };

        GenericOptionsDialog god = new GenericOptionsDialog(wandora, "Wandora HTTP server settings",
                "Wandora HTTP server settings", true,
                new String[][] {
                        new String[] { "Auto start", "boolean", "" + server.isAutoStart(),
                                "Start server automatically when you start Wandora" },
                        new String[] { "Port", "string", "" + server.getPort(),
                                "Port the server is listening to" },
                        new String[] { "Local only", "boolean", "" + server.isLocalOnly(),
                                "Allow only local connections" },
                        new String[] { "Use SSL", "boolean", "" + server.isUseSSL(), "Should server use SSL" },
                        new String[] { "Keystore location", "string", "" + server.getKeystoreFile(),
                                "Where SSL keystore file locates? Keystore is used only if you have selected to use SLL." },
                        new String[] { "Keystore password", "string", "" + server.getKeystorePassword(),
                                "Keystore's password. Keystore is used only if you have selected to use SLL." },
                        //                new String[]{"User name","string",u,"User name. Leave empty for anonymous login"},
                        //                new String[]{"Password","password",p,"Password for the user if user name field is used"},
                        new String[] { "Server path", "string", server.getServerPath(),
                                "Path where Wandora web apps are deployed" },
                        //                new String[]{"Static content path","string",s.getStaticPath(),"Path where static files are located"},
                        //                new String[]{"Template path","string",s.getTemplatePath(),"Path where Velocity templates are located"},
                        //                new String[]{"Template","string",s.getTemplateFile(),"Template file used to create a topic page"},
                        new String[] { "Log level", "combo:" + StringUtils.join(logLevels, ";"),
                                logLevels[server.getLogLevel()],
                                "Lowest level of log messages that are printed" }, },
                wandora);/*w w w  .java 2s.com*/
        god.setSize(800, 400);
        if (wandora != null)
            wandora.centerWindow(god);
        god.setVisible(true);

        if (god.wasCancelled())
            return;

        boolean running = server.isRunning();
        if (running)
            server.stopServer();

        Map<String, String> values = god.getValues();

        server.setAutoStart(Boolean.parseBoolean(values.get("Auto start")));
        server.setPort(Integer.parseInt(values.get("Port")));
        server.setLocalOnly(Boolean.parseBoolean(values.get("Local only")));
        server.setUseSSL(Boolean.parseBoolean(values.get("Use SSL")));
        server.setKeystoreFile(values.get("Keystore location"));
        server.setKeystorePassword(values.get("Keystore password"));
        //            server.setLogin(values.get("User name"),values.get("Password"));
        //            server.setStaticPath(values.get("Static content path"));
        //            server.setTemplatePath(values.get("Template path"));
        //            server.setTemplateFile(values.get("Template"));
        server.setServerPath(values.get("Server path"));
        server.setLogLevel(ArrayUtils.indexOf(logLevels, values.get("Log level")));

        server.writeOptions(wandora.getOptions());

        server.initModuleManager();
        server.readBundleDirectories();

        if (running)
            server.start();

        wandora.menuManager.refreshServerMenu();
    }

    if ((mode & START) != 0) {
        wandora.startHTTPServer();
    }

    else if ((mode & STOP) != 0) {
        wandora.stopHTTPServer();
    }

    if ((mode & UPDATE_MENU) != 0) {
        wandora.menuManager.refreshServerMenu();
    }

    if ((mode & OPEN_PAGE) != 0) {
        try {
            if (!wandora.getHTTPServer().isRunning()) {
                int a = WandoraOptionPane.showConfirmDialog(wandora,
                        "HTTP server is not running at the moment. Would you like to start the server first?",
                        "Start HTTP server?", WandoraOptionPane.OK_CANCEL_OPTION);
                if (a == WandoraOptionPane.OK_OPTION) {
                    wandora.startHTTPServer();
                    wandora.menuManager.refreshServerMenu();
                } else if (a == WandoraOptionPane.CANCEL_OPTION) {
                    return;
                }
            }
            WandoraModulesServer s = wandora.getHTTPServer();

            String uri = (s.isUseSSL() ? "https" : "http") + "://127.0.0.1:" + s.getPort() + "/topic";
            if (forceUrl != null)
                uri = forceUrl;
            else if (webApp != null) {
                uri = webApp.getAppStartPage();
                if (uri == null) {
                    WandoraOptionPane.showMessageDialog(wandora,
                            "Can't launch selected webapp. Webapp says it's URI is null.");
                    return;
                }
            }

            try {
                Desktop desktop = Desktop.getDesktop();
                desktop.browse(new URI(uri));
            } catch (Exception e) {
                log(e);
            }
        } catch (Exception e) {
            wandora.handleError(e);
        }
    }

    if ((mode & OPEN_PAGE_IN_BROWSER_TOPIC_PANEL) != 0) {
        try {
            if (!wandora.getHTTPServer().isRunning()) {
                int a = WandoraOptionPane.showConfirmDialog(wandora,
                        "HTTP server is not running at the moment. Would you like to start the server first?",
                        "Start HTTP server?", WandoraOptionPane.OK_CANCEL_OPTION);
                if (a == WandoraOptionPane.OK_OPTION) {
                    wandora.startHTTPServer();
                    wandora.menuManager.refreshServerMenu();
                }
            }
            WandoraModulesServer s = wandora.getHTTPServer();
            String uri = (s.isUseSSL() ? "https" : "http") + "://127.0.0.1:" + s.getPort() + "/topic";
            if (forceUrl != null)
                uri = forceUrl;
            else if (webApp != null) {
                uri = webApp.getAppStartPage();
                if (uri == null) {
                    WandoraOptionPane.showMessageDialog(wandora,
                            "Can't launch selected webapp. Webapp says it's URI is null.");
                    return;
                }
            }

            try {
                if (param2 != null) {
                    if (param2 instanceof WebViewPanel) {
                        WebViewPanel browserTopicPanel = (WebViewPanel) param2;
                        browserTopicPanel.browse(uri);
                    }
                }
            } catch (Exception e) {
                log(e);
            }
        } catch (Exception e) {
            wandora.handleError(e);
        }
    }
}

From source file:com.moandjiezana.tent.client.TentClientTest.java

@Test
@Ignore/*from   w ww .j a  v  a 2s .c  o  m*/
public void auth() throws Exception {
    TentClient tentClient = new TentClient("https://javaapiclient.tent.is/");
    tentClient.discover();
    tentClient.getProfile();

    HashMap<String, String> scopes = new HashMap<String, String>();
    scopes.put("write_posts", "Mostly test posts.");
    scopes.put("read_followings", "To see if it works");

    RegistrationRequest registrationRequest = new RegistrationRequest("TentClient for Java",
            "Running dev tests", "http://www.moandjiezana.com/tent-client-java",
            new String[] { "http://www.moandjiezana.com/tent-test/index.php" }, scopes);
    RegistrationResponse registrationResponse = tentClient.register(registrationRequest);

    System.out.println("mac_key=" + registrationResponse.getMacKey());
    System.out.println("mac_key_id=" + registrationResponse.getMacKeyId());

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(registrationResponse.getId(),
            "http://www.moandjiezana.com/tent-test/index.php");
    authorizationRequest.setScope(Joiner.on(',').join(registrationRequest.getScopes().keySet()));
    authorizationRequest.setState("myState");
    authorizationRequest.setTentPostTypes(Post.Types.status("v0.1.0"));
    authorizationRequest.setTentProfileInfoTypes(Profile.Core.URI, Profile.Basic.URI);

    String authorizationUrl = tentClient.getAsync().buildAuthorizationUrl(authorizationRequest);
    System.out.println("Auth URL: " + authorizationUrl);
    Desktop.getDesktop().browse(new URI(authorizationUrl));

    System.out.println("Code?");
    BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
    String code = bufferRead.readLine();

    AccessToken accessToken = tentClient.getAsync().getAccessToken(code).get();

    System.out.println("Access Token");
    System.out.println("access_token=" + accessToken.getAccessToken());
    System.out.println("mac_key=" + accessToken.getMacKey());
}

From source file:com.stacksync.desktop.util.FileUtil.java

public static void showWindow(final File file) throws IOException {

    if (openLinuxExplorer("/usr/bin/nautilus", file)) {
        logger.debug("Opened file with /usr/bin/nautilus");
    } else if (openLinuxExplorer("/usr/share/nautilus", file)) {
        logger.debug("Opened file with /usr/share/nautilus");
    } else if (openLinuxExplorer("/usr/bin/xdg-open", file)) {
        logger.debug("Opened file with /usr/bin/xdg-open");
    } else if (openLinuxExplorer("/usr/share/xdg-open", file)) {
        logger.debug("Opened file with /usr/share/xdg-open");
    } else {/*from  w  w w  .  jav a 2 s  . c om*/
        logger.debug("Opened with the default Desktop.");
        Desktop.getDesktop().open(file);
    }

}

From source file:org.mhisoft.common.util.FileUtils.java

/**
 * Launch the URL using the default browser.
 *
 * @param url//ww  w .  j av  a  2s. c  o m
 */
public static void launchURL(String url) {

    try {
        if (Desktop.isDesktopSupported()) {
            // Windows
            Desktop.getDesktop().browse(new URI(url));
        } else {
            // Ubuntu
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("/usr/bin/firefox -new-window " + url);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

From source file:de.interactive_instruments.ShapeChange.UI.DefaultDialog.java

public void actionPerformed(ActionEvent e) {
    if (startButton == e.getSource()) {
        mdl = mdlField.getText().trim();
        startButton.setEnabled(false);/* w w w  .ja  va  2  s  . c  o  m*/
        exitButton.setEnabled(false);
        try {
            options.setParameter("inputFile", mdl);
            if (mdl.toLowerCase().endsWith(".xmi") || mdl.toLowerCase().endsWith(".xml"))
                options.setParameter("inputModelType", "XMI10");
            else if (mdl.toLowerCase().endsWith(".eap"))
                options.setParameter("inputModelType", "EA7");
            else if (mdl.toLowerCase().endsWith(".mdb"))
                options.setParameter("inputModelType", "GSIP");

            options.setParameter("outputDirectory", outField.getText());
            options.setParameter("logFile", outField.getText() + "/log.xml");
            options.setParameter("appSchemaName", asField.getText());
            options.setParameter("reportLevel", reportGroup.getSelection().getActionCommand());
            options.setParameter(Options.TargetXmlSchemaClass, "defaultEncodingRule",
                    ruleGroup.getSelection().getActionCommand());
            if (docCB.isSelected())
                options.setParameter(Options.TargetXmlSchemaClass, "includeDocumentation", "true");
            else
                options.setParameter(Options.TargetXmlSchemaClass, "includeDocumentation", "false");
            if (!visCB.isSelected())
                options.setParameter("publicOnly", "true");
            else
                options.setParameter("publicOnly", "false");

            converter.convert();
        } catch (ShapeChangeAbortException ex) {
            Toolkit.getDefaultToolkit().beep();
        }
        logfile = new File(options.parameter("logFile").replace(".xml", ".html"));
        if (logfile != null && logfile.canRead())
            logButton.setEnabled(true);
        else {
            logfile = new File(options.parameter("logFile"));
            if (logfile != null && logfile.canRead())
                logButton.setEnabled(true);
        }
        exitButton.setEnabled(true);
    } else if (e.getSource() == logButton) {
        try {
            if (Desktop.isDesktopSupported())
                Desktop.getDesktop().open(logfile);
            else if (SystemUtils.IS_OS_WINDOWS)
                Runtime.getRuntime().exec("cmd /c start " + logfile.getPath());
            else
                Runtime.getRuntime().exec("open " + logfile.getPath());
        } catch (IOException e1) {
            e1.printStackTrace();
            System.exit(1);
        }
    } else if (e.getSource() == exitButton) {
        System.exit(0);
    } else if (e.getSource() == mdlButton) {
        int returnVal = fc.showOpenDialog(DefaultDialog.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            mdlField.setText(file.getAbsolutePath());
        }
    } else if (e.getSource() == cfgButton) {
        int returnVal = fc.showOpenDialog(DefaultDialog.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            cfgField.setText(file.getAbsolutePath());
        }
    } else if (e.getSource() == outButton) {
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showOpenDialog(DefaultDialog.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            outField.setText(file.getAbsolutePath());
        }
    }
}

From source file:de.ailis.xadrian.utils.SwingUtils.java

/**
 * Opens a URL in the browser. It first tries to do this with the Desktop
 * API. If this fails then it tries to use the FreeDesktop-API.
 * //from  w w  w .  j  ava 2  s  .co  m
 * @param uri
 *            The URI to open.
 */
public static void openBrowser(final URI uri) {
    try {
        try {
            Desktop.getDesktop().browse(uri);
        } catch (final UnsupportedOperationException e) {
            Runtime.getRuntime().exec("xdg-open '" + uri + "'");
        }
    } catch (final IOException e) {
        LOG.error("Unable to external browser: " + e, e);
    }
}

From source file:com.stacksync.desktop.util.FileUtil.java

public static void openFile(final File file) {
    try {// w  ww.  j  av a2 s.  com
        switch (env.getOperatingSystem()) {
        case Linux:
            showWindow(file);
            break;
        case Mac:
        case Windows:
        default:
            Desktop.getDesktop().open(file);
        }
    } catch (Exception ex) {
        /* Fressen */ }
}

From source file:es.ua.alex952.main.MainBatch.java

/**
 * Main method of the class that runs the specified options in the
 * command line arguments parsed in constructor method
 *///from  w  w w.  j a v a  2 s .co  m
@Override
public void run() {

    if (this.op == Operation.QUIT) {
        logger.debug("Showing help and exiting");
        return;
    }

    switch (this.op) {
    case CREATE: {

        logger.info(
                "Creating job with {} configuration file, {} parameters file, {} lo file, {} tr file, {} gold file",
                new Object[] { this.configFile, this.parametersFile, this.pathLO, this.pathTR, this.pathGold });

        logger.info("Entering job creating stage");

        try {
            this.instance = new JobsCF(this.parametersFile, this.configFile);
            this.instance.setPathLO(pathLO);
            this.instance.setPathTR(pathTR);
            this.instance.setPathGold(pathGold);

            this.instance.create();
            this.id = this.instance.getParameter("id");
            logger.info("Job {} created", this.id);
            this.instance.populate();
            logger.info("Job {} populated", this.id);
            this.instance.order();
            logger.info("Job {} ordered", this.id);
        } catch (ParameterNeeded ex) {
            this.logger.error("A parameter couldn't be found", ex);
        } catch (KeyNotConfigured ex) {
            this.logger.error("The CrowdFlower API key was not correctly configured");
        } catch (IOException ex) {
            this.logger.error("I/O exception ocurred", ex);
        } catch (Exception e) {
            this.logger.error("An error ocurred", e);
        }

        if (!this.daemon) {
            break;
        }
    }
    case DAEMON: {
        try {
            if (this.instance == null) {
                try {
                    this.instance = new JobsCF(this.configFile);
                } catch (KeyNotConfigured ex) {
                    this.logger.error("The CrowdFlower API key was not correctly configured");
                    return;
                } catch (Exception e) {
                    this.logger.error("An error ocurred", e);
                    return;
                }

                this.instance.addParameter("id", this.id);
            }

            boolean finished = false;

            if (this.op == Operation.CREATE) {
                this.logger.info("Waiting first {} seconds", this.frecuency);
                Thread.sleep(this.frecuency);
            }

            do {
                try {
                    if ((finished = this.instance.isFinished()) == true) {
                        this.logger.info("The job {} has already finished. Preparing results", this.id);
                        String graph = this.instance.processResults();

                        if (graph == null) {
                            System.err.println("Results could not been retrieved due some unexpected error");
                        } else {
                            FileOutputStream fos = new FileOutputStream(new File("graph.html"));
                            fos.write(graph.getBytes());
                            fos.close();

                            this.logger.info(
                                    "The html file with the results has been written to the file graph.html");
                            this.logger
                                    .info("Opening default HTML handler (usually a browser) to show results");
                            Desktop.getDesktop().open(new File("graph.html"));

                            finished = true;
                        }
                    } else {
                        this.logger.info("The job {} hasn't finished yet. Waiting {} sec. to check again",
                                this.frecuency);

                        Thread.sleep(this.frecuency);
                    }
                } catch (Exception e) {
                    this.logger.error(
                            "Some error ocurred either checking on the state of the job or gathering its results",
                            e);
                    return;
                }
            } while (!finished);

            break;
        } catch (InterruptedException ex) {
            java.util.logging.Logger.getLogger(MainBatch.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    }
}