List of usage examples for javax.swing JProgressBar setValue
@BeanProperty(bound = false, preferred = true, description = "The progress bar's current value.") public void setValue(int n)
From source file:DownloadDialog.java
/******************************************************************** * Constructor: DownloadDialog/* w w w.j a v a2 s . c o m*/ * Purpose: constructor for download, with necessary references /*******************************************************************/ public DownloadDialog(final MainApplication context, Scheduler scheduler_Ref, JList courseListSelected_Ref, JList courseListAll_Ref) { // Basic setup for dialog setModalityType(Dialog.ModalityType.APPLICATION_MODAL); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); setTitle(TITLE); // Setup proper references this.scheduler = scheduler_Ref; this.courseListSelected = courseListSelected_Ref; this.courseListAll = courseListAll_Ref; // Store available terms storeTerms(); // Constraints GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.insets = new Insets(10, 10, 10, 10); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 0; c.gridwidth = 2; // Main panel panel = new JPanel(new GridBagLayout()); // Add term select box termCB = new JComboBox(termsName.toArray()); panel.add(termCB, c); // Setup username and password labels JLabel userL = new JLabel("Username:"); JLabel passL = new JLabel("Password:"); c.gridwidth = 1; c.gridx = 0; c.weightx = 0; // Add user label c.gridy = 1; c.insets = new Insets(5, 10, 0, 10); panel.add(userL, c); // Add password label c.gridy = 2; c.insets = new Insets(0, 10, 5, 10); panel.add(passL, c); // Setup user and pass text fields user = new JTextField(); pass = new JPasswordField(); c.weightx = 1; c.gridx = 1; // Add user field c.gridy = 1; c.insets = new Insets(5, 10, 2, 10); panel.add(user, c); // Add pass field c.gridy = 2; c.insets = new Insets(2, 10, 5, 10); panel.add(pass, c); // Setup login button JButton login = new JButton("Login"); login.addActionListener(this); c.insets = new Insets(10, 10, 10, 10); c.gridx = 0; c.gridy = 3; c.gridwidth = 2; c.weightx = 1; panel.add(login, c); // Add panel to main box add(panel); // Pack the components and give userbox focus pack(); user.requestFocus(); // Create worker to download courses worker = new SwingWorker<Void, Void>() { protected Void doInBackground() throws Exception { // Reset courses scheduler.resetCourses(); // Constraints GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.insets = new Insets(10, 10, 10, 10); c.gridx = 0; c.weightx = 1; c.weighty = 0; // Remove all elements panel.removeAll(); // Add status JLabel status = new JLabel("Connecting..."); c.gridy = 0; panel.add(status, c); // Add progress bar JProgressBar progressBar = new JProgressBar(0, SUBJECTS.length); c.gridy = 1; panel.add(progressBar, c); progressBar.setPreferredSize(new Dimension(275, 12)); // Revalidate, repaint, and pack //revalidate(); repaint(); pack(); try { // Create client DefaultHttpClient client = new DefaultHttpClient(); // Setup and execute initial login HttpGet initialLogin = new HttpGet("http://jweb.kettering.edu/cku1/twbkwbis.P_ValLogin"); HttpResponse response = client.execute(initialLogin); HTMLParser.parse(response); // Get current term String term = termsValue.get(termCB.getSelectedIndex()); // Consume entity (cookies) HttpEntity entity = response.getEntity(); if (entity != null) entity.consumeContent(); // Create post for login HttpPost login = new HttpPost("http://jweb.kettering.edu/cku1/twbkwbis.P_ValLogin"); // Parameters List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("sid", user.getText())); parameters.add(new BasicNameValuePair("PIN", pass.getText())); login.setEntity(new UrlEncodedFormEntity(parameters)); login.setHeader("Referer", "http://jweb.kettering.edu/cku1/twbkwbis.P_ValLogin"); // Login ! response = client.execute(login); // Store proper cookies List<Cookie> cookies = client.getCookieStore().getCookies(); // Start off assuming logging in failed boolean loggedIn = false; // Check cookies for successful login for (int i = 0; i < cookies.size(); i++) if (cookies.get(i).getName().equals("SESSID")) loggedIn = true; // Success? if (loggedIn) { // Consumption of feed HTMLParser.parse(response); // Execute GET class list page HttpGet classList = new HttpGet( "http://jweb.kettering.edu/cku1/bwskfcls.p_sel_crse_search"); classList.setHeader("Referer", "https://jweb.kettering.edu/cku1/twbkwbis.P_GenMenu"); response = client.execute(classList); HTMLParser.parse(response); // Execute GET for course page HttpGet coursePage = new HttpGet( "http://jweb.kettering.edu/cku1/bwckgens.p_proc_term_date?p_calling_proc=P_CrseSearch&p_term=" + term); coursePage.setHeader("Referer", "http://jweb.kettering.edu/cku1/bwskfcls.p_sel_crse_search"); response = client.execute(coursePage); HTMLParser.parse(response); // Download every subject's data for (int index = 0; index < SUBJECTS.length; index++) { // Don't download if cancel was pressed if (isCancelled()) break; // Update status, progress bar, then store course String subject = SUBJECTS[index]; status.setText("Downloading " + subject); progressBar.setValue(index); scheduler.storeDynamicCourse(subject, client, term); } // Update course list data courseListAll.setListData(scheduler.getCourseIDs().toArray()); // Clear course list data String[] empty = {}; courseListSelected.setListData(empty); context.updatePermutations(); context.updateSchedule(); // Dispose of dialog if cancelled if (!isCancelled()) { dispose(); } } // Invalid login? else { // Update status status.setText("Invalid login."); } } // Failed to download? catch (Exception exc) { // Show stack trace, and update status exc.printStackTrace(); status.setText("Failed downloading."); } return null; } }; // Setup window close event to be same as cancel this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // Cancel all downloads then dispose worker.cancel(true); dispose(); } }); // Make sure dialog is visible setLocationRelativeTo(context); setVisible(true); }
From source file:edu.ku.brc.specify.tasks.subpane.wb.wbuploader.Uploader.java
/** * @param val/* w w w.j a v a2s .c o m*/ * * Sets progress bar progress. */ protected void setCurrentOpProgress(final int val) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (mainPanel == null && !useAppStatBar) { log.error("UI does not exist."); return; } if (!indeterminateProgress) { if (useAppStatBar && !indeterminateProgress) { if (val == -1) { UIRegistry.getStatusBar().incrementValue("UPLOADER"); } else { UIRegistry.getStatusBar().setValue("UPLOADER", val); } } else { JProgressBar pb = mainPanel.getCurrOpProgress(); int newVal = val == -1 ? Math.min(pb.getValue() + 1, pb.getMaximum()) : val; pb.setValue(newVal); if (pb.isStringPainted()) { pb.setString(String.format(getResourceString("WB_UPLOAD_PROGRESSBAR_TEXT"), new Object[] { pb.getName(), Integer.toString(newVal), Integer.toString(pb.getMaximum()) })); } } } } }); }
From source file:com.awesomecoding.minetestlauncher.Main.java
private void initialize() { fileGetter = new FileGetter(userhome + "\\minetest\\temp\\"); latest = fileGetter.getContents("http://socialmelder.com/minetest/latest.txt", true); currentVersion = latest.split("\n")[0]; changelog = fileGetter.getContents("http://socialmelder.com/minetest/changelog.html", false); try {//w w w .j a v a2s .c o m UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } frmMinetestLauncherV = new JFrame(); frmMinetestLauncherV.setResizable(false); frmMinetestLauncherV.setIconImage(Toolkit.getDefaultToolkit() .getImage(Main.class.getResource("/com/awesomecoding/minetestlauncher/icon.png"))); frmMinetestLauncherV.setTitle("Minetest Launcher (Version 0.1)"); frmMinetestLauncherV.setBounds(100, 100, 720, 480); frmMinetestLauncherV.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SpringLayout springLayout = new SpringLayout(); frmMinetestLauncherV.getContentPane().setLayout(springLayout); final JProgressBar progressBar = new JProgressBar(); springLayout.putConstraint(SpringLayout.WEST, progressBar, 10, SpringLayout.WEST, frmMinetestLauncherV.getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, progressBar, -10, SpringLayout.SOUTH, frmMinetestLauncherV.getContentPane()); springLayout.putConstraint(SpringLayout.EAST, progressBar, -130, SpringLayout.EAST, frmMinetestLauncherV.getContentPane()); frmMinetestLauncherV.getContentPane().add(progressBar); final JButton btnDownloadPlay = new JButton("Play!"); springLayout.putConstraint(SpringLayout.WEST, btnDownloadPlay, 6, SpringLayout.EAST, progressBar); springLayout.putConstraint(SpringLayout.SOUTH, btnDownloadPlay, 0, SpringLayout.SOUTH, progressBar); springLayout.putConstraint(SpringLayout.EAST, btnDownloadPlay, -10, SpringLayout.EAST, frmMinetestLauncherV.getContentPane()); frmMinetestLauncherV.getContentPane().add(btnDownloadPlay); final JLabel label = new JLabel("Ready to play!"); springLayout.putConstraint(SpringLayout.WEST, label, 10, SpringLayout.WEST, frmMinetestLauncherV.getContentPane()); springLayout.putConstraint(SpringLayout.NORTH, btnDownloadPlay, 0, SpringLayout.NORTH, label); springLayout.putConstraint(SpringLayout.SOUTH, label, -37, SpringLayout.SOUTH, frmMinetestLauncherV.getContentPane()); springLayout.putConstraint(SpringLayout.NORTH, progressBar, 6, SpringLayout.SOUTH, label); frmMinetestLauncherV.getContentPane().add(label); JTextPane txtpnNewFeatures = new JTextPane(); txtpnNewFeatures.setBackground(SystemColor.window); springLayout.putConstraint(SpringLayout.NORTH, txtpnNewFeatures, 10, SpringLayout.NORTH, frmMinetestLauncherV.getContentPane()); springLayout.putConstraint(SpringLayout.WEST, txtpnNewFeatures, 10, SpringLayout.WEST, frmMinetestLauncherV.getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, txtpnNewFeatures, -10, SpringLayout.NORTH, btnDownloadPlay); springLayout.putConstraint(SpringLayout.EAST, txtpnNewFeatures, 0, SpringLayout.EAST, btnDownloadPlay); txtpnNewFeatures.setEditable(false); txtpnNewFeatures.setContentType("text/html"); txtpnNewFeatures.setText(changelog); txtpnNewFeatures.setFont(new Font("Tahoma", Font.PLAIN, 12)); frmMinetestLauncherV.getContentPane().add(txtpnNewFeatures); File file = new File(userhome + "\\minetest\\version.txt"); if (!file.exists()) newVersion = true; else { String version = fileGetter.getLocalContents(file, false); if (!version.equals(currentVersion)) newVersion = true; } if (newVersion) { label.setText("New Version Available! (" + currentVersion + ")"); btnDownloadPlay.setText("Download & Play"); btnDownloadPlay.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { Thread t = new Thread() { public void run() { File file = new File(userhome + "\\minetest\\version.txt"); String version = fileGetter.getLocalContents(file, false); try { FileUtils.deleteDirectory(new File(userhome + "\\minetest\\minetest-" + version)); } catch (Exception e) { e.printStackTrace(); } fileGetter.download(latest.split("\n")[1], userhome + "\\minetest\\temp\\", "minetest.zip", label, progressBar, btnDownloadPlay, currentVersion); try { label.setText("Cleaning up..."); btnDownloadPlay.setText("Cleaning up..."); FileUtils.deleteDirectory(new File(userhome + "\\minetest\\temp")); } catch (IOException e) { e.printStackTrace(); } System.exit(0); } }; t.start(); } }); } else { btnDownloadPlay.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { try { label.setText("Launching..."); btnDownloadPlay.setEnabled(false); btnDownloadPlay.setText("Launching..."); File file = new File(userhome + "\\minetest\\version.txt"); String version = fileGetter.getLocalContents(file, false); Runtime.getRuntime() .exec(userhome + "\\minetest\\minetest-" + version + "\\bin\\minetest.exe"); System.exit(0); } catch (IOException e) { e.printStackTrace(); } } }); progressBar.setValue(100); } }
From source file:edu.ku.brc.specify.tasks.subpane.wb.wbuploader.Uploader.java
/** * @param min/*from w ww .ja va 2s.c o m*/ * @param max * @param paintString - true if the progress bar should display string description of progress * @param itemName - string description will be: "itemName x of max" (using English resource). * * Initializes progress bar for upload actions. If min and max = 0, sets progress bar is * indeterminate. */ protected void initProgressBar(final int min, final int max, final boolean paintString, final String itemName, final boolean useAppProgress) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (!useAppStatBar && mainPanel == null) { log.error("UI does not exist."); return; } minProgVal = min; maxProgVal = max; indeterminateProgress = minProgVal == 0 && maxProgVal == 0; useAppStatBar = useAppProgress; if (useAppStatBar) { if (indeterminateProgress) { UIRegistry.getStatusBar().setIndeterminate("UPLOADER", indeterminateProgress); } else { UIRegistry.getStatusBar().setProgressRange("UPLOADER", minProgVal, maxProgVal); } } else { JProgressBar pb = mainPanel.getCurrOpProgress(); pb.setVisible(true); if (indeterminateProgress) { pb.setIndeterminate(true); pb.setString(""); } else { if (pb.isIndeterminate()) { pb.setIndeterminate(false); } pb.setStringPainted(paintString); if (paintString) { pb.setName(itemName); } pb.setMinimum(minProgVal); pb.setMaximum(maxProgVal); pb.setValue(minProgVal); } } } }); }
From source file:eu.apenet.dpt.standalone.gui.batch.ConvertAndValidateActionListener.java
public void actionPerformed(ActionEvent event) { labels = dataPreparationToolGUI.getLabels(); continueLoop = true;/*from w w w.j a v a 2 s .co m*/ dataPreparationToolGUI.disableAllBtnAndItems(); dataPreparationToolGUI.disableEditionTab(); dataPreparationToolGUI.disableRadioButtons(); dataPreparationToolGUI.disableAllBatchBtns(); dataPreparationToolGUI.getAPEPanel().setFilename(""); final Object[] objects = dataPreparationToolGUI.getXmlEadList().getSelectedValues(); final ApexActionListener apexActionListener = this; new Thread(new Runnable() { public void run() { FileInstance uniqueFileInstance = null; String uniqueXslMessage = ""; int numberOfFiles = objects.length; int currentFileNumberBatch = 0; ProgressFrame progressFrame = new ProgressFrame(labels, parent, true, false, apexActionListener); JProgressBar batchProgressBar = progressFrame.getProgressBarBatch(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableConversionBtn(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableValidationBtn(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().disableConvertAndValidateBtn(); dataPreparationToolGUI.getXmlEadList().setEnabled(false); for (Object oneFile : objects) { if (!continueLoop) { break; } File file = (File) oneFile; FileInstance fileInstance = dataPreparationToolGUI.getFileInstances().get(file.getName()); if (numberOfFiles == 1) { uniqueFileInstance = fileInstance; } if (!fileInstance.isXml()) { fileInstance.setXml(XmlChecker.isXmlParseable(file) == null); if (!fileInstance.isXml()) { if (type == CONVERT || type == CONVERT_AND_VALIDATE) { fileInstance.setConversionErrors(labels.getString("conversion.error.fileNotXml")); } else if (type == VALIDATE || type == CONVERT_AND_VALIDATE) { fileInstance.setValidationErrors(labels.getString("validation.error.fileNotXml")); } dataPreparationToolGUI.enableSaveBtn(); dataPreparationToolGUI.enableRadioButtons(); dataPreparationToolGUI.enableEditionTab(); } } SummaryWorking summaryWorking = new SummaryWorking(dataPreparationToolGUI.getResultArea(), batchProgressBar); summaryWorking.setTotalNumberFiles(numberOfFiles); summaryWorking.setCurrentFileNumberBatch(currentFileNumberBatch); Thread threadRunner = new Thread(summaryWorking); threadRunner.setName(SummaryWorking.class.toString()); threadRunner.start(); JProgressBar progressBar = null; Thread threadProgress = null; CounterThread counterThread = null; CounterCLevelCall counterCLevelCall = null; if (fileInstance.isXml()) { currentFileNumberBatch = currentFileNumberBatch + 1; if (type == CONVERT || type == CONVERT_AND_VALIDATE) { dataPreparationToolGUI.setResultAreaText(labels.getString("converting") + " " + file.getName() + " (" + (currentFileNumberBatch) + "/" + numberOfFiles + ")"); String eadid = ""; boolean doTransformation = true; if (fileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath())) || fileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath()))) { StaxTransformationTool staxTransformationTool = new StaxTransformationTool(file); staxTransformationTool.run(); LOG.debug("file has eadid? " + staxTransformationTool.isFileWithEadid()); if (!staxTransformationTool.isFileWithEadid()) { EadidQueryComponent eadidQueryComponent; if (staxTransformationTool.getUnitid() != null && !staxTransformationTool.getUnitid().equals("")) { eadidQueryComponent = new EadidQueryComponent( staxTransformationTool.getUnitid()); } else { eadidQueryComponent = new EadidQueryComponent(labels); } int result = JOptionPane.showConfirmDialog(parent, eadidQueryComponent.getMainPanel(), labels.getString("enterEADID"), JOptionPane.OK_CANCEL_OPTION); while (StringUtils.isEmpty(eadidQueryComponent.getEntryEadid()) && result != JOptionPane.CANCEL_OPTION) { result = JOptionPane.showConfirmDialog(parent, eadidQueryComponent.getMainPanel(), labels.getString("enterEADID"), JOptionPane.OK_CANCEL_OPTION); } if (result == JOptionPane.OK_OPTION) { eadid = eadidQueryComponent.getEntryEadid(); } else if (result == JOptionPane.CANCEL_OPTION) { doTransformation = false; } } } if (doTransformation) { int counterMax = 0; if (fileInstance.getConversionScriptName() .equals(Utilities.XSL_DEFAULT_APEEAD_NAME)) { progressBar = progressFrame.getProgressBarSingle(); progressBar.setVisible(true); progressFrame .setTitle(labels.getString("progressTrans") + " - " + file.getName()); CountCLevels countCLevels = new CountCLevels(); counterMax = countCLevels.countOneFile(file); if (counterMax > 0) { counterCLevelCall = new CounterCLevelCall(); counterCLevelCall.initializeCounter(counterMax); counterThread = new CounterThread(counterCLevelCall, progressBar, counterMax); threadProgress = new Thread(counterThread); threadProgress.setName(CounterThread.class.toString()); threadProgress.start(); } } try { try { File xslFile = new File(fileInstance.getConversionScriptPath()); File outputFile = new File(Utilities.TEMP_DIR + "temp_" + file.getName()); outputFile.deleteOnExit(); StringWriter xslMessages; HashMap<String, String> parameters = dataPreparationToolGUI.getParams(); parameters.put("eadidmissing", eadid); CheckIsEadFile checkIsEadFile = new CheckIsEadFile(file); checkIsEadFile.run(); if (checkIsEadFile.isEadRoot()) { File outputFile_temp = new File( Utilities.TEMP_DIR + ".temp_" + file.getName()); TransformationTool.createTransformation(FileUtils.openInputStream(file), outputFile_temp, Utilities.BEFORE_XSL_FILE, null, true, true, null, true, null); xslMessages = TransformationTool.createTransformation( FileUtils.openInputStream(outputFile_temp), outputFile, xslFile, parameters, true, true, null, true, counterCLevelCall); outputFile_temp.delete(); } else { xslMessages = TransformationTool.createTransformation( FileUtils.openInputStream(file), outputFile, xslFile, parameters, true, true, null, true, null); } fileInstance.setConversionErrors(xslMessages.toString()); fileInstance .setCurrentLocation(Utilities.TEMP_DIR + "temp_" + file.getName()); fileInstance.setConverted(); fileInstance.setLastOperation(FileInstance.Operation.CONVERT); uniqueXslMessage = xslMessages.toString(); if (xslMessages.toString().equals("")) { if (fileInstance.getConversionScriptName() .equals(Utilities.XSL_DEFAULT_APEEAD_NAME)) { fileInstance.setConversionErrors( labels.getString("conversion.noExcludedElements")); } else { fileInstance.setConversionErrors( labels.getString("conversion.finished")); } } if (!continueLoop) { break; } } catch (Exception e) { fileInstance.setConversionErrors(labels.getString("conversionException") + "\r\n\r\n-------------\r\n" + e.getMessage()); throw new Exception("Error when converting " + file.getName(), e); } if (threadProgress != null) { counterThread.stop(); threadProgress.interrupt(); } if (progressBar != null) { if (counterMax > 0) { progressBar.setValue(counterMax); } progressBar.setIndeterminate(true); } } catch (Exception e) { LOG.error("Error when converting and validating", e); } finally { summaryWorking.stop(); threadRunner.interrupt(); dataPreparationToolGUI.getXmlEadListLabel().repaint(); dataPreparationToolGUI.getXmlEadList().repaint(); if (progressBar != null) { progressBar.setVisible(false); } } } if (numberOfFiles == 1) { uniqueFileInstance = fileInstance; } } if (type == VALIDATE || type == CONVERT_AND_VALIDATE) { try { try { File fileToValidate = new File(fileInstance.getCurrentLocation()); InputStream is = FileUtils.openInputStream(fileToValidate); dataPreparationToolGUI .setResultAreaText(labels.getString("validating") + " " + file.getName() + " (" + currentFileNumberBatch + "/" + numberOfFiles + ")"); XsdObject xsdObject = fileInstance.getValidationSchema(); List<SAXParseException> exceptions; if (xsdObject.getName().equals(Xsd_enum.DTD_EAD_2002.getReadableName())) { exceptions = DocumentValidation.xmlValidationAgainstDtd( fileToValidate.getAbsolutePath(), Utilities.getUrlPathXsd(xsdObject)); } else { exceptions = DocumentValidation.xmlValidation(is, Utilities.getUrlPathXsd(xsdObject), xsdObject.isXsd11()); } if (exceptions == null || exceptions.isEmpty()) { fileInstance.setValid(true); fileInstance.setValidationErrors(labels.getString("validationSuccess")); if (xsdObject.getFileType().equals(FileInstance.FileType.EAD) && xsdObject.getName().equals("apeEAD")) { XmlQualityCheckerCall xmlQualityCheckerCall = new XmlQualityCheckerCall(); InputStream is2 = FileUtils .openInputStream(new File(fileInstance.getCurrentLocation())); TransformationTool.createTransformation(is2, null, Utilities.XML_QUALITY_FILE, null, true, true, null, false, xmlQualityCheckerCall); String xmlQualityStr = createXmlQualityString(xmlQualityCheckerCall); fileInstance.setValidationErrors( fileInstance.getValidationErrors() + xmlQualityStr); fileInstance.setXmlQualityErrors( createXmlQualityErrors(xmlQualityCheckerCall)); } } else { String errors = Utilities.stringFromList(exceptions); fileInstance.setValidationErrors(errors); fileInstance.setValid(false); } fileInstance.setLastOperation(FileInstance.Operation.VALIDATE); } catch (Exception ex) { fileInstance.setValid(false); fileInstance.setValidationErrors(labels.getString("validationException") + "\r\n\r\n-------------\r\n" + ex.getMessage()); throw new Exception("Error when validating", ex); } } catch (Exception e) { LOG.error("Error when validating", e); } finally { summaryWorking.stop(); threadRunner.interrupt(); dataPreparationToolGUI.getXmlEadListLabel().repaint(); dataPreparationToolGUI.getXmlEadList().repaint(); if (progressBar != null) { progressBar.setVisible(false); } } if (numberOfFiles == 1) { uniqueFileInstance = fileInstance; } } } } Toolkit.getDefaultToolkit().beep(); if (progressFrame != null) { try { progressFrame.stop(); } catch (Exception e) { LOG.error("Error when stopping the progress bar", e); } } dataPreparationToolGUI.getFinalAct().run(); if (numberOfFiles > 1) { dataPreparationToolGUI.getXmlEadList().clearSelection(); } else if (uniqueFileInstance != null) { if (type != VALIDATE) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .setConversionErrorText(replaceGtAndLt(uniqueFileInstance.getConversionErrors())); if (uniqueXslMessage.equals("")) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .checkFlashingTab(APETabbedPane.TAB_CONVERSION, Utilities.FLASHING_GREEN_COLOR); } else { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .checkFlashingTab(APETabbedPane.TAB_CONVERSION, Utilities.FLASHING_RED_COLOR); } } if (type != CONVERT) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .setValidationErrorText(uniqueFileInstance.getValidationErrors()); if (uniqueFileInstance.isValid()) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .checkFlashingTab(APETabbedPane.TAB_VALIDATION, Utilities.FLASHING_GREEN_COLOR); if (uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath()))) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableConversionEdmBtn(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableValidationReportBtn(); } else if (uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath())) || uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.DTD_EAD_2002.getPath())) || uniqueFileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAC_SCHEMA.getPath()))) { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableConversionBtn(); // dataPreparationToolGUI.getAPEPanel().getApeTabbedPane().enableValidationReportBtn(); } } else { dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .checkFlashingTab(APETabbedPane.TAB_VALIDATION, Utilities.FLASHING_RED_COLOR); if (uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_SCHEMA.getPath())) || uniqueFileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAD_SCHEMA.getPath())) || uniqueFileInstance.getValidationSchema() .equals(Utilities.getXsdObjectFromPath(Xsd_enum.DTD_EAD_2002.getPath())) || uniqueFileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_APE_EAC_SCHEMA.getPath())) || uniqueFileInstance.getValidationSchema().equals( Utilities.getXsdObjectFromPath(Xsd_enum.XSD_EAC_SCHEMA.getPath()))) { dataPreparationToolGUI.enableConversionBtns(); dataPreparationToolGUI.getAPEPanel().getApeTabbedPane() .enableConvertAndValidateBtn(); } } } dataPreparationToolGUI.enableMessageReportBtns(); } if (continueLoop) { dataPreparationToolGUI.setResultAreaText(labels.getString("finished")); } else { dataPreparationToolGUI.setResultAreaText(labels.getString("aborted")); } dataPreparationToolGUI.enableSaveBtn(); if (type == CONVERT) { dataPreparationToolGUI.enableValidationBtns(); } dataPreparationToolGUI.enableRadioButtons(); dataPreparationToolGUI.enableEditionTab(); } }).start(); }
From source file:org.nebulaframework.ui.swing.cluster.ClusterMainUI.java
/** * Creates a tab pane for the given GridJob. * //from w w w. java 2s. c o m * @param jobId JobId */ protected void createJobTab(final String jobId) { // Request Job Profile final InternalClusterJobService jobService = ClusterManager.getInstance().getJobService(); final GridJobProfile profile = jobService.getProfile(jobId); // Job Start Time final long startTime = System.currentTimeMillis(); final JPanel jobPanel = new JPanel(); jobPanel.setLayout(new BorderLayout(10, 10)); // Progess Panel JPanel progressPanel = new JPanel(); progressPanel.setLayout(new BorderLayout(10, 10)); progressPanel.setBorder(BorderFactory.createTitledBorder("Progress")); jobPanel.add(progressPanel, BorderLayout.NORTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setStringPainted(true); progressPanel.add(progressBar, BorderLayout.CENTER); addUIElement("jobs." + jobId + ".progress", progressBar); // Add to components map // Buttons Panel JPanel buttonsPanel = new JPanel(); jobPanel.add(buttonsPanel, BorderLayout.SOUTH); buttonsPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); // Terminate Button JButton terminateButton = new JButton("Terminate"); terminateButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Thread(new Runnable() { public void run() { // Job Name = Class Name String name = profile.getJob().getClass().getSimpleName(); // Request user confirmation int option = JOptionPane.showConfirmDialog(ClusterMainUI.this, "Are you sure to terminate GridJob " + name + "?", "Nebula - Terminate GridJob", JOptionPane.YES_NO_OPTION); if (option == JOptionPane.NO_OPTION) return; // Attempt Cancel boolean result = profile.getFuture().cancel(); // Notify results if (result) { JOptionPane.showMessageDialog(ClusterMainUI.this, "Grid Job '" + name + "terminated successfully.", "Nebula - Job Terminated", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(ClusterMainUI.this, "Failed to terminate Grid Job '" + name, "Nebula - Job Termination Failed", JOptionPane.WARNING_MESSAGE); } } }).start(); } }); buttonsPanel.add(terminateButton); addUIElement("jobs." + jobId + ".terminate", terminateButton); // Add to components map // Close Tab Button JButton closeButton = new JButton("Close Tab"); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { removeJobTab(jobId); } }); } }); closeButton.setEnabled(false); buttonsPanel.add(closeButton); addUIElement("jobs." + jobId + ".closetab", closeButton); // Add to components map JPanel centerPanel = new JPanel(); centerPanel.setLayout(new GridBagLayout()); jobPanel.add(centerPanel, BorderLayout.CENTER); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weightx = 1.0; /* -- Job Information -- */ JPanel jobInfoPanel = new JPanel(); jobInfoPanel.setBorder(BorderFactory.createTitledBorder("Job Information")); jobInfoPanel.setLayout(new GridBagLayout()); c.gridy = 0; c.ipady = 30; centerPanel.add(jobInfoPanel, c); GridBagConstraints c1 = new GridBagConstraints(); c1.fill = GridBagConstraints.BOTH; c1.weightx = 1; c1.weighty = 1; // Name jobInfoPanel.add(new JLabel("Name :"), c1); JLabel jobNameLabel = new JLabel(); jobInfoPanel.add(jobNameLabel, c1); jobNameLabel.setText(profile.getJob().getClass().getSimpleName()); addUIElement("jobs." + jobId + ".job.name", jobNameLabel); // Add to components map // Gap jobInfoPanel.add(new JLabel(), c1); // Type jobInfoPanel.add(new JLabel("Type :"), c1); JLabel jobType = new JLabel(); jobType.setText(getJobType(profile.getJob())); jobInfoPanel.add(jobType, c1); addUIElement("jobs." + jobId + ".job.type", jobType); // Add to components map // Job Class Name c1.gridy = 1; c1.gridwidth = 1; jobInfoPanel.add(new JLabel("GridJob Class :"), c1); c1.gridwidth = GridBagConstraints.REMAINDER; JLabel jobClassLabel = new JLabel(); jobClassLabel.setText(profile.getJob().getClass().getName()); jobInfoPanel.add(jobClassLabel, c1); addUIElement("jobs." + jobId + ".job.class", jobClassLabel); // Add to components map /* -- Execution Information -- */ JPanel executionInfoPanel = new JPanel(); executionInfoPanel.setBorder(BorderFactory.createTitledBorder("Execution Statistics")); executionInfoPanel.setLayout(new GridBagLayout()); c.gridy = 1; c.ipady = 30; centerPanel.add(executionInfoPanel, c); GridBagConstraints c3 = new GridBagConstraints(); c3.weightx = 1; c3.weighty = 1; c3.fill = GridBagConstraints.BOTH; // Start Time executionInfoPanel.add(new JLabel("Job Status :"), c3); final JLabel statusLabel = new JLabel("Initializing"); executionInfoPanel.add(statusLabel, c3); addUIElement("jobs." + jobId + ".execution.status", statusLabel); // Add to components map // Status Update Listener profile.getFuture().addGridJobStateListener(new GridJobStateListener() { public void stateChanged(final GridJobState newState) { SwingUtilities.invokeLater(new Runnable() { public void run() { statusLabel.setText(StringUtils.capitalize(newState.toString().toLowerCase())); } }); } }); executionInfoPanel.add(new JLabel(), c3); // Space Holder // Percent Complete executionInfoPanel.add(new JLabel("Completed % :"), c3); final JLabel percentLabel = new JLabel("-N/A-"); executionInfoPanel.add(percentLabel, c3); addUIElement("jobs." + jobId + ".execution.percentage", percentLabel); // Add to components map c3.gridy = 1; // Start Time executionInfoPanel.add(new JLabel("Start Time :"), c3); JLabel startTimeLabel = new JLabel(DateFormat.getInstance().format(new Date(startTime))); executionInfoPanel.add(startTimeLabel, c3); addUIElement("jobs." + jobId + ".execution.starttime", startTimeLabel); // Add to components map executionInfoPanel.add(new JLabel(), c3); // Space Holder // Elapsed Time executionInfoPanel.add(new JLabel("Elapsed Time :"), c3); JLabel elapsedTimeLabel = new JLabel("-N/A-"); executionInfoPanel.add(elapsedTimeLabel, c3); addUIElement("jobs." + jobId + ".execution.elapsedtime", elapsedTimeLabel); // Add to components map c3.gridy = 2; // Tasks Deployed (Count) executionInfoPanel.add(new JLabel("Tasks Deployed :"), c3); JLabel tasksDeployedLabel = new JLabel("-N/A-"); executionInfoPanel.add(tasksDeployedLabel, c3); addUIElement("jobs." + jobId + ".execution.tasks", tasksDeployedLabel); // Add to components map executionInfoPanel.add(new JLabel(), c3); // Space Holder // Results Collected (Count) executionInfoPanel.add(new JLabel("Results Collected :"), c3); JLabel resultsCollectedLabel = new JLabel("-N/A-"); executionInfoPanel.add(resultsCollectedLabel, c3); addUIElement("jobs." + jobId + ".execution.results", resultsCollectedLabel); // Add to components map c3.gridy = 3; // Remaining Tasks (Count) executionInfoPanel.add(new JLabel("Remaining Tasks :"), c3); JLabel remainingTasksLabel = new JLabel("-N/A-"); executionInfoPanel.add(remainingTasksLabel, c3); addUIElement("jobs." + jobId + ".execution.remaining", remainingTasksLabel); // Add to components map executionInfoPanel.add(new JLabel(), c3); // Space Holder // Failed Tasks (Count) executionInfoPanel.add(new JLabel("Failed Tasks :"), c3); JLabel failedTasksLabel = new JLabel("-N/A-"); executionInfoPanel.add(failedTasksLabel, c3); addUIElement("jobs." + jobId + ".execution.failed", failedTasksLabel); // Add to components map /* -- Submitter Information -- */ UUID ownerId = profile.getOwner(); GridNodeDelegate owner = ClusterManager.getInstance().getClusterRegistrationService() .getGridNodeDelegate(ownerId); JPanel ownerInfoPanel = new JPanel(); ownerInfoPanel.setBorder(BorderFactory.createTitledBorder("Owner Information")); ownerInfoPanel.setLayout(new GridBagLayout()); c.gridy = 2; c.ipady = 10; centerPanel.add(ownerInfoPanel, c); GridBagConstraints c2 = new GridBagConstraints(); c2.fill = GridBagConstraints.BOTH; c2.weightx = 1; c2.weighty = 1; // Host Name ownerInfoPanel.add(new JLabel("Host Name :"), c2); JLabel hostNameLabel = new JLabel(owner.getProfile().getName()); ownerInfoPanel.add(hostNameLabel, c2); addUIElement("jobs." + jobId + ".owner.hostname", hostNameLabel); // Add to components map // Gap ownerInfoPanel.add(new JLabel(), c2); // Host IP Address ownerInfoPanel.add(new JLabel("Host IP :"), c2); JLabel hostIPLabel = new JLabel(owner.getProfile().getIpAddress()); ownerInfoPanel.add(hostIPLabel, c2); addUIElement("jobs." + jobId + ".owner.hostip", hostIPLabel); // Add to components map // Owner UUID c2.gridy = 1; c2.gridx = 0; ownerInfoPanel.add(new JLabel("Owner ID :"), c2); JLabel ownerIdLabel = new JLabel(profile.getOwner().toString()); c2.gridx = 1; c2.gridwidth = 4; ownerInfoPanel.add(ownerIdLabel, c2); addUIElement("jobs." + jobId + ".owner.id", ownerIdLabel); // Add to components map SwingUtilities.invokeLater(new Runnable() { public void run() { // Create Tab addUIElement("jobs." + jobId, jobPanel); JTabbedPane tabs = getUIElement("tabs"); tabs.addTab(profile.getJob().getClass().getSimpleName(), jobPanel); tabs.revalidate(); } }); // Execution Information Updater Thread new Thread(new Runnable() { boolean initialized = false; boolean unbounded = false; public void run() { // Unbounded, No Progress Supported if ((!initialized) && profile.getJob() instanceof UnboundedGridJob<?>) { SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setIndeterminate(true); progressBar.setStringPainted(false); // Infinity Symbol percentLabel.setText(String.valueOf('\u221e')); } }); initialized = true; unbounded = true; } // Update Job Info while (true) { try { // 500ms Interval Thread.sleep(500); } catch (InterruptedException e) { log.warn("Interrupted Progress Updater Thread", e); } final int totalCount = profile.getTotalTasks(); final int tasksRem = profile.getTaskCount(); final int resCount = profile.getResultCount(); final int failCount = profile.getFailedCount(); showBusyIcon(); // Task Information JLabel totalTaskLabel = getUIElement("jobs." + jobId + ".execution.tasks"); totalTaskLabel.setText(String.valueOf(totalCount)); // Result Count JLabel resCountLabel = getUIElement("jobs." + jobId + ".execution.results"); resCountLabel.setText(String.valueOf(resCount)); // Remaining Task Count JLabel remLabel = getUIElement("jobs." + jobId + ".execution.remaining"); remLabel.setText(String.valueOf(tasksRem)); // Failed Task Count JLabel failedLabel = getUIElement("jobs." + jobId + ".execution.failed"); failedLabel.setText(String.valueOf(failCount)); // Elapsed Time JLabel elapsedLabel = getUIElement("jobs." + jobId + ".execution.elapsedtime"); elapsedLabel.setText(TimeUtils.timeDifference(startTime)); // Job State final JLabel statusLabel = getUIElement("jobs." + jobId + ".execution.status"); // If not in Executing Mode if ((!profile.getFuture().isJobFinished()) && profile.getFuture().getState() != GridJobState.EXECUTING) { SwingUtilities.invokeLater(new Runnable() { public void run() { // Progress Bar progressBar.setIndeterminate(true); progressBar.setStringPainted(false); // Status Text String state = profile.getFuture().getState().toString(); statusLabel.setText(StringUtils.capitalize(state.toLowerCase())); // Percentage Label percentLabel.setText(String.valueOf('\u221e')); } }); } else { // Executing Mode : Progress Information // Job Finished, Stop if (profile.getFuture().isJobFinished()) { showIdleIcon(); return; } // Double check for status label if (!statusLabel.getText().equalsIgnoreCase("executing")) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String newstate = profile.getFuture().getState().toString(); statusLabel.setText(StringUtils.capitalize(newstate.toLowerCase())); } }); } if (!unbounded) { final int percentage = (int) (profile.percentage() * 100); //final int failCount = profile.get SwingUtilities.invokeLater(new Runnable() { public void run() { // If finished at this point, do not update if (progressBar.getValue() == 100) { return; } // If ProgressBar is in indeterminate if (progressBar.isIndeterminate()) { progressBar.setIndeterminate(false); progressBar.setStringPainted(true); } // Update Progress Bar / Percent Label progressBar.setValue(percentage); percentLabel.setText(percentage + " %"); } }); } } } } }).start(); // Job End Hook to Execute Job End Actions ServiceEventsSupport.addServiceHook(new ServiceHookCallback() { public void onServiceEvent(final ServiceMessage event) { SwingUtilities.invokeLater(new Runnable() { public void run() { JButton close = getUIElement("jobs." + jobId + ".closetab"); JButton terminate = getUIElement("jobs." + jobId + ".terminate"); terminate.setEnabled(false); close.setEnabled(true); JProgressBar progress = getUIElement("jobs." + jobId + ".progress"); JLabel percentage = getUIElement("jobs." + jobId + ".execution.percentage"); progress.setEnabled(false); // If Successfully Finished if (event.getType() == ServiceMessageType.JOB_END) { if (profile.getFuture().getState() != GridJobState.FAILED) { // If Not Job Failed progress.setValue(100); percentage.setText("100 %"); } else { // If Failed percentage.setText("N/A"); } // Stop (if) Indeterminate Progress Bar if (progress.isIndeterminate()) { progress.setIndeterminate(false); progress.setStringPainted(true); } } else if (event.getType() == ServiceMessageType.JOB_CANCEL) { if (progress.isIndeterminate()) { progress.setIndeterminate(false); progress.setStringPainted(false); percentage.setText("N/A"); } } showIdleIcon(); } }); } }, jobId, ServiceMessageType.JOB_CANCEL, ServiceMessageType.JOB_END); }
From source file:org.apache.cayenne.modeler.util.LongRunningTask.java
/** * Updates current state of the progress dialog. *//* w w w.j a va 2 s .c om*/ protected void updateProgress() { if (isCanceled()) { stop(); return; } dialog.getStatusLabel().setText(getCurrentNote()); JProgressBar progressBar = dialog.getProgressBar(); if (!isIndeterminate()) { progressBar.setValue(getCurrentValue()); progressBar.setIndeterminate(false); } else { progressBar.setIndeterminate(true); } }
From source file:org.gofleet.module.routing.RoutingMap.java
private void newPlan(LatLon from) { JDialog d = new JDialog(basicWindow.getFrame(), "Generating New Plan"); try {/*from ww w .j av a 2 s . com*/ JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new RoutingFilter()); fc.setAcceptAllFileFilterUsed(true); int returnVal = fc.showOpenDialog(basicWindow.getFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); log.debug("Opening: " + file.getName()); JProgressBar progressBar = new JProgressBar(0, getNumberLines(file) * 2); progressBar.setValue(0); progressBar.setPreferredSize(new Dimension(150, 50)); progressBar.setStringPainted(true); d.add(progressBar); d.pack(); d.setVisible(true); TSPPlan[] param = processFile(file, progressBar); Map<String, String> values = getValues(from); double[] origin = new double[2]; origin[0] = new Double(values.get("origin_x")); origin[1] = new Double(values.get("origin_y")); TSPPlan[] res = calculateRouteOnWS(new Integer(values.get("maxDistance")), new Integer(values.get("maxTime")), origin, new Integer(values.get("startTime")), param, new Integer(values.get("timeSpentOnStop"))); progressBar.setValue(progressBar.getMaximum() - res.length); processTSPPlan(res, progressBar); } else { log.trace("Open command cancelled by user."); } } catch (Throwable t) { log.error("Error computing new plan", t); JOptionPane.showMessageDialog(basicWindow.getFrame(), "<html><p>" + i18n.getString("Main.Error") + ":</p><p>" + t.toString() + "</p><html>", i18n.getString("Main.Error"), JOptionPane.ERROR_MESSAGE); } finally { d.setVisible(false); d.dispose(); } }
From source file:org.gofleet.module.routing.RoutingMap.java
private void processTSPPlan(TSPPlan[] res, JProgressBar progressBar) { Random random = new Random(); try {//from w ww . j a v a 2s. c o m @SuppressWarnings("unchecked") Collection<Layer> allLayers = Collections.unmodifiableCollection(this.mapView.getAllLayers()); List<Layer> toremove = new LinkedList<Layer>(); for (Layer l : allLayers) { if (l.name.startsWith("Route Plan") || l.name.startsWith("Stops")) toremove.add(l); } for (Layer l : toremove) this.mapView.removeLayer(l); LatLon latlon_origin = null; int id_layer = 0; for (TSPPlan plan : res) { latlon_origin = new LatLon(plan.getOrigin()[1], plan.getOrigin()[0]); log.info(latlon_origin); LineElemStyle ls = new LineElemStyle(); float f = random.nextFloat(); ls.color = Color.getHSBColor(f * random.nextFloat(), 0.9f, 0.9f); ls.width = LogicConstants.getInt("PLAN_WAY_WIDTH", 2); MarkerLayer stops = new MarkerLayer(new GpxData(), "Stops " + id_layer, File.createTempFile("stops", "tmp"), new GpxLayer(new GpxData()), this.mapView); stops.data.add(new StopMarker(latlon_origin, "origin", "tsp_stop", stops, 0, 0, ls.color)); for (String stop : plan.getStops()) { String[] array = stop.split(","); double[] point = new double[2]; point[1] = new Double(array[0]); point[0] = new Double(array[1]); LatLon ll = new LatLon(point[0], point[1]); log.info(ll); stops.data.add(new StopMarker(ll, array[2], "tsp_stop", stops, 0, 0, ls.color)); } this.mapView.addLayer(stops, true); OsmDataLayer layer = new OsmDataLayer(new DataSet(), "Route Plan " + id_layer++, File.createTempFile("planning", "route")); String way2 = plan.getWay(); if (way2 != null) { Way way = new Way(); LatLon info = null; MultiLineString multilinestring = (MultiLineString) wktReader.read(way2); multilinestring.getLength(); int numGeometries = multilinestring.getNumGeometries(); for (int i = 0; i < numGeometries; i++) { for (Coordinate coordenada : multilinestring.getGeometryN(i).getCoordinates()) { LatLon ll = new LatLon(coordenada.y, coordenada.x); way.addNode(new Node(ll)); if (info == null) info = ll; } way.mappaintStyle = ls; layer.data.ways.add(way); way = new Way(); } progressBar.setValue(progressBar.getValue() + 1); StopMarker marker = new StopMarker(info, (new Double(plan.getDistance())).toString().substring(0, 5) + " km in " + (new Double(plan.getTime() / 60)).toString().substring(0, 3) + " hours", "tsp_stop", stops, 0, 0, ls.color); marker.setPaintIcon(false); stops.data.add(marker); } this.mapView.addLayer(layer, true); layer.visible = true; stops.visible = true; } } catch (Throwable e) { log.error("Error painting plan", e); } }
From source file:org.gofleet.module.routing.RoutingMap.java
private TSPPlan[] processFile(File file, JProgressBar progressbar) { try {/*from w w w . j av a 2s . c o m*/ LinkedList<TSPPlan> res = new LinkedList<TSPPlan>(); BufferedReader br = new BufferedReader(new FileReader(file)); String line; int i = 0; TSPPlan plan = new TSPPlan(); while ((line = br.readLine()) != null) { log.trace(line); progressbar.setValue(i++); if (!line.isEmpty()) plan.addStops(line); else { res.add(plan); plan = new TSPPlan(); } } res.add(plan); return res.toArray(new TSPPlan[0]); } catch (Throwable e) { log.error("Error processing file", e); } return null; }