Example usage for javax.swing JFileChooser setDialogTitle

List of usage examples for javax.swing JFileChooser setDialogTitle

Introduction

In this page you can find the example usage for javax.swing JFileChooser setDialogTitle.

Prototype

@BeanProperty(preferred = true, description = "The title of the JFileChooser dialog window.")
public void setDialogTitle(String dialogTitle) 

Source Link

Document

Sets the string that goes in the JFileChooser window's title bar.

Usage

From source file:AudioFilter.java

public static void main(String[] args) {
    AudioFilter audioFilter = new AudioFilter();

    JFileChooser jfc = new JFileChooser();

    jfc.setDialogTitle("Open File");
    jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    jfc.setCurrentDirectory(new File("."));
    jfc.setFileFilter(audioFilter);//from www.  j a  v  a 2  s  .co m
    int result = jfc.showOpenDialog(null);

    if (result == JFileChooser.CANCEL_OPTION) {
        System.out.println("cancel");
    } else if (result == JFileChooser.APPROVE_OPTION) {
        File fFile = jfc.getSelectedFile();
        String filestr = fFile.getAbsolutePath();

        System.out.println(filestr);
    }
}

From source file:Main.java

public static void main(String s[]) {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("choosertitle");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
        System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
    } else {/*w w w  .ja  va2s  . c om*/
        System.out.println("No Selection ");
    }
}

From source file:Main.java

License:asdf

public static void main(String[] argv) throws Exception {
    JFileChooser chooser = new JFileChooser();
    File f = new File(new File("filename.txt").getCanonicalPath());

    chooser.setDialogTitle("asdf");
    chooser.showDialog(new JFrame(""), null);
    File curFile = chooser.getSelectedFile();
}

From source file:Main.java

public static void main(String[] argv) {
    final JFileChooser chooser = new JFileChooser();

    File curDir = chooser.getCurrentDirectory();
    chooser.setDialogTitle("" + curDir.getAbsolutePath());

    chooser.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
                File curDir = chooser.getCurrentDirectory();

                chooser.setDialogTitle("" + curDir.getAbsolutePath());
            }//w w w.  j av a 2s . c  o m
        }
    });
}

From source file:net.redstonelamp.gui.RedstoneLampGUI.java

public static void main(String[] args) {
    JFrame frame = new JFrame("RedstoneLamp");
    frame.setLayout(new GridLayout(2, 1));
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    JLabel label = new JLabel("RedstoneLamp");
    label.setHorizontalAlignment(SwingConstants.CENTER);
    frame.add(label);/* w ww.  j  a v  a 2  s  .c om*/
    JPanel lowPanel = new JPanel();
    JPanel left = new JPanel();
    left.setLayout(new BoxLayout(left, BoxLayout.Y_AXIS));
    lowPanel.add(left);
    JPanel right = new JPanel();
    right.setLayout(new BoxLayout(right, BoxLayout.Y_AXIS));
    lowPanel.add(right);
    JButton openButton = new JButton("Open server at...");
    openButton.addActionListener(e -> {
        JFileChooser chooser = new JFileChooser(new File("."));
        chooser.setDialogTitle("Select RedstoneLamp server home");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
        int action = chooser.showOpenDialog(frame);
        if (action == JFileChooser.APPROVE_OPTION) {
            File selected = chooser.getSelectedFile();
            File jar = new File("RedstoneLamp.jar");
            if (!jar.isFile()) {
                int result = JOptionPane.showConfirmDialog(frame, "Could not find RedstoneLamp installation. "
                        + "Would you like to install RedstoneLamp there?");
                if (result == JOptionPane.YES_OPTION) {
                    installCallback(frame, selected);
                }
                return;
            }
            frame.dispose();
            addHistory(selected);
            currentRoot = new ServerActivity(selected);
        }
    });
    right.add(openButton);
    JButton installButton = new JButton("Install server at...");
    installButton.addActionListener(e -> {
        JFileChooser chooser = new JFileChooser(".");
        chooser.setDialogTitle("Select directory to install server in");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
        int action = chooser.showSaveDialog(frame);
        if (action == JFileChooser.APPROVE_OPTION) {
            File selected = chooser.getSelectedFile();
            File jar = new File("RedstoneLamp.jar");
            if (jar.isFile()) {
                int result = JOptionPane.showConfirmDialog(frame, "A RedstoneLamp jar installation is present. "
                        + "Are you sure you want to reinstall RedstoneLamp there?");
                if (result == JOptionPane.NO_OPTION) {
                    frame.dispose();
                    addHistory(selected);
                    currentRoot = new ServerActivity(selected);
                    return;
                }
            }
            installCallback(frame, selected);
        }
    });
    frame.add(lowPanel);
    frame.pack();
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setLocation(dimension.width / 2 - frame.getSize().width / 2,
            dimension.height / 2 - frame.getSize().height / 2);
    frame.setVisible(true);
}

From source file:jsonbrowse.JsonBrowse.java

/**
 * @param args the command line arguments
 *//*from w ww. j av a  2 s .  c  om*/
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
            | javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(JsonBrowse.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    }
    //</editor-fold>

    String fileName;

    // Get name of JSON file
    Path jsonFilePath;
    if (args.length < 1) {

        JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));
        fc.setDialogTitle("Select JSON file...");
        fc.setFileFilter(new FileNameExtensionFilter("JSON files (*.json/*.txt)", "json", "txt"));
        if ((fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)) {
            jsonFilePath = fc.getSelectedFile().toPath().toAbsolutePath();
        } else {
            return;
        }
    } else {
        Path path = Paths.get(args[0]);
        if (!path.isAbsolute())
            jsonFilePath = Paths.get(System.getProperty("user.dir")).resolve(path);
        else
            jsonFilePath = path;
    }

    // Run app

    try {
        JsonBrowse app = new JsonBrowse(jsonFilePath);
        app.setVisible(true);
    } catch (FileNotFoundException ex) {
        System.out.println("Input file '" + jsonFilePath + "' not found.");
        System.exit(1);
    } catch (IOException ex) {
        System.out.println("Error reading from file '" + jsonFilePath + "'.");
        System.exit(1);
    } catch (InterruptedException ex) {
        Logger.getLogger(JsonBrowse.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:kenh.xscript.ScriptUtils.java

public static void main(String[] args) {
    String file = null;//from   ww  w. ja  v  a 2 s . c o  m

    for (String arg : args) {
        if (StringUtils.startsWithAny(StringUtils.lowerCase(arg), "-f:", "-file:")) {
            file = StringUtils.substringAfter(arg, ":");
        }
    }

    Element e = null;
    try {
        if (StringUtils.isBlank(file)) {

            JFileChooser chooser = new JFileChooser();
            chooser.setDialogTitle("xScript");
            chooser.setAcceptAllFileFilterUsed(false);
            chooser.setFileFilter(new FileFilter() {
                public boolean accept(File f) {
                    if (f.isDirectory()) {
                        return true;
                    } else if (f.isFile() && StringUtils.endsWithIgnoreCase(f.getName(), ".xml")) {
                        return true;
                    }
                    return false;
                }

                public String getDescription() {
                    return "xScript (*.xml)";
                }
            });

            int returnVal = chooser.showOpenDialog(null);
            chooser.requestFocus();

            if (returnVal == JFileChooser.CANCEL_OPTION)
                return;

            File f = chooser.getSelectedFile();

            e = getInstance(f, null);
        } else {
            e = getInstance(new File(file), null);
        }
        //debug(e);
        //System.out.println("----------------------");

        int result = e.invoke();
        if (result == Element.EXCEPTION) {
            Object obj = e.getEnvironment().getVariable(Constant.VARIABLE_EXCEPTION);
            if (obj != null && obj instanceof Throwable) {
                System.err.println();
                ((Throwable) obj).printStackTrace();

            } else {
                System.err.println();
                System.err.println("Unknown EXCEPTION is thrown.");
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();

        System.err.println();

        if (ex instanceof UnsupportedScriptException) {
            UnsupportedScriptException ex_ = (UnsupportedScriptException) ex;
            if (ex_.getElement() != null) {
                debug(ex_.getElement(), System.err);
            }
        }
    } finally {
        if (e != null)
            e.getEnvironment().callback();
    }
}

From source file:net.sf.vntconverter.VntConverter.java

/**
 * Fhrt den VntConverter mit den angegebnen Optionen aus.
 *///w w w  . j av a2s .c  o m
public static void main(String[] args) {
    try {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            // Wenn nicht, dann nicht ...
        }
        JFileChooser fileChooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Text files (txt) and memo files (vnt)",
                "txt", "vnt");
        fileChooser.setCurrentDirectory(new java.io.File("."));
        fileChooser.setDialogTitle("Choose files to convert ...");
        fileChooser.setFileFilter(filter);
        fileChooser.setMultiSelectionEnabled(true);
        if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            JFileChooser directoryChooser = new JFileChooser();
            directoryChooser.setCurrentDirectory(new java.io.File("."));
            directoryChooser.setDialogTitle("Choose target directory ...");
            directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            directoryChooser.setAcceptAllFileFilterUsed(false);
            if (directoryChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                VntConverter converter = new VntConverter();
                String targetDirectoy = directoryChooser.getSelectedFile().getAbsolutePath();
                System.out.println(targetDirectoy);
                for (File file : fileChooser.getSelectedFiles()) {
                    if (file.getName().endsWith(".txt")) {
                        converter.encode(file,
                                new File(targetDirectoy + "\\" + file.getName().replace(".txt", ".vnt")));
                    } else if (file.getName().endsWith(".vnt")) {
                        converter.decode(file,
                                new File(targetDirectoy + "\\" + file.getName().replace(".vnt", ".txt")));
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Exception caught", e);
    }
}

From source file:com.bright.json.JSonRequestor.java

public static void main(String[] args) {
    String fileBasename = null;/*from www. j  a v  a 2  s  .  co m*/
    String[] zipArgs = null;
    JFileChooser chooser = new JFileChooser("/Users/panos/STR_GRID");
    try {

        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Select the input directory");

        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);

        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
            System.out.println("getSelectedFile() : " + chooser.getSelectedFile());

            // String fileBasename =
            // chooser.getSelectedFile().toString().substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator)+1,chooser.getSelectedFile().toString().lastIndexOf("."));
            fileBasename = chooser.getSelectedFile().toString()
                    .substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator) + 1);
            System.out.println("Base name: " + fileBasename);

            zipArgs = new String[] { chooser.getSelectedFile().toString(),
                    chooser.getCurrentDirectory().toString() + File.separator + fileBasename + ".zip" };
            com.bright.utils.ZipFile.main(zipArgs);

        } else {
            System.out.println("No Selection ");

        }
    } catch (Exception e) {

        System.out.println(e.toString());

    }

    JTextField uiHost = new JTextField("ucs-head.brightcomputing.com");
    // TextPrompt puiHost = new
    // TextPrompt("hadoop.brightcomputing.com",uiHost);
    JTextField uiUser = new JTextField("nexus");
    // TextPrompt puiUser = new TextPrompt("nexus", uiUser);
    JTextField uiPass = new JPasswordField("system");
    // TextPrompt puiPass = new TextPrompt("", uiPass);
    JTextField uiWdir = new JTextField("/home/nexus/pp1234");
    // TextPrompt puiWdir = new TextPrompt("/home/nexus/nexus_workdir",
    // uiWdir);
    JTextField uiOut = new JTextField("foo");
    // TextPrompt puiOut = new TextPrompt("foobar123", uiOut);

    JPanel myPanel = new JPanel(new GridLayout(5, 1));
    myPanel.add(new JLabel("Bright HeadNode hostname:"));
    myPanel.add(uiHost);
    // myPanel.add(Box.createHorizontalStrut(1)); // a spacer
    myPanel.add(new JLabel("Username:"));
    myPanel.add(uiUser);
    myPanel.add(new JLabel("Password:"));
    myPanel.add(uiPass);
    myPanel.add(new JLabel("Working Directory:"));
    myPanel.add(uiWdir);
    // myPanel.add(Box.createHorizontalStrut(1)); // a spacer
    myPanel.add(new JLabel("Output Study Name ( -s ):"));
    myPanel.add(uiOut);

    int result = JOptionPane.showConfirmDialog(null, myPanel, "Please fill in all the fields.",
            JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.OK_OPTION) {
        System.out.println("Input received.");

    }

    String rfile = uiWdir.getText();
    String rhost = uiHost.getText();
    String ruser = uiUser.getText();
    String rpass = uiPass.getText();
    String nexusOut = uiOut.getText();

    String[] myarg = new String[] { zipArgs[1], ruser + "@" + rhost + ":" + rfile, nexusOut, fileBasename };
    com.bright.utils.ScpTo.main(myarg);

    String cmURL = "https://" + rhost + ":8081/json";
    List<Cookie> cookies = doLogin(ruser, rpass, cmURL);
    chkVersion(cmURL, cookies);

    jobSubmit myjob = new jobSubmit();
    jobSubmit.jobObject myjobObj = new jobSubmit.jobObject();

    myjob.setService("cmjob");
    myjob.setCall("submitJob");

    myjobObj.setQueue("defq");
    myjobObj.setJobname("myNexusJob");
    myjobObj.setAccount(ruser);
    myjobObj.setRundirectory(rfile);
    myjobObj.setUsername(ruser);
    myjobObj.setGroupname("cmsupport");
    myjobObj.setPriority("1");
    myjobObj.setStdinfile(rfile + "/stdin-mpi");
    myjobObj.setStdoutfile(rfile + "/stdout-mpi");
    myjobObj.setStderrfile(rfile + "/stderr-mpi");
    myjobObj.setResourceList(Arrays.asList(""));
    myjobObj.setDependencies(Arrays.asList(""));
    myjobObj.setMailNotify(false);
    myjobObj.setMailOptions("ALL");
    myjobObj.setMaxWallClock("00:10:00");
    myjobObj.setNumberOfProcesses(1);
    myjobObj.setNumberOfNodes(1);
    myjobObj.setNodes(Arrays.asList(""));
    myjobObj.setCommandLineInterpreter("/bin/bash");
    myjobObj.setUserdefined(Arrays.asList("cd " + rfile, "date", "pwd"));
    myjobObj.setExecutable("mpirun");
    myjobObj.setArguments("-env I_MPI_FABRICS shm:tcp " + Constants.NEXUSSIM_EXEC + " -mpi -c " + rfile + "/"
            + fileBasename + "/" + fileBasename + " -s " + rfile + "/" + fileBasename + "/" + nexusOut);
    myjobObj.setModules(Arrays.asList("shared", "nexus", "intel-mpi/64"));
    myjobObj.setDebug(false);
    myjobObj.setBaseType("Job");
    myjobObj.setIsSlurm(true);
    myjobObj.setUniqueKey(0);
    myjobObj.setModified(false);
    myjobObj.setToBeRemoved(false);
    myjobObj.setChildType("SlurmJob");
    myjobObj.setJobID("Nexus test");

    // Map<String,jobSubmit.jobObject > mymap= new HashMap<String,
    // jobSubmit.jobObject>();
    // mymap.put("Slurm",myjobObj);
    ArrayList<Object> mylist = new ArrayList<Object>();
    mylist.add("slurm");
    mylist.add(myjobObj);
    myjob.setArgs(mylist);

    GsonBuilder builder = new GsonBuilder();
    builder.enableComplexMapKeySerialization();

    // Gson g = new Gson();
    Gson g = builder.create();

    String json2 = g.toJson(myjob);

    // To be used from a real console and not Eclipse
    Delete.main(zipArgs[1]);
    String message = JSonRequestor.doRequest(json2, cmURL, cookies);
    @SuppressWarnings("resource")
    Scanner resInt = new Scanner(message).useDelimiter("[^0-9]+");
    int jobID = resInt.nextInt();
    System.out.println("Job ID: " + jobID);

    JOptionPane optionPane = new JOptionPane(message);
    JDialog myDialog = optionPane.createDialog(null, "CMDaemon response: ");
    myDialog.setModal(false);
    myDialog.setVisible(true);

    ArrayList<Object> mylist2 = new ArrayList<Object>();
    mylist2.add("slurm");
    String JobID = Integer.toString(jobID);
    mylist2.add(JobID);
    myjob.setArgs(mylist2);
    myjob.setService("cmjob");
    myjob.setCall("getJob");
    String json3 = g.toJson(myjob);
    System.out.println("JSON Request No. 4 " + json3);

    cmReadFile readfile = new cmReadFile();
    readfile.setService("cmmain");
    readfile.setCall("readFile");
    readfile.setUserName(ruser);

    int fileByteIdx = 1;

    readfile.setPath(rfile + "/" + fileBasename + "/" + fileBasename + ".sum@+" + fileByteIdx);
    String json4 = g.toJson(readfile);

    String monFile = JSonRequestor.doRequest(json4, cmURL, cookies).replaceAll("^\"|\"$", "");
    if (monFile.startsWith("Unable")) {
        monFile = "";
    } else {
        fileByteIdx += countLines(monFile, "\\\\n");
        System.out.println("");
    }

    StringBuffer output = new StringBuffer();
    // Get the correct Line Separator for the OS (CRLF or LF)
    String nl = System.getProperty("line.separator");
    String filename = chooser.getCurrentDirectory().toString() + File.separator + fileBasename + ".sum.txt";
    System.out.println("Local monitoring file: " + filename);

    output.append(monFile.replaceAll("\\\\n", System.getProperty("line.separator")));

    String getJobJSON = JSonRequestor.doRequest(json3, cmURL, cookies);
    jobGet getJobObj = new Gson().fromJson(getJobJSON, jobGet.class);
    System.out.println("Job " + jobID + " status: " + getJobObj.getStatus().toString());

    while (getJobObj.getStatus().toString().equals("RUNNING")
            || getJobObj.getStatus().toString().equals("COMPLETING")) {
        try {

            getJobJSON = JSonRequestor.doRequest(json3, cmURL, cookies);
            getJobObj = new Gson().fromJson(getJobJSON, jobGet.class);
            System.out.println("Job " + jobID + " status: " + getJobObj.getStatus().toString());

            readfile.setPath(rfile + "/" + fileBasename + "/" + fileBasename + ".sum@+" + fileByteIdx);
            json4 = g.toJson(readfile);
            monFile = JSonRequestor.doRequest(json4, cmURL, cookies).replaceAll("^\"|\"$", "");
            if (monFile.startsWith("Unable")) {
                monFile = "";
            } else {

                output.append(monFile.replaceAll("\\\\n", System.getProperty("line.separator")));
                System.out.println("FILE INDEX:" + fileByteIdx);
                fileByteIdx += countLines(monFile, "\\\\n");
            }
            Thread.sleep(Constants.STATUS_CHECK_INTERVAL);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }

    }

    Gson gson_nice = new GsonBuilder().setPrettyPrinting().create();
    String json_out = gson_nice.toJson(getJobJSON);
    System.out.println(json_out);
    System.out.println("JSON Request No. 5 " + json4);

    readfile.setPath(rfile + "/" + fileBasename + "/" + fileBasename + ".sum@+" + fileByteIdx);
    json4 = g.toJson(readfile);
    monFile = JSonRequestor.doRequest(json4, cmURL, cookies).replaceAll("^\"|\"$", "");
    if (monFile.startsWith("Unable")) {
        monFile = "";
    } else {

        output.append(monFile.replaceAll("\\\\n", System.getProperty("line.separator")));
        fileByteIdx += countLines(monFile, "\\\\n");
    }
    System.out.println("FILE INDEX:" + fileByteIdx);

    /*
     * System.out.print("Monitoring file: " + monFile.replaceAll("\\n",
     * System.getProperty("line.separator"))); try {
     * FileUtils.writeStringToFile( new
     * File(chooser.getCurrentDirectory().toString() + File.separator +
     * fileBasename + ".sum.txt"), monFile.replaceAll("\\n",
     * System.getProperty("line.separator"))); } catch (IOException e) {
     * 
     * e.printStackTrace(); }
     */

    if (getJobObj.getStatus().toString().equals("COMPLETED")) {
        String[] zipArgs_from = new String[] { chooser.getSelectedFile().toString(),
                chooser.getCurrentDirectory().toString() + File.separator + fileBasename + "_out.zip" };
        String[] myarg_from = new String[] {
                ruser + "@" + rhost + ":" + rfile + "/" + fileBasename + "_out.zip", zipArgs_from[1], rfile,
                fileBasename };
        com.bright.utils.ScpFrom.main(myarg_from);

        JOptionPane optionPaneS = new JOptionPane("Job execution completed without errors!");
        JDialog myDialogS = optionPaneS.createDialog(null, "Job status: ");
        myDialogS.setModal(false);
        myDialogS.setVisible(true);

    } else {
        JOptionPane optionPaneF = new JOptionPane("Job execution FAILED!");
        JDialog myDialogF = optionPaneF.createDialog(null, "Job status: ");
        myDialogF.setModal(false);
        myDialogF.setVisible(true);
    }

    try {
        System.out.println("Local monitoring file: " + filename);

        BufferedWriter out = new BufferedWriter(new FileWriter(filename));
        String outText = output.toString();
        String newString = outText.replace("\\\\n", nl);

        System.out.println("Text: " + outText);
        out.write(newString);

        out.close();
        rmDuplicateLines.main(filename);
    } catch (IOException e) {
        e.printStackTrace();
    }
    doLogout(cmURL, cookies);
    System.exit(0);
}

From source file:com.bright.json.PGS.java

public static void main(String[] args) throws FileNotFoundException {

    String fileBasename = null;/*from   w w  w  .jav a 2  s.com*/

    JFileChooser chooser = new JFileChooser();
    try {
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Spreadsheets", "xls", "xlsx");
        chooser.setFileFilter(filter);
        chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.home")));
        chooser.setDialogTitle("Select the Excel file");

        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);

        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
            System.out.println("getSelectedFile() : " + chooser.getSelectedFile());

            // String fileBasename =
            // chooser.getSelectedFile().toString().substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator)+1,chooser.getSelectedFile().toString().lastIndexOf("."));
            fileBasename = chooser.getSelectedFile().toString()
                    .substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator) + 1);
            System.out.println("Base name: " + fileBasename);

        } else {
            System.out.println("No Selection ");

        }
    } catch (Exception e) {

        System.out.println(e.toString());

    }
    String fileName = chooser.getSelectedFile().toString();
    InputStream inp = new FileInputStream(fileName);
    Workbook workbook = null;
    if (fileName.toLowerCase().endsWith("xlsx")) {
        try {
            workbook = new XSSFWorkbook(inp);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else if (fileName.toLowerCase().endsWith("xls")) {
        try {
            workbook = new HSSFWorkbook(inp);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    Sheet nodeSheet = workbook.getSheet("Devices");
    Sheet interfaceSheet = workbook.getSheet("Interfaces");
    System.out.println("Read nodes sheet.");
    // Row nodeRow = nodeSheet.getRow(1);
    // System.out.println(row.getCell(0).toString());
    // System.exit(0);

    JTextField uiHost = new JTextField("demo.brightcomputing.com");
    // TextPrompt puiHost = new
    // TextPrompt("demo.brightcomputing.com",uiHost);
    JTextField uiUser = new JTextField("root");
    // TextPrompt puiUser = new TextPrompt("root", uiUser);
    JTextField uiPass = new JPasswordField("");
    // TextPrompt puiPass = new TextPrompt("x5deix5dei", uiPass);

    JPanel myPanel = new JPanel(new GridLayout(5, 1));
    myPanel.add(new JLabel("Bright HeadNode hostname:"));
    myPanel.add(uiHost);
    // myPanel.add(Box.createHorizontalStrut(1)); // a spacer
    myPanel.add(new JLabel("Username:"));
    myPanel.add(uiUser);
    myPanel.add(new JLabel("Password:"));
    myPanel.add(uiPass);

    int result = JOptionPane.showConfirmDialog(null, myPanel, "Please fill in all the fields.",
            JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.OK_OPTION) {
        System.out.println("Input received.");

    }

    String rhost = uiHost.getText();
    String ruser = uiUser.getText();
    String rpass = uiPass.getText();

    String cmURL = "https://" + rhost + ":8081/json";
    List<Cookie> cookies = doLogin(ruser, rpass, cmURL);
    chkVersion(cmURL, cookies);

    Map<String, Long> categories = UniqueKeyMap(cmURL, "cmdevice", "getCategories", cookies);
    Map<String, Long> networks = UniqueKeyMap(cmURL, "cmnet", "getNetworks", cookies);
    Map<String, Long> partitions = UniqueKeyMap(cmURL, "cmpart", "getPartitions", cookies);
    Map<String, Long> racks = UniqueKeyMap(cmURL, "cmpart", "getRacks", cookies);
    Map<String, Long> switches = UniqueKeyMap(cmURL, "cmdevice", "getEthernetSwitches", cookies);
    // System.out.println(switches.get("switch01"));
    // System.out.println("Size of the map: "+ switches.size());
    // System.exit(0);
    cmDevice newnode = new cmDevice();
    cmDevice.deviceObject devObj = new cmDevice.deviceObject();
    cmDevice.switchObject switchObj = new cmDevice.switchObject();
    // cmDevice.netObject netObj = new cmDevice.netObject();

    List<String> emptyslist = new ArrayList<String>();

    // Row nodeRow = nodeSheet.getRow(1);
    // Row ifRow = interfaceSheet.getRow(1);
    // System.out.println(nodeRow.getCell(0).toString());
    // nodeRow.getCell(3).getStringCellValue()
    Map<String, ArrayList<cmDevice.netObject>> ifmap = new HashMap<String, ArrayList<cmDevice.netObject>>();
    // Map<String,netObject> helperMap = new HashMap<String,netObject>();
    // Iterator<Row> rows = interfaceSheet.rowIterator ();
    // while (rows. < interfaceSheet.getPhysicalNumberOfRows()) {

    // List<netObject> netList = new ArrayList<netObject>();
    for (int i = 0; i < interfaceSheet.getPhysicalNumberOfRows(); i++) {
        Row ifRow = interfaceSheet.getRow(i);
        if (ifRow.getRowNum() == 0) {
            continue; // just skip the rows if row number is 0
        }

        System.out.println("Row nr: " + ifRow.getRowNum());
        cmDevice.netObject netObj = new cmDevice.netObject();
        ArrayList<cmDevice.netObject> helperList = new ArrayList<cmDevice.netObject>();
        netObj.setBaseType("NetworkInterface");
        netObj.setCardType(ifRow.getCell(3).getStringCellValue());
        netObj.setChildType(ifRow.getCell(4).getStringCellValue());
        netObj.setDhcp((ifRow.getCell(5).getNumericCellValue() > 0.1) ? true : false);
        netObj.setIp(ifRow.getCell(7).getStringCellValue());
        // netObj.setMac(ifRow.getCell(0).toString());
        //netObj.setModified(true);
        netObj.setName(ifRow.getCell(1).getStringCellValue());
        netObj.setNetwork(networks.get(ifRow.getCell(6).getStringCellValue()));
        //netObj.setOldLocalUniqueKey(0L);
        netObj.setRevision("");
        netObj.setSpeed(ifRow.getCell(8, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
        netObj.setStartIf("ALWAYS");
        netObj.setToBeRemoved(false);
        netObj.setUniqueKey((long) ifRow.getCell(2).getNumericCellValue());
        //netObj.setAdditionalHostnames(new ArrayList<String>(Arrays.asList(ifRow.getCell(9, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*"))));
        //netObj.setMac(ifRow.getCell(10, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
        netObj.setMode((int) ifRow.getCell(11, Row.CREATE_NULL_AS_BLANK).getNumericCellValue());
        netObj.setOptions(ifRow.getCell(12, Row.CREATE_NULL_AS_BLANK).getStringCellValue());
        netObj.setMembers(new ArrayList<String>(Arrays
                .asList(ifRow.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*"))));
        // ifmap.put(ifRow.getCell(0).getStringCellValue(), new
        // HashMap<String, cmDevice.netObject>());
        // helperMap.put(ifRow.getCell(1).getStringCellValue(), netObj) ;
        // ifmap.get(ifRow.getCell(0).getStringCellValue()).putIfAbsent(ifRow.getCell(1).getStringCellValue(),
        // netObj);
        // ifmap.put(ifRow.getCell(0).getStringCellValue(), helperMap);

        if (!ifmap.containsKey(ifRow.getCell(0).getStringCellValue())) {
            ifmap.put(ifRow.getCell(0).getStringCellValue(), new ArrayList<cmDevice.netObject>());
        }
        helperList = ifmap.get(ifRow.getCell(0).getStringCellValue());
        helperList.add(netObj);
        ifmap.put(ifRow.getCell(0).getStringCellValue(), helperList);

        continue;
    }

    for (int i = 0; i < nodeSheet.getPhysicalNumberOfRows(); i++) {
        Row nodeRow = nodeSheet.getRow(i);
        if (nodeRow.getRowNum() == 0) {
            continue; // just skip the rows if row number is 0
        }

        newnode.setService("cmdevice");
        newnode.setCall("addDevice");

        Map<String, Long> ifmap2 = new HashMap<String, Long>();
        for (cmDevice.netObject j : ifmap.get(nodeRow.getCell(0).getStringCellValue()))
            ifmap2.put(j.getName(), j.getUniqueKey());

        switchObj.setEthernetSwitch(switches.get(nodeRow.getCell(8).getStringCellValue()));
        System.out.println(nodeRow.getCell(8).getStringCellValue());
        System.out.println(switches.get(nodeRow.getCell(8).getStringCellValue()));
        switchObj.setPrt((int) nodeRow.getCell(9).getNumericCellValue());
        switchObj.setBaseType("SwitchPort");

        devObj.setBaseType("Device");
        // devObj.setCreationTime(0L);
        devObj.setCustomPingScript("");
        devObj.setCustomPingScriptArgument("");
        devObj.setCustomPowerScript("");
        devObj.setCustomPowerScriptArgument("");
        devObj.setCustomRemoteConsoleScript("");
        devObj.setCustomRemoteConsoleScriptArgument("");
        devObj.setDisksetup("");
        devObj.setBmcPowerResetDelay(0L);
        devObj.setBurning(false);
        devObj.setEthernetSwitch(switchObj);
        devObj.setExcludeListFull("");
        devObj.setExcludeListGrab("");
        devObj.setExcludeListGrabnew("");
        devObj.setExcludeListManipulateScript("");
        devObj.setExcludeListSync("");
        devObj.setExcludeListUpdate("");
        devObj.setFinalize("");
        devObj.setRack(racks.get(nodeRow.getCell(10).getStringCellValue()));
        devObj.setRackHeight((long) nodeRow.getCell(11).getNumericCellValue());
        devObj.setRackPosition((long) nodeRow.getCell(12).getNumericCellValue());
        devObj.setIndexInsideContainer(0L);
        devObj.setInitialize("");
        devObj.setInstallBootRecord(false);
        devObj.setInstallMode("");
        devObj.setIoScheduler("");
        devObj.setLastProvisioningNode(0L);
        devObj.setMac(nodeRow.getCell(6).getStringCellValue());

        devObj.setModified(true);
        devObj.setCategory(categories.get(nodeRow.getCell(1).getStringCellValue()));
        devObj.setChildType("PhysicalNode");
        //devObj.setDatanode((nodeRow.getCell(5).getNumericCellValue() > 0.1) ? true
        //      : false);
        devObj.setHostname(nodeRow.getCell(0).getStringCellValue());
        devObj.setModified(true);
        devObj.setPartition(partitions.get(nodeRow.getCell(2).getStringCellValue()));
        devObj.setUseExclusivelyFor("Category");

        devObj.setNextBootInstallMode("");
        devObj.setNotes("");
        devObj.setOldLocalUniqueKey(0L);

        devObj.setPowerControl(nodeRow.getCell(7).getStringCellValue());

        // System.out.println(ifmap.get("excelnode001").size());
        // System.out.println(ifmap.get(nodeRow.getCell(0).getStringCellValue()).get(nodeRow.getCell(3).getStringCellValue()).getUniqueKey());

        devObj.setManagementNetwork(networks.get(nodeRow.getCell(3).getStringCellValue()));

        devObj.setProvisioningNetwork(ifmap2.get(nodeRow.getCell(4).getStringCellValue()));
        devObj.setProvisioningTransport("RSYNCDAEMON");
        devObj.setPxelabel("");
        // "rack": 90194313218,
        // "rackHeight": 1,
        // "rackPosition": 4,
        devObj.setRaidconf("");
        devObj.setRevision("");

        devObj.setSoftwareImageProxy(null);
        devObj.setStartNewBurn(false);

        devObj.setTag("00000000a000");
        devObj.setToBeRemoved(false);
        // devObj.setUcsInfoConfigured(null);
        // devObj.setUniqueKey(12345L);

        devObj.setUserdefined1("");
        devObj.setUserdefined2("");

        ArrayList<Object> mylist = new ArrayList<Object>();

        ArrayList<cmDevice.netObject> mylist2 = new ArrayList<cmDevice.netObject>();
        ArrayList<Object> emptylist = new ArrayList<Object>();

        devObj.setFsexports(emptylist);
        devObj.setFsmounts(emptylist);
        devObj.setGpuSettings(emptylist);
        devObj.setFspartAssociations(emptylist);

        devObj.setPowerDistributionUnits(emptyslist);

        devObj.setRoles(emptylist);
        devObj.setServices(emptylist);
        devObj.setStaticRoutes(emptylist);

        mylist2 = ifmap.get(nodeRow.getCell(0).getStringCellValue());

        devObj.setNetworks(mylist2);
        mylist.add(devObj);
        mylist.add(1);
        newnode.setArgs(mylist);

        GsonBuilder builder = new GsonBuilder();
        builder.enableComplexMapKeySerialization();

        // Gson g = new Gson();
        Gson g = builder.create();

        String json2 = g.toJson(newnode);

        // To be used from a real console and not Eclipse

        String message = JSonRequestor.doRequest(json2, cmURL, cookies);
        continue;
    }

    JOptionPane optionPaneF = new JOptionPane("The nodes have been added!");
    JDialog myDialogF = optionPaneF.createDialog(null, "Complete:  ");
    myDialogF.setModal(false);
    myDialogF.setVisible(true);
    doLogout(cmURL, cookies);
    // System.exit(0);
}