List of usage examples for java.beans PropertyChangeEvent getNewValue
public Object getNewValue()
From source file:org.apache.catalina.loader.WebappLoader.java
/** * Process property change events from our associated Context. * * @param event The property change event that has occurred *///from ww w . j a v a 2 s . c om public void propertyChange(PropertyChangeEvent event) { // Validate the source of this event if (!(event.getSource() instanceof Context)) return; Context context = (Context) event.getSource(); // Process a relevant property change if (event.getPropertyName().equals("reloadable")) { try { setReloadable(((Boolean) event.getNewValue()).booleanValue()); } catch (NumberFormatException e) { log.error(sm.getString("webappLoader.reloadable", event.getNewValue().toString())); } } }
From source file:pipeline.GUI_utils.ListOfPointsView.java
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override/*w ww .ja v a 2 s. co m*/ public void show() { if (frame != null) frame.toFront(); if (table == null) { spreadsheetEngine = new DependencyEngine(new BasicEngineProvider()); setupTableModel(points); silenceUpdates.incrementAndGet(); table = new JXTablePerColumnFiltering(tableModel); table.setRolloverEnabled(true); // table.setDragEnabled(true); table.setFillsViewportHeight(false); table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); table.setShowGrid(true); table.setShowHorizontalLines(true); table.setColumnSelectionAllowed(true); table.setRowSelectionAllowed(true); table.setColumnControlVisible(true); table.setHighlighters(new Highlighter[] { HighlighterFactory.createAlternateStriping() }); table.addPropertyChangeListener("horizontalScrollEnabled", new PropertyChangeListener() { JViewport viewPort, filteringViewPort, columnDescViewPort; int lastX; ChangeListener scrollListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (viewPort == null || filteringViewPort == null) { return; } Point position = viewPort.getViewPosition(); if (position.x == lastX) { return; } filteringViewPort.setViewPosition(position); columnDescViewPort.setViewPosition(position); lastX = position.x; } }; @Override public void propertyChange(PropertyChangeEvent evt) { if (viewPort != null) { viewPort.removeChangeListener(scrollListener); } if (evt.getNewValue().equals(true)) { viewPort = getTableViewPort(table); if (viewPort == null) { return; } table.filteringTable.setHorizontalScrollEnabled(true); table.tableForColumnDescriptions.setHorizontalScrollEnabled(true); table.updateFilteringTableSetup(); filteringViewPort = getTableViewPort(table.filteringTable); columnDescViewPort = getTableViewPort(table.tableForColumnDescriptions); viewPort.addChangeListener(scrollListener); scrollListener.stateChanged(null); } else { table.filteringTable.setHorizontalScrollEnabled(false); table.tableForColumnDescriptions.setHorizontalScrollEnabled(false); } } }); modelForColumnDescriptions = new dataModelAllEditable(1, tableModel.getColumnCount()); Vector<String> rowVector0 = (Vector<String>) modelForColumnDescriptions.getDataVector().get(0); for (int j = 0; j < tableModel.getColumnCount(); j++) { rowVector0.setElementAt(tableModel.getColumnName(j), j); } boolean done; do { done = true; for (TableColumn i : table.getColumns(true)) { TableColumnExt iCast = (TableColumnExt) i; if (iCast.getTitle().equals("Class") || iCast.getTitle().equals("c") || iCast.getTitle().equals("t") || iCast.getTitle().equals("clusterID") || iCast.getTitle().equals("userCell 2") || iCast.getTitle().equals("userCell 3")) { if (iCast.isVisible()) { iCast.setVisible(false); done = false; break; } } } } while (!done); SwingUtilities.invokeLater(modelForColumnDescriptions::fireTableDataChanged); JScrollPane scrollPane = new JScrollPane(table); scrollPane.setPreferredSize(new Dimension(2000, 2000)); updateColumnDescriptions(); silenceUpdates.decrementAndGet(); setSpreadsheetColumnEditorAndRenderer(); tableForColumnDescriptions = new JXTable(modelForColumnDescriptions); table.tableForColumnDescriptions = tableForColumnDescriptions; JScrollPane jScrollPaneForNames = new JScrollPane(tableForColumnDescriptions); jScrollPaneForNames.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); JPanel controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); JButton createScatterPlotButton = new JButton("Scatter plot from selected columns"); controlPanel.add(createScatterPlotButton); createScatterPlotButton.setActionCommand("Scatter plot from selected columns"); createScatterPlotButton.addActionListener(this); realTimeUpdateCheckbox = new JCheckBox("Update display in real time"); controlPanel.add(realTimeUpdateCheckbox); realTimeUpdateCheckbox.setActionCommand("Update display in real time"); realTimeUpdateCheckbox.addActionListener(this); JButton forceUpdate = new JButton("Force display update"); controlPanel.add(forceUpdate); forceUpdate.setActionCommand("Force display update"); forceUpdate.addActionListener(this); JButton extendFormula = new JButton("Extend formula to column"); controlPanel.add(extendFormula); extendFormula.setActionCommand("Extend formula to column"); extendFormula.addActionListener(this); JButton saveFormulas = new JButton("Save user formulas..."); saveFormulas.addActionListener(this); saveFormulas.setActionCommand("Save user formulas"); controlPanel.add(saveFormulas); JButton reloadFormulas = new JButton("Reload user formulas..."); reloadFormulas.addActionListener(this); reloadFormulas.setActionCommand("Reload user formulas"); controlPanel.add(reloadFormulas); controlPanel.add(new JLabel("Color with:")); coloringComboBox = new JComboBox(); controlPanel.add(coloringComboBox); DefaultComboBoxModel comboBoxModel = (DefaultComboBoxModel) coloringComboBox.getModel(); coloringComboBox.addActionListener(this); for (int i = 0; i < tableModel.getColumnCount(); i++) { comboBoxModel.addElement(tableModel.getColumnName(i)); } JButton saveTableToFile = new JButton("Save table to file"); controlPanel.add(saveTableToFile); saveTableToFile.setActionCommand("Save table to file"); saveTableToFile.addActionListener(this); /* final JCheckBox useCalibration = new JCheckBox("Use calibration"); useCalibration.addActionListener(e -> { if (points == null) return; boolean selected = useCalibration.isSelected(); if (selected && !(points instanceof PluginIOCalibrable)) { Utils.displayMessage("Type " + points.getClass().getName() + " does not have calibration", true, LogLevel.ERROR); return; } PluginIOCalibrable calibrable = (PluginIOCalibrable) points; if (selected && (calibrable.getCalibration() == null)) { Utils.displayMessage("Calibration information is not present in the segmentation; one " + "way of adding it is to give the source image (with calibration) as an input " + "to the active contour plugin", true, LogLevel.ERROR); return; } float xyCalibration = selected ? ((float) calibrable.getCalibration().pixelWidth) : 0; float zCalibration = selected ? ((float) calibrable.getCalibration().pixelDepth) : 0; updateCalibration(xyCalibration, zCalibration); }); PluginIOCalibrable calibrable = null; if (points instanceof PluginIOCalibrable) calibrable = (PluginIOCalibrable) points; boolean calibrationPresent = calibrable != null && calibrable.getCalibration() != null; useCalibration.setSelected(calibrationPresent); if (calibrationPresent) { updateCalibration((float) calibrable.getCalibration().pixelWidth, (float) calibrable.getCalibration().pixelDepth); } controlPanel.add(useCalibration); */ frame = new JFrame(points.getName()); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); listener = new WindowListenerWeakRef(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { close();// So all references to data are nulled, to ensure garbage collection } }); frame.addWindowListener(listener); frame.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.gridx = 0; c.gridy = GridBagConstraints.RELATIVE; c.weighty = 0.75; c.weightx = 1.0; c.gridwidth = 1; c.gridheight = 1; frame.add(scrollPane, c); c.weighty = 0.0; JScrollPane scrollPane2 = new JScrollPane(table.filteringTable); scrollPane2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scrollPane2.setMinimumSize(new Dimension(1, 250)); frame.add(scrollPane2, c); c.weighty = 0.0; jScrollPaneForNames.setMinimumSize(new Dimension(1, 40)); jScrollPaneForNames.setMaximumSize(new Dimension(9999999, 40)); frame.add(jScrollPaneForNames, c); c.weighty = 0.0; c.fill = GridBagConstraints.HORIZONTAL; controlPanel.setMinimumSize(new Dimension(1, 80)); frame.add(controlPanel, c); table.setHorizontalScrollEnabled(true); table.updateFilteringTableSetup(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int height = screenSize.height; int width = screenSize.width; frame.setSize((int) (0.67 * width), height / 2); frame.setLocation((int) (0.33 * width), height / 2); frame.setVisible(true); } if ((tableUpdateThread == null) || (!tableUpdateThread.isAlive())) { tableUpdateThread = new Thread(() -> { try { checkForDirtiness(); } catch (Exception e) { Utils.log("Exception in ListOfPointsView GUI update thread", LogLevel.ERROR); Utils.printStack(e); } }, "ListOfPointsView GUI update thread"); tableUpdateThread.start(); } }
From source file:Installer.java
@Override public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { int progress = (Integer) evt.getNewValue(); System.out.println(progress); }// w w w . j a v a 2 s . co m }
From source file:org.jdesktop.swingworker.AccumulativeRunnable.java
public final void test6493680() throws Exception { final AtomicInteger lastProgressValue = new AtomicInteger(-1); final Exchanger<Boolean> exchanger = new Exchanger<Boolean>(); class Test {//from ww w . ja va 2 s.c o m private final AtomicInteger lastProgressValue = new AtomicInteger(-1); private final Exchanger<Boolean> exchanger = new Exchanger<Boolean>(); boolean test() throws Exception { TestSwingWorker swingWorker = new TestSwingWorker(); swingWorker.addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { lastProgressValue.set((Integer) evt.getNewValue()); } } }); swingWorker.execute(); return exchanger.exchange(true); } class TestSwingWorker extends SwingWorker<Void, Void> { @Override protected Void doInBackground() throws Exception { for (int i = 0; i <= 100; i++) { Thread.sleep(1); setProgress(i); } return null; } @Override protected void done() { boolean isPassed = (lastProgressValue.get() == 100); try { exchanger.exchange(isPassed); } catch (Exception ingore) { } } } } /* * because timing is involved in this bug we will run the test * NUMBER_OF_TRIES times. * the tes`t passes if it does not fail once. */ final int NUMBER_OF_TRIES = 50; for (int i = 0; i < NUMBER_OF_TRIES; i++) { assertTrue((new Test()).test()); } }
From source file:edu.ku.brc.af.core.db.MySQLBackupService.java
public boolean doRestoreBulkDataInBackground(final String databaseName, final String options, final String restoreZipFilePath, final SimpleGlassPane glassPane, final String completionMsgKey, final PropertyChangeListener pcl, final boolean doSynchronously, final boolean doDropDatabase) { getNumberofTables();/*w w w.j a v a 2s .c om*/ SynchronousWorker backupWorker = new SynchronousWorker() { long dspMegs = 0; @Override protected Integer doInBackground() throws Exception { boolean skipTrackExceptions = BasicSQLUtils.isSkipTrackExceptions(); BasicSQLUtils.setSkipTrackExceptions(false); try { String userName = itUsername != null ? itUsername : DBConnection.getInstance().getUserName(); String password = itPassword != null ? itPassword : DBConnection.getInstance().getPassword(); DBConnection currDBConn = DBConnection.getInstance(); String dbName = currDBConn.getDatabaseName(); DBMSUserMgr dbMgr = DBMSUserMgr.getInstance(); if (dbMgr != null) { boolean isConnected = dbMgr.connectToDBMS(userName, password, currDBConn.getServerName(), dbName, currDBConn.isEmbedded()); if (isConnected) { if (doDropDatabase) { if (dbMgr.doesDBExists(databaseName) && !dbMgr.dropDatabase(databaseName)) { log.error("Database[" + databaseName + "] could not be dropped before load."); UIRegistry.showLocalizedError("MySQLBackupService.ERR_DRP_DB", databaseName); return null; } if (!dbMgr.createDatabase(databaseName)) { log.error("Database[" + databaseName + "] could not be created before load."); UIRegistry.showLocalizedError("MySQLBackupService.CRE_DRP_DB", databaseName); return null; } } DatabaseDriverInfo driverInfo = DatabaseDriverInfo .getDriver(DBConnection.getInstance().getDriverName()); String connStr = DBConnection.getInstance().getConnectionStr(); DBConnection itDBConn = DBConnection.createInstance(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(), databaseName, connStr, userName, password); Connection connection = itDBConn.createConnection(); connection.setCatalog(databaseName); List<File> unzippedFiles = ZipFileHelper.getInstance() .unzipToFiles(new File(restoreZipFilePath)); boolean dbCreated = false; for (File file : unzippedFiles) { //System.out.println(file.getName()); if (file.getName().equals("createdb.sql")) { long size = restoreFile(connection, file); log.debug("size: " + size); dbCreated = true; } } if (dbCreated) { for (File file : unzippedFiles) { if (file.getName().endsWith("infile")) { String fPath = file.getCanonicalPath(); if (UIHelper.isWindows()) { fPath = StringUtils.replace(fPath, "\\", "\\\\"); } String sql = "LOAD DATA LOCAL INFILE '" + fPath + "' INTO TABLE " + FilenameUtils.getBaseName(file.getName()); log.debug(sql); //System.err.println(sql); int rv = BasicSQLUtils.update(connection, sql); log.debug("done fPath[" + fPath + "] rv= " + rv); //System.err.println("done fPath["+fPath+"] rv= "+rv); } } } ZipFileHelper.getInstance().cleanUp(); /*if (!dbMgr.dropDatabase(databaseName)) { log.error("Database["+databaseName+"] could not be dropped after load."); UIRegistry.showLocalizedError("MySQLBackupService.ERR_DRP_DBAF", databaseName); }*/ setProgress(100); //errorMsg = sb.toString(); itDBConn.close(); } else { // error can't connect } } else { // error } } catch (Exception ex) { ex.printStackTrace(); errorMsg = ex.toString(); if (pcl != null) { pcl.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1)); } } finally { BasicSQLUtils.setSkipTrackExceptions(skipTrackExceptions); } return null; } @Override protected void done() { super.done(); JStatusBar statusBar = UIRegistry.getStatusBar(); if (statusBar != null) { statusBar.setProgressDone(STATUSBAR_NAME); } if (glassPane != null) { UIRegistry.clearSimpleGlassPaneMsg(); } if (StringUtils.isNotEmpty(errorMsg)) { UIRegistry.showError(errorMsg); } if (statusBar != null) { statusBar.setText(UIRegistry.getLocalizedMessage(completionMsgKey, dspMegs)); } if (pcl != null) { pcl.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, DONE, 0, 1)); } } }; if (glassPane != null) { glassPane.setProgress(0); } backupWorker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (MEGS.equals(evt.getPropertyName()) && glassPane != null) { int value = (Integer) evt.getNewValue(); if (value < 100) { glassPane.setProgress((Integer) evt.getNewValue()); } else { glassPane.setProgress(100); } } } }); if (doSynchronously) { return backupWorker.doWork(); } backupWorker.execute(); return true; }
From source file:edu.ku.brc.af.core.db.MySQLBackupService.java
/** * Does the backup on a SwingWorker Thread. * @param isMonthly whether it is a monthly backup * @param doSendAppExit requests sending an application exit command when done * @return true if the prefs are set up and there were no errors before the SwingWorker thread was started *//*from ww w .ja v a 2 s . c o m*/ private boolean doBackUp(final boolean isMonthly, final boolean doSendAppExit, final PropertyChangeListener propChgListener) { AppPreferences remotePrefs = AppPreferences.getLocalPrefs(); final String mysqldumpLoc = remotePrefs.get(MYSQLDUMP_LOC, getDefaultMySQLDumpLoc()); final String backupLoc = remotePrefs.get(MYSQLBCK_LOC, getDefaultBackupLoc()); if (!(new File(mysqldumpLoc)).exists()) { UIRegistry.showLocalizedError("MySQLBackupService.MYSQL_NO_DUMP", mysqldumpLoc); if (propChgListener != null) { propChgListener.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1)); } return false; } File backupDir = new File(backupLoc); if (!backupDir.exists()) { if (!backupDir.mkdir()) { UIRegistry.showLocalizedError("MySQLBackupService.MYSQL_NO_BK_DIR", backupDir.getAbsoluteFile()); if (propChgListener != null) { propChgListener.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1)); } return false; } } errorMsg = null; final String databaseName = DBConnection.getInstance().getDatabaseName(); getNumberofTables(); SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() { protected String fullPath = null; /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Integer doInBackground() throws Exception { FileOutputStream backupOut = null; try { Thread.sleep(100); // Create output file SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_kk_mm_ss"); String fileName = sdf.format(Calendar.getInstance().getTime()) + (isMonthly ? "_monthly" : "") + ".sql"; fullPath = backupLoc + File.separator + fileName; File file = new File(fullPath); backupOut = new FileOutputStream(file); writeStats(getCollectionStats(getTableNames()), getStatsName(fullPath)); String userName = DBConnection.getInstance().getUserName(); String password = DBConnection.getInstance().getPassword(); if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) { Pair<String, String> up = UserAndMasterPasswordMgr.getInstance().getUserNamePasswordForDB(); if (up != null && up.first != null && up.second != null) { userName = up.first; password = up.second; } } String port = DatabaseDriverInfo.getDriver(DBConnection.getInstance().getDriverName()) .getPort(); String server = DBConnection.getInstance().getServerName(); Vector<String> args = new Vector<String>(); args.add(mysqldumpLoc); args.add("--user=" + userName); args.add("--password=" + password); args.add("--host=" + server); if (port != null) { args.add("--port=" + port); } args.add(databaseName); Process process = Runtime.getRuntime().exec(args.toArray(new String[0])); InputStream input = process.getInputStream(); byte[] bytes = new byte[8192 * 2]; double oneMeg = (1024.0 * 1024.0); long dspMegs = 0; long totalBytes = 0; do { int numBytes = input.read(bytes, 0, bytes.length); totalBytes += numBytes; if (numBytes > 0) { long megs = (long) (totalBytes / oneMeg); if (megs != dspMegs) { dspMegs = megs; long megsWithTenths = (long) ((totalBytes * 10.0) / oneMeg); firePropertyChange(MEGS, 0, megsWithTenths); } backupOut.write(bytes, 0, numBytes); } else { break; } } while (true); StringBuilder sb = new StringBuilder(); String line; BufferedReader errIn = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((line = errIn.readLine()) != null) { //System.err.println(line); if (line.startsWith("ERR") || StringUtils.contains(line, "Got error")) { sb.append(line); sb.append("\n"); if (StringUtils.contains(line, "1044") && StringUtils.contains(line, "LOCK TABLES")) { sb.append("\n"); sb.append(UIRegistry.getResourceString("MySQLBackupService.LCK_TBL_ERR")); sb.append("\n"); } } } errorMsg = sb.toString(); } catch (Exception ex) { ex.printStackTrace(); errorMsg = ex.toString(); UIRegistry.showLocalizedError("MySQLBackupService.EXCP_BK"); } finally { if (backupOut != null) { try { backupOut.flush(); backupOut.close(); } catch (IOException ex) { ex.printStackTrace(); errorMsg = ex.toString(); } } } return null; } @Override protected void done() { super.done(); UIRegistry.getStatusBar().setProgressDone(STATUSBAR_NAME); UIRegistry.clearSimpleGlassPaneMsg(); if (StringUtils.isNotEmpty(errorMsg)) { UIRegistry.showError(errorMsg); } if (doSendAppExit) { CommandDispatcher.dispatch(new CommandAction("App", "AppReqExit")); } if (propChgListener != null) { propChgListener .propertyChange(new PropertyChangeEvent(MySQLBackupService.this, DONE, null, fullPath)); } } }; final JStatusBar statusBar = UIRegistry.getStatusBar(); statusBar.setIndeterminate(STATUSBAR_NAME, true); UIRegistry.writeSimpleGlassPaneMsg(getLocalizedMessage("MySQLBackupService.BACKINGUP", databaseName), 24); backupWorker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (MEGS.equals(evt.getPropertyName())) { long value = (Long) evt.getNewValue(); double val = value / 10.0; statusBar.setText(UIRegistry.getLocalizedMessage("MySQLBackupService.BACKUP_MEGS", val)); } } }); backupWorker.execute(); return true; }
From source file:org.mwc.cmap.xyplot.views.XYPlotView.java
private void setupFiringChangesToChart() { // see if we've alreay been configured if (_timeListener != null) return;/*from ww w .j av a2 s.c om*/ // get the document being edited final IWorkbench wb = PlatformUI.getWorkbench(); final IWorkbenchWindow win = wb.getActiveWorkbenchWindow(); final IWorkbenchPage page = win.getActivePage(); editor = null; // the page might not yet be open... if (page != null) { editor = page.getActiveEditor(); // do we have an active editor? if (editor == null) { // see if there are any editors at all open final IEditorReference[] theEditors = page.getEditorReferences(); for (int i = 0; i < theEditors.length; i++) { final IEditorReference thisE = theEditors[i]; editor = thisE.getEditor(false); // right, see if it has a time manager final TimeProvider tp = (TimeProvider) editor.getAdapter(TimeProvider.class); if (tp != null) { final String hisId = tp.getId(); if (hisId == _myId) break; } } // nope, drop out. return; } } TimeProvider prov = null; if (editor != null) { // get it's time-provider interface prov = (TimeProvider) editor.getAdapter(TimeProvider.class); } else CorePlugin.logError(Status.WARNING, "Failed to identify time provider", null); if (prov != null) { // create our listener _timeListener = new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { // ok - fire the time change to the chart final HiResDate newDTG = (HiResDate) evt.getNewValue(); // right tell the plot it's new time _thePlot.newTime(null, newDTG, null); // and tell the plot holder to redraw everything _chartInPanel.newTime(null, newDTG, null); refreshPlot(); } }; // add our listener to the time object prov.addListener(_timeListener, TimeProvider.TIME_CHANGED_PROPERTY_NAME); // fire the current time to our chart (just to start us off) _chartInPanel.newTime(null, prov.getTime(), null); refreshPlot(); } }
From source file:edu.ku.brc.specify.datamodel.busrules.CollectionObjectBusRules.java
/** * //from w ww. jav a 2s . c o m */ public void doCreateBatchOfColObj(final Pair<String, String> catNumPair) { if (catNumPair.getFirst().equals(catNumPair.getSecond())) { return; } DBFieldInfo CatNumFld = DBTableIdMgr.getInstance().getInfoById(CollectionObject.getClassTableId()) .getFieldByColumnName("CatalogNumber"); final UIFieldFormatterIFace formatter = CatNumFld.getFormatter(); if (!formatter.isIncrementer()) { //XXX this will have been checked earlier, right? UIRegistry.showLocalizedError(NonIncrementingCatNum); return; } final Vector<String> nums = new Vector<String>(); processBatchContents(catNumPair, false, false, nums); SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() { private Vector<Pair<Integer, String>> objectsAdded = new Vector<Pair<Integer, String>>(); private Vector<String> objectsNotAdded = new Vector<String>(); private RecordSet batchRS; //private boolean invalidEntry = false; /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Integer doInBackground() throws Exception { String catNum = catNumPair.getFirst(); Integer collId = AppContextMgr.getInstance().getClassObject(Collection.class).getId(); String coIdSql = "select CollectionObjectID from collectionobject where CollectionMemberID = " + collId + " and CatalogNumber = '"; objectsAdded.add(new Pair<Integer, String>( (Integer) BasicSQLUtils.querySingleObj(coIdSql + catNum + "'"), catNum)); int cnt = 0; CollectionObject co = null; //CollectionObject carryForwardCo = (CollectionObject )formViewObj.getDataObj(); CollectionObject carryForwardCo; DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); try { carryForwardCo = session.get(CollectionObject.class, ((CollectionObject) formViewObj.getDataObj()).getId()); } finally { session.close(); } Thread.sleep(666); //Perhaps this is unnecessary, but it seems //to prevent sporadic "illegal access to loading collection" hibernate errors. try { for (String currentCat : nums) { try { co = new CollectionObject(); co.initialize(); //Collection doesn't get set in co.initialize(), or carryForward, but it needs to be set. co.setCollection(AppContextMgr.getInstance().getClassObject(Collection.class)); //ditto, but doesn't so much need to be set co.setModifiedByAgent(carryForwardCo.getModifiedByAgent()); co.setCatalogNumber(currentCat); formViewObj.setNewObject(co); if (formViewObj.saveObject()) { objectsAdded.add(new Pair<Integer, String>( (Integer) BasicSQLUtils .querySingleObj(coIdSql + co.getCatalogNumber() + "'"), co.getCatalogNumber())); } else { objectsNotAdded.add(formatter.formatToUI(co.getCatalogNumber()).toString()); } } catch (Exception ex) { log.error(ex); objectsNotAdded.add(formatter.formatToUI(currentCat) + ": " + (ex.getLocalizedMessage() == null ? "" : ex.getLocalizedMessage())); } cnt++; firePropertyChange(GLASSKEY, 0, cnt); } firePropertyChange(GLASSKEY, 0, nums.size()); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(Uploader.class, ex); } formViewObj.setDataObj(carryForwardCo); saveBatchObjectsToRS(); return objectsAdded.size(); } /** * Save the objects added to a Recordset */ protected void saveBatchObjectsToRS() { batchRS = new RecordSet(); batchRS.initialize(); batchRS.setDbTableId(CollectionObject.getClassTableId()); String name = getResourceString(BatchRSBaseName) + " " + formatter.formatToUI(catNumPair.getFirst()) + "-" + formatter.formatToUI(catNumPair.getSecond()); if (objectsNotAdded.size() > 0) { name += "-" + UIRegistry.getResourceString(IncompleteSaveFlag); } batchRS.setName(name); for (Pair<Integer, String> obj : objectsAdded) { batchRS.addItem(obj.getFirst()); } DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); boolean transOpen = false; try { BusinessRulesIFace busRule = DBTableIdMgr.getInstance().getBusinessRule(RecordSet.class); if (busRule != null) { busRule.beforeSave(batchRS, session); } batchRS.setTimestampCreated(new Timestamp(System.currentTimeMillis())); batchRS.setOwner(AppContextMgr.getInstance().getClassObject(SpecifyUser.class)); session.beginTransaction(); transOpen = true; session.save(batchRS); if (busRule != null) { if (!busRule.beforeSaveCommit(batchRS, session)) { session.rollback(); throw new Exception("Business rules processing failed"); } } session.commit(); transOpen = false; if (busRule != null) { busRule.afterSaveCommit(batchRS, session); } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(Uploader.class, ex); if (transOpen) { session.rollback(); } } } /** * Add the batch RS to the RecordSetTask UI */ protected void addBatchRSToUI() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { CommandAction cmd = new CommandAction(RecordSetTask.RECORD_SET, RecordSetTask.ADD_TO_NAV_BOX); cmd.setData(batchRS); CommandDispatcher.dispatch(cmd); } }); } /* (non-Javadoc) * @see javax.swing.SwingWorker#done() */ @Override protected void done() { super.done(); processingSeries.set(false); addBatchRSToUI(); UIRegistry.clearSimpleGlassPaneMsg(); if (objectsNotAdded.size() == 0) { UIRegistry.displayLocalizedStatusBarText(BatchSaveSuccess, formatter.formatToUI(catNumPair.getFirst()), formatter.formatToUI(catNumPair.getSecond())); } else { showBatchErrorObjects(objectsNotAdded, BatchSaveErrorsTitle, BatchSaveErrors); } } }; final SimpleGlassPane gp = UIRegistry.writeSimpleGlassPaneMsg(getI10N("SAVING_BATCH"), 24); gp.setProgress(0); worker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (GLASSKEY.equals(evt.getPropertyName())) { double value = (double) ((Integer) evt.getNewValue()).intValue(); int percent = (int) (value / ((double) nums.size()) * 100.0); gp.setProgress(percent); } } }); processingSeries.set(true); worker.execute(); // try { // worker.get(); // } catch (Exception ex) { // ex.printStackTrace(); // } }
From source file:org.jdesktop.swingworker.AccumulativeRunnable.java
public final void testPropertyChange() throws Exception { final Exchanger<Boolean> boolExchanger = new Exchanger<Boolean>(); final SwingWorker<?,?> test = new SwingWorker<Object, Object>() { @Override/*from w w w. j a va2 s . c om*/ protected Object doInBackground() throws Exception { firePropertyChange("test", null, "test"); return null; } }; test.addPropertyChangeListener( new PropertyChangeListener() { boolean isOnEDT = true; public void propertyChange(PropertyChangeEvent evt) { isOnEDT &= SwingUtilities.isEventDispatchThread(); if ("state".equals(evt.getPropertyName()) && StateValue.DONE == evt.getNewValue()) { try { boolExchanger.exchange(isOnEDT); } catch (Exception ignore) { ignore.printStackTrace(); } } } }); test.execute(); assertTrue(boolExchanger.exchange(null, TIME_OUT, TIME_OUT_UNIT)); }
From source file:edu.ku.brc.af.core.db.MySQLBackupService.java
/** * @param databaseName//w w w . j ava2 s . c om * @param restoreFilePath * @param glassPane * @param completionMsgKey */ protected boolean doRestoreInBackground(final String databaseName, final String restoreFilePath, final SimpleGlassPane glassPane, final String completionMsgKey, final PropertyChangeListener pcl, final boolean doSynchronously) { AppPreferences remotePrefs = AppPreferences.getLocalPrefs(); final String mysqlLoc = remotePrefs.get(MYSQL_LOC, getDefaultMySQLLoc()); getNumberofTables(); SynchronousWorker backupWorker = new SynchronousWorker() { long dspMegs = 0; long fileSize = 0; /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Integer doInBackground() throws Exception { FileInputStream input = null; try { String userName = itUsername != null ? itUsername : DBConnection.getInstance().getUserName(); String password = itPassword != null ? itPassword : DBConnection.getInstance().getPassword(); String port = DatabaseDriverInfo.getDriver(DBConnection.getInstance().getDriverName()) .getPort(); String server = DBConnection.getInstance().getServerName(); String cmdLine = String.format("%s -u %s --password=%s --host=%s %s %s", mysqlLoc, userName, password, server, (port != null ? ("--port=" + port) : ""), databaseName); Vector<String> args = new Vector<String>(); args.add(mysqlLoc); args.add("--user=" + userName); args.add("--password=" + password); args.add("--host=" + server); if (port != null) { args.add("--port=" + port); } args.add(databaseName); Process process = Runtime.getRuntime().exec(args.toArray(new String[0])); Thread.sleep(100); OutputStream out = process.getOutputStream(); // wait as long it takes till the other process has prompted. try { File inFile = new File(restoreFilePath); fileSize = inFile.length(); //System.out.println(fileSize); double oneMB = (1024.0 * 1024.0); double threshold = fileSize < (oneMB * 4) ? 8192 * 8 : oneMB; long totalBytes = 0; dspMegs = 0; input = new FileInputStream(inFile); try { byte[] bytes = new byte[8192 * 4]; do { int numBytes = input.read(bytes, 0, bytes.length); totalBytes += numBytes; if (numBytes > 0) { out.write(bytes, 0, numBytes); long megs = (long) (totalBytes / threshold); if (megs != dspMegs) { dspMegs = megs; firePropertyChange(MEGS, dspMegs, (int) ((100.0 * totalBytes) / fileSize)); } } else { break; } } while (true); } finally { input.close(); } } catch (IOException ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(MySQLBackupService.class, ex); ex.printStackTrace(); errorMsg = ex.toString(); UIRegistry.showLocalizedError("MySQLBackupService.EXCP_RS"); } catch (Exception ex) { ex.printStackTrace(); if (pcl != null) { pcl.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1)); } } setProgress(100); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = in.readLine()) != null) { //System.err.println(line); } in = new BufferedReader(new InputStreamReader(process.getErrorStream())); StringBuilder sb = new StringBuilder(); while ((line = in.readLine()) != null) { if (line.startsWith("ERR")) { sb.append(line); sb.append("\n"); } } errorMsg = sb.toString(); } catch (Exception ex) { ex.printStackTrace(); errorMsg = ex.toString(); if (pcl != null) { pcl.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1)); } } return null; } @Override protected void done() { super.done(); JStatusBar statusBar = UIRegistry.getStatusBar(); if (statusBar != null) { statusBar.setProgressDone(STATUSBAR_NAME); } if (glassPane != null) { UIRegistry.clearSimpleGlassPaneMsg(); } if (StringUtils.isNotEmpty(errorMsg)) { UIRegistry.showError(errorMsg); } if (statusBar != null) { statusBar.setText(UIRegistry.getLocalizedMessage(completionMsgKey, dspMegs)); } if (pcl != null) { pcl.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, DONE, 0, 1)); } } }; if (glassPane != null) { glassPane.setProgress(0); } backupWorker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (MEGS.equals(evt.getPropertyName()) && glassPane != null) { int value = (Integer) evt.getNewValue(); if (value < 100) { glassPane.setProgress((Integer) evt.getNewValue()); } else { glassPane.setProgress(100); } } } }); if (doSynchronously) { return backupWorker.doWork(); } backupWorker.execute(); return true; }