List of usage examples for java.awt Desktop getDesktop
public static synchronized Desktop getDesktop()
From source file:gtu.zcognos.DimensionUI.java
private void initGUI() { try {/*from w w w. j a v a 2s . c om*/ final SwingActionUtil swingUtil = (SwingActionUtil) SwingActionUtil.newInstance(this); { GroupLayout thisLayout = new GroupLayout((JComponent) getContentPane()); getContentPane().setLayout(thisLayout); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); { projectId = new JTextField(); } { jLabel1 = new JLabel(); jLabel1.setText("PROJECT_ID"); } { create = new JButton(); create.setText("create"); create.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("create.actionPerformed", evt); } }); } { reportId = new JTextField(); } { jLabel8 = new JLabel(); jLabel8.setText("report id"); } { addDimensionFromDb = new JButton(); addDimensionFromDb.setText("add from db"); addDimensionFromDb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("addFromDb.actionPerformed", evt); } }); } { dataSourceTable = new JTextField(); dataSourceTable.setText("rscdpg0901"); } { jLabel7 = new JLabel(); jLabel7.setText("data source table"); } { addDimension = new JButton(); addDimension.setText("add"); addDimension.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("add.actionPerformed", evt); } }); } { dimensionName = new JTextField(); } { jLabel6 = new JLabel(); jLabel6.setText("dimension chinese name"); } { jLabel5 = new JLabel(); jLabel5.setText("rscdzzzz id index"); } { String[] idx = new String[20]; for (int ii = 0; ii < idx.length; ii++) { idx[ii] = "id" + (ii + 1); } ComboBoxModel rscdzzzzIdIndexModel = new DefaultComboBoxModel(idx); rscdzzzzIdIndex = new JComboBox(); rscdzzzzIdIndex.setModel(rscdzzzzIdIndexModel); } { jLabel3 = new JLabel(); jLabel3.setText("Dimension"); } { jScrollPane1 = new JScrollPane(); { DefaultListModel dimensionListModel = new DefaultListModel(); dimensionList = new JList(); jScrollPane1.setViewportView(dimensionList); dimensionList.setModel(dimensionListModel); dimensionList.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { JListUtil.newInstance(dimensionList).defaultJListKeyPressed(evt); } }); } } { exportDir = new JButton(); exportDir.setText("export dir"); exportDir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("exportDir.actionPerformed", evt); } }); } { category = new JTextField(); } { jLabel4 = new JLabel(); jLabel4.setText("category"); } { tableName = new JTextField(); } { jLabel2 = new JLabel(); jLabel2.setText("merge table name"); } thisLayout .setHorizontalGroup(thisLayout.createSequentialGroup().addContainerGap(12, 12) .addGroup(thisLayout.createParallelGroup() .addComponent(jLabel3, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE) .addGroup(thisLayout.createSequentialGroup().addGap(19).addGroup(thisLayout .createParallelGroup().addGroup(thisLayout.createSequentialGroup() .addComponent(exportDir, GroupLayout.PREFERRED_SIZE, 119, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent( addDimension, GroupLayout.PREFERRED_SIZE, 119, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(thisLayout.createParallelGroup().addComponent( addDimensionFromDb, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 191, GroupLayout.PREFERRED_SIZE) .addGroup(thisLayout.createSequentialGroup().addGap( 88) .addComponent(create, GroupLayout.PREFERRED_SIZE, 119, GroupLayout.PREFERRED_SIZE)))) .addGroup(thisLayout.createSequentialGroup().addGroup(thisLayout .createParallelGroup() .addComponent(jLabel6, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE)) .addGap(39) .addGroup(thisLayout.createParallelGroup() .addComponent(dimensionName, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 204, GroupLayout.PREFERRED_SIZE) .addComponent(rscdzzzzIdIndex, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 204, GroupLayout.PREFERRED_SIZE) .addComponent(category, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 204, GroupLayout.PREFERRED_SIZE) .addComponent(reportId, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 204, GroupLayout.PREFERRED_SIZE) .addComponent(tableName, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 204, GroupLayout.PREFERRED_SIZE) .addComponent(dataSourceTable, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 204, GroupLayout.PREFERRED_SIZE) .addComponent(projectId, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 204, GroupLayout.PREFERRED_SIZE))) .addComponent(jScrollPane1, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 436, GroupLayout.PREFERRED_SIZE)))) .addContainerGap(11, 11)); thisLayout.setVerticalGroup(thisLayout.createSequentialGroup().addContainerGap(12, 12) .addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(projectId, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(dataSourceTable, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(tableName, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(reportId, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(category, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(thisLayout.createParallelGroup() .addComponent(jLabel5, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(rscdzzzzIdIndex, GroupLayout.Alignment.LEADING, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED) .addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(dimensionName, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(addDimension, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(exportDir, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(addDimensionFromDb, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGap(11) .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 269, GroupLayout.PREFERRED_SIZE) .addGap(12).addComponent(create, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addContainerGap(9, 9)); } this.setSize(513, 632); swingUtil.addAction("exportDir.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { File file = JFileChooserUtil.newInstance().selectDirectoryOnly().showOpenDialog() .getApproveSelectedFile(); if (file != null) { baseDir = file; } } }); swingUtil.addAction("addFromDb.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { String project = projectId.getText(); Validate.notEmpty(project, "projectId is null"); Validate.notEmpty(dataSourceTable.getText(), "dataSourceTable is null"); DefaultListModel model = (DefaultListModel) dimensionList.getModel(); for (Dimension_ ddd : InformixDbConn.queryGetDaminsion(dataSourceTable.getText(), project)) { model.addElement(ddd); } } }); swingUtil.addAction("add.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { // Validate.notEmpty(tableName.getText(), // "tableName is null"); Validate.notEmpty(category.getText(), "category is null"); Validate.notEmpty(dimensionName.getText(), "dimensionName is null"); Validate.notEmpty(dataSourceTable.getText(), "dataSourceTable is null"); // Validate.notEmpty(reportId.getText(), // "reportId is null"); String report_id = StringUtils.defaultString(reportId.getText(), projectId.getText()); String tName = tableName.getText(); if (StringUtils.isEmpty(tName)) { tName = randomTableName(); } DefaultListModel model = (DefaultListModel) dimensionList.getModel(); model.addElement(new Dimension_(dataSourceTable.getText(), tName, category.getText(), (String) rscdzzzzIdIndex.getSelectedItem(), dimensionName.getText(), report_id)); } }); swingUtil.addAction("create.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { String project = projectId.getText(); Validate.notEmpty(project, "projectId is null"); Validate.notNull(baseDir, "exportDir is null"); File destDir = new File(baseDir, project); Map<String, Object> map = new HashMap<String, Object>(); List<Map<String, String>> llist = new ArrayList<Map<String, String>>(); int idx = 2; int categoryId = 1; DefaultListModel model = (DefaultListModel) dimensionList.getModel(); for (Enumeration<?> enu = model.elements(); enu.hasMoreElements();) { Dimension_ di = (Dimension_) enu.nextElement(); Map mmm = new HashMap(); mmm.put("rscdpg0901", di.dataSourceTable);// mmm.put("rscdpg0901a", di.tableName);// mmm.put("rscdpg0901a_category", di.category);// mmm.put("rscdpg0901a_report_id", di.reportId);// mmm.put("rscdzzzz_id", di.idIndex);// mmm.put("rscdpg0901a_dname", di.dimensionName);// llist.add(mmm); } map.put("PROJECT_ID", project); map.put("RSCDPG0901", llist); map.put("rscdpg0901", dataSourceTable.getText()); ConfigCopy.getInstance().applyBaseDir(baseDir).applyProjectId(project).execute(); Dimension.getInstance()// .applyDestDir(destDir.getAbsolutePath())// .applyParameter(map)// .execute(); JOptionPaneUtil.newInstance().iconInformationMessage() .showMessageDialog(project + " create completed!!\r\n dir : " // + destDir.getAbsolutePath(), project); Desktop.getDesktop().open(destDir); } }); } catch (Exception e) { e.printStackTrace(); } }
From source file:rems.Global.java
public static void runSalesInvoice(String outputUsd, String outfileName, String jsprReportPath, String reportTitle, String rptSQL) { //String reportPath = "C:/1_DESIGNS/MYAPPS/REMSProcessRunner/reports/jasper2.jrxml"; try {// www.j a va 2 s. com //Compile jrxml file. //System.out.println("Inside Jasper"); //System.in.read(); String orgNm = Global.getOrgName(Global.UsrsOrg_ID).replace("\r\n", " ").replace("\r", " ") .replace("\n", " "); String pstl = Global.getOrgPstlAddrs(Global.UsrsOrg_ID).replace("\r\n", " ").replace("\r", " ") .replace("\n", " "); //Contacts Nos String cntcts = Global.getOrgContactNos(Global.UsrsOrg_ID).replace("\r\n", " ").replace("\r", " ") .replace("\n", " "); //Email Address String email = Global.getOrgEmailAddrs(Global.UsrsOrg_ID).replace("\r\n", " ").replace("\r", " ") .replace("\n", " "); String website = Global.getOrgWebsite(Global.UsrsOrg_ID).replace("\r\n", " ").replace("\r", " ") .replace("\n", " "); String online = ""; if (!email.trim().equals("")) { online += "Email: " + email; if (!website.equals("")) { online += " Website: " + website; } } String fileName = jsprReportPath; File theFile = new File(fileName); JasperDesign jasperDesign = JRXmlLoader.load(theFile); JRDesignBand band = new JRDesignBand(); band.setHeight(90); JRDesignImage image = new JRDesignImage(jasperDesign); image.setX(1); image.setY(0); image.setHeight(70); image.setWidth(70); JRDesignExpression expression = new JRDesignExpression(); //expression.setValueClass(java.lang.String.class); //C:/Users/richard.adjei-mensah/JaspersoftWorkspace/MyReports/1.png expression.setText("$P{ImageUrl}"); image.setExpression(expression); band.addElement(image); JRDesignStaticText staticText = new JRDesignStaticText(); staticText.setX(90); staticText.setY(2); staticText.setWidth(465); staticText.setHeight(15); //staticText.setHorizontalAlignment(JRAlignment.HORIZONTAL_ALIGN_CENTER); staticText.setText(orgNm); band.addElement(staticText); staticText = new JRDesignStaticText(); staticText.setX(90); staticText.setY(16); staticText.setWidth(465); staticText.setHeight(15); //staticText.setHorizontalAlignment(JRAlignment.HORIZONTAL_ALIGN_CENTER); staticText.setText(pstl); band.addElement(staticText); staticText = new JRDesignStaticText(); staticText.setX(90); staticText.setY(30); staticText.setWidth(465); staticText.setHeight(15); //staticText.setHorizontalAlignment(JRAlignment.HORIZONTAL_ALIGN_CENTER); staticText.setText(cntcts); band.addElement(staticText); staticText = new JRDesignStaticText(); staticText.setX(90); staticText.setY(45); staticText.setWidth(465); staticText.setHeight(15); //staticText.setHorizontalAlignment(JRAlignment.HORIZONTAL_ALIGN_CENTER); staticText.setText(online); band.addElement(staticText); staticText = new JRDesignStaticText(); staticText.setX(0); staticText.setY(73); staticText.setWidth(555); staticText.setHeight(15); staticText.setBold(true); staticText.setFontName("Arial"); staticText.setUnderline(false); staticText.setFontSize(12F); staticText.setForecolor(Color.BLUE); staticText.setHorizontalTextAlign(HorizontalTextAlignEnum.CENTER); staticText.setText(reportTitle); band.addElement(staticText); JRDesignLine nwLine = new JRDesignLine(); nwLine.setX(0); nwLine.setY(72); nwLine.setWidth(555); nwLine.setHeight(0); band.addElement(nwLine); nwLine = new JRDesignLine(); nwLine.setX(0); nwLine.setY(88); nwLine.setWidth(555); nwLine.setHeight(0); band.addElement(nwLine); jasperDesign.setTitle(band);//setPageHeader //Build a new query //rptSQL String theQuery = "SELECT * FROM org.org_details WHERE org_name ilike '%%'"; System.out.println(rptSQL); // update the data query JRDesignQuery newQuery = new JRDesignQuery(); newQuery.setText(theQuery); jasperDesign.setQuery(newQuery); JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); //JasperReport jasperReport = JasperCompileManager.compileReport(reportPath); Map<String, Object> params = new HashMap<String, Object>(); //"C:/Users/richard.adjei-mensah/JaspersoftWorkspace/MyReports/1.png" params.put("ImageUrl", Global.getOrgImgsDrctry() + "/" + String.valueOf(Global.UsrsOrg_ID) + ".png"); Connection connection; Class.forName("org.postgresql.Driver"); connection = DriverManager.getConnection( "jdbc:postgresql://" + Global.Hostnme + ":" + Global.Portnum + "/" + Global.Dbase, Global.Uname, Global.Pswd); System.out.println("Filling report..."); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, connection); if (outputUsd.equals("MICROSOFT EXCEL")) { JRXlsExporter xlsExporter = new JRXlsExporter(); xlsExporter.setExporterInput(new SimpleExporterInput(jasperPrint)); xlsExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outfileName)); SimpleXlsReportConfiguration xlsReportConfiguration = new SimpleXlsReportConfiguration(); //SimpleXlsExporterConfiguration xlsExporterConfiguration = new SimpleXlsExporterConfiguration(); xlsReportConfiguration.setOnePagePerSheet(false); xlsReportConfiguration.setRemoveEmptySpaceBetweenRows(true); xlsReportConfiguration.setDetectCellType(true); xlsReportConfiguration.setWhitePageBackground(false); xlsExporter.setConfiguration(xlsReportConfiguration); xlsExporter.exportReport(); } else if (outputUsd.equals("PDF")) { JasperExportManager.exportReportToPdfFile(jasperPrint, outfileName); } else if (outputUsd.equals("HTML")) { JasperExportManager.exportReportToHtmlFile(jasperPrint, outfileName); } else if (outputUsd.equals("STANDARD")) { JasperExportManager.exportReportToPdfFile(jasperPrint, outfileName); } else if (outputUsd.equals("MICROSOFT WORD")) { JRRtfExporter rtfExporter = new JRRtfExporter(); rtfExporter.setExporterInput(new SimpleExporterInput(jasperPrint)); rtfExporter.setExporterOutput(new SimpleWriterExporterOutput(outfileName)); SimpleRtfReportConfiguration rtfReportConfiguration = new SimpleRtfReportConfiguration(); //SimpleRtfExporterConfiguration xlsExporterConfiguration = new SimpleRtfExporterConfiguration(); rtfExporter.setConfiguration(rtfReportConfiguration); rtfExporter.exportReport(); } else if (outputUsd.equals("CHARACTER SEPARATED FILE (CSV)")) { JRCsvExporter exporter = new JRCsvExporter(); exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); exporter.setExporterOutput(new SimpleWriterExporterOutput(outfileName)); SimpleCsvReportConfiguration rtfReportConfiguration = new SimpleCsvReportConfiguration(); //SimpleCsvExporterConfiguration xlsExporterConfiguration = new SimpleCsvExporterConfiguration(); exporter.setConfiguration(rtfReportConfiguration); exporter.exportReport(); } else { JasperExportManager.exportReportToPdfFile(jasperPrint, outfileName); } //JasperViewer.viewReport(jasperPrint, false); System.out.println("Opening report"); if (Desktop.isDesktopSupported()) { try { File myFile = new File(outfileName); Desktop.getDesktop().open(myFile); } catch (IOException ex) { // no application registered for PDFs } } // Runtime runTime = Runtime.getRuntime(); // Process process = runTime // .exec("C:/Users/richard.adjei-mensah/Desktop/Test1.pdf"); // // System.out.println("Closing report"); // process.destroy(); connection.close(); } catch (JRException ex) { System.out.println(ex.getMessage()); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); } catch (SQLException e) { System.out.println(e.getMessage()); } try { Thread.sleep(5000); } catch (InterruptedException e) { System.out.println(e.getMessage()); } }
From source file:com.g2inc.scap.editor.gui.windows.EditorMainWindow.java
private void initFilemenu() { final EditorMainWindow parentWinRef = this; exitMenuItem.addActionListener(new ActionListener() { @Override//from w w w. ja va2 s .co m public void actionPerformed(ActionEvent e) { parentWinRef.dispose(); } }); openOvalMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { final JFileChooser fc = new JFileChooser(); fc.setDialogType(JFileChooser.OPEN_DIALOG); File lastOpenedFrom = guiProps.getLastOpenedFromFile(); // Set current directory fc.setCurrentDirectory(lastOpenedFrom); FileFilter ff = new OcilOrOvalFilesFilter("OVAL"); fc.setFileFilter(ff); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int ret = fc.showOpenDialog(EditorMainWindow.getInstance()); if (ret == JFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); File parent = f.getAbsoluteFile().getParentFile(); guiProps.setLastOpenedFrom(parent.getAbsolutePath()); guiProps.save(); openFile(f, SCAPDocumentClassEnum.OVAL); } } }); saveMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { // get the currently open window JInternalFrame selectedWin = desktopPane.getSelectedFrame(); if (selectedWin != null) { SCAPDocument scapDoc = null; Document dom = null; String filename = null; if (selectedWin instanceof OvalEditorForm) { OvalEditorForm oef = (OvalEditorForm) selectedWin; scapDoc = oef.getDocument(); dom = scapDoc.getDoc(); filename = scapDoc.getFilename(); } else if (selectedWin instanceof CPEDictionaryEditorForm) { CPEDictionaryEditorForm cef = (CPEDictionaryEditorForm) selectedWin; scapDoc = cef.getDocument(); dom = scapDoc.getDoc(); filename = scapDoc.getFilename(); } if (dom != null) { // since this is a save operation, not save as, we won't // prompt the user for where to store the file try { scapDoc.save(); ((EditorForm) selectedWin).setDirty(false); } catch (Exception e) { String message = "An error occured trying to save to file " + filename + ": " + e.getMessage(); EditorUtil.showMessageDialog(parentWinRef, message, EditorMessages.SAVE_ERROR_DIALOG_TITLE, JOptionPane.ERROR_MESSAGE); } } } } }); saveAsMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { // get the currently open window JInternalFrame selectedWin = desktopPane.getSelectedFrame(); if (selectedWin != null) { SCAPDocument scapDoc = null; Document dom = null; String filename = null; String windowTitle = null; if (selectedWin instanceof OvalEditorForm) { windowTitle = OvalEditorForm.WINDOW_TITLE_BASE; OvalEditorForm oef = (OvalEditorForm) selectedWin; scapDoc = oef.getDocument(); dom = scapDoc.getDoc(); filename = scapDoc.getFilename(); } else if (selectedWin instanceof CPEDictionaryEditorForm) { windowTitle = CPEDictionaryEditorForm.WINDOW_TITLE_BASE; CPEDictionaryEditorForm cef = (CPEDictionaryEditorForm) selectedWin; scapDoc = cef.getDocument(); dom = scapDoc.getDoc(); filename = scapDoc.getFilename(); } else { return; } if (dom != null) { String newFilename = null; SCAPDocumentTypeEnum docType = scapDoc.getDocumentType(); FileSaveAsWizard saveAsWiz = new FileSaveAsWizard(EditorMainWindow.getInstance(), true, docType); //saveAsWiz.pack(); saveAsWiz.setLocationRelativeTo(EditorMainWindow.getInstance()); saveAsWiz.setVisible(true); if (saveAsWiz.wasCancelled()) { return; } newFilename = saveAsWiz.getFilename(); try { scapDoc.setFilename(newFilename); scapDoc.saveAs(newFilename); EditorUtil.markActiveWindowDirty(EditorMainWindow.getInstance(), false); ((EditorForm) selectedWin).refreshRootNode(); } catch (Exception e) { LOG.error(e.getMessage(), e); EditorUtil.showMessageDialog(parentWinRef, "An error occured trying to save to file " + newFilename + ": " + e.getMessage(), "Save Error", JOptionPane.ERROR_MESSAGE); return; } SCAPContentManager scm = SCAPContentManager.getInstance(); if (scm != null) { scm.removeDocument(filename); scm.addDocument(newFilename, scapDoc); selectedWin.setTitle(windowTitle + (new File(newFilename)).getAbsolutePath()); } else { LOG.error("SCM instance is null here!"); } } } } }); newXCCDFFromOvalMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { //generateXccdfFromOvalOrOcil("OVAL"); final JFileChooser fc = new JFileChooser(); fc.setDialogType(JFileChooser.OPEN_DIALOG); File lastOpenedFrom = guiProps.getLastOpenedFromFile(); // Set current directory fc.setCurrentDirectory(lastOpenedFrom); FileFilter ff = new OcilOrOvalFilesFilter("OVAL"); fc.setFileFilter(ff); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int ret = fc.showOpenDialog(EditorMainWindow.getInstance()); if (ret == JFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); File parent = f.getAbsoluteFile().getParentFile(); guiProps.setLastOpenedFrom(parent.getAbsolutePath()); guiProps.save(); try { InputStream is = this.getClass().getClassLoader().getResourceAsStream("oval-to-xccdf.xsl"); File xsltfile = new File("oval-to-xccdf.xsl"); OutputStream outputStream = new FileOutputStream(xsltfile); IOUtils.copy(is, outputStream); outputStream.close(); OvalToXCCDF1.ovalToXccdf(f, xsltfile); xsltfile.delete(); String reverseDNS = JOptionPane.showInputDialog("reverse_DNS:"); if (reverseDNS == null || reverseDNS.length() == 0) { JOptionPane.showMessageDialog(null, "Enter the reverse_DNS", "alert", JOptionPane.ERROR_MESSAGE); } else { JFileChooser fc1 = new JFileChooser(); fc1.setCurrentDirectory(f); int ret1 = fc1.showSaveDialog(EditorMainWindow.getInstance()); if (ret1 == JFileChooser.APPROVE_OPTION) { File savefile = fc1.getSelectedFile(); is = this.getClass().getClassLoader().getResourceAsStream("xccdf_1.1_to_1.2.xsl"); xsltfile = new File("oval-to-xccdf.xsl"); outputStream = new FileOutputStream(xsltfile); IOUtils.copy(is, outputStream); outputStream.close(); File temp = new File("temp.xml"); XCCDF1to2.xccdf12(savefile, reverseDNS, xsltfile, temp); JOptionPane.showMessageDialog(null, "XCCDF File Created: " + savefile.getAbsolutePath(), "XCCDF Created", JOptionPane.PLAIN_MESSAGE); xsltfile.delete(); temp.delete(); temp = null; } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } // openFile(f, SCAPDocumentClassEnum.OVAL); } } }); newOvalMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { CreateOvalWizard wiz = new CreateOvalWizard(true); wiz.setName("create_oval_wizard"); wiz.pack(); wiz.setVisible(true); if (!wiz.wasCancelled()) { // User has been through the wizard to select // 1. an Oval schema version (eg, OVAL55) // 2. one or more platforms (eg, "windows", "solaris", etc) // 3. a file name for the new Oval file // Now we are ready to actually create the file String createdFilename = createNewOvalDocument(wiz); if (createdFilename == null) { LOG.error("newOvalMenuItem.actionlistener: Created filename was null!"); return; } File f = new File(createdFilename); guiProps.setLastOpenedFromFile(f.getParentFile()); guiProps.save(); SCAPContentManager scm = SCAPContentManager.getInstance(); if (scm != null) { OvalDefinitionsDocument dd = (OvalDefinitionsDocument) scm.getDocument(f.getAbsolutePath()); openFile(dd); } } wiz.setVisible(false); wiz.dispose(); } }); /* wizModeMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { WizardModeWindow wizModeWin = new WizardModeWindow(); EditorMainWindow emw = EditorMainWindow.getInstance(); JDesktopPane emwDesktopPane = emw.getDesktopPane(); wizModeWin.setTitle("Wizard Mode"); wizModeWin.pack(); wizModeWin.addInternalFrameListener(new WeakInternalFrameListener(EditorMainWindow.getInstance())); Dimension dpDim = emwDesktopPane.getSize(); int x = (dpDim.width - wizModeWin.getWidth()) / 2; int y = (dpDim.height - wizModeWin.getHeight()) / 2; wizModeWin.setLocation(x, y); emwDesktopPane.add(wizModeWin); wizModeWin.setVisible(true); setWizMode(true); } });*/ ugMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); InputStream resource = this.getClass().getResourceAsStream("/User_Guide.pdf"); try { File userGuideFile = File.createTempFile("UserGuide", ".pdf"); userGuideFile.deleteOnExit(); OutputStream out = new FileOutputStream(userGuideFile); try { // copy contents from resource to out IOUtils.copy(resource, out); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Couldn't copy between streams."); } finally { out.close(); } desktop.open(userGuideFile); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Could not call Open on desktop object."); } finally { try { if (resource != null) { resource.close(); } } catch (IOException ex) { LOG.error("Error displaying user guide", ex); JOptionPane.showMessageDialog(null, "Desktop not supported. Cannot open user guide."); } } } else { JOptionPane.showMessageDialog(null, "Desktop not supported. Cannot open user guide."); } } }); }
From source file:Report_PRCR_New_ETF_Excel_File_Generator.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try {/* w ww. j a v a2s . c o m*/ DatabaseManager dbm = DatabaseManager.getDbCon(); Date_Handler dt = new Date_Handler(); String year = yearfield.getText(); String month = dt.return_month_as_num(monthfield.getText()); String employee_detail_file_location; if (mv.SoftwareVersion() == 1) { employee_detail_file_location = dbm.checknReturnData("file_locations", "id", "13", "location") + "/" + year + month + ".xls"; System.out.println(employee_detail_file_location); copyFileUsingApacheCommonsIO( new File(dbm.checknReturnData("file_locations", "id", "12", "location")), new File(employee_detail_file_location)); } else if (mv.SoftwareVersion() == 2) { employee_detail_file_location = dbm.checknReturnData("file_locations", "id", "14", "location") + "/" + year + month + ".xls"; System.out.println(employee_detail_file_location); copyFileUsingApacheCommonsIO( new File(dbm.checknReturnData("file_locations", "id", "13", "location")), new File(employee_detail_file_location)); } else { employee_detail_file_location = dbm.checknReturnData("file_locations", "id", "13", "location") + "/" + year + month + ".xls"; System.out.println(employee_detail_file_location); copyFileUsingApacheCommonsIO( new File(dbm.checknReturnData("file_locations", "id", "12", "location")), new File(employee_detail_file_location)); } InputStream inp = new FileInputStream(employee_detail_file_location); Workbook wb = WorkbookFactory.create(inp); org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(0); String payment_date_year_month_date = null; String table_name = "pr_workdata_" + year + "_" + month; String previous_table_name = null; if (Integer.parseInt(month) == 1) { previous_table_name = "pr_workdata_" + (Integer.parseInt(year) - 1) + "_" + 12; } else { if ((Integer.parseInt(month) - 1) < 10) { previous_table_name = "pr_workdata_" + year + "_0" + (Integer.parseInt(month) - 1); } else { previous_table_name = "pr_workdata_" + year + "_" + (Integer.parseInt(month) - 1); } } double employee_contribution_percentage = Math .round(Double.parseDouble( dbm.checknReturnData("prcr_new_epf_details", "name", "etf_rate", "value")) * 100.0) / 100.0; String nic = null; String surname = null; String initials = null; int member_no = 0; /*double tot_contribution = 0; double employers_contribution = 0;*/ double member_contribution = 0; double tot_earnings = 0; /*String member_status = null; String zone = null; int employer_number = 0; int contribution_period = 0; int data_submission_no = 0; double no_of_days_worked = 0; int occupation_classification_grade = 0; int payment_mode = 0; int payment_date = 0; String payment_reference = null; int d_o_code = 0; member_status = "E"; zone = dbm.checknReturnData("prcr_new_epf_details", "name", "zone", "value"); employer_number = Integer.parseInt(dbm.checknReturnData("prcr_new_epf_details", "name", "employer_number", "value")); contribution_period = Integer.parseInt(year + month); data_submission_no = 1; occupation_classification_grade = Integer.parseInt(dbm.checknReturnData("prcr_new_epf_details", "name", "occupation_classification_grade", "value")); int normal_days = 0; int sundays = 0; double ot_before = 0; double ot_after = 0; double hours_as_decimal = 0; int count = 0; double total_member_contribution = 0; int need_both_reports = 1; if (chk.isSelected()) { need_both_reports = 0; } else { need_both_reports = 1; } */ int count = 0; ResultSet query = dbm .query("SELECT * FROM `" + table_name + "` WHERE `register_or_casual` = 1 AND `total_pay` > 0"); while (query.next()) { ResultSet query1 = dbm .query("SELECT * FROM `personal_info` WHERE `code` = '" + query.getInt("code") + "' "); while (query1.next()) { nic = query1.getString("nic").replaceAll("\\s+", ""); surname = split_name(query1.getString("name"))[1]; initials = split_name(query1.getString("name"))[0]; member_no = Integer.parseInt(query1.getString("code")); //occupation_classification_grade = Integer.parseInt(query1.getString("occupation_grade")); //d_o_code = Integer.parseInt(dbm.checknReturnData("prcr_new_epf_details", "name", "d_o_code", "value")); tot_earnings = Math.round(query.getDouble("total_pay") * 100.0) / 100.0; //employers_contribution = Math.round(tot_earnings * employer_contribution_percentage * 100.0) / 100.0; //member_contribution = Math.round(tot_earnings * employee_contribution_percentage * 100.0) / 100.0; //tot_contribution = employers_contribution + member_contribution; //total_member_contribution = total_member_contribution + tot_contribution; member_contribution = Math.round(tot_earnings * employee_contribution_percentage * 100.0) / 100.0; //normal_days = query.getInt("normal_days"); //sundays = query.getInt("sundays"); /* ot_before = query.getDouble("ot_before_hours"); ot_after = query.getDouble("ot_after_hours"); if ((ot_before + ot_after) > 0) { hours_as_decimal = (ot_before + ot_after) / 100; } else { hours_as_decimal = 0; } if ((normal_days + sundays + hours_as_decimal) > 0) { no_of_days_worked = Math.round((normal_days + sundays + hours_as_decimal) * 100.0) / 100.0; } else { no_of_days_worked = 0; } */ // no_of_days_worked = normal_days + sundays; /* if (dbm.checkWhetherDataExists(previous_table_name, "code", query1.getString("code")) == 1) { member_status = "E"; } else { member_status = "N"; } */ Row row = sheet.getRow(1 + count); if (row == null) { row = sheet.createRow(1 + count); } for (int k = 0; k < 5; k++) { Cell cell = row.getCell(k); switch (k) { case 0: cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(member_no); break; case 1: cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(initials); break; case 2: cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(surname); break; case 3: cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellValue(nic); break; case 4: cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(member_contribution); break; default: break; } } count++; } query1.close(); } query.close(); FileOutputStream fileOut = new FileOutputStream(employee_detail_file_location); wb.write(fileOut); fileOut.close(); Desktop.getDesktop().open(new File(employee_detail_file_location)); } catch (Exception ex) { System.out.println(ex); msg.showMessage( "Problem Occured.Check whether the Excel file is alredy opened.Please close it and try again..", "Error", "error"); } }
From source file:coreferenceresolver.gui.MainGUI.java
private void applyClassifierBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_applyClassifierBtnActionPerformed JFileChooser inputFileChooser = new JFileChooser(defaulPath); inputFileChooser.setDialogTitle("Choose where your classified result file saved"); inputFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (inputFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { resultFilePathTF1.setText(inputFileChooser.getSelectedFile().getAbsolutePath() + File.separator + "classified_result.txt"); noteTF.setText("Create classified result file waiting ..."); new Thread(new Runnable() { @Override/* w w w. j ava 2 s. c om*/ public void run() { try { WekaMain.run(inputFilePathTF.getText(), markupFilePathTF.getText(), trainingFilePathTF.getText(), testingFilePathTF.getText(), resultFilePathTF1.getText()); noteTF.setText("Create result file done!"); String folderPathOpen = resultFilePathTF1.getText().substring(0, resultFilePathTF1.getText().lastIndexOf(File.separatorChar)); Desktop.getDesktop().open(new File(folderPathOpen)); //Open the window for predicted chains ClassifiedResultGUI.render(true); //Open the window for actual chains ClassifiedResultGUI.render(false); } catch (Exception ex) { Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); } else { noteTF.setText("No classified result file location selected"); } }
From source file:org.sleuthkit.autopsy.report.ReportXLS.java
@Override public void getPreview(String path) { File file = new File(path); try {/*from ww w . ja va2 s .c o m*/ Desktop.getDesktop().open(file); } catch (IOException e) { Logger.getLogger(ReportXLS.class.getName()).log(Level.WARNING, "Could not open XLS report! ", e); } }
From source file:SdkUnitTests.java
@Test public void GetDiagnosticLogsTest() { byte[] fileBytes = null; try {//from ww w . j a v a 2 s.co m // String currentDir = new java.io.File(".").getCononicalPath(); String currentDir = System.getProperty("user.dir"); Path path = Paths.get(currentDir + SignTest1File); fileBytes = Files.readAllBytes(path); } catch (IOException ioExcp) { Assert.assertEquals(null, ioExcp); } // create an envelope to be signed EnvelopeDefinition envDef = new EnvelopeDefinition(); envDef.setEmailSubject("DownLoadEnvelopeDocumentsTest"); envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope."); // add a document to the envelope Document doc = new Document(); String base64Doc = Base64.getEncoder().encodeToString(fileBytes); doc.setDocumentBase64(base64Doc); doc.setName("TestFile.pdf"); doc.setDocumentId("1"); List<Document> docs = new ArrayList<Document>(); docs.add(doc); envDef.setDocuments(docs); // Add a recipient to sign the document Signer signer = new Signer(); signer.setEmail(UserName); String name = "Pat Developer"; signer.setName(name); signer.setRecipientId("1"); // this value represents the client's unique identifier for the signer String clientUserId = "2939"; signer.setClientUserId(clientUserId); // Create a SignHere tab somewhere on the document for the signer to sign SignHere signHere = new SignHere(); signHere.setDocumentId("1"); signHere.setPageNumber("1"); signHere.setRecipientId("1"); signHere.setXPosition("100"); signHere.setYPosition("100"); List<SignHere> signHereTabs = new ArrayList<SignHere>(); signHereTabs.add(signHere); Tabs tabs = new Tabs(); tabs.setSignHereTabs(signHereTabs); signer.setTabs(tabs); // Above causes issue envDef.setRecipients(new Recipients()); envDef.getRecipients().setSigners(new ArrayList<Signer>()); envDef.getRecipients().getSigners().add(signer); // send the envelope (otherwise it will be "created" in the Draft folder envDef.setStatus("sent"); try { ApiClient apiClient = new ApiClient(); apiClient.setBasePath(BaseUrl); String creds = createAuthHeaderCreds(UserName, Password, IntegratorKey); apiClient.addDefaultHeader("X-DocuSign-Authentication", creds); Configuration.setDefaultApiClient(apiClient); AuthenticationApi authApi = new AuthenticationApi(); LoginInformation loginInfo = authApi.login(); Assert.assertNotSame(null, loginInfo); Assert.assertNotNull(loginInfo.getLoginAccounts()); Assert.assertTrue(loginInfo.getLoginAccounts().size() > 0); List<LoginAccount> loginAccounts = loginInfo.getLoginAccounts(); Assert.assertNotNull(loginAccounts.get(0).getAccountId()); String accountId = loginInfo.getLoginAccounts().get(0).getAccountId(); DiagnosticsApi diagApi = new DiagnosticsApi(); DiagnosticsSettingsInformation diagSettings = new DiagnosticsSettingsInformation(); diagSettings.setApiRequestLogging("true"); diagApi.updateRequestLogSettings(diagSettings); EnvelopesApi envelopesApi = new EnvelopesApi(); EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef); Assert.assertNotNull(envelopeSummary); Assert.assertNotNull(envelopeSummary.getEnvelopeId()); System.out.println("EnvelopeSummary: " + envelopeSummary); byte[] pdfBytes = envelopesApi.getDocument(accountId, envelopeSummary.getEnvelopeId(), "combined"); try { File pdfFile = File.createTempFile("ds_", "pdf", null); FileOutputStream fos = new FileOutputStream(pdfFile); fos.write(pdfBytes); // show the PDF Desktop.getDesktop().open(pdfFile); } catch (Exception ex) { Assert.fail("Could not create pdf File"); } ApiRequestLogsResult logsList = diagApi.listRequestLogs(); String requestLogId = logsList.getApiRequestLogs().get(0).getRequestLogId(); byte[] diagBytes = diagApi.getRequestLog(requestLogId); try { File diagFile = File.createTempFile("ds_", "txt", null); FileOutputStream fos = new FileOutputStream(diagFile); fos.write(diagBytes); // show the PDF Desktop.getDesktop().open(diagFile); } catch (Exception ex) { Assert.fail("Could not create diag log File"); } } catch (ApiException ex) { System.out.println("Exception: " + ex); Assert.assertEquals(null, ex); } }
From source file:com.msc.dao.facturierswing.Main.java
private void FilePrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FilePrintActionPerformed try {//from w ww . j a v a 2 s. c o m Facture f = createFacture(jLabelNoFacture.getText().isEmpty()); f.setClient(getClientById(f.getIdClient())); Request r = new Request("facture", "print"); Response res = r.sendRequest(f, WebService.METHOD.POST); java.lang.reflect.Type fooType = new TypeToken<Helper<String>>() { }.getType(); Helper<String> h = (Helper<String>) res.getObject(null, fooType); res.setToken(h.getToken()); byte[] pdf = Base64.decodeBase64(h.getMyObject()); File file = new File(".", f.getClient().toString() + "-" + f.getNoFacture() + ".pdf"); FileOutputStream fos = new FileOutputStream(file); IOUtils.write(pdf, fos); IOUtils.closeQuietly(fos); Desktop.getDesktop().open(file.getAbsoluteFile()); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:de.adv_online.aaa.profiltool.ProfilDialog.java
public void actionPerformed(ActionEvent e) { if (startButton == e.getSource()) { startTransformation();/*from www.j av a 2 s . c om*/ } else if (e.getSource() == viewLogButton) { 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) { closeDialog(); } }
From source file:gtu._work.ui.PropertyEditUI.java
private void initGUI() { try {/*from w w w . j a v a 2 s . c o m*/ setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); BorderLayout thisLayout = new BorderLayout(); this.setTitle("PropertyEditUI"); getContentPane().setLayout(thisLayout); { jMenuBar1 = new JMenuBar(); setJMenuBar(jMenuBar1); { jMenu1 = new JMenu(); jMenuBar1.add(jMenu1); jMenu1.setText("File"); { jMenuItem1 = new JMenuItem(); jMenu1.add(jMenuItem1); jMenuItem1.setText("open directory"); jMenuItem1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { File file = JCommonUtil._jFileChooser_selectDirectoryOnly(); loadCurrentFile(file); } }); } { openDirectoryAndChildren = new JMenuItem(); jMenu1.add(openDirectoryAndChildren); openDirectoryAndChildren.setText("open directory and children"); openDirectoryAndChildren.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("openDirectoryAndChildren.actionPerformed, event=" + evt); File file = JCommonUtil._jFileChooser_selectDirectoryOnly(); if (file == null) { // file = // PropertiesUtil.getJarCurrentPath(getClass());//XXX file = new File("D:\\my_tool\\english"); JCommonUtil._jOptionPane_showMessageDialog_info("load C:\\L-CONFIG !"); } DefaultListModel model = new DefaultListModel(); List<File> list = new ArrayList<File>(); FileUtil.searchFileMatchs(file, ".*\\.properties", list); for (File f : list) { File_ ff = new File_(); ff.file = f; model.addElement(ff); } backupFileList = list; fileList.setModel(model); } }); } { jMenuItem2 = new JMenuItem(); jMenu1.add(jMenuItem2); jMenuItem2.setText("save"); jMenuItem2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { System.out.println("jMenu3.actionPerformed, event=" + evt); if (currentFile == null) { return; } if (JCommonUtil._JOptionPane_showConfirmDialog_yesNoOption( "save to " + currentFile.getName(), "SAVE")) { try { Properties prop = new Properties(); // try { // prop.load(new // FileInputStream(currentFile)); // } catch (Exception e) { // e.printStackTrace(); // JCommonUtil.handleException(e); // return; // } loadModelToProperties(prop); prop.store(new FileOutputStream(currentFile), getTitle()); } catch (Exception e) { e.printStackTrace(); JCommonUtil.handleException(e); } } } }); } { jMenuItem3 = new JMenuItem(); jMenu1.add(jMenuItem3); jMenuItem3.setText("save to target"); jMenuItem3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { File file = JFileChooserUtil.newInstance().selectFileOnly().showSaveDialog() .getApproveSelectedFile(); if (file == null) { JCommonUtil._jOptionPane_showMessageDialog_error("file name is not correct!"); return; } if (!file.getName().contains(".properties")) { file = new File(file.getParent(), file.getName() + ".properties"); } try { Properties prop = new Properties(); // try { // prop.load(new // FileInputStream(currentFile)); // } catch (Exception e) { // e.printStackTrace(); // JCommonUtil.handleException(e); // return; // } loadModelToProperties(prop); prop.store(new FileOutputStream(file), getTitle()); } catch (Exception e) { e.printStackTrace(); JCommonUtil.handleException(e); } } }); } { jMenuItem4 = new JMenuItem(); jMenu1.add(jMenuItem4); jMenuItem4.setText("save file(sorted)"); jMenuItem4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if (currentFile == null) { return; } try { BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(currentFile))); List<String> sortList = new ArrayList<String>(); for (String line = null; (line = reader.readLine()) != null;) { sortList.add(line); } reader.close(); Collections.sort(sortList); StringBuilder sb = new StringBuilder(); for (String line : sortList) { sb.append(line + "\n"); } FileUtil.saveToFile(currentFile, sb.toString(), "UTF8"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); } { jMenuItem5 = new JMenuItem(); jMenu1.add(jMenuItem5); jMenuItem5.setText(""); jMenuItem5.addActionListener(new ActionListener() { private void setMeaning(String meaning, int rowPos) { propTable.getRowSorter().getModel().setValueAt(meaning, rowPos, 2); } private void setMeaningEn1(String english, int rowPos, List<String> errSb) { EnglishTester_Diectory eng = new EnglishTester_Diectory(); try { WordInfo wordInfo = eng.parseToWordInfo(english); String meaning = getChs2Big5(wordInfo.getMeaning()); if (hasChinese(meaning)) { setMeaning(meaning, rowPos); } else { setMeaningEn2(english, rowPos, errSb); } } catch (Exception e) { errSb.add(english); e.printStackTrace(); } } private void setMeaningEn2(String english, int rowPos, List<String> errSb) { EnglishTester_Diectory2 eng2 = new EnglishTester_Diectory2(); try { WordInfo2 wordInfo = eng2.parseToWordInfo(english); String meaning = getChs2Big5(StringUtils.join(wordInfo.getMeaningList(), ";")); setMeaning(meaning, rowPos); } catch (Exception e) { errSb.add(english); e.printStackTrace(); } } private boolean hasChinese(String val) { return new StringUtil_().getChineseWord(val, true).length() > 0; } private Properties loadFromMemoryBank() { try { Properties prop = new Properties(); File f1 = new File( "D:/gtu001_dropbox/Dropbox/Apps/gtu001_test/etc_config/EnglishSearchUI_MemoryBank.properties"); File f2 = new File( "e:/gtu001_dropbox/Dropbox/Apps/gtu001_test/etc_config/EnglishSearchUI_MemoryBank.properties"); for (File f : new File[] { f1, f2 }) { if (f.exists()) { HermannEbbinghaus_Memory memory = new HermannEbbinghaus_Memory(); memory.init(f); List<MemData> memLst = memory.getAllMemData(true); for (MemData d : memLst) { prop.setProperty(d.getKey(), getChs2Big5(d.getRemark())); } break; } } return prop; } catch (Exception ex) { throw new RuntimeException(ex); } } public void actionPerformed(ActionEvent evt) { if (currentFile == null) { return; } // Properties memoryProp = loadFromMemoryBank(); Properties memoryProp = new Properties(); List<String> errSb = new ArrayList<String>(); for (int row = 0; row < propTable.getModel().getRowCount(); row++) { int rowPos = propTable.getRowSorter().convertRowIndexToModel(row); String english = StringUtils.trimToEmpty( (String) propTable.getRowSorter().getModel().getValueAt(rowPos, 1)) .toLowerCase(); String desc = (String) propTable.getRowSorter().getModel().getValueAt(rowPos, 2); if (memoryProp.containsKey(english) && StringUtils.isNotBlank(memoryProp.getProperty(english))) { setMeaning(memoryProp.getProperty(english), rowPos); } else { if (StringUtils.isBlank(desc) || !hasChinese(desc)) { if (!english.contains(" ")) { setMeaningEn1(english, rowPos, errSb); } else { setMeaningEn2(english, rowPos, errSb); } } } if (StringUtils.trimToEmpty(desc).contains("?")) { setMeaning("", rowPos); } } if (!errSb.isEmpty()) { JCommonUtil._jOptionPane_showMessageDialog_error(":\n" + errSb); } } }); } { JMenuItem jMenuItem6 = new JMenuItem(); jMenu1.add(jMenuItem6); jMenuItem6.setText(""); jMenuItem6.addActionListener(new ActionListener() { private void setMeaning(String meaning, int rowPos) { propTable.getRowSorter().getModel().setValueAt(meaning, rowPos, 2); } public void actionPerformed(ActionEvent evt) { for (int row = 0; row < propTable.getModel().getRowCount(); row++) { int rowPos = propTable.getRowSorter().convertRowIndexToModel(row); String english = StringUtils.trimToEmpty( (String) propTable.getRowSorter().getModel().getValueAt(rowPos, 1)) .toLowerCase(); String desc = (String) propTable.getRowSorter().getModel().getValueAt(rowPos, 2); if (StringUtils.trimToEmpty(desc).contains("?")) { setMeaning("", rowPos); } } } }); } } } { jTabbedPane1 = new JTabbedPane(); getContentPane().add(jTabbedPane1, BorderLayout.CENTER); { jPanel2 = new JPanel(); BorderLayout jPanel2Layout = new BorderLayout(); jPanel2.setLayout(jPanel2Layout); jTabbedPane1.addTab("editor", null, jPanel2, null); { jScrollPane1 = new JScrollPane(); jPanel2.add(jScrollPane1, BorderLayout.CENTER); jScrollPane1.setPreferredSize(new java.awt.Dimension(550, 314)); { TableModel propTableModel = new DefaultTableModel( new String[][] { { "", "", "" }, { "", "", "" } }, new String[] { "index", "Key", "value" }); propTable = new JTable(); JTableUtil.defaultSetting_AutoResize(propTable); jScrollPane1.setViewportView(propTable); propTable.setModel(propTableModel); propTable.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { JTableUtil xxxxxx = JTableUtil.newInstance(propTable); int[] rows = xxxxxx.getSelectedRows(); for (int ii : rows) { System.out.println(xxxxxx.getModel().getValueAt(ii, 1)); } JPopupMenuUtil.newInstance(propTable).applyEvent(evt) .addJMenuItem(JTableUtil.newInstance(propTable).getDefaultJMenuItems()) .show(); } }); } } { queryText = new JTextField(); jPanel2.add(queryText, BorderLayout.NORTH); queryText.getDocument() .addDocumentListener(JCommonUtil.getDocumentListener(new HandleDocumentEvent() { @Override public void process(DocumentEvent event) { if (currentFile == null) { return; } Properties prop = new Properties(); try { prop.load(new FileInputStream(currentFile)); } catch (Exception e) { e.printStackTrace(); JCommonUtil.handleException(e); return; } loadPropertiesToModel(prop); String text = JCommonUtil.getDocumentText(event); Pattern pattern = null; try { pattern = Pattern.compile(text); } catch (Exception ex) { } DefaultTableModel model = JTableUtil.newInstance(propTable).getModel(); for (int ii = 0; ii < model.getRowCount(); ii++) { String key = (String) model.getValueAt(ii, 1); String value = (String) model.getValueAt(ii, 2); if (key.contains(text)) { continue; } if (value.contains(text)) { continue; } if (pattern != null) { if (pattern.matcher(key).find()) { continue; } if (pattern.matcher(value).find()) { continue; } } model.removeRow(propTable.convertRowIndexToModel(ii)); ii--; } } })); } } { jPanel3 = new JPanel(); BorderLayout jPanel3Layout = new BorderLayout(); jPanel3.setLayout(jPanel3Layout); jTabbedPane1.addTab("folder", null, jPanel3, null); { jScrollPane2 = new JScrollPane(); jPanel3.add(jScrollPane2, BorderLayout.CENTER); jScrollPane2.setPreferredSize(new java.awt.Dimension(550, 314)); { fileList = new JList(); jScrollPane2.setViewportView(fileList); fileList.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { JListUtil.newInstance(fileList).defaultJListKeyPressed(evt); } }); fileList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { final File_ file = JListUtil.getLeadSelectionObject(fileList); if (evt.getButton() == MouseEvent.BUTTON1) { Properties prop = new Properties(); currentFile = file.file; setTitle(currentFile.getName()); try { prop.load(new FileInputStream(file.file)); } catch (Exception e) { e.printStackTrace(); } loadPropertiesToModel(prop); } if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() == 2) { try { Runtime.getRuntime().exec(String.format("cmd /c \"%s\"", file.file)); } catch (IOException e1) { e1.printStackTrace(); } } final File parent = file.file.getParentFile(); JMenuItem openTargetDir = new JMenuItem(); openTargetDir.setText("open : " + parent); openTargetDir.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Desktop.getDesktop().open(parent); } catch (IOException e1) { JCommonUtil.handleException(e1); } } }); JPopupMenuUtil.newInstance(fileList).addJMenuItem(openTargetDir).applyEvent(evt) .show(); } }); } } { fileQueryText = new JTextField(); jPanel3.add(fileQueryText, BorderLayout.NORTH); fileQueryText.getDocument() .addDocumentListener(JCommonUtil.getDocumentListener(new HandleDocumentEvent() { @Override public void process(DocumentEvent event) { String text = JCommonUtil.getDocumentText(event); DefaultListModel model = new DefaultListModel(); for (File f : backupFileList) { if (f.getName().contains(text)) { File_ ff = new File_(); ff.file = f; model.addElement(ff); } } fileList.setModel(model); } })); } { contentQueryText = new JTextField(); jPanel3.add(contentQueryText, BorderLayout.SOUTH); contentQueryText.addActionListener(new ActionListener() { void addModel(File f, DefaultListModel model) { File_ ff = new File_(); ff.file = f; model.addElement(ff); } public void actionPerformed(ActionEvent evt) { DefaultListModel model = new DefaultListModel(); String text = contentQueryText.getText(); if (StringUtils.isEmpty(contentQueryText.getText())) { return; } Pattern pattern = Pattern.compile(text); Properties pp = null; for (File f : backupFileList) { pp = new Properties(); try { pp.load(new FileInputStream(f)); for (String key : pp.stringPropertyNames()) { if (key.isEmpty()) { continue; } if (pp.getProperty(key) == null || pp.getProperty(key).isEmpty()) { continue; } if (key.contains(text)) { addModel(f, model); break; } if (pp.getProperty(key).contains(text)) { addModel(f, model); break; } if (pattern.matcher(key).find()) { addModel(f, model); break; } if (pattern.matcher(pp.getProperty(key)).find()) { addModel(f, model); break; } } } catch (Exception e) { e.printStackTrace(); } } fileList.setModel(model); } }); } } } JCommonUtil.setJFrameIcon(this, "resource/images/ico/english.ico"); JCommonUtil.setJFrameCenter(this); pack(); this.setSize(571, 408); loadCurrentFile(null); } catch (Exception e) { e.printStackTrace(); } }