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.photon.phresco.framework.rest.api.UtilService.java

/**
 * Open folder.//w  ww  . jav a2 s .  c o  m
 *
 * @param appDirName the app dir name
 * @param type the type
 * @return the response
 */
@GET
@Path("/openFolder")
@Produces(MediaType.APPLICATION_JSON)
public Response openFolder(@QueryParam(REST_QUERY_APPDIR_NAME) String appDirName,
        @QueryParam(REST_QUERY_TYPE) String type, @QueryParam(REST_QUERY_MODULE_NAME) String moduleName) {
    ResponseInfo<String> responseData = new ResponseInfo<String>();
    try {
        if (Desktop.isDesktopSupported()) {
            //            if (StringUtils.isNotEmpty(moduleName)) {
            //               appDirName = appDirName + File.separator + moduleName;
            //            }

            String rootModulePath = "";
            String subModuleName = "";

            if (StringUtils.isNotEmpty(moduleName)) {
                rootModulePath = Utility.getProjectHome() + appDirName;
                subModuleName = moduleName;
            } else {
                rootModulePath = Utility.getProjectHome() + appDirName;
            }

            File file = new File(getPath(rootModulePath, subModuleName, type));
            if (file.exists()) {
                Desktop.getDesktop().open(file);
            } else {
                StringBuilder sbOpenPath = new StringBuilder(rootModulePath);
                Desktop.getDesktop().open(new File(sbOpenPath.toString()));
            }
        }
        ResponseInfo<String> finalOutput = responseDataEvaluation(responseData, null, null,
                RESPONSE_STATUS_SUCCESS, PHR3C00001);
        return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                .build();
    } catch (Exception e) {
        ResponseInfo<ProjectInfo> finalOutput = responseDataEvaluation(responseData, e, null,
                RESPONSE_STATUS_ERROR, PHR3C10001);
        return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                .build();
    }
}

From source file:org.sleeksnap.gui.options.UploaderPanel.java

private void browseButtonActionPerformed(final java.awt.event.ActionEvent evt) {
    try {//from   w  w w  . ja v  a  2 s  .  c  o  m
        Desktop.getDesktop().open(new File(Util.getWorkingDirectory(), "uploaders"));
    } catch (final IOException e1) {
        e1.printStackTrace();
    }
}

From source file:com.unicornlabs.kabouter.reporting.PowerReport.java

public static void GeneratePowerReport(Date startDate, Date endDate) {
    try {//from w  w w  .j a  va 2  s . c o m
        Historian theHistorian = (Historian) BusinessObjectManager.getBusinessObject(Historian.class.getName());
        ArrayList<String> powerLogDeviceIds = theHistorian.getPowerLogDeviceIds();

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        File outputFile = new File("PowerReport.pdf");
        outputFile.createNewFile();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
        document.open();

        document.add(new Paragraph("Power Report for " + startDate.toString() + " to " + endDate.toString()));

        document.newPage();

        DecimalFormat df = new DecimalFormat("#.###");

        for (String deviceId : powerLogDeviceIds) {
            ArrayList<Powerlog> powerlogs = theHistorian.getPowerlogs(deviceId, startDate, endDate);
            double total = 0;
            double max = 0;
            Date maxTime = startDate;
            double average = 0;
            XYSeries series = new XYSeries(deviceId);
            XYDataset dataset = new XYSeriesCollection(series);

            for (Powerlog log : powerlogs) {
                total += log.getPower();
                if (log.getPower() > max) {
                    max = log.getPower();
                    maxTime = log.getId().getLogtime();
                }
                series.add(log.getId().getLogtime().getTime(), log.getPower());
            }

            average = total / powerlogs.size();

            document.add(new Paragraph("\nDevice: " + deviceId));
            document.add(new Paragraph("Average Power Usage: " + df.format(average)));
            document.add(new Paragraph("Maximum Power Usage: " + df.format(max) + " at " + maxTime.toString()));
            document.add(new Paragraph("Total Power Usage: " + df.format(total)));
            //Create a custom date axis to display dates on the X axis
            DateAxis dateAxis = new DateAxis("Date");
            //Make the labels vertical
            dateAxis.setVerticalTickLabels(true);

            //Create the power axis
            NumberAxis powerAxis = new NumberAxis("Power");

            //Set both axes to auto range for their values
            powerAxis.setAutoRange(true);
            dateAxis.setAutoRange(true);

            //Create the tooltip generator
            StandardXYToolTipGenerator ttg = new StandardXYToolTipGenerator("{0}: {2}",
                    new SimpleDateFormat("yyyy/MM/dd HH:mm"), NumberFormat.getInstance());

            //Set the renderer
            StandardXYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES, ttg,
                    null);

            //Create the plot
            XYPlot plot = new XYPlot(dataset, dateAxis, powerAxis, renderer);

            //Create the chart
            JFreeChart myChart = new JFreeChart(deviceId, JFreeChart.DEFAULT_TITLE_FONT, plot, true);

            PdfContentByte pcb = writer.getDirectContent();
            PdfTemplate tp = pcb.createTemplate(480, 360);
            Graphics2D g2d = tp.createGraphics(480, 360, new DefaultFontMapper());
            Rectangle2D r2d = new Rectangle2D.Double(0, 0, 480, 360);
            myChart.draw(g2d, r2d);
            g2d.dispose();
            pcb.addTemplate(tp, 0, 0);

            document.newPage();
        }

        document.close();

        JOptionPane.showMessageDialog(null, "Report Generated.");

        Desktop.getDesktop().open(outputFile);
    } catch (FileNotFoundException fnfe) {
        JOptionPane.showMessageDialog(null,
                "Unable To Open File For Writing, Make Sure It Is Not Currently Open");
    } catch (IOException ex) {
        Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:smsapp.utils.Utils.java

public static void openFile(String folderName, String fileName) {
    File f = new File(folderName + "" + File.separator + "" + fileName);
    Desktop dt = Desktop.getDesktop();
    try {//from   www .j a va2s .  c o  m
        dt.open(f);
    } catch (IOException ex) {
        Logger.getLogger(ControllerWhatsapp.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    }
    System.out.println("Done.");
}

From source file:net.mybox.mybox.ClientGUI.java

private void launchFileBrowser() {

    Desktop desktop = null;//from   ww w .  j  a  v a 2 s . co  m

    if (Desktop.isDesktopSupported()) {
        File dir = new File(client.GetClientDir());
        desktop = Desktop.getDesktop();

        try {
            desktop.open(dir);
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
        }
    }

}

From source file:osu.beatmapdownloader.JFrame.java

public void goWebsite() {
       String text = "NewKey";
       L_madeBy.setText("<html>Made by player: <a href=\"\">" + text + "</a></html>");
       L_madeBy.setCursor(new Cursor(Cursor.HAND_CURSOR));
       L_madeBy.addMouseListener(new MouseAdapter() {
           @Override/*from  w  w w. j ava 2s.  co m*/
           public void mouseClicked(MouseEvent e) {
               try {
                   Desktop.getDesktop().browse(new URI("https://osu.ppy.sh/u/637668"));
               } catch (URISyntaxException | IOException ex) {
               }
           }
       });
   }

From source file:com.devbury.mkremote.server.QuickLaunchServiceImpl.java

public boolean isSupported() {
    boolean supported = false;
    supported = Desktop.isDesktopSupported();
    logger.debug("isDesktopSupported {}", supported);
    if (supported) {
        supported = Desktop.getDesktop().isSupported(Action.OPEN);
        logger.debug("isOpenSupported {}", supported);
    }//from  w  w  w . j a  v  a 2s  .  c o m
    return supported;
}

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

@Test
@Ignore/*from   w  w  w. j  a  v  a  2s  .com*/
public void register() throws Exception {
    TentClient tentClient = new TentClient("https://javaapiclient.tent.is");
    tentClient.discover();
    Profile profile = tentClient.getProfile();
    //    
    //    System.out.println(profile.getCore().getEntity());
    //    System.out.println(profile.getBasic().getName());
    //    System.out.println(profile.getBasic().getAvatarUrl());
    //    
    //    List<Post> posts = tentClient.getPosts();
    //    
    //    printPosts(posts);
    //    
    //    List<Following> followings = tentClient.getFollowings();
    //    
    //    for (Following following : followings) {
    //      TentClient followingTentClient = new TentClient();
    //      followingTentClient.discover(following.getEntity());
    //      Profile followingProfile = followingTentClient.getProfile();
    //      Following followingDetail = tentClient.getFollowing(following);
    //      
    //      System.out.println(following.getEntity() + " / id=" + following.getId());
    //      System.out.println(followingProfile.getBasic().getName());
    //      printPosts(followingTentClient.getPosts());
    //    }

    HashMap<String, String> scopes = new HashMap<String, String>();
    scopes.put("write_profile", "Not really used, just testing");

    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("id=" + registrationResponse.getId());
    System.out.println("mac_key_id=" + registrationResponse.getMacKeyId());
    System.out.println("mac_key=" + registrationResponse.getMacKey());
    System.out.println("mac_algorithm=" + registrationResponse.getMacAlgorithm());

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(registrationResponse.getId(),
            registrationRequest.getRedirectUris()[0]);
    authorizationRequest.setScope("write_profile");
    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));
}

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);// www .  ja v a  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:org.openlegacy.tools.maven.SessionRunner.java

private void openBrowser(int port) {
    Object browserPath = getProperty(BROWSER_PATH, null);
    if (browserPath != null) {
        try {/*from  w w  w.j a  v  a 2s  . c o  m*/
            Desktop.getDesktop().browse(new URL("http://localhost:" + port).toURI());
        } catch (Exception e) {
            getLog().warn("Unable to open browser at:" + browserPath);
        }
    }
}