List of usage examples for javax.swing JTextArea append
public void append(String str)
From source file:DragFileDemo.java
public boolean importData(JComponent c, Transferable t) { JTextArea tc; if (!canImport(c, t.getTransferDataFlavors())) { return false; }//from w w w. j a va 2 s. co m //A real application would load the file in another //thread in order to not block the UI. This step //was omitted here to simplify the code. try { if (hasFileFlavor(t.getTransferDataFlavors())) { String str = null; java.util.List files = (java.util.List) t.getTransferData(fileFlavor); for (int i = 0; i < files.size(); i++) { File file = (File) files.get(i); //Tell the tabbedpane controller to add //a new tab with the name of this file //on the tab. The text area that will //display the contents of the file is returned. tc = tpc.addTab(file.toString()); BufferedReader in = null; try { in = new BufferedReader(new FileReader(file)); while ((str = in.readLine()) != null) { tc.append(str + newline); } } catch (IOException ioe) { System.out.println("importData: Unable to read from file " + file.toString()); } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { System.out.println("importData: Unable to close file " + file.toString()); } } } } return true; } else if (hasStringFlavor(t.getTransferDataFlavors())) { tc = (JTextArea) c; if (tc.equals(source) && (tc.getCaretPosition() >= p0.getOffset()) && (tc.getCaretPosition() <= p1.getOffset())) { shouldRemove = false; return true; } String str = (String) t.getTransferData(stringFlavor); tc.replaceSelection(str); return true; } } catch (UnsupportedFlavorException ufe) { System.out.println("importData: unsupported data flavor"); } catch (IOException ieo) { System.out.println("importData: I/O exception"); } return false; }
From source file:edu.ku.brc.specify.tasks.subpane.wb.DataImportDialog.java
/** * Takes the list of data import errors and displays then to the user * * void//from ww w.j a v a2 s . c om */ protected void showErrors() { JList listOfErrors = genListOfErrorWhereTableDataDefiesSizeConstraints(model.getColumnNames(), model.getData()); if ((model.getColumnNames() == null) || (model.getData() == null) || (listOfErrors == null) || (listOfErrors.getModel().getSize() == 0)) { JTextArea textArea = new JTextArea(); textArea.setRows(25); textArea.setColumns(60); //String newline = "\n"; //for (int i = 0; i < listOfErrors.getModel().getSize(); i++) //{ textArea.append(getResourceString("WB_PARSE_FILE_ERROR2")); //} textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setEditable(false); textArea.setCaretPosition(0); JScrollPane pane = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); JOptionPane.showMessageDialog(UIRegistry.getTopWindow(), pane, getResourceString("DATA_IMPORT_ISSUES"), JOptionPane.WARNING_MESSAGE); okBtn.setEnabled(false); } else if (listOfErrors.getModel().getSize() > 0) { JTextArea textArea = new JTextArea(); textArea.setRows(25); textArea.setColumns(60); String newline = "\n"; for (int i = 0; i < listOfErrors.getModel().getSize(); i++) { textArea.append((String) listOfErrors.getModel().getElementAt(i) + newline + newline); } textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setEditable(false); textArea.setCaretPosition(0); JScrollPane pane = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); JOptionPane.showMessageDialog(UIRegistry.getTopWindow(), pane, getResourceString("DATA_IMPORT_ISSUES"), JOptionPane.WARNING_MESSAGE); } }
From source file:frameworks.Masken.java
public void individuelleMaskePruefen(EDPSession session, String maskennummer, String prio, JTextArea jTLog) { try {// w w w . j a v a2s . c o m EDPEditor edpE1 = null; boolean individuelleMaskeDa = false; edpE1 = session.createEditor(); edpE1.beginEdit(EDPEditor.EDIT_GET, "Infosystem", "", EDPEditor.REFTYPE_NUMSW, "MASKE"); edpE1.setFieldVal(0, "selmasknr", maskennummer); edpE1.setFieldVal(0, "bstart", ""); int maxrows = edpE1.getRowCount(); int aktrow = 1; // schauen ob eine individuelle Maske schon vorhanden ist while (aktrow <= maxrows) { if (edpE1.getFieldVal(aktrow, "tprio").equals(prio.toUpperCase()) && edpE1.getFieldVal(aktrow, "tstdmaske").equals("nein")) { // Individuelle Maske ist vorhanden individuelleMaskeDa = true; } aktrow++; } if (individuelleMaskeDa == false) { // wenn keine Maske vorhanden, dann individualisieren aktrow = 1; while (aktrow <= maxrows) { if (edpE1.getFieldVal(aktrow, "tprio").equals(prio.toUpperCase())) { edpE1.setFieldVal(aktrow, "tindivid", ""); } aktrow++; } } edpE1.endEditSave(); } catch (CantBeginEditException ex) { Logger.getLogger(Masken.class.getName()).log(Level.SEVERE, null, ex); jTLog.append(ex.toString()); jTLog.paint(jTLog.getGraphics()); } catch (CantChangeFieldValException ex) { Logger.getLogger(Masken.class.getName()).log(Level.SEVERE, null, ex); jTLog.append(ex.toString()); jTLog.paint(jTLog.getGraphics()); } catch (CantReadFieldPropertyException ex) { Logger.getLogger(Masken.class.getName()).log(Level.SEVERE, null, ex); jTLog.append(ex.toString()); jTLog.paint(jTLog.getGraphics()); } catch (CantSaveException ex) { Logger.getLogger(Masken.class.getName()).log(Level.SEVERE, null, ex); jTLog.append(ex.toString()); jTLog.paint(jTLog.getGraphics()); } }
From source file:frameworks.Masken.java
public boolean maskenInstall(JTable table, JTextArea jTLog, EDPSession session, String LinuxUser, String LinuxPass, String Host) { try {/*from w w w . jav a 2s .c o m*/ ByteArrayOutputStream error = new ByteArrayOutputStream(); StringBuilder fromServer = new StringBuilder(); StringBuilder screenls = new StringBuilder(); StringBuilder screenlsstring = new StringBuilder(); String maskennummer; String fromServerString = ""; String[] fromServerArray; String resourcesServerString = ""; String[] resourcesServerArray; ArrayList datei = new ArrayList(); String prio = ""; String xmlziel = ""; String resourcesziel = ""; int masksearch = 0; int sshexitstatus = 0; File file = null; int zielzeile = 0; String tabellekopf = ""; boolean failure = false; int firstcell = 0; int lastcell = 0; boolean newpanenotebook = true; //SSh Verbindung zum Mandanten ffnen SshClient sshclient = new SshClient(); sshclient.connect(LinuxUser, LinuxPass, Host, 22); jTLog.append("----------Maskenimport----------\n"); jTLog.append("Vorhandene Masken aus Mandanten ermittelt\n"); jTLog.paint(jTLog.getGraphics()); //Dateinamen erzeugen for (int i = 0; i < table.getRowCount(); i++) { //Fehlerflag auf true setzen failure = true; xmlziel = table.getValueAt(i, 2).toString().replace(table.getValueAt(i, 0).toString(), table.getValueAt(i, 1).toString()); xmlziel = table.getValueAt(i, 2).toString(); resourcesziel = table.getValueAt(i, 3).toString().replace(table.getValueAt(i, 0).toString(), table.getValueAt(i, 1).toString()); maskennummer = table.getValueAt(i, 1).toString(); // hab ich eine ZD und ein Masken TGZ? if (table.getValueAt(i, 3).equals("TGZ")) { xmlziel = table.getValueAt(i, 2).toString(); prio = xmlziel.substring(xmlziel.indexOf(".") + 1, xmlziel.lastIndexOf(".")); prio = prio.substring(prio.indexOf(".") + 1, prio.length()); // Dann kann ich die Maske einfach auf den Serverv kopieren file = new File(GlobalVars.dir + "\\Masken\\" + table.getValueAt(i, 2).toString()); sshexitstatus = sshclient.sendfile(file.toString(), xmlziel); jTLog.append("Neue Maske " + maskennummer + prio + " wird hochgeladen\n"); jTLog.paint(jTLog.getGraphics()); // und importieren jTLog.append("Neue Maske " + maskennummer + prio + " wird im Mandanten importiert\n"); jTLog.paint(jTLog.getGraphics()); sshexitstatus = sshclient.sendcommand( "eval `sh denv.sh`;screen_import.sh -n " + maskennummer + " -p " + prio + " " + xmlziel, error, fromServer); // und generieren jTLog.append("Neue Maske " + maskennummer + prio + " wird generiert\n"); jTLog.paint(jTLog.getGraphics()); // Maske generieren maskegenerieren(session, maskennummer, prio); jTLog.append(error.toString()); jTLog.paint(jTLog.getGraphics()); // Kein ZD und kein TGZ File, also muss die Maske integriert werden } else { datei.clear(); prio = xmlziel.substring(xmlziel.indexOf(".") + 1, xmlziel.lastIndexOf(".")); prio = prio.substring(prio.indexOf(".") + 1, prio.indexOf("-")); //Tabelle oder Kopf tabellekopf = xmlziel.substring(xmlziel.lastIndexOf(".") - 1, xmlziel.lastIndexOf(".")); if (tabellekopf.equals("Z")) { tabellekopf = "_T.xml"; } else { tabellekopf = "_M.xml"; } // Maske individualisieren falls notwendig individuelleMaskePruefen(session, maskennummer, prio, jTLog); // Maske sichern mit screen_export jTLog.append( "Maske " + maskennummer + " " + prio + " wird gesichert und kann mit screen_import -n " + maskennummer + " -p " + prio + " screen_restauriert werden\n"); jTLog.paint(jTLog.getGraphics()); sshexitstatus = sshclient.sendcommand( "eval `sh denv.sh`;screen_export.sh -n " + maskennummer + " -p " + prio, error, fromServer); //Tmp leeren File tmpdir = new File("tmp"); if (tmpdir.exists() && (tmpdir.isDirectory())) { deleteDir(tmpdir); } new File("tmp").mkdir(); // Masken.tgz abholen jTLog.append("Maske " + maskennummer + " " + prio + " wird geladen\n"); jTLog.paint(jTLog.getGraphics()); String servermaske = "./screen." + maskennummer + "." + prio + ".tgz"; sshexitstatus = sshclient.getfile(servermaske, "tmp\\"); if (sshexitstatus == -1) {// Maske wurde erfolgreich geladen //Maske einlesen jTLog.append("Maske " + maskennummer + " " + prio + " wird ausgepackt\n"); jTLog.paint(jTLog.getGraphics()); //tgz lokal auspacken uncompressTarGZ(new File("tmp\\screen." + maskennummer + "." + prio + ".tgz"), new File("tmp\\")); // tgz lschen new File("tmp\\screen." + maskennummer + "." + prio + ".tgz").delete(); String changemaske = "screen_" + maskennummer + "_" + prio + tabellekopf; //Maske einlesen jTLog.append("Maske " + maskennummer + " " + prio + " wird erweitert\n"); jTLog.paint(jTLog.getGraphics()); BufferedReader inservermaske = null; inservermaske = new BufferedReader(new FileReader("tmp\\screens\\screen_" + maskennummer + "\\" + prio + "\\screen_" + maskennummer + "_" + prio + tabellekopf)); BufferedReader inmaske = null; inmaske = new BufferedReader( new FileReader(GlobalVars.dir + "\\Masken\\" + table.getValueAt(i, 2).toString())); PrintWriter outservermaske = new PrintWriter( new BufferedWriter(new FileWriter("tmp\\screens\\screen_" + maskennummer + "\\" + prio + "\\Xscreen_" + maskennummer + "_" + prio + tabellekopf))); int lineNr = 0; zielzeile = 0; firstcell = 0; lastcell = 0; String line = inservermaske.readLine(); while (line != null) { datei.add(line); if (line.contains("<cell") && (firstcell == 0)) firstcell = lineNr; if (line.contains("</layout.grid") && (firstcell != 0)) lastcell = lineNr; if (line.contains("</pane.notebook>")) { zielzeile = lineNr; newpanenotebook = false; } lineNr++; line = inservermaske.readLine(); } inservermaske.close(); // Raus schreiben der Datei for (int izeilen = 0; izeilen < lineNr - 1; izeilen++) { outservermaske.print(datei.get(izeilen) + "\n"); if ((zielzeile == 0) && (firstcell == izeilen)) { outservermaske.print( "<layout.notebook>\n<pane.notebook msgId=\"b825893d-f00a-4500-ae24-c2fe5364ae0e\">\n <layout.grid>\n" + " <cell gridX=\"0\" gridY=\"0\">\n"); } if ((zielzeile == 0) && (lastcell == izeilen)) { outservermaske.print("</pane.notebook>\n"); zielzeile = izeilen; } if ((izeilen == zielzeile) && (zielzeile != 0)) { line = inmaske.readLine(); while (line != null) { // Zuerst die Datei einlesen und jede Zeile raus schreiben outservermaske.print(line + "\n"); line = inmaske.readLine(); } if (newpanenotebook) outservermaske.print("</layout.notebook>\n </cell>\n </layout.grid> \n"); } } outservermaske.close(); // Neue Datei nun auf die alte kopieren Files.move( Paths.get("tmp\\screens\\screen_" + maskennummer + "\\" + prio + "\\Xscreen_" + maskennummer + "_" + prio + tabellekopf), Paths.get("tmp\\screens\\screen_" + maskennummer + "\\" + prio + "\\screen_" + maskennummer + "_" + prio + tabellekopf), REPLACE_EXISTING); // Resources Dateien anschauen // Append an die Resources.language // sshexitstatus = sshclient.sendcommand("cat ./screens/screen_" + maskennummer + "/" + prio + "/ResourcesFW >> ./screens/screen_" + maskennummer + "/" + prio + "/Resources.language", error, fromServer); String resourcesstring = FileUtils.readFileToString( new File(GlobalVars.dir + "\\Masken\\" + table.getValueAt(i, 3).toString()), "utf-8"); FileWriter fw = new FileWriter(new File( "tmp\\screens\\screen_" + maskennummer + "\\" + prio + "\\Resources.language"), true); fw.write(resourcesstring);//appends the string to the file if (newpanenotebook) fw.write("b825893d-f00a-4500-ae24-c2fe5364ae0e=Allgemein\n"); fw.close(); //An Resources_* den String auch noch anhngen // dazu erst mal die Dateien suchen Path dir = Paths.get("tmp\\screens\\screen_" + maskennummer + "\\" + prio); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "Resources_*")) { for (Path resourcesfile : stream) { fw = new FileWriter(resourcesfile.toFile(), true); fw.write(resourcesstring);//appends the string to the file if (newpanenotebook) fw.write("b825893d-f00a-4500-ae24-c2fe5364ae0e=Allgemein\n"); fw.close(); } } // Tgz wieder erzeugen createTarGzip("tmp\\", "tmp\\screen." + maskennummer + "." + prio + ".tgz"); // Maske wieder auf Server schieben sshexitstatus = sshclient.sendfile("\\tmp\\screen." + maskennummer + "." + prio + ".tgz", "screen." + maskennummer + "." + prio + ".tgz"); jTLog.append("Neue Maske " + maskennummer + prio + " wird hochgeladen\n"); jTLog.paint(jTLog.getGraphics()); // und importieren jTLog.append("Neue Maske " + maskennummer + prio + " wird im Mandanten importiert\n"); jTLog.paint(jTLog.getGraphics()); sshexitstatus = sshclient .sendcommand( "eval `sh denv.sh`;screen_import.sh -n " + maskennummer + " -p " + prio + " " + "screen." + maskennummer + "." + prio + ".tgz", error, fromServer); // und generieren jTLog.append("Neue Maske " + maskennummer + prio + " wird generiert\n"); jTLog.paint(jTLog.getGraphics()); // Maske generieren maskegenerieren(session, maskennummer, prio); jTLog.append(error.toString()); jTLog.paint(jTLog.getGraphics()); } /* //Alter Weg // Maske abholen jTLog.append("Maske " + maskennummer + " " + prio + " wird geladen\n"); jTLog.paint(jTLog.getGraphics()); //String servermaske = "./screens/screen_" + maskennummer + "/" + prio + "/screen_" + maskennummer + "_" + prio + "_M.xml"; servermaske = "./screens/screen_" + maskennummer + "/" + prio + "/screen_" + maskennummer + "_" + prio + tabellekopf; sshexitstatus = sshclient.getfile(servermaske, "tmp\\" + maskennummer + prio + ".xml"); if (sshexitstatus == -1) {// Maske wurde erfolgreich geladen //Maske einlesen jTLog.append("Maske " + maskennummer + " " + prio + " wird erweitert\n"); jTLog.paint(jTLog.getGraphics()); BufferedReader inservermaske = null; inservermaske = new BufferedReader(new FileReader("tmp\\" + maskennummer + prio + ".xml")); BufferedReader inmaske = null; inmaske = new BufferedReader(new FileReader(GlobalVars.dir + "\\Masken\\" + table.getValueAt(i, 2).toString())); PrintWriter outservermaske = new PrintWriter(new BufferedWriter(new FileWriter("tmp\\" + maskennummer + prio + "X.xml"))); int lineNr = 0; String line = inservermaske.readLine(); while (line != null) { datei.add(line); if (line.contains("</pane.notebook>")) { zielzeile = lineNr; } lineNr++; line = inservermaske.readLine(); } inservermaske.close(); // Raus schreiben der Datei for (int izeilen = 0; izeilen < lineNr - 1; izeilen++) { outservermaske.print(datei.get(izeilen) + "\n"); if (izeilen == zielzeile) { line = inmaske.readLine(); while (line != null) { // Zuerst die Datei einlesen und jede Zeile raus schreiben outservermaske.print(line + "\n"); line = inmaske.readLine(); } } } outservermaske.close(); //Datei zurck zum server schicken jTLog.append("Maske " + maskennummer + " " + prio + " wird gesendet\n"); jTLog.paint(jTLog.getGraphics()); sshexitstatus = sshclient.sendfile("tmp\\" + maskennummer + prio + "X.xml", servermaske); if (sshexitstatus == -1) {// Maske wurde auf Server bertragen // Jetzt noch die Resources Datei an die Resources auf dem server anhngen sshexitstatus = sshclient.sendfile(GlobalVars.dir + "\\Masken\\" + table.getValueAt(i, 3).toString(), "./screens/screen_" + maskennummer + "/" + prio + "/ResourcesFW"); if (sshexitstatus == -1) { sshexitstatus = sshclient.sendcommand("cat ./screens/screen_" + maskennummer + "/" + prio + "/ResourcesFW >> ./screens/screen_" + maskennummer + "/" + prio + "/Resources.language", error, fromServer); //Resources wurde auf Server bertragen jTLog.append(error.toString()); jTLog.paint(jTLog.getGraphics()); if (sshexitstatus==0) { sshexitstatus = sshclient.sendcommand("ls screens/screen_" + maskennummer + "/" + prio + "/Resources_* -l", error, fromServer); jTLog.append(error.toString()); jTLog.paint(jTLog.getGraphics()); if (sshexitstatus == 0) { resourcesServerString = fromServer.toString(); resourcesServerArray = resourcesServerString.split("\n"); ///Bisher alles gut gelaufen, deswegen failure auf false setzen failure = false; for (int iresources = 0; iresources < resourcesServerArray.length; iresources++) { if (resourcesServerArray[iresources].toString().contains("Resources")) { sshexitstatus = sshclient.sendcommand("cat ./screens/screen_" + maskennummer + "/" + prio + "/ResourcesFW >>" + resourcesServerArray[iresources].toString().substring(resourcesServerArray[iresources].lastIndexOf(" "), resourcesServerArray[iresources].length()), error, fromServer); if (sshexitstatus != 0) { failure = true; } jTLog.append(error.toString()); jTLog.paint(jTLog.getGraphics()); } } jTLog.append("Maske " + maskennummer + " " + prio + " wird generiert\n"); // Maske nun noch generieren maskegenerieren(session, maskennummer, prio); } } } } }*/ if (failure) { //Alte Maske wieder importieren // jTLog.append(error.toString()); // jTLog.append("Gesicherte Maske wird wieder installiert !!! manuelle Nacharbeit notwendig!!!\n"); // jTLog.paint(jTLog.getGraphics()); // sshexitstatus = sshclient.sendcommand("eval `sh denv.sh`;screen_import.sh -n " + maskennummer + " -p " + prio+" screen."+maskennummer+"."+prio+".tgz", error, fromServer); } } } } catch (JSchException ex) { Logger.getLogger(Masken.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Masken.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(Masken.class.getName()).log(Level.SEVERE, null, ex); } catch (SftpException ex) { Logger.getLogger(Masken.class.getName()).log(Level.SEVERE, null, ex); } return true; }
From source file:gui.LauncherFrame.java
/** * creates a text pane containing text and adds it to a tabbed frame * /*ww w . j a va 2 s. c o m*/ * @param tabbedPane - the tabbed frame to add the text panel to * @param tabName - title of the text panel tab * @param filename - name of file containing the text to add to the text panel */ private void addTextTab(javax.swing.JTabbedPane tabbedPane, String tabName, String filename) { File textfile = new File(filename); if (!textfile.isFile()) { debug.print(DebugMessage.StatusType.Error, "File is not valid: " + filename); return; } if (tabName == null || tabName.isEmpty()) { debug.print(DebugMessage.StatusType.Error, "Invalid name for tab: " + tabName); return; } BufferedReader in = null; try { // create a text area and place it in a scrollable panel javax.swing.JTextArea fileText = new javax.swing.JTextArea(0, 0); fileText.setLineWrap(true); fileText.setWrapStyleWord(true); javax.swing.JScrollPane fileScroll = new javax.swing.JScrollPane(fileText); // place the scroll pane in the tabbed pane tabbedPane.addTab(tabName, fileScroll); // now read the file contents into the text area in = new BufferedReader(new FileReader(textfile)); String line = in.readLine(); while (line != null) { fileText.append(line + "\n"); line = in.readLine(); } fileText.setCaretPosition(0); // set position to start of file } catch (FileNotFoundException ex) { debug.print(DebugMessage.StatusType.Error, ex + "<FILE_NOT_FOUND> - accessing " + tabName + " file"); } catch (IOException ex) { debug.print(DebugMessage.StatusType.Error, ex + "<IO_EXCEPTION>"); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { debug.print(DebugMessage.StatusType.Error, ex + "<IO_EXCEPTION>"); } } } }
From source file:base.BasePlayer.AddGenome.java
public void actionPerformed(ActionEvent event) { if (event.getSource() == download) { if (!downloading) { downloading = true;//from w ww. j ava 2 s . c o m downloadGenome(genometable.getValueAt(genometable.getSelectedRow(), 0).toString()); downloading = false; } } else if (event.getSource() == getLinks) { URL[] urls = AddGenome.genomeHash .get(genometable.getValueAt(genometable.getSelectedRow(), 0).toString()); JPopupMenu menu = new JPopupMenu(); JTextArea area = new JTextArea(); JScrollPane menuscroll = new JScrollPane(); area.setFont(Main.menuFont); menu.add(menuscroll); menu.setPreferredSize(new Dimension( menu.getFontMetrics(Main.menuFont).stringWidth(urls[0].toString()) + Main.defaultFontSize * 10, (int) menu.getFontMetrics(Main.menuFont).getHeight() * 4)); //area.setMaximumSize(new Dimension(300, 600)); area.setLineWrap(true); area.setWrapStyleWord(true); for (int i = 0; i < urls.length; i++) { area.append(urls[i].toString() + "\n"); } area.setCaretPosition(0); area.revalidate(); menuscroll.getViewport().add(area); menu.pack(); menu.show(this, 0, 0); } else if (event.getSource() == checkEnsembl) { if (ensemblfetch) { menu.show(AddGenome.treescroll, 0, 0); } else { EnsemblFetch fetcher = new EnsemblFetch(); fetcher.execute(); } } else if (event.getSource() == checkUpdates) { URL testfile = null; try { // kattoo onko paivityksia annotaatioon String ref = selectedNode.toString(); if (AddGenome.genomeHash.get(ref) != null) { ArrayList<String> testfiles = new ArrayList<String>(); if (Main.drawCanvas != null) { for (int i = 0; i < Main.genomehash.get(ref).size(); i++) { testfiles.add(Main.genomehash.get(ref).get(i).getName().replace(".bed.gz", "")); } } testfile = AddGenome.genomeHash.get(ref)[1]; String result = Main.checkFile(testfile, testfiles); if (result.length() == 0) { Main.showError("You have newest annotation file.", "Note"); } else { int n = JOptionPane.showConfirmDialog(Main.drawCanvas, "New annotation file found: " + result + "\nDownload it now?", "Note", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { URL fileurl = new URL(testfile.getProtocol() + "://" + testfile.getHost() + testfile.getPath().substring(0, testfile.getPath().lastIndexOf("/") + 1) + result); OutputRunner runner = new OutputRunner(fileurl, ref); runner.downloadAnnotation = true; runner.execute(); } } } else { Main.showError("This genome is not from Ensembl list, could not check for updates.", "Note", AddGenome.genometable); } } catch (Exception e) { Main.showError("Cannot connect to " + testfile.getHost() + ".\nTry again later.", "Error"); e.printStackTrace(); } } else if (event.getSource() == remove) { if (!selectedNode.isLeaf()) { String removeref = selectedNode.toString(); // Boolean same = false; try { if (Main.drawCanvas != null) { if (removeref.equals(Main.refDropdown.getSelectedItem().toString())) { Main.referenceFile.close(); // same = true; if (ChromDraw.exonReader != null) { ChromDraw.exonReader.close(); } } } if (Main.genomehash.containsKey(removeref)) { for (int i = Main.genomehash.get(removeref).size() - 1; i >= 0; i--) { Main.genomehash.get(removeref).remove(i); } Main.genomehash.remove(removeref); } if (Main.drawCanvas != null) { Main.refModel.removeElement(removeref); Main.refDropdown.removeItem(removeref); Main.refDropdown.revalidate(); } for (int i = 0; i < Main.genome.getItemCount(); i++) { if (Main.genome.getItem(i).getName() != null) { if (Main.genome.getItem(i).getName().equals(removeref)) { Main.genome.remove(Main.genome.getItem(i)); break; } } } FileUtils.deleteDirectory(new File(Main.genomeDir.getCanonicalPath() + "/" + removeref)); checkGenomes(); Main.setAnnotationDrop(""); if (Main.genomehash.size() == 0) { Main.refDropdown.setSelectedIndex(0); Main.setChromDrop("-1"); } } catch (Exception e) { e.printStackTrace(); try { Main.showError("Could not delete genome folder.\nYou can do it manually by deleting folder " + Main.genomeDir.getCanonicalPath() + "/" + removeref, "Note"); } catch (IOException e1) { e1.printStackTrace(); } } } else { try { if (Main.drawCanvas != null) { if (ChromDraw.exonReader != null) { ChromDraw.exonReader.close(); } } Main.removeAnnotationFile(selectedNode.getParent().toString(), selectedNode.toString()); FileUtils.deleteDirectory(new File(Main.genomeDir.getCanonicalPath() + "/" + selectedNode.getParent().toString() + "/annotation/" + selectedNode.toString())); // root.remove(selectedNode.getParent().getIndex(selectedNode)); // root.remove // checkGenomes(); } catch (Exception e) { e.printStackTrace(); try { Main.showError("Could not delete genome folder.\nYou can do it manually by deleting folder " + Main.genomeDir.getCanonicalPath() + "/" + selectedNode.getParent().toString() + "/annotation/" + selectedNode.toString(), "Note"); } catch (IOException e1) { e1.printStackTrace(); } } treemodel.removeNodeFromParent(selectedNode); } } else if (event.getSource() == add) { if (genomeFile == null) { if (new File(genomeFileText.getText()).exists()) { genomeFile = new File(genomeFileText.getText()); } else { genomeFileText.setText("Select reference genome fasta-file."); genomeFileText.setForeground(Color.red); return; } } /*if(genomeName.getText().contains("Give name") || genomeName.getText().length() == 0) { genomeName.setText("Give name of the genome"); genomeName.setForeground(Color.red); genomeName.revalidate(); } else if(!annotation && new File(Main.userDir +"/genomes/"+genomeName.getText().trim().replace("\\s+", "_")).exists()) { genomeName.setText("This genome exists already."); genomeName.setForeground(Color.red); genomeName.revalidate(); } else */ if ((genomeFileText.getText().length() == 0 || genomeFileText.getText().startsWith("Select reference"))) { genomeFileText.setText("Select reference genome fasta-file."); genomeFileText.setForeground(Color.red); genomeFileText.revalidate(); } else { OutputRunner runner = new OutputRunner( genomeFile.getName().replace(".fasta", "").replace(".gz", ""), genomeFile, annotationFile); runner.execute(); } } else if (event.getSource() == openRef) { try { JFileChooser chooser = new JFileChooser(Main.downloadDir); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setAcceptAllFileFilterUsed(false); MyFilterFasta fastaFilter = new MyFilterFasta(); chooser.addChoosableFileFilter(fastaFilter); chooser.setDialogTitle("Select reference fasta-file"); if (Main.screenSize != null) { chooser.setPreferredSize(new Dimension((int) Main.screenSize.getWidth() / 3, (int) Main.screenSize.getHeight() / 3)); } int returnVal = chooser.showOpenDialog((Component) this.getParent()); if (returnVal == JFileChooser.APPROVE_OPTION) { genomeFile = chooser.getSelectedFile(); Main.downloadDir = genomeFile.getParent(); Main.writeToConfig("DownloadDir=" + genomeFile.getParent()); genomeFileText.setText(genomeFile.getName()); genomeFileText.revalidate(); frame.pack(); } } catch (Exception ex) { ex.printStackTrace(); } } else if (event.getSource() == openAnno) { try { JFileChooser chooser = new JFileChooser(Main.downloadDir); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setAcceptAllFileFilterUsed(false); MyFilterGFF gffFilter = new MyFilterGFF(); chooser.addChoosableFileFilter(gffFilter); chooser.setDialogTitle("Select annotation gff3-file"); if (Main.screenSize != null) { chooser.setPreferredSize(new Dimension((int) Main.screenSize.getWidth() / 3, (int) Main.screenSize.getHeight() / 3)); } int returnVal = chooser.showOpenDialog((Component) this.getParent()); if (returnVal == JFileChooser.APPROVE_OPTION) { if (genomeFile == null) { genomeFile = Main.fastahash.get(Main.hoverGenome); } annotationFile = chooser.getSelectedFile(); Main.downloadDir = annotationFile.getParent(); Main.writeToConfig("DownloadDir=" + annotationFile.getParent()); OutputRunner runner = new OutputRunner( genomeFile.getName().replace(".fasta", "").replace(".gz", ""), genomeFile, annotationFile); runner.execute(); } } catch (Exception ex) { ex.printStackTrace(); } } }
From source file:com.tascape.qa.th.android.driver.App.java
/** * The method starts a GUI to let an user inspect element tree and take screenshot when the user is interacting * with the app-under-test manually. Please make sure to set timeout long enough for manual interaction. * * @param timeoutMinutes timeout in minutes to fail the manual steps * * @throws Exception if case of error/*from www . j av a2 s. co m*/ */ public void interactManually(int timeoutMinutes) throws Exception { LOG.info("Start manual UI interaction"); long end = System.currentTimeMillis() + timeoutMinutes * 60000L; AtomicBoolean visible = new AtomicBoolean(true); AtomicBoolean pass = new AtomicBoolean(false); String tName = Thread.currentThread().getName() + "m"; SwingUtilities.invokeLater(() -> { JDialog jd = new JDialog((JFrame) null, "Manual Device UI Interaction - " + device.getProductDetail()); jd.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); JPanel jpContent = new JPanel(new BorderLayout()); jd.setContentPane(jpContent); jpContent.setPreferredSize(new Dimension(1088, 828)); jpContent.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); JPanel jpInfo = new JPanel(); jpContent.add(jpInfo, BorderLayout.PAGE_START); jpInfo.setLayout(new BorderLayout()); { JButton jb = new JButton("PASS"); jb.setForeground(Color.green.darker()); jb.setFont(jb.getFont().deriveFont(Font.BOLD)); jpInfo.add(jb, BorderLayout.LINE_START); jb.addActionListener(event -> { pass.set(true); jd.dispose(); visible.set(false); }); } { JButton jb = new JButton("FAIL"); jb.setForeground(Color.red); jb.setFont(jb.getFont().deriveFont(Font.BOLD)); jpInfo.add(jb, BorderLayout.LINE_END); jb.addActionListener(event -> { pass.set(false); jd.dispose(); visible.set(false); }); } JLabel jlTimeout = new JLabel("xxx seconds left", SwingConstants.CENTER); jpInfo.add(jlTimeout, BorderLayout.CENTER); jpInfo.add(jlTimeout, BorderLayout.CENTER); new SwingWorker<Long, Long>() { @Override protected Long doInBackground() throws Exception { while (System.currentTimeMillis() < end) { Thread.sleep(1000); long left = (end - System.currentTimeMillis()) / 1000; this.publish(left); } return 0L; } @Override protected void process(List<Long> chunks) { Long l = chunks.get(chunks.size() - 1); jlTimeout.setText(l + " seconds left"); if (l < 850) { jlTimeout.setForeground(Color.red); } } }.execute(); JPanel jpResponse = new JPanel(new BorderLayout()); JPanel jpProgress = new JPanel(new BorderLayout()); jpResponse.add(jpProgress, BorderLayout.PAGE_START); JTextArea jtaJson = new JTextArea(); jtaJson.setEditable(false); jtaJson.setTabSize(4); Font font = jtaJson.getFont(); jtaJson.setFont(new Font("Courier New", font.getStyle(), font.getSize())); JTree jtView = new JTree(); JTabbedPane jtp = new JTabbedPane(); jtp.add("tree", new JScrollPane(jtView)); jtp.add("json", new JScrollPane(jtaJson)); jpResponse.add(jtp, BorderLayout.CENTER); JPanel jpScreen = new JPanel(); jpScreen.setMinimumSize(new Dimension(200, 200)); jpScreen.setLayout(new BoxLayout(jpScreen, BoxLayout.PAGE_AXIS)); JScrollPane jsp1 = new JScrollPane(jpScreen); jpResponse.add(jsp1, BorderLayout.LINE_START); JPanel jpJs = new JPanel(new BorderLayout()); JTextArea jtaJs = new JTextArea(); jpJs.add(new JScrollPane(jtaJs), BorderLayout.CENTER); JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jpResponse, jpJs); jSplitPane.setResizeWeight(0.88); jpContent.add(jSplitPane, BorderLayout.CENTER); JPanel jpLog = new JPanel(); jpLog.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0)); jpLog.setLayout(new BoxLayout(jpLog, BoxLayout.LINE_AXIS)); JCheckBox jcbTap = new JCheckBox("Enable Click", null, false); jpLog.add(jcbTap); jpLog.add(Box.createHorizontalStrut(8)); JButton jbLogUi = new JButton("Log Screen"); jpResponse.add(jpLog, BorderLayout.PAGE_END); { jpLog.add(jbLogUi); jbLogUi.addActionListener((ActionEvent event) -> { jtaJson.setText("waiting for screenshot..."); Thread t = new Thread(tName) { @Override public void run() { LOG.debug("\n\n"); try { WindowHierarchy wh = device.loadWindowHierarchy(); jtView.setModel(getModel(wh)); jtaJson.setText(""); jtaJson.append(wh.root.toJson().toString(2)); jtaJson.append("\n"); File png = device.takeDeviceScreenshot(); BufferedImage image = ImageIO.read(png); int w = device.getDisplayWidth(); int h = device.getDisplayHeight(); BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = resizedImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, w, h, null); g2.dispose(); JLabel jLabel = new JLabel(new ImageIcon(resizedImg)); jpScreen.removeAll(); jsp1.setPreferredSize(new Dimension(w + 30, h)); jpScreen.add(jLabel); jLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { LOG.debug("clicked at {},{}", e.getPoint().getX(), e.getPoint().getY()); if (jcbTap.isSelected()) { device.click(e.getPoint().x, e.getPoint().y); device.waitForIdle(); jbLogUi.doClick(); } } }); } catch (Exception ex) { LOG.error("Cannot log screen", ex); jtaJson.append("Cannot log screen"); } jtaJson.append("\n\n\n"); LOG.debug("\n\n"); jd.setSize(jd.getBounds().width + 1, jd.getBounds().height + 1); jd.setSize(jd.getBounds().width - 1, jd.getBounds().height - 1); } }; t.start(); }); } jpLog.add(Box.createHorizontalStrut(38)); { JButton jbLogMsg = new JButton("Log Message"); jpLog.add(jbLogMsg); JTextField jtMsg = new JTextField(10); jpLog.add(jtMsg); jtMsg.addFocusListener(new FocusListener() { @Override public void focusLost(final FocusEvent pE) { } @Override public void focusGained(final FocusEvent pE) { jtMsg.selectAll(); } }); jtMsg.addKeyListener(new KeyAdapter() { @Override public void keyPressed(java.awt.event.KeyEvent e) { if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { jbLogMsg.doClick(); } } }); jbLogMsg.addActionListener(event -> { Thread t = new Thread(tName) { @Override public void run() { String msg = jtMsg.getText(); if (StringUtils.isNotBlank(msg)) { LOG.info("{}", msg); jtMsg.selectAll(); } } }; t.start(); try { t.join(); } catch (InterruptedException ex) { LOG.error("Cannot take screenshot", ex); } jtMsg.requestFocus(); }); } jpLog.add(Box.createHorizontalStrut(38)); { JButton jbClear = new JButton("Clear"); jpLog.add(jbClear); jbClear.addActionListener(event -> { jtaJson.setText(""); }); } JPanel jpAction = new JPanel(); jpContent.add(jpAction, BorderLayout.PAGE_END); jpAction.setLayout(new BoxLayout(jpAction, BoxLayout.LINE_AXIS)); jpJs.add(jpAction, BorderLayout.PAGE_END); jd.pack(); jd.setVisible(true); jd.setLocationRelativeTo(null); jbLogUi.doClick(); }); while (visible.get()) { if (System.currentTimeMillis() > end) { LOG.error("Manual UI interaction timeout"); break; } Thread.sleep(500); } if (pass.get()) { LOG.info("Manual UI Interaction returns PASS"); } else { Assert.fail("Manual UI Interaction returns FAIL"); } }
From source file:search2go.UIFrame.java
private void blast(JTextField queries, JFormattedTextField eValue, JTextField db, JTextField threads, JComboBox type, JTextArea output, boolean fullProcess) throws IOException { Path queriesPath = new Path(queries.getText()); Path dbPath = new Path(db.getText()); String threadNo = threads.getText(); String blastType = type.getSelectedItem().toString().replace("BLAST", ""); currentProj.setQueries(queriesPath.toEscString()); currentProj.setPathToDB(dbPath.toEscString()); currentProj.setThreadNo(Integer.parseInt(threadNo)); currentProj.setBlastTypeIndex(type.getSelectedIndex()); currentProj.setEthreshold(Integer.parseInt(txtBlastE.getText())); blastSequence = new ProcessSequence(currentProj, new ProcessSequenceEnd() { @Override//from w w w . j ava2 s . c o m public void run() { output.append("BLAST Done! Please proceed to Mapping\n"); prgBlast.setIndeterminate(false); currentProj.setAvailable(true); currentProj.setStage(1); if (fullProcess) { map(txtBitScoreFP, eValue, cbxDBIDFP, txtFullOutput, true); } blastButton.restore(); } }); Path outLoc = new Path(currentProj.getPath()); outLoc.append("BLAST_Results.xml"); Process blastProcess = new Process(output, outLoc); blastProcess.setBaseCommand(""); blastProcess.setScriptCommand(type.getSelectedItem().toString().toLowerCase()); blastProcess.addParameter("query", queriesPath.toEscString()); blastProcess.addParameter("db", dbPath.toEscString()); blastProcess.addParameter("num_threads", threadNo); if (!eValue.getText().equals("")) blastProcess.addParameter("evalue", eValue.getText()); blastProcess.addParameter("outfmt", Integer.toString(5)); blastSequence.addProcess(blastProcess); try { blastSequence.start(); blastButton.setStopTargets(blastSequence); if (!fullProcess) blastButton.activate(); currentProj.setStage(0); output.setText("Searching...\n"); prgBlast.setIndeterminate(true); } catch (IOException ex) { javax.swing.JOptionPane.showMessageDialog(this, "Error running BLAST search."); } }
From source file:search2go.UIFrame.java
private void map(JFormattedTextField bitScore, JFormattedTextField eValue, JComboBox originDB, JTextArea output, boolean fullProcess) { currentProj.setSelectedDBIndex(originDB.getSelectedIndex()); currentProj.setBitScoreThreshold(Integer.parseInt(bitScore.getText())); currentProj.setEthreshold(Integer.parseInt(txtMapE.getText())); mapSequence = new ProcessSequence(currentProj, new ProcessSequenceEnd() { @Override//w ww. j a va2 s. c om public void run() { if (!output.getText().contains( "No valid hits found. Please retry with lower bit score or higher e-value thresholds.")) { if (currentProj.willDoCC()) currentProj.setStage(0, 2); if (currentProj.willDoBP()) currentProj.setStage(1, 2); if (currentProj.willDoBP()) currentProj.setStage(2, 2); output.append("Mapping done! Please proceed to Identification.\n"); if (fullProcess) { output.append("Identifying...\n"); identify(true); } } currentProj.setAvailable(true); prgMapping.setIndeterminate(false); mapButton.restore(); } }); Process mapProcess = new Process(output); Path mapScriptPath = new Path("Processes"); mapScriptPath.append("MapFromBlast.py"); mapProcess.setScriptCommand(mapScriptPath.toEscString()); mapSequence.addProcess(mapProcess); mapProcess.addParameter("dir", currentProj.getPath().toEscString()); if (!bitScore.getText().equals("")) mapProcess.addParameter("bs", bitScore.getText()); if (!eValue.getText().equals("")) mapProcess.addParameter("e", eValue.getText()); mapProcess.addParameter("id", originDB.getSelectedItem().toString().replaceAll(" ", "")); Path blastLoc = new Path(currentProj.getPath()); blastLoc.append("BLAST_Results.xml"); mapProcess.addParameter("o", blastLoc.toString()); mapProcess.addParameter("gdb", currentProj.getTargetDBString()); try { mapSequence.start(); mapButton.setStopTargets(mapSequence); if (!fullProcess) mapButton.activate(); if (currentProj.willDoCC()) currentProj.setStage(0, 1); if (currentProj.willDoBP()) currentProj.setStage(1, 1); if (currentProj.willDoBP()) currentProj.setStage(2, 1); System.out.println(currentProj.getStage()); output.setText("Mapping...\n"); prgMapping.setIndeterminate(true); } catch (IOException ex) { javax.swing.JOptionPane.showMessageDialog(this, "Error running mapping program."); } }
From source file:Ephemeris.mySlavePropagator.java
public static void propagate(double a, double e, double i, double omega, double raan, double lM, double stepS, double duration, boolean solarBL, boolean aeroBL, JTextArea TF) { try {//from w w w . ja v a2 s . c om // configure Orekit Autoconfiguration.configureOrekit(); // Inertial frame Frame inertialFrame = FramesFactory.getEME2000(); // Initial date in UTC time scale TimeScale utc = TimeScalesFactory.getUTC(); AbsoluteDate initialDate = new AbsoluteDate(2016, 01, 01, 12, 00, 00.000, utc); // gravitation coefficient double mu = 3.986004415e+14; // Orbit construction as Keplerian Orbit initialOrbit = new KeplerianOrbit(a, e, i, omega, raan, lM, PositionAngle.MEAN, inertialFrame, initialDate, mu); // Initial state definition SpacecraftState initialState = new SpacecraftState(initialOrbit); // Adaptive step integrator with a minimum step of 0.001 and a maximum step of 1000 final double minStep = 0.001; final double maxstep = 1000.0; final double positionTolerance = 0.1; final double initStep = stepS; final OrbitType propagationType = OrbitType.KEPLERIAN; final double[][] tolerances = NumericalPropagator.tolerances(positionTolerance, initialOrbit, propagationType); AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxstep, tolerances[0], tolerances[1]); integrator.setInitialStepSize(initStep); NumericalPropagator propagator = new NumericalPropagator(integrator); propagator.setOrbitType(propagationType); // Force Model (reduced to perturbing gravity field) final NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(10, 10); ForceModel holmesFeatherstone = new HolmesFeatherstoneAttractionModel( FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider); // Aero drag final Frame earthFrame = CelestialBodyFactory.getEarth().getBodyOrientedFrame(); final double ae = provider.getAe(); final SphericalSpacecraft ssc = new SphericalSpacecraft(1, 0.47, 0., 1.2); final OneAxisEllipsoid earth = new OneAxisEllipsoid(ae, Constants.WGS84_EARTH_FLATTENING, earthFrame); Atmosphere atmosphere = new HarrisPriester(CelestialBodyFactory.getSun(), earth); ForceModel aerodrag = new DragForce(atmosphere, ssc); //Solar radiation pressure ForceModel solarPressure = new SolarRadiationPressure(CelestialBodyFactory.getSun(), ae, ssc); // Add force model to the propagator propagator.addForceModel(holmesFeatherstone); if (aeroBL) propagator.addForceModel(aerodrag); if (solarBL) propagator.addForceModel(solarPressure); // Set up initial state in the propagator propagator.setInitialState(initialState); // Set the propagator to slave mode (could be omitted as it is the default mode) propagator.setSlaveMode(); // Overall duration in seconds for extrapolation //double duration = 630.; // Stop date final AbsoluteDate finalDate = initialDate.shiftedBy(duration); // Step duration in seconds double stepT = stepS; // Extrapolation loop //int cpt = 1; for (AbsoluteDate extrapDate = initialDate; extrapDate .compareTo(finalDate) <= 0; extrapDate = extrapDate.shiftedBy(60 * stepT)) { SpacecraftState currentState = propagator.propagate(extrapDate); //System.out.println(/*"step " + */cpt++); //System.out.println(/*" time : " + */currentState.getDate()); //System.out.println(" " + currentState.getOrbit()); KeplerianOrbit o = (KeplerianOrbit) currentState.getOrbit(); String tempSTR; tempSTR = String.format(Locale.US, "%s %12.3f %10.8f %10.6f %10.6f %10.6f %10.6f%n", currentState.getDate(), o.getA(), o.getE(), FastMath.toDegrees(o.getI()), FastMath.toDegrees(o.getPerigeeArgument()), FastMath.toDegrees(o.getRightAscensionOfAscendingNode()), FastMath.toDegrees(o.getTrueAnomaly())); TF.append(tempSTR); } } catch (OrekitException oe) { System.err.println(oe.getMessage()); } }