List of usage examples for javax.swing SwingWorker execute
public final void execute()
From source file:edu.ku.brc.specify.web.HttpLargeFileTransfer.java
/** * @param infileName/*from ww w. j a v a 2 s. co m*/ * @param outFileName * @param changeListener * @return */ public boolean compressFile(final String infileName, final String outFileName, final PropertyChangeListener propChgListener) { final File file = new File(infileName); if (file.exists()) { long fileSize = file.length(); if (fileSize > 0) { SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() { protected String errorMsg = null; protected FileInputStream fis = null; protected GZIPOutputStream fos = null; /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Integer doInBackground() throws Exception { try { Thread.sleep(100); long totalSize = file.length(); long bytesCnt = 0; FileInputStream fis = new FileInputStream(infileName); GZIPOutputStream fos = new GZIPOutputStream(new FileOutputStream(outFileName)); byte[] bytes = new byte[BUFFER_SIZE * 10]; while (true) { int len = fis.read(bytes); if (len > 0) { fos.write(bytes, 0, len); bytesCnt += len; firePropertyChange("MEGS", 0, (int) (((double) bytesCnt / (double) totalSize) * 100.0)); } else { break; } } fis.close(); fos.close(); } catch (Exception ex) { ex.printStackTrace(); errorMsg = ex.toString(); } finally { try { if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } catch (IOException ex) { errorMsg = ex.toString(); } } firePropertyChange("MEGS", 0, 100); return null; } @Override protected void done() { super.done(); UIRegistry.getStatusBar().setProgressDone(HttpLargeFileTransfer.class.toString()); //UIRegistry.clearSimpleGlassPaneMsg(); if (StringUtils.isNotEmpty(errorMsg)) { UIRegistry.showError(errorMsg); } if (propChgListener != null) { propChgListener.propertyChange( new PropertyChangeEvent(HttpLargeFileTransfer.this, "Done", 0, 1)); } } }; final JStatusBar statusBar = UIRegistry.getStatusBar(); statusBar.setIndeterminate(HttpLargeFileTransfer.class.toString(), true); UIRegistry.writeSimpleGlassPaneMsg(getLocalizedMessage("Compressing Backup..."), 24); backupWorker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if ("MEGS".equals(evt.getPropertyName())) { Integer value = (Integer) evt.getNewValue(); double val = value / 10.0; statusBar .setText(UIRegistry.getLocalizedMessage("MySQLBackupService.BACKUP_MEGS", val)); } } }); backupWorker.execute(); } else { // file doesn't exist } } else { // file doesn't exist } return false; }
From source file:edu.ku.brc.specify.tools.schemalocale.SchemaToolsDlg.java
/** * //from w w w . j a v a2s . co m */ @SuppressWarnings("unchecked") protected void exportSchemaLocales() { FileDialog dlg = new FileDialog(((Frame) UIRegistry.getTopWindow()), getResourceString("Save"), FileDialog.SAVE); dlg.setVisible(true); String fileName = dlg.getFile(); if (fileName != null) { final File outFile = new File(dlg.getDirectory() + File.separator + fileName); //final File outFile = new File("xxx.xml"); final SimpleGlassPane glassPane = new SimpleGlassPane(getResourceString("SL_EXPORT_SCHEMA"), 18); glassPane.setBarHeight(12); glassPane.setFillColor(new Color(0, 0, 0, 85)); setGlassPane(glassPane); glassPane.setVisible(true); SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() { @Override protected Integer doInBackground() throws Exception { DataProviderSessionIFace session = null; try { session = DataProviderFactory.getInstance().createSession(); int dispId = AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId(); String sql = String.format( "FROM SpLocaleContainer WHERE disciplineId = %d AND schemaType = %d", dispId, schemaType); List<SpLocaleContainer> spContainers = (List<SpLocaleContainer>) session.getDataList(sql); try { FileWriter fw = new FileWriter(outFile); //fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<vector>\n"); fw.write("<vector>\n"); BeanWriter beanWriter = new BeanWriter(fw); XMLIntrospector introspector = beanWriter.getXMLIntrospector(); introspector.getConfiguration().setWrapCollectionsInElement(true); beanWriter.getBindingConfiguration().setMapIDs(false); beanWriter.setWriteEmptyElements(false); beanWriter.enablePrettyPrint(); double step = 100.0 / (double) spContainers.size(); double total = 0.0; for (SpLocaleContainer container : spContainers) { // force Load of lazy collections container.getDescs().size(); container.getNames().size(); // Leaving this Code as an example of specifying the bewtixt file. /*InputStream inputStream = Specify.class.getResourceAsStream("datamodel/SpLocaleContainer.betwixt"); //InputStream inputStream = Specify.class.getResourceAsStream("/edu/ku/brc/specify/tools/schemalocale/SpLocaleContainer.betwixt"); InputSource inputSrc = new InputSource(inputStream); beanWriter.write(container, inputSrc); inputStream.close(); */ beanWriter.write(container); total += step; firePropertyChange("progress", 0, (int) total); } fw.write("</vector>\n"); fw.close(); } catch (Exception ex) { ex.printStackTrace(); } } catch (Exception e) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, e); e.printStackTrace(); } finally { if (session != null) { session.close(); } } return null; } @Override protected void done() { super.done(); glassPane.setVisible(false); } }; backupWorker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { if (evt.getPropertyName().equals("progress")) { glassPane.setProgress((Integer) evt.getNewValue()); } } }); backupWorker.execute(); } }
From source file:com.mirth.connect.client.ui.ChannelPanel.java
public void doDeleteChannel() { if (isSaveEnabled() && !promptSave(true)) { return;// www. j a va 2 s .c o m } if (isGroupSelected()) { JOptionPane.showMessageDialog(parent, "This operation can only be performed on channels."); return; } final List<Channel> selectedChannels = getSelectedChannels(); if (selectedChannels.size() == 0) { return; } if (!parent.alertOption(parent, "Are you sure you want to delete the selected channel(s)?\nAny selected deployed channel(s) will first be undeployed.")) { return; } final String workingId = parent.startWorking("Deleting channel..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { public Void doInBackground() { Set<String> channelIds = new HashSet<String>(selectedChannels.size()); for (Channel channel : selectedChannels) { channelIds.add(channel.getId()); } try { parent.mirthClient.removeChannels(channelIds); } catch (ClientException e) { parent.alertThrowable(parent, e); } return null; } public void done() { doRefreshChannels(); parent.stopWorking(workingId); } }; worker.execute(); }
From source file:com.mirth.connect.client.ui.ChannelPanel.java
public void doEnableChannel() { if (isSaveEnabled() && !promptSave(true)) { return;/*from w w w . j a v a 2s. c o m*/ } final List<Channel> selectedChannels = getSelectedChannels(); if (selectedChannels.size() == 0) { parent.alertWarning(parent, "Channel no longer exists."); return; } final Set<String> channelIds = new HashSet<String>(); Set<Channel> failedChannels = new HashSet<Channel>(); String firstValidationMessage = null; for (Iterator<Channel> it = selectedChannels.iterator(); it.hasNext();) { Channel channel = it.next(); String validationMessage = null; if (channel instanceof InvalidChannel) { failedChannels.add(channel); it.remove(); } else if ((validationMessage = parent.channelEditPanel.checkAllForms(channel)) != null) { if (firstValidationMessage == null) { firstValidationMessage = validationMessage; } failedChannels.add(channel); it.remove(); } else { channelIds.add(channel.getId()); } } if (!channelIds.isEmpty()) { final String workingId = parent.startWorking("Enabling channel..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { public Void doInBackground() { for (Channel channel : selectedChannels) { channel.setEnabled(true); } try { parent.mirthClient.setChannelEnabled(channelIds, true); } catch (ClientException e) { parent.alertThrowable(parent, e); } return null; } public void done() { doRefreshChannels(); parent.stopWorking(workingId); } }; worker.execute(); } if (!failedChannels.isEmpty()) { if (failedChannels.size() == 1) { Channel channel = failedChannels.iterator().next(); if (channel instanceof InvalidChannel) { InvalidChannel invalidChannel = (InvalidChannel) channel; Throwable cause = invalidChannel.getCause(); parent.alertThrowable(parent, cause, "Channel \"" + invalidChannel.getName() + "\" is invalid and cannot be enabled. " + getMissingExtensions(invalidChannel) + "Original cause:\n" + cause.getMessage()); } else { parent.alertCustomError(parent, firstValidationMessage, CustomErrorDialog.ERROR_ENABLING_CHANNEL); } } else { String message = "The following channels are invalid or not configured properly:\n\n"; for (Channel channel : failedChannels) { message += " " + channel.getName() + " (" + channel.getId() + ")\n"; } parent.alertError(parent, message); } } }
From source file:com.mirth.connect.client.ui.ChannelPanel.java
public void doDisableChannel() { if (isSaveEnabled() && !promptSave(true)) { return;/*from w ww .jav a 2 s.com*/ } final List<Channel> selectedChannels = getSelectedChannels(); if (selectedChannels.size() == 0) { parent.alertWarning(parent, "Channel no longer exists."); return; } final String workingId = parent.startWorking("Disabling channels..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { public Void doInBackground() { Set<String> channelIds = new HashSet<String>(); for (Channel channel : selectedChannels) { if (!(channel instanceof InvalidChannel)) { channel.setEnabled(false); channelIds.add(channel.getId()); } } try { parent.mirthClient.setChannelEnabled(channelIds, false); } catch (ClientException e) { parent.alertThrowable(parent, e); } return null; } public void done() { doRefreshChannels(); parent.stopWorking(workingId); } }; worker.execute(); }
From source file:com.pianobakery.complsa.LicenseKeyGUI.java
private void useTrialKeyButtonActionPerformed(ActionEvent evt) { /**//from www.j a v a 2s. com * First validate license and get a temporary license object to * check for validation status later. */ License temporaryLicenseObject = LicenseValidator.validate(trialLicKey, publicKey, internalString, nameforValidation, companyforValidation, hardwareIDMethod); /** * If given license key is valid, then save it on disk, and update * GUI fields. */ if (temporaryLicenseObject.getValidationStatus() == ValidationStatus.LICENSE_VALID) { licenseObject = temporaryLicenseObject; try { /** * We use Apache commons-io (FileUtils class) to easily save * string to file. */ FileUtils.writeStringToFile(new File(licenseKeyFileOnDisk), trialLicKey); /** * Since license key is changed delete license text file if * exists on disk left from previous license key. */ FileUtils.deleteQuietly(new File(licenseTextFileOnDisk)); } catch (IOException ex) { Logger.getLogger(LicenseKeyGUI.class.getName()).log(Level.SEVERE, null, ex); } updateGUIFieldsWithLicenseObject(); /** * We use a SwingWorker here because it will connect to license server * for activation, and it may take 2-3 seconds. */ SwingWorker<License, Void> worker = new SwingWorker<License, Void>() { @Override protected void done() { try { /** * Again we get license object to a temporary object to * check for ActivationStatus. */ License temporaryLicenseObject = (License) get(); /** * If it is successfully activated save on disk and update * GUI fields. */ if (temporaryLicenseObject.getActivationStatus() == ActivationStatus.ACTIVATION_COMPLETED) { licenseObject = temporaryLicenseObject; try { /** * We use Apache commons-io (FileUtils class) to * easily save string to file. * * licenseObject.getLicenseString() method returns * activated license string. */ FileUtils.writeStringToFile(new File(licenseTextFileOnDisk), licenseObject.getLicenseString()); } catch (IOException ex) { Logger.getLogger(LicenseKeyGUI.class.getName()).log(Level.SEVERE, null, ex); } updateGUIFieldsWithLicenseObject(); } else { /** * If activation cannot be completed, display an error * message. */ JOptionPane.showMessageDialog(null, "License activation error: " + temporaryLicenseObject.getActivationStatus(), "Activation Error", JOptionPane.ERROR_MESSAGE); } } catch (InterruptedException ex) { Logger.getLogger(LicenseKeyGUI.class.getName()).log(Level.SEVERE, null, ex); } catch (ExecutionException ex) { Logger.getLogger(LicenseKeyGUI.class.getName()).log(Level.SEVERE, null, ex); } progressjLabel.setText(""); /** * Activation progress is complete, enable buttons again. */ activatejButton.setEnabled(true); changeProductKeyjButton.setEnabled(true); JOptionPane.showMessageDialog(null, "Please restart to enable the license", "Restart...", JOptionPane.INFORMATION_MESSAGE); } @Override protected License doInBackground() { /** * Since example licenses are on Online.License4J the method * below will activate on Online.License4J when autoActivate * method is called without a license server address. */ return LicenseValidator.autoActivate(licenseObject); /** * If you want to test your own "Auto License Generation and * Activation Server" you should give its address as argument * like below. */ //return LicenseValidator.autoActivate(licenseObject, "http://YourServer.com/algas/autoactivate"); } }; worker.execute(); progressjLabel.setText("Activating ..."); /** * It is good to disable "activate" and "change product key" buttons * while activation is in progress. */ activatejButton.setEnabled(false); changeProductKeyjButton.setEnabled(false); } else { /** * If given license is not valid, display an error message. */ JOptionPane.showMessageDialog(null, "License error: " + temporaryLicenseObject.getValidationStatus(), "License Error", JOptionPane.ERROR_MESSAGE); } }
From source file:net.sourceforge.atunes.kernel.modules.repository.RepositoryHandler.java
/** * Imports folders passed as argument to repository * /* w w w . j a va2 s. c o m*/ * @param folders * @param path */ private void importFolders(final List<File> folders, final String path) { SwingWorker<List<AudioFile>, Void> worker = new SwingWorker<List<AudioFile>, Void>() { @Override protected List<AudioFile> doInBackground() throws Exception { VisualHandler.getInstance().showIndeterminateProgressDialog( StringUtils.getString(LanguageTool.getString("READING_FILES_TO_IMPORT"), "...")); return RepositoryLoader.getSongsForFolders(folders); } @Override protected void done() { super.done(); VisualHandler.getInstance().hideIndeterminateProgressDialog(); try { final List<AudioFile> filesToLoad = get(); TagAttributesReviewed tagAttributesReviewed = null; // Review tags if selected in settings if (ApplicationState.getInstance().isReviewTagsBeforeImport()) { ReviewImportDialog reviewImportDialog = VisualHandler.getInstance().getReviewImportDialog(); reviewImportDialog.show(folders, filesToLoad); if (reviewImportDialog.isDialogCancelled()) { return; } tagAttributesReviewed = reviewImportDialog.getResult(); } final ImportFilesProcess process = new ImportFilesProcess(filesToLoad, folders, path, tagAttributesReviewed); process.addProcessListener(new ProcessListener() { @Override public void processCanceled() { // Nothing to do, files copied will be removed before calling this method } @Override public void processFinished(final boolean ok) { if (!ok) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { VisualHandler.getInstance().showErrorDialog( LanguageTool.getString("ERRORS_IN_IMPORT_PROCESS")); } }); } catch (InterruptedException e) { // Do nothing } catch (InvocationTargetException e) { // Do nothing } } else { // If import is ok then add files to repository addFilesAndRefresh(process.getFilesTransferred()); } } }); process.execute(); } catch (InterruptedException e) { getLogger().error(LogCategories.REPOSITORY, e); } catch (ExecutionException e) { getLogger().error(LogCategories.REPOSITORY, e); } } }; worker.execute(); }
From source file:com.mirth.connect.client.ui.Frame.java
public void doRefreshUser() { final String workingId = startWorking("Loading users..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { public Void doInBackground() { refreshUser();/*from ww w .j a v a2s. c om*/ return null; } public void done() { stopWorking(workingId); } }; worker.execute(); }
From source file:es.emergya.ui.gis.FleetControlMapViewer.java
@Override public void actionPerformed(final ActionEvent e) { final CustomMapView mapViewLocal = this.mapView; SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() { @Override// w w w .j a va 2 s . c o m protected Object doInBackground() throws Exception { try { final MouseEvent mouseEvent = FleetControlMapViewer.this.eventOriginal; if (e.getActionCommand().equals(// Centrar aqui i18n.getString(Locale.ROOT, "map.menu.centerHere"))) { mapViewLocal.zoomToFactor(mapViewLocal.getEastNorth(mouseEvent.getX(), mouseEvent.getY()), mapViewLocal.zoomFactor); } else if (e.getActionCommand().equals(// nueva incidencia i18n.getString("map.menu.newIncidence"))) { Incidencia f = new Incidencia(); f.setCreador(Authentication.getUsuario()); LatLon from = mapViewLocal.getLatLon(mouseEvent.getX(), mouseEvent.getY()); GeometryFactory gf = new GeometryFactory(); f.setGeometria(gf.createPoint(new Coordinate(from.lon(), from.lat()))); IncidenceDialog id = new IncidenceDialog(f, i18n.getString("Incidences.summary.title") + " " + i18n.getString("Incidences.nuevaIncidencia"), "tittleficha_icon_recurso"); id.setVisible(true); } else if (e.getActionCommand().equals(// ruta desde i18n.getString("map.menu.route.from"))) { routeDialog.showRouteDialog(mapViewLocal.getLatLon(mouseEvent.getX(), mouseEvent.getY()), null, mapViewLocal); } else if (e.getActionCommand().equals(// ruta hasta i18n.getString("map.menu.route.to"))) { routeDialog.showRouteDialog(null, mapViewLocal.getLatLon(mouseEvent.getX(), mouseEvent.getY()), mapViewLocal); } else if (e.getActionCommand().equals(// Actualizar gps i18n.getString("map.menu.gps"))) { if (!(menuObjective instanceof Recurso)) { return null; } GPSDialog sdsDialog = null; for (Frame f : Frame.getFrames()) { if (f instanceof GPSDialog) if (((GPSDialog) f).getRecurso().equals(menuObjective)) sdsDialog = (GPSDialog) f; } if (sdsDialog == null) sdsDialog = new GPSDialog((Recurso) menuObjective); sdsDialog.setVisible(true); sdsDialog.setExtendedState(JFrame.NORMAL); } else if (e.getActionCommand().equals(// Ficha i18n.getString("map.menu.summary"))) { if (log.isTraceEnabled()) { log.trace("Mostramos la ficha del objetivo del menu"); } if (menuObjective instanceof Recurso) { log.trace(">recurso"); SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() { @Override protected Object doInBackground() throws Exception { for (Frame f : JFrame.getFrames()) { if (f.getName().equals(((Recurso) menuObjective).getIdentificador()) && f instanceof SummaryDialog) { if (f.isShowing()) { f.toFront(); f.setExtendedState(JFrame.NORMAL); return null; } } } new SummaryDialog((Recurso) menuObjective).setVisible(true); return null; } }; sw.execute(); } else if (menuObjective instanceof Incidencia) { if (log.isTraceEnabled()) { log.trace(">incidencia"); } SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() { @Override protected Object doInBackground() throws Exception { for (Frame f : JFrame.getFrames()) { if (f.getName().equals(((Incidencia) menuObjective).getTitulo()) && f instanceof IncidenceDialog) { if (log.isTraceEnabled()) { log.trace("Ya lo tenemos abierto"); } if (f.isShowing()) { f.toFront(); f.setExtendedState(JFrame.NORMAL); } else { f.setVisible(true); f.setExtendedState(JFrame.NORMAL); } return null; } } if (log.isTraceEnabled()) { log.trace("Abrimos uno nuevo"); } new IncidenceDialog((Incidencia) menuObjective, i18n.getString("Incidences.summary.title") + " " + ((Incidencia) menuObjective).getTitulo(), "tittleficha_icon_recurso").setVisible(true); return null; } }; sw.execute(); } else { return null; } } else if (e.getActionCommand().equals( // Mas cercanos i18n.getString("map.menu.showNearest"))) { if (log.isTraceEnabled()) { log.trace("showNearest"); } if (menuObjective != null) { for (Frame f : JFrame.getFrames()) { String identificador = menuObjective.toString(); if (menuObjective instanceof Recurso) { identificador = ((Recurso) menuObjective).getIdentificador(); } if (menuObjective != null && f.getName().equals(identificador) && f instanceof NearestResourcesDialog && f.isDisplayable()) { if (log.isTraceEnabled()) { log.trace("Encontrado " + f); } if (f.isShowing()) { f.toFront(); f.setExtendedState(JFrame.NORMAL); } else { f.setVisible(true); f.setExtendedState(JFrame.NORMAL); } return null; } } } NearestResourcesDialog d; if (menuObjective instanceof Recurso) { d = new NearestResourcesDialog((Recurso) menuObjective, mapViewLocal); } else if (menuObjective instanceof Incidencia) { d = new NearestResourcesDialog((Incidencia) menuObjective, mapViewLocal.getLatLon(mouseEvent.getX(), mouseEvent.getY()), mapViewLocal); } else { d = new NearestResourcesDialog( mapViewLocal.getLatLon(mouseEvent.getX(), mouseEvent.getY()), mapViewLocal); } d.setVisible(true); } else { log.error("ActionCommand desconocido: " + e.getActionCommand()); } } catch (Throwable t) { log.error("Error al ejecutar la accion del menu contextual", t); } return null; } }; sw.execute(); }
From source file:com.mirth.connect.client.ui.Frame.java
public void doShowUsers() { if (userPanel == null) { userPanel = new UserPanel(); }//from w w w . j a v a2s . c om if (!confirmLeave()) { return; } final String workingId = startWorking("Loading users..."); setBold(viewPane, 2); setPanelName("Users"); setCurrentContentPage(userPanel); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { public Void doInBackground() { refreshUser(); return null; } public void done() { setFocus(userTasks); stopWorking(workingId); } }; worker.execute(); }