List of usage examples for java.io BufferedWriter newLine
public void newLine() throws IOException
From source file:eu.crowdrec.contest.sender.RequestSender.java
/** * read logFile then sends line by line to server. * /*from ww w .j a v a 2 s.c o m*/ * @param inLogFileName * path to log file. That can be a zip file or text file. * @param outLogFile * path to outLog file. The outLog file should be analyzed by the evaluator. * if the filename is null; no output will be generated * @param serverURL * URL of the server */ public static void sender(final String inLogFileName, final String outLogFile, final String serverURL) { // handle the log file // check type of file // try to read the defined logFile BufferedReader br = null; BufferedWriter bw = null; try { // if outLogFile name is not null, create an output file if (outLogFile != null && outLogFile.length() > 0) { bw = new BufferedWriter(new FileWriter(new File(outLogFile), false)); } // support a list of files in a directory File inLogFile = new File(inLogFileName); InputStream is; if (inLogFile.isFile()) { is = new FileInputStream(inLogFileName); // support gZip files if (inLogFile.getName().toLowerCase().endsWith(".gz")) { is = new GZIPInputStream(is); } } else { // if the input is a directory, consider all files based on a pattern File[] childs = inLogFile.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { final String fileName = name.toLowerCase(); return fileName.endsWith("data.idomaar.txt.gz") || fileName.endsWith("data.idomaar.txt") || fileName.endsWith(".data.gz"); } }); if (childs == null || childs.length == 0) { throw new IOException("invalid inLogFileName or empty directory"); } Arrays.sort(childs, new Comparator<File>() { @Override public int compare(File o1, File o2) { return o1.getName().compareTo(o2.getName()); } }); Vector<InputStream> isChilds = new Vector<InputStream>(); for (int i = 0; i < childs.length; i++) { InputStream tmpIS = new FileInputStream(childs[i]); // support gZip files if (childs[i].getName().toLowerCase().endsWith(".gz")) { tmpIS = new GZIPInputStream(tmpIS); } isChilds.add(tmpIS); } is = new SequenceInputStream(isChilds.elements()); } // read the log file line by line br = new BufferedReader(new InputStreamReader(is)); try { for (String line = br.readLine(); line != null; line = br.readLine()) { // ignore invalid lines and header if (line.startsWith("null") || line.startsWith("#")) { continue; } if (useThreadPool) { RequestSenderThread t = new RequestSenderThread(line, serverURL, bw); try { // try to limit the speed of sending requests if (Thread.activeCount() > 1000) { if (logger.isDebugEnabled()) { logger.debug("Thread.activeCount() = " + Thread.activeCount()); } Thread.sleep(200); } } catch (Exception e) { logger.info(e.toString()); } t.start(); } else { // send parameters to http server and get response. final long startTime = System.currentTimeMillis(); String result = HttpLib.HTTPCLIENT.equals(httpLib) ? excutePostWithHttpClient(line, serverURL) : excutePost(line, serverURL); // analyze whether an answer is expected boolean answerExpected = false; if (line.contains("\"event_type\": \"recommendation_request\"")) { answerExpected = true; } if (answerExpected) { if (logger.isInfoEnabled()) { logger.info("serverResponse: " + result); } // if the output file is not null, write the output in a synchronized way if (bw != null) { String[] data = LogFileUtils.extractEvaluationRelevantDataFromInputLine(line); String requestId = data[0]; String userId = data[1]; String itemId = data[2]; String domainId = data[3]; String timeStamp = data[4]; long responseTime = System.currentTimeMillis() - startTime; synchronized (bw) { try { bw.write("prediction\t" + requestId + "\t" + timeStamp + "\t" + responseTime + "\t" + itemId + "\t" + userId + "\t" + domainId + "\t" + result); bw.newLine(); } catch (Exception e) { e.printStackTrace(); } } } } } } } catch (IOException e) { logger.warn(e.toString(), e); } } catch (FileNotFoundException e) { logger.error("logFile not found e:" + e.toString()); } catch (IOException e) { logger.error("reading the logFile failed e:" + e.toString()); } finally { if (br != null) { try { br.close(); } catch (IOException e) { logger.debug("close read-log file failed"); } } if (bw != null) { try { // wait for ensuring that all request are finished // this simplifies the management of thread and worked fine for all test machines Thread.sleep(5000); bw.flush(); } catch (Exception e) { logger.debug("close write-log file failed"); } } } }
From source file:gtu._work.ui.ExecuteOpener.java
private void initGUI() { final SwingActionUtil swingUtil = SwingActionUtil.newInstance(this); ToolTipManager.sharedInstance().setInitialDelay(0); try {/* w w w. j a v a 2s . c o m*/ { this.setTitle("execute browser"); this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); this.setPreferredSize(new java.awt.Dimension(870, 551)); this.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { swingUtil.invokeAction("frame.mouseClicked", evt); } }); } { jTabbedPane1 = new JTabbedPane(); getContentPane().add(jTabbedPane1); jTabbedPane1.setPreferredSize(new java.awt.Dimension(384, 265)); jTabbedPane1.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { swingUtil.invokeAction("jTabbedPane1.stateChanged", evt); } }); jTabbedPane1.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { swingUtil.invokeAction("jTabbedPane1.mouseClicked", evt); } }); { jPanel1 = new JPanel(); BorderLayout jPanel1Layout = new BorderLayout(); jPanel1.setLayout(jPanel1Layout); jTabbedPane1.addTab("file list", null, jPanel1, null); { jPanel4 = new JPanel(); BorderLayout jPanel4Layout = new BorderLayout(); jPanel4.setLayout(jPanel4Layout); jPanel1.add(jPanel4, BorderLayout.NORTH); jPanel4.setPreferredSize(new java.awt.Dimension(508, 81)); { jScrollPane1 = new JScrollPane(); jPanel4.add(jScrollPane1, BorderLayout.CENTER); { exeArea = new JTextArea(); jScrollPane1.setViewportView(exeArea); } } { jPanel5 = new JPanel(); BorderLayout jPanel5Layout = new BorderLayout(); jPanel5.setLayout(jPanel5Layout); jPanel4.add(jPanel5, BorderLayout.EAST); jPanel5.setPreferredSize(new java.awt.Dimension(202, 81)); { addArea = new JButton(); jPanel5.add(addArea, BorderLayout.CENTER); addArea.setText("addArea"); addArea.setPreferredSize(new java.awt.Dimension(58, 30)); addArea.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("addArea.actionPerformed", evt); } }); } } { queryText = new JTextField(); jPanel4.add(queryText, BorderLayout.NORTH); queryText.getDocument() .addDocumentListener(JCommonUtil.getDocumentListener(new HandleDocumentEvent() { public void process(DocumentEvent event) { try { String query = JCommonUtil.getDocumentText(event); Pattern ptn = Pattern.compile(query); DefaultListModel model = new DefaultListModel(); for (Object key : prop.keySet()) { String val = key.toString(); if (val.contains(query)) { model.addElement(key); continue; } if (ptn.matcher(val).find()) { model.addElement(key); continue; } } execList.setModel(model); } catch (Exception ex) { } } })); } } { jPanel3 = new JPanel(); jPanel1.add(jPanel3, BorderLayout.CENTER); BorderLayout jPanel3Layout = new BorderLayout(); jPanel3.setLayout(jPanel3Layout); jPanel3.setPreferredSize(new java.awt.Dimension(480, 220)); { jScrollPane2 = new JScrollPane(); jPanel3.add(jScrollPane2, BorderLayout.CENTER); { DefaultListModel execListModel = new DefaultListModel(); for (Object obj : prop.keySet()) { execListModel.addElement((String) obj); } execList = new JList(); jScrollPane2.setViewportView(execList); execList.setModel(execListModel); execList.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { swingUtil.invokeAction("execList.keyPressed", evt); } }); execList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent evt) { swingUtil.invokeAction("execList.valueChanged", evt); } }); execList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { swingUtil.invokeAction("execList.mouseClicked", evt); } }); } } } { jPanel6 = new JPanel(); jPanel1.add(jPanel6, BorderLayout.SOUTH); jPanel6.setPreferredSize(new java.awt.Dimension(741, 47)); { saveList = new JButton(); jPanel6.add(saveList); saveList.setText("save list to default properties"); saveList.setPreferredSize(new java.awt.Dimension(227, 28)); saveList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("saveList.actionPerformed", evt); } }); } { clearExecList = new JButton(); jPanel6.add(clearExecList); clearExecList.setText("clear properties"); clearExecList.setPreferredSize(new java.awt.Dimension(170, 28)); clearExecList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("clearExecList.actionPerformed", evt); } }); } { reloadList = new JButton(); jPanel6.add(reloadList); reloadList.setText("reload list"); reloadList.setPreferredSize(new java.awt.Dimension(156, 28)); reloadList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("reloadList.actionPerformed", evt); } }); } { contentFilterBtn = new JButton(); jPanel6.add(contentFilterBtn); contentFilterBtn.setText("content filter"); contentFilterBtn.setPreferredSize(new java.awt.Dimension(176, 27)); contentFilterBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("contentFilterBtn.actionPerformed", evt); } }); } } } { jPanel2 = new JPanel(); FlowLayout jPanel2Layout = new FlowLayout(); jTabbedPane1.addTab("config", null, jPanel2, null); jPanel2.setPreferredSize(new java.awt.Dimension(573, 300)); jPanel2.setLayout(jPanel2Layout); { executeAll = new JButton(); jPanel2.add(executeAll); executeAll.setText("execute all files"); executeAll.setPreferredSize(new java.awt.Dimension(137, 27)); executeAll.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("execute.actionPerformed", evt); } }); } { browser = new JButton(); jPanel2.add(browser); browser.setText("add file"); browser.setPreferredSize(new java.awt.Dimension(140, 28)); browser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("browser.actionPerformed", evt); } }); } { loadProp = new JButton(); jPanel2.add(loadProp); loadProp.setText("load properties"); loadProp.setPreferredSize(new java.awt.Dimension(158, 32)); loadProp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("loadProp.actionPerformed", evt); } }); } { executeExport = new JButton(); jPanel2.add(executeExport); executeExport.setText("export list"); executeExport.setPreferredSize(new java.awt.Dimension(145, 31)); executeExport.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("executeExport.actionPerformed", evt); } }); } { exportListHasOrignTree = new JButton(); jPanel2.add(exportListHasOrignTree); exportListHasOrignTree.setText("export list has orign tree"); exportListHasOrignTree.setPreferredSize(new java.awt.Dimension(204, 32)); exportListHasOrignTree.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("exportListHasOrignTree.actionPerformed", evt); } }); } { moveFiles = new JButton(); jPanel2.add(moveFiles); moveFiles.setText("move selected"); moveFiles.setPreferredSize(new java.awt.Dimension(161, 31)); moveFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("moveFiles.actionPerformed", evt); } }); } { deleteSelected = new JButton(); jPanel2.add(deleteSelected); deleteSelected.setText("delete selected"); deleteSelected.setPreferredSize(new java.awt.Dimension(165, 31)); deleteSelected.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("deleteSelected.actionPerformed", evt); } }); } { loadClipboardPath = new JButton(); jPanel2.add(loadClipboardPath); loadClipboardPath.setText("load clipboard path"); loadClipboardPath.setPreferredSize(new java.awt.Dimension(222, 31)); loadClipboardPath.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("loadClipboardPath.actionPerformed", evt); } }); } { deleteEmptyDir = new JButton(); jPanel2.add(deleteEmptyDir); deleteEmptyDir.setText("delete empty dir"); deleteEmptyDir.setPreferredSize(new java.awt.Dimension(222, 31)); deleteEmptyDir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("deleteEmptyDir.actionPerformed", evt); } }); } { openSvnUpdate = new JButton(); jPanel2.add(openSvnUpdate); openSvnUpdate.setText("list svn new or modify file"); openSvnUpdate.setPreferredSize(new java.awt.Dimension(210, 34)); openSvnUpdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("openSvnUpdate.actionPerformed", evt); } }); } } { jPanel7 = new JPanel(); BorderLayout jPanel7Layout = new BorderLayout(); jPanel7.setLayout(jPanel7Layout); jTabbedPane1.addTab("properties", null, jPanel7, null); { jScrollPane3 = new JScrollPane(); jPanel7.add(jScrollPane3, BorderLayout.CENTER); jScrollPane3.setPreferredSize(new java.awt.Dimension(741, 415)); { DefaultListModel propertiesListModel = new DefaultListModel(); propertiesList = new JList(); reloadCurrentDirPropertiesList(); jScrollPane3.setViewportView(propertiesList); propertiesList.setModel(propertiesListModel); propertiesList.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { swingUtil.invokeAction("propertiesList.keyPressed", evt); } }); propertiesList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { swingUtil.invokeAction("propertiesList.mouseClicked", evt); } }); } } } { jPanel8 = new JPanel(); BorderLayout jPanel8Layout = new BorderLayout(); jTabbedPane1.addTab("scanner", null, jPanel8, null); jPanel8.setLayout(jPanel8Layout); { jPanel9 = new JPanel(); jPanel8.add(jPanel9, BorderLayout.NORTH); jPanel9.setPreferredSize(new java.awt.Dimension(741, 187)); { scanDirText = new JTextField(); scanDirText.setToolTipText("scan dir"); jPanel9.add(scanDirText); scanDirText.setPreferredSize(new java.awt.Dimension(225, 24)); scanDirText.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { swingUtil.invokeAction("scanDirText.mouseClicked", evt); } }); } { jScrollPane6 = new JScrollPane(); jPanel9.add(jScrollPane6); jScrollPane6.setPreferredSize(new java.awt.Dimension(168, 69)); { scannerText = new JTextArea(); scannerText.setToolTipText("query condition"); jScrollPane6.setViewportView(scannerText); } } { fileScan = new JButton(); jPanel9.add(fileScan); fileScan.setText("start / stop"); fileScan.setPreferredSize(new java.awt.Dimension(113, 24)); fileScan.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("fileScan.actionPerformed", evt); } }); } { useRegexOnly = new JCheckBox(); jPanel9.add(useRegexOnly); useRegexOnly.setText("regex only"); } { DefaultComboBoxModel scanTypeModel = new DefaultComboBoxModel(); for (ScanType s : ScanType.values()) { scanTypeModel.addElement(s); } scanType = new JComboBox(); scanType.setToolTipText("scan type"); jPanel9.add(scanType); scanType.setModel(scanTypeModel); scanType.setPreferredSize(new java.awt.Dimension(147, 24)); } { DefaultComboBoxModel jComboBox1Model = new DefaultComboBoxModel(); for (FileOrDirType f : FileOrDirType.values()) { jComboBox1Model.addElement(f); } fileOrDirTypeCombo = new JComboBox(); jPanel9.add(fileOrDirTypeCombo); fileOrDirTypeCombo.setModel(jComboBox1Model); fileOrDirTypeCombo.setToolTipText("scan file or directory!"); } { addListToExecList = new JButton(); jPanel9.add(addListToExecList); addListToExecList.setText("add list to file list"); addListToExecList.setPreferredSize(new java.awt.Dimension(158, 24)); addListToExecList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { swingUtil.invokeAction("addListToExecList.actionPerformed", evt); } }); } { ignoreScanText = new JTextField(); ignoreScanText.setToolTipText("ignore scan condition"); ignoreScanText.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (!JMouseEventUtil.buttonLeftClick(2, evt)) { return; } String ignore = null; if (StringUtils.isBlank(ignore = ignoreScanText.getText())) { return; } DefaultListModel model = (DefaultListModel) ignoreScanList.getModel(); model.addElement(ignore); } }); jPanel9.add(ignoreScanText); ignoreScanText.setPreferredSize(new java.awt.Dimension(153, 24)); } { jScrollPane5 = new JScrollPane(); jPanel9.add(jScrollPane5); jScrollPane5.setPreferredSize(new java.awt.Dimension(125, 73)); jScrollPane5.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); jScrollPane5.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); { DefaultListModel ignoreScanListModel = new DefaultListModel(); ignoreScanList = new JList(); ignoreScanList.setToolTipText("ignore scan condition list"); jScrollPane5.setViewportView(ignoreScanList); ignoreScanList.setModel(ignoreScanListModel); ignoreScanList.setPreferredSize(new java.awt.Dimension(125, 73)); ignoreScanList.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { JListUtil.newInstance(ignoreScanList).defaultJListKeyPressed(evt); } }); } } { innerScannerText = new JTextField(); innerScannerText.setToolTipText("inner scan query condition"); jPanel9.add(innerScannerText); innerScannerText.setPreferredSize(new java.awt.Dimension(164, 24)); innerScannerText.addMouseListener(new MouseAdapter() { Thread innerScanThread = null; boolean innerScanStop = false; public void mouseClicked(MouseEvent evt) { if (!JMouseEventUtil.buttonLeftClick(2, evt)) { return; } final String innerText = innerScannerText.getText(); if (arrayBackupForInnerScan == null) { return; } innerScanStop = true; if (innerScanThread == null || innerScanThread.getState() == Thread.State.TERMINATED) { innerScanThread = new Thread(Thread.currentThread().getThreadGroup(), new Runnable() { public void run() { innerScanStop = false; System.out.println( toString() + " ... start!! ==> " + innerScanStop); DefaultListModel model = new DefaultListModel(); scanList.setModel(model); for (int ii = 0; ii < arrayBackupForInnerScan.length; ii++) { if (arrayBackupForInnerScan[ii].toString() .contains(innerText)) { model.addElement(arrayBackupForInnerScan[ii]); } if (innerScanStop) { System.out.println(toString() + " ... over!! ==> " + innerScanStop); break; } } System.out.println(toString() + " ... run over!! ==> " + innerScanStop); } }, "innerScanner_" + System.currentTimeMillis()); innerScanThread.setDaemon(true); innerScanThread.start(); } } }); } } { jScrollPane4 = new JScrollPane(); jPanel8.add(jScrollPane4, BorderLayout.CENTER); { DefaultListModel scanListModel = new DefaultListModel(); scanList = new JList(); jScrollPane4.setViewportView(scanList); scanList.setModel(scanListModel); scanList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { swingUtil.invokeAction("scanList.mouseClicked", evt); } }); scanList.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { swingUtil.invokeAction("scanList.keyPressed", evt); } }); } } { scannerStatus = new JLabel(); jPanel8.add(scannerStatus, BorderLayout.SOUTH); scannerStatus.setPreferredSize(new java.awt.Dimension(741, 27)); } } } swingUtil.addAction("moveFiles.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { DefaultListModel model = (DefaultListModel) execList.getModel(); if (model.getSize() == 0 || execList.getSelectedValues().length == 0) { JOptionPaneUtil.newInstance().iconErrorMessage() .showMessageDialog("no selected file can move!", "ERROR"); return; } File exportListTo = FileUtil.getDefaultExportDir(ExecuteOpener.class, true); File file = null; List<File> list = new ArrayList<File>(); for (Object obj : execList.getSelectedValues()) { file = new File((String) obj); if (file.exists() && file.isFile()) { list.add(file); } } File fromBaseDir = FileUtil.exportReceiveBaseDir(list); System.out.println("fromBaseDir = " + fromBaseDir); int cutLen = 0; if (fromBaseDir != null) { cutLen = fromBaseDir.getAbsolutePath().length(); } StringBuilder err = new StringBuilder(); File newFile = null; for (Object obj : execList.getSelectedValues()) { file = new File((String) obj); if (file.exists() && file.isFile()) { newFile = new File(exportListTo + "/" + file.getParent().substring(cutLen), file.getName()); newFile.getParentFile().mkdirs(); System.out.println("move to : " + newFile); file.renameTo(newFile); if (!newFile.exists()) { err.append(file + "\n"); } } } if (err.length() > 0) { JOptionPaneUtil.newInstance().iconErrorMessage() .showMessageDialog("move file error : \n" + err, "ERROR"); } else { JOptionPaneUtil.newInstance().iconInformationMessage().showMessageDialog( "move file success : " + execList.getSelectedValues().length, "SUCCESS"); } } }); swingUtil.addAction("deleteSelected.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { StringBuilder sb = new StringBuilder(); for (Object obj : execList.getSelectedValues()) { sb.append(new File((String) obj).getName() + "\n"); } if (JOptionPaneUtil.ComfirmDialogResult.YES_OK_OPTION != JOptionPaneUtil.newInstance() .confirmButtonYesNo().iconWaringMessage() .showConfirmDialog("are you sure delete file : \n" + sb, "DELETE")) { return; } File file = null; sb = new StringBuilder(); for (Object obj : execList.getSelectedValues()) { file = new File((String) obj); if (!file.exists()) { continue; } if (file.isDirectory() && file.list().length == 0) { if (!file.delete()) { sb.append(file.getName() + "\n"); } continue; } if (!file.delete()) { sb.append(file.getName() + "\n"); } } if (sb.length() != 0) { JOptionPaneUtil.newInstance().iconErrorMessage() .showMessageDialog("delete error list :\n" + sb, "ERROR"); } else { JOptionPaneUtil.newInstance().iconPlainMessage().showMessageDialog("delete completed!", "SUCCESS"); } } }); swingUtil.addAction("loadClipboardPath.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { File file = new File(ClipboardUtil.getInstance().getContents()); if (!file.exists()) { return; } List<File> list = new ArrayList<File>(); FileUtil.searchFileMatchs(file, ".*", list); prop.clear(); for (File f : list) { if (f.isFile()) { prop.setProperty(f.getAbsolutePath(), ""); } } DefaultListModel model = new DefaultListModel(); for (Object key : prop.keySet()) { model.addElement(key); } execList.setModel(model); } }); swingUtil.addAction("deleteEmptyDir.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { File file = JFileChooserUtil.newInstance().selectDirectoryOnly().showOpenDialog() .getApproveSelectedFile(); if (file == null) { JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog("file is not correct!", "ERROR"); return; } if (JOptionPaneUtil.ComfirmDialogResult.YES_OK_OPTION != JOptionPaneUtil.newInstance() .iconWaringMessage().confirmButtonYesNo() .showConfirmDialog("are you sure delete empty dir in \n" + file, "WARRNING")) { return; } List<File> delDir = new ArrayList<File>(); FileUtil.deleteEmptyDir(file, delDir); JOptionPaneUtil.newInstance().iconInformationMessage().showMessageDialog( "delete dir list : \n" + delDir.toString().replace(',', '\n'), "DELETE"); } }); swingUtil.addAction("browser.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { File file = JFileChooserUtil.newInstance().selectFileAndDirectory().showOpenDialog() .getApproveSelectedFile(); if (file != null) { DefaultListModel model = (DefaultListModel) execList.getModel(); model.addElement(file.getAbsolutePath()); } } }); swingUtil.addAction("addArea.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { if (StringUtils.isBlank(exeArea.getText())) { return; } DefaultListModel model = (DefaultListModel) execList.getModel(); StringTokenizer token = new StringTokenizer(exeArea.getText(), "\t\n\r\f"); while (token.hasMoreElements()) { String val = ((String) token.nextElement()).trim(); model.addElement(val); prop.put(val, ""); } } }); swingUtil.addAction("execute.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { DefaultListModel model = (DefaultListModel) execList.getModel(); for (Enumeration<?> enu = model.elements(); enu.hasMoreElements();) { String val = (String) enu.nextElement(); exec(val); } } }); swingUtil.addAction("execList.keyPressed", new Action() { public void action(EventObject evt) throws Exception { JListUtil.newInstance(execList).defaultJListKeyPressed(evt); } }); //DEFAULT PROP SAVE swingUtil.addAction("saveList.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { String orignName = JOptionPaneUtil.newInstance().iconPlainMessage() .showInputDialog("input properties file name", "SAVE"); File saveFile = null; if (StringUtils.isNotBlank(orignName)) { String fileName = orignName; if (!fileName.toLowerCase().endsWith(".properties")) { fileName += ".properties"; } fileName = ExecuteOpener.class.getSimpleName() + "_" + fileName; prop.clear(); DefaultListModel model = (DefaultListModel) execList.getModel(); for (Enumeration<?> enu = model.elements(); enu.hasMoreElements();) { String val = (String) enu.nextElement(); prop.put(val, ""); } saveFile = new File(jarPositionDir, fileName); } else { saveFile = currentPropFile; } prop.store(new FileOutputStream(saveFile), orignName); JOptionPaneUtil.newInstance().iconPlainMessage().showMessageDialog(saveFile, "PROPERTIES CREATE"); } }); swingUtil.addAction("clearExecList.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { // prop.clear(); // reloadExecListProperties(prop); execList.setModel(new DefaultListModel()); } }); swingUtil.addAction("execList.mouseClicked", new Action() { public void action(EventObject evt) throws Exception { // right button single click event if (JMouseEventUtil.buttonRightClick(1, evt)) { JPopupMenuUtil popupUtil = JPopupMenuUtil.newInstance(execList).applyEvent(evt); if (execList.getSelectedValues().length == 1) { popupUtil.addJMenuItem( JFileExecuteUtil.newInstance(new File((String) execList.getSelectedValues()[0])) .createDefaultJMenuItems()); popupUtil.addJMenuItem("----------------", false); } popupUtil.addJMenuItem("eclipse home", new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultListModel model = (DefaultListModel) execList.getModel(); Object[] arry = model.toArray(); for (Object obj : arry) { try { Runtime.getRuntime().exec(String.format("cmd /c call \"%s\" \"%s\"", "C:/?/eclipse_jee/eclipse.exe", obj)); } catch (IOException ex) { JCommonUtil.handleException(ex); } } } }); popupUtil.addJMenuItem("eclipse company", new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultListModel model = (DefaultListModel) execList.getModel(); Object[] arry = model.toArray(); for (Object obj : arry) { try { Runtime.getRuntime().exec(String.format("cmd /c call \"%s\" \"%s\"", "C:/?/iisi_eclipse/eclipse.exe", obj)); } catch (IOException ex) { JCommonUtil.handleException(ex); } } } }); popupUtil.addJMenuItem("----------------", false); popupUtil// .addJMenuItem("sort list", new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultListModel model = (DefaultListModel) execList.getModel(); Object[] arry = model.toArray(); Arrays.sort(arry); DefaultListModel model2 = new DefaultListModel(); for (Object obj : arry) { model2.addElement(obj); } execList.setModel(model2); } }).addJMenuItem("keep exists", new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultListModel model = (DefaultListModel) execList.getModel(); DefaultListModel model2 = new DefaultListModel(); for (Object obj : model.toArray()) { if (new File((String) obj).exists()) { model2.addElement(obj); } } execList.setModel(model2); } }).addJMenuItem("remove duplicate", new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultListModel model = (DefaultListModel) execList.getModel(); DefaultListModel model2 = new DefaultListModel(); Set<String> set = new HashSet<String>(); for (Object obj : model.toArray()) { set.add((String) obj); } for (String val : set) { model2.addElement(val); } execList.setModel(model2); } }).addJMenuItem("remove folder", new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultListModel model = (DefaultListModel) execList.getModel(); for (int ii = 0; ii < model.getSize(); ii++) { if (new File((String) model.getElementAt(ii)).isDirectory()) { model.removeElementAt(ii); ii--; } } } }).addJMenuItem("remove empty folder", new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultListModel model = (DefaultListModel) execList.getModel(); File dir = null; for (int ii = 0; ii < model.getSize(); ii++) { dir = new File((String) model.getElementAt(ii)); if (dir.isDirectory() && dir.list().length == 0) { model.removeElementAt(ii); ii--; } } } }).addJMenuItem("----------------", false) .addJMenuItem("diff left : " + (diffLeft != null ? diffLeft.getName() : ""), true, new ActionListener() { public void actionPerformed(ActionEvent arg0) { File value = new File( (String) JListUtil.getLeadSelectionObject(execList)); if (value != null && value.isFile() && value.exists()) { diffLeft = value; } } }) .addJMenuItem("diff right : " + (diffRight != null ? diffRight.getName() : ""), true, new ActionListener() { public void actionPerformed(ActionEvent arg0) { File value = new File( (String) JListUtil.getLeadSelectionObject(execList)); if (value != null && value.isFile() && value.exists()) { diffRight = value; } } }) .addJMenuItem((diffLeft != null && diffRight != null) ? "diff compare" : "", (diffLeft != null && diffRight != null), new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { Runtime.getRuntime().exec(String.format( "cmd /c call TortoiseMerge.exe /base:\"%s\" /theirs:\"%s\"", diffLeft, diffRight)); } catch (IOException ex) { JCommonUtil.handleException(ex); } } }) .addJMenuItem((execList.getSelectedValues().length == 2) ? "diff compare" : "", (execList.getSelectedValues().length == 2), new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { Runtime.getRuntime().exec(String.format( "cmd /c call TortoiseMerge.exe /base:\"%s\" /theirs:\"%s\"", execList.getSelectedValues()[0], execList.getSelectedValues()[1])); } catch (IOException ex) { JCommonUtil.handleException(ex); } } }) .addJMenuItem("----------------", false)// .show();// } // left button double click event int pos = execList.getLeadSelectionIndex(); if (pos == -1) { return; } if (((MouseEvent) evt).getClickCount() < 2) { return; } DefaultListModel model = (DefaultListModel) execList.getModel(); String val = (String) model.getElementAt(pos); exec(val); } }); swingUtil.addAction("loadProp.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { File file = JFileChooserUtil.newInstance().selectFileOnly().showOpenDialog() .getApproveSelectedFile(); if (file == null) { JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog("file not correct!", "ERROR"); return; } reloadExecListProperties(file); setTitle("load prop : " + file.getName()); } }); swingUtil.addAction("reloadList.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { reloadExecListProperties(prop); } }); swingUtil.addAction("exportListHasOrignTree.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { DefaultListModel model = (DefaultListModel) execList.getModel(); if (model.isEmpty()) { JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog("no file can export!", "ERROR"); return; } List<File> allList = new ArrayList<File>(); for (int ii = 0; ii < model.getSize(); ii++) { allList.add(new File((String) model.getElementAt(ii))); } File baseDir = FileUtil.exportReceiveBaseDir(allList); System.out.println("common base dir : " + baseDir); boolean dynamicBaseDir = baseDir == null; File tmp = null; File copyTo = null; int realCopyCount = 0; File exportListTo = FileUtil.getDefaultExportDir(ExecuteOpener.class, true); for (int ii = 0; ii < model.getSize(); ii++) { String val = (String) model.getElementAt(ii); if (StringUtils.isBlank(val)) { continue; } tmp = new File(val); if (tmp.isDirectory()) { continue; } File copyFrom = getCorrectFile(tmp); if (dynamicBaseDir) { baseDir = FileUtil.getRoot(copyFrom); } copyTo = FileUtil.exportFileToTargetPath(copyFrom, baseDir, exportListTo); if (!copyTo.getParentFile().exists()) { copyTo.getParentFile().mkdirs(); } System.out.println("## file : " + tmp + " -- > " + copyFrom); System.out.println("\t copy to : " + copyTo); FileUtil.copyFile(copyFrom, copyTo); realCopyCount++; } JOptionPaneUtil.newInstance().iconInformationMessage().showMessageDialog( "copy completed!\ntotal : " + model.getSize() + "\ncopy : " + realCopyCount, "SUCCESS"); } }); swingUtil.addAction("executeExport.actionPerformed", new Action() { public void action(EventObject evt) throws Exception { DefaultListModel model = (DefaultListModel) execList.getModel(); if (model.isEmpty()) { JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog("no file can export!", "ERROR"); return; } File tmp = null; File copyTo = null; int realCopyCount = 0; File exportListTo = FileUtil.getDefaultExportDir(ExecuteOpener.class, true); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(exportListTo + "/output_log.txt"), "BIG5")); for (int ii = 0; ii < model.getSize(); ii++) { String val = (String) model.getElementAt(ii); if (StringUtils.isBlank(val)) { continue; } tmp = new File(val); if (tmp.isDirectory()) { continue; } if (isNeedToCopy(exportListTo, tmp)) { File copyFrom = getCorrectFile(tmp); System.out.println("## file : " + tmp + " -- > " + copyFrom); copyTo = new File(exportListTo, copyFrom.getName()); for (int jj = 0; copyTo.exists(); jj++) { String name = copyFrom.getName(); int pos = name.lastIndexOf("."); String prefix = name.substring(0, pos); String rearfix = name.substring(pos); copyTo = new File(exportListTo, prefix + "_R" + jj + rearfix); } FileUtil.copyFile(copyFrom, copyTo); writer.write(tmp.getAbsolutePath() + (!tmp.getName().equals(copyTo.getName()) ? "\t [rename] : " + copyTo.getName() : "")); realCopyCount++; } else { writer.write(tmp.getAbsolutePath() + "\t [has same file, ommit!]"); } writer.newLine(); } writer.flush(); writer.close(); JOptionPaneUtil.newInstance().iconInformationMessage().showMessageDialog( "copy completed!\ntotal : " + model.getSize() + "\ncopy : " + realCopyCount, "SUCCESS"); } }); swingUtil.addAction("jTabbedPane1.mouseClicked", new Action() { public void action(EventObject evt) throws Exception { if (!JMouseEventUtil.buttonLeftClick(2, evt)) { return; } File file = new File(getTitle()); if (file.exists()) { JOptionPaneUtil.newInstance().iconPlainMessage().showMessageDialog(file, "current properties"); } ClipboardUtil.getInstance().setContents(file); } }); swingUtil.addAction("propertiesList.mouseClicked", new Action() { public void action(EventObject evt) throws Exception { File file = (File) propertiesList.getSelectedValue(); JPopupMenuUtil.newInstance(propertiesList).applyEvent(evt) .addJMenuItem("reload list", new ActionListener() { public void actionPerformed(ActionEvent paramActionEvent) { reloadCurrentDirPropertiesList(); } }).addJMenuItem(JFileExecuteUtil.newInstance(file).createDefaultJMenuItems()).show(); if (file == null) { return; } if (!JMouseEventUtil.buttonLeftClick(2, evt)) { return; } prop.clear(); prop.load(new FileInputStream(file)); currentPropFile = file; reloadExecListProperties(prop); setTitle("properties : " + file.getName()); } }); swingUtil.addAction("propertiesList.keyPressed", new Action() { public void action(EventObject evt) throws Exception { if (!JMouseEventUtil.buttonLeftClick(2, evt)) { return; } JListUtil.newInstance(propertiesList).defaultJListKeyPressed(evt); } }); swingUtil.addAction("jTabbedPane1.stateChanged", new Action() { public void action(EventObject evt) throws Exception { if (jTabbedPane1.getSelectedIndex() == 2) { reloadCurrentDirPropertiesList(); } } }); swingUtil.addAction("scanList.keyPressed", new Action() { public void action(EventObject evt) throws Exception { JListUtil.newInstance(scanList).defaultJListKeyPressed(evt); } }); swingUtil.addAction("scanList.mouseClicked", new Action() { public void action(EventObject evt) throws Exception { System.out.println("index = " + scanList.getLeadSelectionIndex()); final Object[] vals = scanList.getSelectedValues(); if (vals == null || vals.length == 0) { return; } JPopupMenuUtil.newInstance(scanList).applyEvent(evt) .addJMenuItem("add to file list : " + vals.length, new ActionListener() { public void actionPerformed(ActionEvent arg0) { File file = null; DefaultListModel model = (DefaultListModel) execList.getModel(); for (Object v : vals) { file = (File) v; model.addElement(file.getAbsolutePath()); } } }).show(); } }); swingUtil.addAction("fileScan.actionPerformed", new Action() { Thread scanMainThread = null; public void action(EventObject evt) throws Exception { String scanText_ = scannerText.getText(); final boolean anyFileMatch = StringUtils.isEmpty(scanText_); final String scanText = anyFileMatch ? UUID.randomUUID().toString() : scanText_; final FileOrDirType fileOrDirType = (FileOrDirType) fileOrDirTypeCombo.getSelectedItem(); String scanDir_ = scanDirText.getText(); final File scanDir = new File(scanDir_); if (StringUtils.isEmpty(scanDir_)) { JOptionPaneUtil.newInstance().iconErrorMessage() .showMessageDialog("scan dir text can't empty!", "ERROR"); return; } if (!scanDir.exists()) { JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog("directory is't exists!", "ERROR"); return; } Object[] igArry_ = ((DefaultListModel) ignoreScanList.getModel()).toArray(); final String[] igArry = new String[igArry_.length]; for (int ii = 0; ii < igArry.length; ii++) { igArry[ii] = (String) igArry_[ii]; } final boolean ignoreCheck = igArry.length > 0; final DefaultListModel model = new DefaultListModel(); final StringTokenizer tok = new StringTokenizer(scanText); if (scanMainThread == null || scanMainThread.getState() == Thread.State.TERMINATED) { scanMainThread = new Thread(Thread.currentThread().getThreadGroup(), new Runnable() { ScanType scanTp; public void run() { currentScannerThreadStop = false; final long startTime = System.currentTimeMillis(); scanTp = (ScanType) scanType.getSelectedItem(); List<Thread> threadList = new ArrayList<Thread>(); final Map<String, Integer> matchCountMap = new HashMap<String, Integer>(); for (; tok.hasMoreElements();) { final String scanVal = (String) tok.nextElement(); System.out.println("add scan condition = " + scanVal); Pattern ppp = null; try { ppp = Pattern.compile(scanVal); } catch (Exception ex) { System.out.println(ex); } final Pattern scanTextPattern = ppp; Thread currentScannerThread = new Thread( Thread.currentThread().getThreadGroup(), new Runnable() { int matchCount = 0; void addElement(File file) { if (scanTp.filter(anyFileMatch, scanVal, scanTextPattern, file, ignoreCheck, igArry)) { for (int ii = 0;; ii++) { try { model.addElement(file); matchCount++; break; } catch (Exception ex) { System.err.println( file + ", error occor !!! ==> " + ex); if (ii > 10) { break; } } } } } void find(File file) { if (currentScannerThreadStop) { return; } if (file == null || !file.exists()) { System.out .println("file == null || !file.exists()\t" + file); return; } scannerStatus.setText( model.getSize() + " : " + file.getAbsolutePath()); if (file.isDirectory()) { if (file.listFiles() != null) { for (File f : file.listFiles()) { find(f); } } else { System.out .println("file.listFiles() == null!!\t" + file); } switch (fileOrDirType) { case DIRECTORY_ONLY: addElement(file); break; case ALL: addElement(file); break; } } if (file.isFile()) { switch (fileOrDirType) { case FILE_ONLY: addElement(file); break; case ALL: addElement(file); break; } } } public void run() { find(scanDir); matchCountMap.put(scanVal, matchCount); } }, "file_scann_" + System.currentTimeMillis()); currentScannerThread.setDaemon(true); currentScannerThread.start(); threadList.add(currentScannerThread); } for (;;) { try { Thread.sleep(1000); boolean allTerminated = true; for (int ii = 0; ii < threadList.size(); ii++) { if (threadList.get(ii).getState() != Thread.State.TERMINATED) { allTerminated = false; break; } } if (allTerminated) { System.out.println("all done..."); break; } } catch (InterruptedException e) { JCommonUtil.handleException(e); } } long endTime = System.currentTimeMillis() - startTime; String status = "scan completed \n during :" + endTime + "\n file : " + model.getSize() + "\n \tResult : \n " + matchCountMap; JOptionPaneUtil.newInstance().iconPlainMessage().showMessageDialog(status, "COMPLETED"); scannerStatus.setText(status); scanList.setModel(model); arrayBackupForInnerScan = ((DefaultListModel) scanList.getModel()).toArray(); currentScannerThreadStop = false; } }, "file_scann_main_" + System.currentTimeMillis()); scanMainThread.setDaemon(true); scanMainThread.start(); } else { if (JCommonUtil._JOptionPane_showConfirmDialog_yesNoOption( "scanner is running \n want to stop??", "WARNING")) { currentScannerThreadStop = true; } } } }); swingUtil.addAction("scanDirText.mouseClicked", new Action() { public void action(EventObject evt) throws Exception { if (!JMouseEventUtil.buttonLeftClick(2, evt)) { return; } File dir = JFileChooserUtil.newInstance().selectDirectoryOnly().showOpenDialog() .getApproveSelectedFile(); if (dir == null) { return; } scanDirText.setText(dir.getAbsolutePath()); } }); swingUtil.addAction("addListToExecList.actionPerformed", new Action() { Thread moveThread = null; public void action(EventObject evt) throws Exception { if (moveThread != null && moveThread.getState() != Thread.State.TERMINATED) { JCommonUtil._jOptionPane_showMessageDialog_error("add list process already running!"); return; } moveThread = new Thread(Thread.currentThread().getThreadGroup(), new Runnable() { public void run() { DefaultListModel model = (DefaultListModel) scanList.getModel(); DefaultListModel model2 = (DefaultListModel) execList.getModel(); for (int ii = 0; ii < model.getSize(); ii++) { File f = (File) model.getElementAt(ii); model2.addElement(f.getAbsolutePath()); } if (model.getSize() > 1000) { JCommonUtil._jOptionPane_showMessageDialog_info( "add list completed!\n" + model.getSize()); } } }, "addListToExecList.actionPerformed_" + System.currentTimeMillis()); moveThread.setDaemon(true); moveThread.start(); } }); swingUtil.addAction("openSvnUpdate.actionPerformed", new Action() { Pattern svnPattern = Pattern.compile("^(?:[M|\\?])\\s+\\d*\\s+(.+)$"); Thread svnThread = null; public void action(EventObject evt) throws Exception { if (svnThread != null && svnThread.getState() != Thread.State.TERMINATED) { JCommonUtil._jOptionPane_showMessageDialog_error("svn scan process already running!"); return; } final File svnDir = JCommonUtil._jFileChooser_selectDirectoryOnly(); if (svnDir == null) { JCommonUtil._jOptionPane_showMessageDialog_error("dir is not correct!"); return; } svnThread = new Thread(Thread.currentThread().getThreadGroup(), new Runnable() { public void run() { try { Process process = Runtime.getRuntime() .exec(String.format("svn status -u \"%s\"", svnDir)); BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream())); Matcher matcher = null; File file = null; DefaultListModel model = new DefaultListModel(); List<File> scanList = new ArrayList<File>(); for (String line = null; (line = reader.readLine()) != null;) { matcher = svnPattern.matcher(line); if (matcher.find()) { file = new File(matcher.group(1)); if (file.isFile()) { model.addElement(file.getAbsolutePath()); } if (file.isDirectory()) { scanList.clear(); FileUtil.searchFileMatchs(file, ".*", scanList); for (File f : scanList) { model.addElement(f.getAbsolutePath()); } } } else { System.out.println("ignore : [" + line + "]"); } } reader.close(); execList.setModel(model); setTitle("svn : " + svnDir); JCommonUtil._jOptionPane_showMessageDialog_info("svn scan completed!"); } catch (IOException e) { JCommonUtil.handleException(e); } } }, "svn_scan" + System.currentTimeMillis()); svnThread.setDaemon(true); svnThread.start(); } }); swingUtil.addAction("contentFilterBtn.actionPerformed", new Action() { Thread thread = null; String encode = Charset.defaultCharset().displayName(); public void action(EventObject evt) throws Exception { if (thread != null && thread.getState() != Thread.State.TERMINATED) { JCommonUtil._jOptionPane_showMessageDialog_error("scan process already running!"); return; } final String filter = JCommonUtil._jOptionPane_showInputDialog("input filter content?"); if (StringUtils.isEmpty(filter)) { JCommonUtil._jOptionPane_showMessageDialog_error("filter is empty!"); return; } Pattern tmpPattern = null; try { tmpPattern = Pattern.compile(filter); } catch (Exception ex) { } final Pattern filterPattern = tmpPattern; try { encode = JCommonUtil._jOptionPane_showInputDialog("input encode?", encode); } catch (Exception ex) { JCommonUtil._jOptionPane_showMessageDialog_error("error encode!"); return; } thread = new Thread(Thread.currentThread().getThreadGroup(), new Runnable() { public void run() { DefaultListModel model = (DefaultListModel) execList.getModel(); DefaultListModel model_ = new DefaultListModel(); File file = null; BufferedReader reader = null; for (int ii = 0; ii < model.getSize(); ii++) { file = new File((String) model.getElementAt(ii)); if (!file.exists()) { continue; } try { reader = new BufferedReader( new InputStreamReader(new FileInputStream(file), encode)); for (String line = null; (line = reader.readLine()) != null;) { if (line.contains(filter)) { model_.addElement(file.getAbsolutePath()); break; } if (filterPattern != null && filterPattern.matcher(line).find()) { model_.addElement(file.getAbsolutePath()); break; } } reader.close(); } catch (Exception e) { JCommonUtil.handleException(e); } } execList.setModel(model_); JCommonUtil._jOptionPane_showMessageDialog_info("completed!"); } }, UUID.randomUUID().toString()); thread.setDaemon(true); thread.start(); } }); swingUtil.addAction("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", new Action() { public void action(EventObject evt) throws Exception { } }); this.setSize(870, 551); } catch (Exception e) { e.printStackTrace(); } }
From source file:ffx.potential.parsers.BiojavaFilter.java
/** * <p>/*from w w w . j a va 2s . c o m*/ * writeAtom</p> * * @param atom a {@link ffx.potential.bonded.Atom} object. * @param serial a int. * @param sb a {@link java.lang.StringBuilder} object. * @param anisouSB a {@link java.lang.StringBuilder} object. * @param bw a {@link java.io.BufferedWriter} object. * @throws java.io.IOException if any. */ public void writeAtom(Atom atom, int serial, StringBuilder sb, StringBuilder anisouSB, BufferedWriter bw) throws IOException { String name = atom.getName(); if (name.length() > 4) { name = name.substring(0, 4); } else if (name.length() == 1) { name = name + " "; } else if (name.length() == 2) { if (atom.getAtomType().valence == 0) { name = name + " "; } else { name = name + " "; } } double xyz[] = vdwH ? atom.getRedXYZ() : atom.getXYZ(null); sb.replace(6, 16, String.format("%5s " + padLeft(name.toUpperCase(), 4), Hybrid36.encode(5, serial))); Character altLoc = atom.getAltLoc(); if (altLoc != null) { sb.setCharAt(16, altLoc); } else { sb.setCharAt(16, ' '); } sb.replace(30, 66, String.format("%8.3f%8.3f%8.3f%6.2f%6.2f", xyz[0], xyz[1], xyz[2], atom.getOccupancy(), atom.getTempFactor())); name = Atom.ElementSymbol.values()[atom.getAtomicNumber() - 1].toString(); name = name.toUpperCase(); if (atom.isDeuterium()) { name = "D"; } sb.replace(76, 78, padLeft(name, 2)); sb.replace(78, 80, String.format("%2d", 0)); if (!listMode) { bw.write(sb.toString()); bw.newLine(); } else { listOutput.add(sb.toString()); } // ============================================================================= // 1 - 6 Record name "ANISOU" // 7 - 11 Integer serial Atom serial number. // 13 - 16 Atom name Atom name. // 17 Character altLoc Alternate location indicator // 18 - 20 Residue name resName Residue name. // 22 Character chainID Chain identifier. // 23 - 26 Integer resSeq Residue sequence number. // 27 AChar iCode Insertion code. // 29 - 35 Integer u[0][0] U(1,1) // 36 - 42 Integer u[1][1] U(2,2) // 43 - 49 Integer u[2][2] U(3,3) // 50 - 56 Integer u[0][1] U(1,2) // 57 - 63 Integer u[0][2] U(1,3) // 64 - 70 Integer u[1][2] U(2,3) // 77 - 78 LString(2) element Element symbol, right-justified. // 79 - 80 LString(2) charge Charge on the atom. // ============================================================================= double[] anisou = atom.getAnisou(null); if (anisou != null) { anisouSB.replace(6, 80, sb.substring(6, 80)); anisouSB.replace(28, 70, String.format("%7d%7d%7d%7d%7d%7d", (int) (anisou[0] * 1e4), (int) (anisou[1] * 1e4), (int) (anisou[2] * 1e4), (int) (anisou[3] * 1e4), (int) (anisou[4] * 1e4), (int) (anisou[5] * 1e4))); if (!listMode) { bw.write(anisouSB.toString()); bw.newLine(); } else { listOutput.add(anisouSB.toString()); } } }
From source file:ffx.potential.parsers.BiojavaFilter.java
public void writeSIFTAtom(Atom atom, int serial, StringBuilder sb, StringBuilder anisouSB, BufferedWriter bw, String siftScore) throws IOException { String name = atom.getName(); if (name.length() > 4) { name = name.substring(0, 4);//w w w. j a va 2 s.c o m } else if (name.length() == 1) { name = name + " "; } else if (name.length() == 2) { if (atom.getAtomType().valence == 0) { name = name + " "; } else { name = name + " "; } } double xyz[] = vdwH ? atom.getRedXYZ() : atom.getXYZ(null); sb.replace(6, 16, String.format("%5s " + padLeft(name.toUpperCase(), 4), Hybrid36.encode(5, serial))); Character altLoc = atom.getAltLoc(); if (altLoc != null) { sb.setCharAt(16, altLoc); } else { sb.setCharAt(16, ' '); } if (siftScore == null) { sb.replace(30, 66, String.format("%8.3f%8.3f%8.3f%6.2f%6.2f", xyz[0], xyz[1], xyz[2], atom.getOccupancy(), 110.0)); } else { sb.replace(30, 66, String.format("%8.3f%8.3f%8.3f%6.2f%6.2f", xyz[0], xyz[1], xyz[2], atom.getOccupancy(), (1 + (-1 * Float.parseFloat(siftScore))) * 100)); } name = Atom.ElementSymbol.values()[atom.getAtomicNumber() - 1].toString(); name = name.toUpperCase(); if (atom.isDeuterium()) { name = "D"; } sb.replace(76, 78, padLeft(name, 2)); sb.replace(78, 80, String.format("%2d", 0)); if (!listMode) { bw.write(sb.toString()); bw.newLine(); } else { listOutput.add(sb.toString()); } // ============================================================================= // 1 - 6 Record name "ANISOU" // 7 - 11 Integer serial Atom serial number. // 13 - 16 Atom name Atom name. // 17 Character altLoc Alternate location indicator // 18 - 20 Residue name resName Residue name. // 22 Character chainID Chain identifier. // 23 - 26 Integer resSeq Residue sequence number. // 27 AChar iCode Insertion code. // 29 - 35 Integer u[0][0] U(1,1) // 36 - 42 Integer u[1][1] U(2,2) // 43 - 49 Integer u[2][2] U(3,3) // 50 - 56 Integer u[0][1] U(1,2) // 57 - 63 Integer u[0][2] U(1,3) // 64 - 70 Integer u[1][2] U(2,3) // 77 - 78 LString(2) element Element symbol, right-justified. // 79 - 80 LString(2) charge Charge on the atom. // ============================================================================= double[] anisou = atom.getAnisou(null); if (anisou != null) { anisouSB.replace(6, 80, sb.substring(6, 80)); anisouSB.replace(28, 70, String.format("%7d%7d%7d%7d%7d%7d", (int) (anisou[0] * 1e4), (int) (anisou[1] * 1e4), (int) (anisou[2] * 1e4), (int) (anisou[3] * 1e4), (int) (anisou[4] * 1e4), (int) (anisou[5] * 1e4))); if (!listMode) { bw.write(anisouSB.toString()); bw.newLine(); } else { listOutput.add(anisouSB.toString()); } } }
From source file:ffx.potential.parsers.PDBFilter.java
/** * <p>//from w w w . j av a 2s . c o m * writeFile</p> * * @param saveFile a {@link java.io.File} object. * @param append a {@link java.lang.StringBuilder} object. * @param printLinear Whether to print atoms linearly or by element * @return Success of writing. */ public boolean writeFile(File saveFile, boolean append, boolean printLinear) { if (saveFile == null) { return false; } if (vdwH) { logger.info(" Printing hydrogens to van der Waals centers instead of nuclear locations."); } if (nSymOp != 0) { logger.info(String.format(" Printing atoms with symmetry operator %s\n", activeMolecularAssembly.getCrystal().spaceGroup.getSymOp(nSymOp).toString())); } /** * Create StringBuilders for ATOM, ANISOU and TER records that can be * reused. */ StringBuilder sb = new StringBuilder("ATOM "); StringBuilder anisouSB = new StringBuilder("ANISOU"); StringBuilder terSB = new StringBuilder("TER "); StringBuilder model = null; for (int i = 6; i < 80; i++) { sb.append(' '); anisouSB.append(' '); terSB.append(' '); } FileWriter fw; BufferedWriter bw; try { File newFile = saveFile; if (!append) { if (!noVersioning) { newFile = version(saveFile); } } else if (modelsWritten >= 0) { model = new StringBuilder(String.format("MODEL %-4d", ++modelsWritten)); for (int i = 15; i < 80; i++) { model.append(' '); } } activeMolecularAssembly.setFile(newFile); activeMolecularAssembly.setName(newFile.getName()); if (logWrites) { logger.log(Level.INFO, " Saving {0}", newFile.getName()); } fw = new FileWriter(newFile, append); bw = new BufferedWriter(fw); /** * Will come before CRYST1 and ATOM records, but after anything * written by writeFileWithHeader (particularly X-ray refinement * statistics). */ String[] headerLines = activeMolecularAssembly.getHeaderLines(); for (String line : headerLines) { bw.write(String.format("%s\n", line)); } if (model != null) { if (!listMode) { bw.write(model.toString()); bw.newLine(); } else { listOutput.add(model.toString()); } } // ============================================================================= // The CRYST1 record presents the unit cell parameters, space group, and Z // value. If the structure was not determined by crystallographic means, CRYST1 // simply provides the unitary values, with an appropriate REMARK. // // 7 - 15 Real(9.3) a a (Angstroms). // 16 - 24 Real(9.3) b b (Angstroms). // 25 - 33 Real(9.3) c c (Angstroms). // 34 - 40 Real(7.2) alpha alpha (degrees). // 41 - 47 Real(7.2) beta beta (degrees). // 48 - 54 Real(7.2) gamma gamma (degrees). // 56 - 66 LString sGroup Space group. // 67 - 70 Integer z Z value. // ============================================================================= Crystal crystal = activeMolecularAssembly.getCrystal(); if (crystal != null && !crystal.aperiodic()) { Crystal c = crystal.getUnitCell(); if (!listMode) { bw.write(format("CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %10s\n", c.a, c.b, c.c, c.alpha, c.beta, c.gamma, padRight(c.spaceGroup.pdbName, 10))); } else { listOutput.add(format("CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %10s", c.a, c.b, c.c, c.alpha, c.beta, c.gamma, padRight(c.spaceGroup.pdbName, 10))); } } // ============================================================================= // The SSBOND record identifies each disulfide bond in protein and polypeptide // structures by identifying the two residues involved in the bond. // The disulfide bond distance is included after the symmetry operations at // the end of the SSBOND record. // // 8 - 10 Integer serNum Serial number. // 12 - 14 LString(3) "CYS" Residue name. // 16 Character chainID1 Chain identifier. // 18 - 21 Integer seqNum1 Residue sequence number. // 22 AChar icode1 Insertion code. // 26 - 28 LString(3) "CYS" Residue name. // 30 Character chainID2 Chain identifier. // 32 - 35 Integer seqNum2 Residue sequence number. // 36 AChar icode2 Insertion code. // 60 - 65 SymOP sym1 Symmetry oper for 1st resid // 67 - 72 SymOP sym2 Symmetry oper for 2nd resid // 74 78 Real(5.2) Length Disulfide bond distance // // If SG of cysteine is disordered then there are possible alternate linkages. // wwPDB practice is to put together all possible SSBOND records. This is // problematic because the alternate location identifier is not specified in // the SSBOND record. // ============================================================================= int serNum = 1; Polymer polymers[] = activeMolecularAssembly.getChains(); if (polymers != null) { for (Polymer polymer : polymers) { ArrayList<Residue> residues = polymer.getResidues(); for (Residue residue : residues) { if (residue.getName().equalsIgnoreCase("CYS")) { List<Atom> cysAtoms = residue.getAtomList(); Atom SG1 = null; for (Atom atom : cysAtoms) { if (atom.getName().equalsIgnoreCase("SG")) { SG1 = atom; break; } } List<Bond> bonds = SG1.getBonds(); for (Bond bond : bonds) { Atom SG2 = bond.get1_2(SG1); if (SG2.getName().equalsIgnoreCase("SG")) { if (SG1.xyzIndex < SG2.xyzIndex) { bond.energy(false); if (!listMode) { bw.write(format("SSBOND %3d CYS %1s %4s CYS %1s %4s %36s %5.2f\n", serNum++, SG1.getChainID().toString(), Hybrid36.encode(4, SG1.getResidueNumber()), SG2.getChainID().toString(), Hybrid36.encode(4, SG2.getResidueNumber()), "", bond.getValue())); } else { listOutput.add( format("SSBOND %3d CYS %1s %4s CYS %1s %4s %36s %5.2f\n", serNum++, SG1.getChainID().toString(), Hybrid36.encode(4, SG1.getResidueNumber()), SG2.getChainID().toString(), Hybrid36.encode(4, SG2.getResidueNumber()), "", bond.getValue())); } } } } } } } } // ============================================================================= // // 7 - 11 Integer serial Atom serial number. // 13 - 16 Atom name Atom name. // 17 Character altLoc Alternate location indicator. // 18 - 20 Residue name resName Residue name. // 22 Character chainID Chain identifier. // 23 - 26 Integer resSeq Residue sequence number. // 27 AChar iCode Code for insertion of residues. // 31 - 38 Real(8.3) x Orthogonal coordinates for X in Angstroms. // 39 - 46 Real(8.3) y Orthogonal coordinates for Y in Angstroms. // 47 - 54 Real(8.3) z Orthogonal coordinates for Z in Angstroms. // 55 - 60 Real(6.2) occupancy Occupancy. // 61 - 66 Real(6.2) tempFactor Temperature factor. // 77 - 78 LString(2) element Element symbol, right-justified. // 79 - 80 LString(2) charge Charge on the atom. // ============================================================================= // 1 2 3 4 5 6 7 //123456789012345678901234567890123456789012345678901234567890123456789012345678 //ATOM 1 N ILE A 16 60.614 71.140 -10.592 1.00 7.38 N //ATOM 2 CA ILE A 16 60.793 72.149 -9.511 1.00 6.91 C MolecularAssembly molecularAssemblies[] = this.getMolecularAssemblys(); int serial = 1; // Loop over biomolecular chains if (polymers != null) { for (Polymer polymer : polymers) { currentSegID = polymer.getName(); currentChainID = polymer.getChainID(); sb.setCharAt(21, currentChainID); // Loop over residues ArrayList<Residue> residues = polymer.getResidues(); for (Residue residue : residues) { String resName = residue.getName(); if (resName.length() > 3) { resName = resName.substring(0, 3); } int resID = residue.getResidueNumber(); sb.replace(17, 20, padLeft(resName.toUpperCase(), 3)); sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID))); // Loop over atoms ArrayList<Atom> residueAtoms = residue.getAtomList(); ArrayList<Atom> backboneAtoms = residue.getBackboneAtoms(); boolean altLocFound = false; for (Atom atom : backboneAtoms) { writeAtom(atom, serial++, sb, anisouSB, bw); Character altLoc = atom.getAltLoc(); if (altLoc != null && !altLoc.equals(' ')) { altLocFound = true; } residueAtoms.remove(atom); } for (Atom atom : residueAtoms) { writeAtom(atom, serial++, sb, anisouSB, bw); Character altLoc = atom.getAltLoc(); if (altLoc != null && !altLoc.equals(' ')) { altLocFound = true; } } // Write out alternate conformers if (altLocFound) { for (int ma = 1; ma < molecularAssemblies.length; ma++) { MolecularAssembly altMolecularAssembly = molecularAssemblies[ma]; Polymer altPolymer = altMolecularAssembly.getPolymer(currentChainID, currentSegID, false); Residue altResidue = altPolymer.getResidue(resName, resID, false); backboneAtoms = altResidue.getBackboneAtoms(); residueAtoms = altResidue.getAtomList(); for (Atom atom : backboneAtoms) { if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ') && !atom.getAltLoc().equals('A')) { writeAtom(atom, serial++, sb, anisouSB, bw); } residueAtoms.remove(atom); } for (Atom atom : residueAtoms) { if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ') && !atom.getAltLoc().equals('A')) { writeAtom(atom, serial++, sb, anisouSB, bw); } } } } } terSB.replace(6, 11, String.format("%5s", Hybrid36.encode(5, serial++))); terSB.replace(12, 16, " "); terSB.replace(16, 26, sb.substring(16, 26)); if (!listMode) { bw.write(terSB.toString()); bw.newLine(); } else { listOutput.add(terSB.toString()); } } } sb.replace(0, 6, "HETATM"); sb.setCharAt(21, 'A'); int resID = 1; Polymer polymer = activeMolecularAssembly.getPolymer('A', "A", false); if (polymer != null) { ArrayList<Residue> residues = polymer.getResidues(); for (Residue residue : residues) { int resID2 = residue.getResidueNumber(); if (resID2 >= resID) { resID = resID2 + 1; } } } /** * Loop over molecules, ions and then water. */ ArrayList<Molecule> molecules = activeMolecularAssembly.getMolecules(); for (int i = 0; i < molecules.size(); i++) { Molecule molecule = (Molecule) molecules.get(i); Character chainID = molecule.getChainID(); sb.setCharAt(21, chainID); String resName = molecule.getResidueName(); if (resName.length() > 3) { resName = resName.substring(0, 3); } sb.replace(17, 20, padLeft(resName.toUpperCase(), 3)); sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID))); ArrayList<Atom> moleculeAtoms = molecule.getAtomList(); boolean altLocFound = false; for (Atom atom : moleculeAtoms) { writeAtom(atom, serial++, sb, anisouSB, bw); Character altLoc = atom.getAltLoc(); if (altLoc != null && !altLoc.equals(' ')) { altLocFound = true; } } // Write out alternate conformers if (altLocFound) { for (int ma = 1; ma < molecularAssemblies.length; ma++) { MolecularAssembly altMolecularAssembly = molecularAssemblies[ma]; MSNode altmolecule = altMolecularAssembly.getMolecules().get(i); moleculeAtoms = altmolecule.getAtomList(); for (Atom atom : moleculeAtoms) { if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ') && !atom.getAltLoc().equals('A')) { writeAtom(atom, serial++, sb, anisouSB, bw); } } } } resID++; } ArrayList<MSNode> ions = activeMolecularAssembly.getIons(); for (int i = 0; i < ions.size(); i++) { Molecule ion = (Molecule) ions.get(i); Character chainID = ion.getChainID(); sb.setCharAt(21, chainID); String resName = ion.getResidueName(); if (resName.length() > 3) { resName = resName.substring(0, 3); } sb.replace(17, 20, padLeft(resName.toUpperCase(), 3)); sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID))); ArrayList<Atom> ionAtoms = ion.getAtomList(); boolean altLocFound = false; for (Atom atom : ionAtoms) { writeAtom(atom, serial++, sb, anisouSB, bw); Character altLoc = atom.getAltLoc(); if (altLoc != null && !altLoc.equals(' ')) { altLocFound = true; } } // Write out alternate conformers if (altLocFound) { for (int ma = 1; ma < molecularAssemblies.length; ma++) { MolecularAssembly altMolecularAssembly = molecularAssemblies[ma]; MSNode altion = altMolecularAssembly.getIons().get(i); ionAtoms = altion.getAtomList(); for (Atom atom : ionAtoms) { if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ') && !atom.getAltLoc().equals('A')) { writeAtom(atom, serial++, sb, anisouSB, bw); } } } } resID++; } ArrayList<MSNode> waters = activeMolecularAssembly.getWaters(); for (int i = 0; i < waters.size(); i++) { Molecule water = (Molecule) waters.get(i); Character chainID = water.getChainID(); sb.setCharAt(21, chainID); String resName = water.getResidueName(); if (resName.length() > 3) { resName = resName.substring(0, 3); } sb.replace(17, 20, padLeft(resName.toUpperCase(), 3)); sb.replace(22, 26, String.format("%4s", Hybrid36.encode(4, resID))); ArrayList<Atom> waterAtoms = water.getAtomList(); boolean altLocFound = false; for (Atom atom : waterAtoms) { writeAtom(atom, serial++, sb, anisouSB, bw); Character altLoc = atom.getAltLoc(); if (altLoc != null && !altLoc.equals(' ')) { altLocFound = true; } } // Write out alternate conformers if (altLocFound) { for (int ma = 1; ma < molecularAssemblies.length; ma++) { MolecularAssembly altMolecularAssembly = molecularAssemblies[ma]; MSNode altwater = altMolecularAssembly.getWaters().get(i); waterAtoms = altwater.getAtomList(); for (Atom atom : waterAtoms) { if (atom.getAltLoc() != null && !atom.getAltLoc().equals(' ') && !atom.getAltLoc().equals('A')) { writeAtom(atom, serial++, sb, anisouSB, bw); } } } } resID++; } String end = model != null ? "ENDMDL" : "END"; if (!listMode) { bw.write(end); bw.newLine(); } else { listOutput.add(end); } bw.close(); } catch (Exception e) { String message = "Exception writing to file: " + saveFile.toString(); logger.log(Level.WARNING, message, e); return false; } return true; }
From source file:ffx.potential.parsers.PDBFilter.java
private void writeSIFTAtom(Atom atom, int serial, StringBuilder sb, StringBuilder anisouSB, BufferedWriter bw, String siftScore) throws IOException { String name = atom.getName(); if (name.length() > 4) { name = name.substring(0, 4);// w ww .j a v a2 s.c o m } else if (name.length() == 1) { name = name + " "; } else if (name.length() == 2) { if (atom.getAtomType().valence == 0) { name = name + " "; } else { name = name + " "; } } double xyz[] = vdwH ? atom.getRedXYZ() : atom.getXYZ(null); if (nSymOp != 0) { Crystal crystal = activeMolecularAssembly.getCrystal(); SymOp symOp = crystal.spaceGroup.getSymOp(nSymOp); double[] newXYZ = new double[xyz.length]; crystal.applySymOp(xyz, newXYZ, symOp); xyz = newXYZ; } sb.replace(6, 16, String.format("%5s " + padLeft(name.toUpperCase(), 4), Hybrid36.encode(5, serial))); Character altLoc = atom.getAltLoc(); if (altLoc != null) { sb.setCharAt(16, altLoc); } else { sb.setCharAt(16, ' '); } if (siftScore == null) { sb.replace(30, 66, String.format("%8.3f%8.3f%8.3f%6.2f%6.2f", xyz[0], xyz[1], xyz[2], atom.getOccupancy(), 110.0)); } else { sb.replace(30, 66, String.format("%8.3f%8.3f%8.3f%6.2f%6.2f", xyz[0], xyz[1], xyz[2], atom.getOccupancy(), (1 + (-1 * Float.parseFloat(siftScore))) * 100)); } name = Atom.ElementSymbol.values()[atom.getAtomicNumber() - 1].toString(); name = name.toUpperCase(); if (atom.isDeuterium()) { name = "D"; } sb.replace(76, 78, padLeft(name, 2)); sb.replace(78, 80, String.format("%2d", 0)); if (!listMode) { bw.write(sb.toString()); bw.newLine(); } else { listOutput.add(sb.toString()); } // ============================================================================= // 1 - 6 Record name "ANISOU" // 7 - 11 Integer serial Atom serial number. // 13 - 16 Atom name Atom name. // 17 Character altLoc Alternate location indicator // 18 - 20 Residue name resName Residue name. // 22 Character chainID Chain identifier. // 23 - 26 Integer resSeq Residue sequence number. // 27 AChar iCode Insertion code. // 29 - 35 Integer u[0][0] U(1,1) // 36 - 42 Integer u[1][1] U(2,2) // 43 - 49 Integer u[2][2] U(3,3) // 50 - 56 Integer u[0][1] U(1,2) // 57 - 63 Integer u[0][2] U(1,3) // 64 - 70 Integer u[1][2] U(2,3) // 77 - 78 LString(2) element Element symbol, right-justified. // 79 - 80 LString(2) charge Charge on the atom. // ============================================================================= double[] anisou = atom.getAnisou(null); if (anisou != null) { anisouSB.replace(6, 80, sb.substring(6, 80)); anisouSB.replace(28, 70, String.format("%7d%7d%7d%7d%7d%7d", (int) (anisou[0] * 1e4), (int) (anisou[1] * 1e4), (int) (anisou[2] * 1e4), (int) (anisou[3] * 1e4), (int) (anisou[4] * 1e4), (int) (anisou[5] * 1e4))); if (!listMode) { bw.write(anisouSB.toString()); bw.newLine(); } else { listOutput.add(anisouSB.toString()); } } }
From source file:de.dfki.km.perspecting.obie.connection.RDFTripleParser.java
/** * // w ww . j av a 2 s . c om * @param input * @param mimetype * @param sessionPath * @param absoluteBaseURI * @return * @throws Exception */ public TripleStats parseTriples(final InputStream[] input, final MediaType rdf_mimetype, final File sessionPath, final String absoluteBaseURI, final MediaType file_mimetype) throws Exception { final TripleStats stats = new TripleStats(); // int count = 0; new File(sessionPath.getAbsolutePath() + "/dump/").mkdirs(); stats.datatypeProps = new File(sessionPath.getAbsolutePath() + "/dump/datatypeProperties.lst"); stats.objectProps = new File(sessionPath.getAbsolutePath() + "/dump/objectProperties.lst"); stats.datatypeProps.deleteOnExit(); stats.objectProps.deleteOnExit(); stats.datatypeProps.setReadable(true, false); stats.objectProps.setReadable(true, false); if (stats.datatypeProps.exists() && stats.objectProps.exists()) { return stats; } // stats.literalLanguageList = new File(sessionPath + // "/dump/literals_language.lst"); // final BufferedWriter literalLanguageWriter = new BufferedWriter(new // FileWriter( // stats.literalLanguageList, true)); final BufferedWriter datatypePropertiesWriter = new BufferedWriter( new FileWriter(stats.datatypeProps, false)); final BufferedWriter objectPropertiesWriter = new BufferedWriter(new FileWriter(stats.objectProps, false)); final ArrayList<Callable<Boolean>> threads = new ArrayList<Callable<Boolean>>(); int sourceCount = 0; for (final InputStream stream : input) { final String source = (++sourceCount) + ""; log.info("Parsing: " + source + " from ( " + input.length + " )"); final RDFParser parser = getParser(rdf_mimetype); parser.setRDFHandler(new RDFHandler() { long tripleCount = 0; @Override public void startRDF() throws RDFHandlerException { log.info("Start parsing RDF triples"); } @Override public void handleStatement(Statement stmt) throws RDFHandlerException { try { tripleCount++; if (tripleCount % 10000 == 0) { log.info(source + ": Parsed " + tripleCount + " RDF triples"); } // get triple components String p = stmt.getPredicate().toString(); String s = stmt.getSubject().toString(); String o = stmt.getObject().toString(); // test URIs if (s.length() > URISIZE) { log.warning("Skipping too long subject " + s); return; } if (p.length() > URISIZE) { log.warning("Skipping too long predicate " + p); return; } if (stmt.getSubject() instanceof URI) s = fixJavaURI(s); p = fixJavaURI(p); // check object properties URIs if (stmt.getObject() instanceof URI) { if (o.length() > URISIZE) { return; } else { o = fixJavaURI(o); appendObjectTriple(s, p, o); } } else if (stmt.getObject() instanceof Literal) { o = stmt.getObject().stringValue().replaceAll("[\n\t\\\\\"]", "").trim(); if (o.length() < 2 || o.length() > 100) { return; } appendLiteralTriple(s, p, o, ((Literal) stmt.getObject()).getLanguage()); } else { log.warning("Skipping bad triple " + stmt); } } catch (Exception e) { log.log(Level.SEVERE, "Error in parsing: " + source, e); } } /** * Encodes characters invalid (e.g. "|") in the uri and returns * the encoded string. * * @param uri * uri to enctode * @return encoded uri */ private String fixJavaURI(String uri) { try { new java.net.URI(uri); } catch (URISyntaxException e) { String badChar = Character.toString(uri.charAt(e.getIndex())); try { log.fine("Fixing bad uri: " + uri); return fixJavaURI(uri.replace(badChar, URLEncoder.encode(badChar, "utf-8"))); } catch (UnsupportedEncodingException e1) { throw new RuntimeException(e1); } } return uri; } private void appendLiteralTriple(String subject, String predicate, String literal, String language) throws IOException { if (language == null) { language = ALL; } synchronized (SEMAPHOR) { stats.datatypePropsSize++; datatypePropertiesWriter.write(RDFTripleParser.encloseCharacterString(subject)); datatypePropertiesWriter.append(','); datatypePropertiesWriter.write(RDFTripleParser.encloseCharacterString(predicate)); datatypePropertiesWriter.append(','); datatypePropertiesWriter.write(RDFTripleParser.encloseCharacterString(literal)); datatypePropertiesWriter.append(','); datatypePropertiesWriter .write(Integer.toString(hashing.hash(literal.toLowerCase(Locale.US)))); datatypePropertiesWriter.newLine(); } } private void appendObjectTriple(String subject, String predicate, String object) throws IOException { synchronized (SEMAPHOR) { stats.objectPropsSize++; objectPropertiesWriter.write(RDFTripleParser.encloseCharacterString(subject)); objectPropertiesWriter.append(','); objectPropertiesWriter.write(RDFTripleParser.encloseCharacterString(predicate)); objectPropertiesWriter.append(','); objectPropertiesWriter.write(RDFTripleParser.encloseCharacterString(object)); objectPropertiesWriter.newLine(); } } @Override public void handleNamespace(String arg0, String arg1) throws RDFHandlerException { } @Override public void handleComment(String arg0) throws RDFHandlerException { } @Override public void endRDF() throws RDFHandlerException { log.info("Finished parsing RDF triples " + tripleCount + " RDF triples"); } }); threads.add(new Callable<Boolean>() { /* * (non-Javadoc) * * @see java.util.concurrent.Callable#call() */ @Override public Boolean call() throws Exception { InputStream unpackedStream = getStream(stream, file_mimetype); try { if (absoluteBaseURI != null) parser.parse(unpackedStream, absoluteBaseURI); else parser.parse(unpackedStream, BASEURI); } catch (Exception e) { new Exception("Error during parsing " + source + " with mimetype " + file_mimetype, e) .printStackTrace(); unpackedStream.close(); return false; } unpackedStream.close(); return true; } }); } for (Future<Boolean> future : pool.invokeAll(threads)) { if (!future.get()) { throw new Exception("error occured during parsing"); } } // literalLanguageWriter.close(); objectPropertiesWriter.close(); datatypePropertiesWriter.close(); return stats; }
From source file:com.actelion.research.table.view.JVisualization.java
public String getStatisticalValues() { if (mChartType == cChartTypeScatterPlot) return "Incompatible chart type."; String[][] categoryList = new String[6][]; int[] categoryColumn = new int[6]; int categoryColumnCount = 0; if (isSplitView()) { for (int i = 0; i < 2; i++) { if (mSplittingColumn[i] != cColumnUnassigned) { categoryColumn[categoryColumnCount] = mSplittingColumn[i]; categoryList[categoryColumnCount] = mTableModel.getCategoryList(mSplittingColumn[i]); categoryColumnCount++;//from w w w. j ava 2 s .c o m } } } for (int axis = 0; axis < mDimensions; axis++) { if (mIsCategoryAxis[axis]) { categoryColumn[categoryColumnCount] = mAxisIndex[axis]; categoryList[categoryColumnCount] = new String[mCategoryVisibleCount[axis]]; if (mAxisIndex[axis] == cColumnUnassigned) { // box/whisker plot with unassigned category axis categoryList[categoryColumnCount][0] = "<All Rows>"; } else { String[] list = mTableModel.getCategoryList(categoryColumn[categoryColumnCount]); for (int j = 0; j < mCategoryVisibleCount[axis]; j++) categoryList[categoryColumnCount][j] = list[mCategoryMin[axis] + j]; } categoryColumnCount++; } } if (isCaseSeparationDone()) { categoryColumn[categoryColumnCount] = mCaseSeparationColumn; categoryList[categoryColumnCount] = mTableModel.getCategoryList(mCaseSeparationColumn); categoryColumnCount++; } boolean includePValue = false; boolean includeFoldChange = false; int pValueColumn = getPValueColumn(); int referenceCategoryIndex = -1; if (pValueColumn != cColumnUnassigned) { referenceCategoryIndex = getCategoryIndex(pValueColumn, mPValueRefCategory); if (referenceCategoryIndex != -1) { includePValue = mBoxplotShowPValue; includeFoldChange = mBoxplotShowFoldChange; } } StringWriter stringWriter = new StringWriter(1024); BufferedWriter writer = new BufferedWriter(stringWriter); try { // construct the title line for (int i = 0; i < categoryColumnCount; i++) { String columnTitle = (categoryColumn[i] == -1) ? "Category" : mTableModel.getColumnTitleWithSpecialType(categoryColumn[i]); writer.append(columnTitle + "\t"); } if (mChartType != cChartTypeBoxPlot) writer.append("Rows in Category"); if ((mChartType == cChartTypeBars || mChartType == cChartTypePies) && mChartMode != cChartModeCount) { String name = mTableModel.getColumnTitleWithSpecialType(mChartColumn); writer.append((mChartMode == cChartModePercent) ? "\tPercent of Rows" : (mChartMode == cChartModeMean) ? "\tMean of " + name : (mChartMode == cChartModeMean) ? "\tSum of " + name : (mChartMode == cChartModeMin) ? "\tMinimum of " + name : (mChartMode == cChartModeMax) ? "\tMaximum of " + name : ""); } if (mChartType == cChartTypeBoxPlot || mChartType == cChartTypeWhiskerPlot) { if (mChartType == cChartTypeBoxPlot) { writer.append("Total Count"); writer.append("\tOutlier Count"); } writer.append("\tMean Value"); writer.append("\t1st Quartile"); writer.append("\tMedian"); writer.append("\t3rd Quartile"); writer.append("\tLower Adjacent Limit"); writer.append("\tUpper Adjacent Limit"); /* if (includeFoldChange || includePValue) don't use additional column writer.append("\tIs Reference Group"); */ if (includeFoldChange) writer.append( mTableModel.isLogarithmicViewMode(mAxisIndex[((BoxPlotViewInfo) mChartInfo).barAxis]) ? "\tlog2(Fold Change)" : "\tFold Change"); if (includePValue) writer.append("\tp-Value"); } writer.newLine(); int[] categoryIndex = new int[6]; while (categoryIndex[0] < categoryList[0].length) { int columnIndex = 0; int hv = 0; if (isSplitView()) { if (mSplittingColumn[0] != cColumnUnassigned) hv += categoryIndex[columnIndex++]; if (mSplittingColumn[1] != cColumnUnassigned) hv += categoryIndex[columnIndex++] * categoryList[0].length; } int cat = 0; for (int axis = 0; axis < mDimensions; axis++) if (mIsCategoryAxis[axis]) cat += categoryIndex[columnIndex++] * mCombinedCategoryCount[axis]; if (isCaseSeparationDone()) cat += categoryIndex[columnIndex++]; if (mChartInfo.pointsInCategory[hv][cat] != 0) { for (int i = 0; i < categoryColumnCount; i++) { writer.append(categoryList[i][categoryIndex[i]]); if ((includeFoldChange || includePValue) && pValueColumn == categoryColumn[i] && mPValueRefCategory.equals(categoryList[i][categoryIndex[i]])) writer.append(" (ref)"); writer.append("\t"); } if (mChartType != cChartTypeBoxPlot) writer.append("" + mChartInfo.pointsInCategory[hv][cat]); if ((mChartType == cChartTypeBars || mChartType == cChartTypePies) && mChartMode != cChartModeCount) writer.append("\t" + formatValue(mChartInfo.barValue[hv][cat], mChartColumn)); if (mChartType == cChartTypeBoxPlot || mChartType == cChartTypeWhiskerPlot) { BoxPlotViewInfo vi = (BoxPlotViewInfo) mChartInfo; if (mChartType == cChartTypeBoxPlot) { writer.append("" + (mChartInfo.pointsInCategory[hv][cat] + vi.outlierCount[hv][cat])); writer.append("\t" + vi.outlierCount[hv][cat]); } int column = mAxisIndex[((BoxPlotViewInfo) mChartInfo).barAxis]; writer.append("\t" + formatValue(vi.barValue[hv][cat], column)); writer.append("\t" + formatValue(vi.boxQ1[hv][cat], column)); writer.append("\t" + formatValue(vi.median[hv][cat], column)); writer.append("\t" + formatValue(vi.boxQ3[hv][cat], column)); writer.append("\t" + formatValue(vi.boxLAV[hv][cat], column)); writer.append("\t" + formatValue(vi.boxUAV[hv][cat], column)); /* if (includeFoldChange || includePValue) { don't use additional column int refHV = getReferenceHV(hv, pValueColumn, referenceCategoryIndex); int refCat = getReferenceCat(cat, pValueColumn, referenceCategoryIndex, new int[1+mDimensions]); writer.append("\t"+((hv==refHV && cat==refCat) ? "yes" : "no")); } */ if (includeFoldChange) { writer.append("\t"); if (!Float.isNaN(vi.foldChange[hv][cat])) writer.append(new DecimalFormat("#.#####").format(vi.foldChange[hv][cat])); } if (includePValue) { writer.append("\t"); if (!Float.isNaN(vi.pValue[hv][cat])) writer.append(new DecimalFormat("#.#####").format(vi.pValue[hv][cat])); } } writer.newLine(); } // update category indices for next row for (int i = categoryColumnCount - 1; i >= 0; i--) { if (++categoryIndex[i] < categoryList[i].length || i == 0) break; categoryIndex[i] = 0; } } writer.close(); } catch (IOException ioe) { } return stringWriter.toString(); }
From source file:edu.du.penrose.systems.fedoraApp.util.MetsBatchFileSplitter.java
/** * Split the batchIngest command file. If the batch contains additions put the results into the 'mets/new' directory. If updates put the * files into the 'mets/upates' directory. The ingest command (only one per batchfile!!) is saved in a comment prior to the <mets:mets> * element for each split file. This means the batch can only contain files of one type ie adds or updates. * <br><br>/*from w ww .j a v a 2 s.c om*/ * If an error occurs we will try to remove any generated output file and then throw an exception. * <br> * One the ingest command line is found ie "<ingestControl command="A" type="pidInOBJID" />" ALL other command line are ignored!! AFter that * point we only look for <mets:mets> and </mets:mets> to split the file. * * NOTE Since this method may need to get fedora pids The following libraries are needed... * wsdl4j-1.5.1.jar * commons-discovery.jar * fcrepo-server-3.4-utilities-main.jar * jaxrpc.jar * logback-core-0.9.18.jar * logback-classic-0.9.18.jar * trippi-1.1.2-core.jar * fcrepo-common-3.4.jar * fcrepo-client-admin-3.4.jar * jdom.jar * * @param ingestOptions set batchIngestDate, batchDescription, * @param threadStatus can be null. * @param inFile batch file to split * @param metsNewDirectory * @param metsUpdatesDirectory * @param nameFileFromOBJID create xml file's that are named the same as it's OBJID element. This seems like a good idea but if the file * already exists you will get a error, killing the entire ingest. * @param fedoraUser used for a replyWithPid ingest. If null we will pull from the batchIngest.properties file. * @param fedoraPassword used for a replyWithPid ingest. If null we will pull from the batchIngest.properties file. * * @return IF the batch file is an add of type 'replyWithPid' return a map of OBJID and PIDs otherwise return null. NOTE: if the <mets:mets OBJID> element is * empty in the batch file, both the key and the value of the returned map will contain the pid. * * @throws Exception */ static public Map<String, String> splitMetsBatchFile_version_2(BatchIngestOptions ingestOptions, ThreadStatusMsg threadStatus, File inFile, String metsNewDirectory, String metsUpdatesDirectory, boolean nameFileFromOBJID, String fedoraHost, String fedoraPort, String fedoraUser, String fedoraPassword) throws Exception { Map<String, String> pidMap = null; FileInputStream batchFileInputStream; try { batchFileInputStream = new FileInputStream(inFile); } catch (FileNotFoundException e) { throw new FatalException(e.getMessage()); } DataInputStream batchFileDataInputStream = new DataInputStream(batchFileInputStream); BufferedReader batchFileBufferedReader = new BufferedReader( new InputStreamReader(batchFileDataInputStream)); String oneLine = null; String ingestControlLine = null; int fileCount = 0; String documentType = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; String batchCreationDate = null; String batchDescription = null; String metsDirectory = null; // will get set to either the new directory or the updates directory. File outFile = null; FileOutputStream metsFileOutputStream = null; BufferedWriter metsBufferedWriter = null; boolean headerFoundLookOnlyForMetsNow = false; while (batchFileBufferedReader.ready()) { oneLine = batchFileBufferedReader.readLine(); if (!headerFoundLookOnlyForMetsNow) { if (oneLine.contains("<?xml version") && oneLine.trim().startsWith("<")) { documentType = oneLine; } // LOOK FOR BATCH DESCRIPTION if (oneLine.contains(BATCH_DESCRIPTION_ELEMENT_MARKER) && oneLine.indexOf("<!") == -1) { int tempLocation1 = oneLine.indexOf("batchCreationDate=" + QUOTE); if (tempLocation1 == -1) { oneLine.indexOf("batchCreationDate=" + APOST); } int tempLocation2 = oneLine.indexOf(QUOTE, tempLocation1 + 19); if (tempLocation2 == -1) { oneLine.indexOf(APOST, tempLocation1 + 19); } batchCreationDate = oneLine.substring(tempLocation1 + 19, tempLocation2); ingestOptions.setBatchIngestDate(batchCreationDate); oneLine = batchFileBufferedReader.readLine(); if (!oneLine.contains("<literal>")) { throw new FatalException("Invalid batchDescription"); } StringBuffer tempBatchDescription = new StringBuffer(); boolean endBatchDescription = false; do { tempBatchDescription.append(oneLine); if (oneLine.contains("</literal>")) { endBatchDescription = true; batchDescription = tempBatchDescription.toString(); batchDescription = batchDescription.replace("<literal>", ""); // it may all be on one line. batchDescription = batchDescription.replace("</literal>", ""); } oneLine = batchFileBufferedReader.readLine(); } while (!endBatchDescription); ingestOptions.setBatchDescription(batchDescription.trim()); } // look for batch command at the top of the file, prior to the first <mets:mets> if (oneLine.contains((INGEST_CONTROL_ELEMENT_MARKER)) && oneLine.indexOf("<!") == -1) { if ((!oneLine.contains("command")) || (!oneLine.contains("type"))) { throw new FatalException( "The batch control element must have both command and type attributes"); } ingestControlLine = oneLine.trim(); boolean validCommandLine = parseCommandLine(ingestOptions, ingestControlLine); if (!validCommandLine) { throw new Exception("ERROR: Invalid command line found in batch ingest file:" + inFile + " , " + ingestControlLine); } headerFoundLookOnlyForMetsNow = true; switch (ingestOptions.getIngestCommand()) { case UPDATE: metsDirectory = metsUpdatesDirectory; break; case ADD: metsDirectory = metsNewDirectory; break; default: throw new Exception("ERROR: Invalid ingest command"); } } // if line is ingestControl (command line) } else // if-else headerFoundLookOnlyForMetsNow { if (oneLine.contains((INGEST_CONTROL_ELEMENT_MARKER)) && oneLine.indexOf("<!") == -1) { logger.warn("More than one ingest control line found in batch file! extras will be ignored:" + inFile); } // look for <mets:mets> and get complete <mets:mets> element if (oneLine.contains("<mets:mets") && oneLine.indexOf("<!") == -1) { boolean haveEntireMetsLine = false; while (!haveEntireMetsLine) { StringBuffer tempBuffer = new StringBuffer(oneLine); String moreOfMetsLine = null; if (!oneLine.contains(">")) { moreOfMetsLine = batchFileBufferedReader.readLine(); tempBuffer.append(moreOfMetsLine); if (moreOfMetsLine.contains(">")) { haveEntireMetsLine = true; oneLine = tempBuffer.toString(); } else { oneLine = tempBuffer.toString(); } } else { haveEntireMetsLine = true; } } // process everything up to </mets:mets> String objID = MetsBatchFileSplitter.getObjID(oneLine); if (nameFileFromOBJID) { outFile = new File(metsDirectory + objID + ".xml"); logger.info("outputSplitFile METS file: " + metsDirectory + objID + ".xml"); if (outFile.exists()) { String errorMsg = "file already exists:" + outFile.getName(); System.out.println(errorMsg); logger.error(errorMsg); throw new FatalException(errorMsg); } } else { switch (ingestOptions.getIngestThreadType()) { case BACKGROUND: // TBD this is probably an error case MANUAL: outFile = new File(metsDirectory + edu.du.penrose.systems.util.FileUtil.getDateTimeMilliSecondEnsureUnique() + ".xml"); break; case REMOTE: outFile = new File(metsDirectory + edu.du.penrose.systems.util.FileUtil.getDateTimeMilliSecondEnsureUnique() + FedoraAppConstants.REMOTE_TASK_NAME_SUFFIX + ".xml"); break; } } // oneLine now contains the entire <mets:mets....> line logger.info("outputSplitFile METS file: " + outFile.toString() + "\n\n"); boolean errorOccurred = false; try { metsFileOutputStream = new FileOutputStream(outFile); metsBufferedWriter = new BufferedWriter( new OutputStreamWriter(metsFileOutputStream, "UTF-8")); metsBufferedWriter.write(documentType); metsBufferedWriter.newLine(); switch (ingestOptions.getIngestCommand()) { case ADD: switch (ingestOptions.getAddCommandType()) { case REPLY_WITH_PID: // we get one pid at a time, write it to the <mets:mets> line OBJID value and add it to the pidMap String[] tempPids = null; if (fedoraPassword == null || fedoraUser == null || fedoraHost == null || fedoraPort == null) { tempPids = FedoraAppUtil.getPIDs(ingestOptions.getInstitution(), new NonNegativeInteger("1")); } else { tempPids = FedoraAppUtil.getPIDs(fedoraHost, Integer.valueOf(fedoraPort), fedoraUser, fedoraPassword, ingestOptions.getInstitution(), new NonNegativeInteger("1")); } String reservedPid = tempPids[0]; metsBufferedWriter.write("<!--" + ingestControlLine + "-->\n"); if (pidMap == null) { pidMap = new LinkedHashMap<String, String>(); } oneLine = putPidInMetsLineOBJID(oneLine, reservedPid); if (objID.contentEquals("")) { pidMap.put(reservedPid, reservedPid); } else { pidMap.put(objID, reservedPid); } break; case PID_IN_OBJID: case NORMAL: default: metsBufferedWriter.write("<!--" + ingestControlLine + "-->\n"); } break; case UPDATE: metsBufferedWriter.write("<!--" + ingestControlLine + "-->\n"); break; case NOT_SET: default: throw new Exception("ERROR: Invalid ingest command"); } // read lines from batch file and write to the new mets file until </mets:mets> line while (!oneLine.contains("</mets:mets")) { // null pointer on premature end of file. metsBufferedWriter.write(oneLine); metsBufferedWriter.newLine(); oneLine = batchFileBufferedReader.readLine(); if (oneLine == null) { throw new FatalException("Error spliting batch file, missing </mets:mets>"); } } metsBufferedWriter.write(oneLine); metsBufferedWriter.newLine(); metsBufferedWriter.close(); } catch (Exception e) { errorOccurred = true; // for cleanup, see below. throw new Exception(e); } finally { metsBufferedWriter.close(); if (errorOccurred) { outFile.delete(); //clean up. } } fileCount++; if (threadStatus != null) { threadStatus.setStatus("Spliting XML file #: " + fileCount); } } // if <mets:mets> found (look for another mets section now). } // if-else ! headerFoundLookOnlyForMetsNow } // while return pidMap; // may be null }
From source file:ffx.potential.parsers.PDBFilter.java
/** * <p>/*from w ww. ja v a2 s . c o m*/ * writeAtom</p> * * @param atom a {@link ffx.potential.bonded.Atom} object. * @param serial a int. * @param sb a {@link java.lang.StringBuilder} object. * @param anisouSB a {@link java.lang.StringBuilder} object. * @param bw a {@link java.io.BufferedWriter} object. * @throws java.io.IOException if any. */ private void writeAtom(Atom atom, int serial, StringBuilder sb, StringBuilder anisouSB, BufferedWriter bw) throws IOException { if (ignoreUnusedAtoms && !atom.getUse()) { return; } String name = atom.getName(); if (name.length() > 4) { name = name.substring(0, 4); } else if (name.length() == 1) { name = name + " "; } else if (name.length() == 2) { if (atom.getAtomType().valence == 0) { name = name + " "; } else { name = name + " "; } } double xyz[] = vdwH ? atom.getRedXYZ() : atom.getXYZ(null); if (nSymOp != 0) { Crystal crystal = activeMolecularAssembly.getCrystal(); SymOp symOp = crystal.spaceGroup.getSymOp(nSymOp); double[] newXYZ = new double[xyz.length]; crystal.applySymOp(xyz, newXYZ, symOp); xyz = newXYZ; } sb.replace(6, 16, String.format("%5s " + padLeft(name.toUpperCase(), 4), Hybrid36.encode(5, serial))); Character altLoc = atom.getAltLoc(); if (altLoc != null) { sb.setCharAt(16, altLoc); } else { sb.setCharAt(16, ' '); } /*sb.replace(30, 66, String.format("%8.3f%8.3f%8.3f%6.2f%6.2f", xyz[0], xyz[1], xyz[2], atom.getOccupancy(), atom.getTempFactor()));*/ /** * On the following code: * #1: StringBuilder.replace will allow for longer strings, expanding the * StringBuilder's length if necessary. * #2: sb was never re-initialized, so if there was overflow, sb would * continue to be > 80 characters long, resulting in broken PDB files * #3: It may be wiser to have XYZ coordinates result in shutdown, not * truncation of coordinates. * #4: Excessive B-factors aren't much of an issue; if the B-factor is * past 999.99, that's the difference between "density extends to Venus" * and "density extends to Pluto". */ StringBuilder decimals = new StringBuilder(); for (int i = 0; i < 3; i++) { try { decimals.append(StringUtils.fwFpDec(xyz[i], 8, 3)); } catch (IllegalArgumentException ex) { String newValue = StringUtils.fwFpTrunc(xyz[i], 8, 3); logger.info(String.format(" XYZ %d coordinate %8.3f for atom %s " + "overflowed bounds of 8.3f string specified by PDB " + "format; truncating value to %s", i, xyz[i], atom.toString(), newValue)); decimals.append(newValue); } } try { decimals.append(StringUtils.fwFpDec(atom.getOccupancy(), 6, 2)); } catch (IllegalArgumentException ex) { logger.severe( String.format(" Occupancy %f for atom %s is impossible; " + "value must be between 0 and 1", atom.getOccupancy(), atom.toString())); } try { decimals.append(StringUtils.fwFpDec(atom.getTempFactor(), 6, 2)); } catch (IllegalArgumentException ex) { String newValue = StringUtils.fwFpTrunc(atom.getTempFactor(), 6, 2); logger.info(String.format( " Atom temp factor %6.2f for atom %s overflowed " + "bounds of 6.2f string specified by PDB format; truncating " + "value to %s", atom.getTempFactor(), atom.toString(), newValue)); decimals.append(newValue); } sb.replace(30, 66, decimals.toString()); name = Atom.ElementSymbol.values()[atom.getAtomicNumber() - 1].toString(); name = name.toUpperCase(); if (atom.isDeuterium()) { name = "D"; } sb.replace(76, 78, padLeft(name, 2)); sb.replace(78, 80, String.format("%2d", 0)); if (!listMode) { bw.write(sb.toString()); bw.newLine(); } else { listOutput.add(sb.toString()); } // ============================================================================= // 1 - 6 Record name "ANISOU" // 7 - 11 Integer serial Atom serial number. // 13 - 16 Atom name Atom name. // 17 Character altLoc Alternate location indicator // 18 - 20 Residue name resName Residue name. // 22 Character chainID Chain identifier. // 23 - 26 Integer resSeq Residue sequence number. // 27 AChar iCode Insertion code. // 29 - 35 Integer u[0][0] U(1,1) // 36 - 42 Integer u[1][1] U(2,2) // 43 - 49 Integer u[2][2] U(3,3) // 50 - 56 Integer u[0][1] U(1,2) // 57 - 63 Integer u[0][2] U(1,3) // 64 - 70 Integer u[1][2] U(2,3) // 77 - 78 LString(2) element Element symbol, right-justified. // 79 - 80 LString(2) charge Charge on the atom. // ============================================================================= double[] anisou = atom.getAnisou(null); if (anisou != null) { anisouSB.replace(6, 80, sb.substring(6, 80)); anisouSB.replace(28, 70, String.format("%7d%7d%7d%7d%7d%7d", (int) (anisou[0] * 1e4), (int) (anisou[1] * 1e4), (int) (anisou[2] * 1e4), (int) (anisou[3] * 1e4), (int) (anisou[4] * 1e4), (int) (anisou[5] * 1e4))); if (!listMode) { bw.write(anisouSB.toString()); bw.newLine(); } else { listOutput.add(anisouSB.toString()); } } }