@Override public synchronized JasperReport loadReportFile() { try { SwingWorker<JasperReport, Void> worker = new SwingWorker<JasperReport, Void>() { @Override protected JasperReport doInBackground() throws Exception { try { String filename = "Expedition.jrxml"; jasperReport = JasperCompileManager.compileReport("printing/" + filename); } catch (Exception ex) { Exceptions.printStackTrace(ex); } return jasperReport; } }; worker.execute(); jasperReport = worker.get(); } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } catch (ExecutionException ex) { Exceptions.printStackTrace(ex); } return jasperReport; }
public void updateGUI() { SwingWorker<AnimationPanel, Void> swingWorker; swingWorker = new SwingWorker<AnimationPanel, Void>() { @Override protected AnimationPanel doInBackground() throws Exception { return ControlCenter.animationPanel; } @Override protected void done() { try { ControlCenterServices.time_step++; AnimationPanel panel = get(); panel.clearUAVImageBeforeUpdate(); panel.updateImageAtEachIteration(); panel.repaint(); } catch (InterruptedException | ExecutionException e) { } } }; swingWorker.execute(); }
public void start(boolean return_when_done) { // TODO Auto-generated method stub SwingWorker worker = new SwingWorker() { final NodeDistances this$0; protected Object doInBackground() throws Exception { return new NodeDistancesTask(); } { this$0 = NodeDistances.this; // super(); } }; worker.execute(); if (return_when_done) try { worker.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
/** Updates all the markers in marker layers */ public void updateMarkers() { Rectangle r = getBoundingBox(); final LatLon tl, br; // tomamos los pois en un area de 3 pantallas cuadradas, de manera que // se pueda arrastrar sin notar que no estan cargados los poi de mas // allá, ya que solo se deberian cargar cuando deja de moverse. tl = getLatLon(r.x - r.width, r.y - r.height); br = getLatLon(r.x + 2 * r.width, r.y + 2 * r.height); if (mapUpdater == null || mapUpdater.isDone()) { mapUpdater = new SwingWorker<Object, Object>() { @Override protected Object doInBackground() throws Exception { try { updateIncidences(tl, br); updateResources(tl, br); } catch (Throwable t) { log.error("Error al actualizar marcadores", t); } return null; } @Override protected void done() { repaint(); } }; mapUpdater.execute(); } }
private void requestAccessToken() { if (loginModel.isServerSelected()) { SwingWorker<String, Object> worker = new SwingWorker<String, Object>() { @Override protected String doInBackground() throws Exception { if (!requestRunning) { requestRunning = true; boolean success = (loginModel.getAccessToken() == ResponseCode.SUCCESS); if (!success) { errorLabel.setText(getLocalized(APP_NOT_AUTHORIZED_IN_STUDIP_LABEL)); } else { errorLabel.setText(""); model .getPluginModel() .activateNewPlugin( loginModel.getPluginInformation(), loginModel.getOAuthConnector()); } } return "done"; } }; errorLabel.setText(""); setBussyMouse(true); worker.execute(); } }
/*Called when the panel is set. Real istallation will start from here */ @Override public void display() { progressBar.setIndeterminate(true); // now start the real installation!! final BatchInstaller batch = new BatchInstaller( WizardSettingsContainer.getInstance().getDbInfos(), WizardSettingsContainer.getInstance().getInstallDirectoryPath(), progressBar, progressString, WizardSettingsContainer.getInstance().isInitDB(), WizardSettingsContainer.getInstance().isInstallDesigner()); // Execute installation task in background: GUI is still responsive :) SwingWorker<String, Object> worker = new SwingWorker() { public String doInBackground() { batch.doInstall(); ActualInstallationWizardPanel.this.remove(progressBar); waitLabel.setText("Installation Completed"); reallyFinisehd = true; ActualInstallationWizardPanel.this.repaint(); return "finished"; } protected void done() { progressBar.setEnabled(false); } }; worker.execute(); }
/** パースした検査結果を登録する。 */ private void addLabtest() { final List<NLaboImportSummary> modules = getTableModel().getDataProvider(); final javax.swing.SwingWorker worker = new javax.swing.SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { LaboDelegater laboDelegater = new LaboDelegater(); for (NLaboImportSummary summary : modules) { PatientModel pm = laboDelegater.putNLaboModule(summary.getModule()); if (pm != null) { summary.setPatient(pm); summary.setResult(SUCCESS); } else { summary.setResult(ERROR); } // Table 更新 Runnable awt = new Runnable() { @Override public void run() { getTableModel().fireTableDataChanged(); } }; EventQueue.invokeLater(awt); } return null; } }; worker.addPropertyChangeListener( new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getNewValue().equals(javax.swing.SwingWorker.StateValue.STARTED)) { getProgressBar().setIndeterminate(true); } else if (evt.getNewValue().equals(javax.swing.SwingWorker.StateValue.DONE)) { getProgressBar().setIndeterminate(false); getProgressBar().setValue(0); worker.removePropertyChangeListener(this); } } }); worker.execute(); }
private void orphanedSKUsFixActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_orphanedSKUsFixActionPerformed SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { orphanedSKUsFix.setEnabled(false); percentage = 0; int counter = 0; long starttimer; long timerSeconds; newThread = new Thread(new ProgressThread(orphanedSKUsProgress, true)); apiLimitThread = new Thread(new UpdateThread(desktop.getConnectivity())); apiLimitThread.start(); newThread.start(); currentTask = "Deleting SKUs"; Statement retrieveData = database.createStatement(); retrieveData.setQueryTimeout(30); try { ResultSet orphanedSKUs = retrieveData.executeQuery( "SELECT skuid " + "FROM allSKUs AS child " + "WHERE NOT EXISTS " + "(SELECT 1 FROM allProducts AS parent " + "WHERE parent.prodid = child.prodid);"); while (orphanedSKUs.next()) { starttimer = System.nanoTime(); store.delete("products/skus/" + orphanedSKUs.getInt("skuid")); counter++; percentage = (counter * 100) / orphanedSkus; timerSeconds = (System.nanoTime() - starttimer) * (orphanedSkus - counter); timer = ""; int day = (int) TimeUnit.NANOSECONDS.toDays(timerSeconds); long hours = TimeUnit.NANOSECONDS.toHours(timerSeconds) - (day * 24); long minute = TimeUnit.NANOSECONDS.toMinutes(timerSeconds) - (TimeUnit.NANOSECONDS.toHours(timerSeconds) * 60); long second = TimeUnit.NANOSECONDS.toSeconds(timerSeconds) - (TimeUnit.NANOSECONDS.toMinutes(timerSeconds) * 60); if (day > 0) timer += day + "d "; if (hours > 0) timer += hours + "h "; if (minute > 0) timer += minute + "m "; if (second > 0) timer += second + "s "; } } catch (SQLException ex) { System.out.println("Issue with the following: " + ex.getMessage()); } retrieveData.close(); return null; } }; worker.execute(); } // GEN-LAST:event_orphanedSKUsFixActionPerformed
@Override public void performAction() { Properties config = new Properties(); config.setProperty( IComputeQuality.class.getSimpleName(), "it.unibas.spicy.findmappings.strategies.computequality.ComputeQualityStructuralAnalysis"); Application.reset(config); executeInjection(); mappingFinder.cleanUp(); Scenario scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO); MappingTask mappingTask = scenario.getMappingTask(); if (mappingTask.getTargetProxy().getInstances().isEmpty()) { NotifyDescriptor nd = new NotifyDescriptor.Message( NbBundle.getMessage(Costanti.class, Costanti.WARNING_NOT_TARGET_INSTANCES), DialogDescriptor.WARNING_MESSAGE); DialogDisplayer.getDefault().notify(nd); return; } checkValueCorrespondenceInMappingTask(mappingTask); SwingWorker swingWorker = new SwingWorker() { private Scenario scenario; @Override protected Object doInBackground() throws Exception { scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO); MappingTask mappingTask = scenario.getMappingTask(); List<AnnotatedMappingTask> bestMappingTasks = mappingFinder.findBestMappings(mappingTask); modello.putBean(Costanti.BEST_MAPPING_TASKS, bestMappingTasks); IOProvider.getDefault().getIO(Costanti.FLUSSO_SPICY, false).select(); return true; } @Override protected void done() { try { if ((Boolean) get() && !isCancelled()) { actionViewSpicy.performActionWithScenario(this.scenario); actionViewBestMappings.performActionWithScenario(this.scenario); } } catch (InterruptedException ex) { logger.error(ex); } catch (ExecutionException ex) { logger.error(ex); } } }; swingWorker.execute(); }
public static void saveManySplashImages() { boolean okPressed = SingleDirChooserPanel.selectOutputDir(true); if (!okPressed) { return; } ProgressMonitor progressMonitor = Utils.createPercentageProgressMonitor("Save Many Splash Images", "Stop"); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override public Void doInBackground() { int nurOfSplashImages = 32; for (int i = 0; i < nurOfSplashImages; i++) { OutputFormat outputFormat = OutputFormat.getLastOutputFormat(); String fileName = String.format("splash%04d.%s", i, outputFormat.toString()); progressMonitor.setProgress((int) ((float) i * 100 / nurOfSplashImages)); progressMonitor.setNote("Creating " + fileName); if (progressMonitor.isCanceled()) { break; } Runnable guiTask = () -> { createSplashImage(); File lastSaveDir = FileChoosers.getLastSaveDir(); File f = new File(lastSaveDir, fileName); Composition comp = ImageComponents.getActiveComp().get(); outputFormat.saveComposition(comp, f, false); ImageComponents.getActiveIC().close(); ValueNoise.reseed(); }; try { EventQueue.invokeAndWait(guiTask); Thread.sleep(1000L); } catch (InterruptedException | InvocationTargetException e) { Messages.showException(e); } } // end of for loop progressMonitor.close(); return null; } // end of doInBackground() }; worker.execute(); }
/** * Starts a SwingWorker that loads the application in the background. * * <p>Called in the event dispatch thread using invokeLater. */ private void run() { showProgressDialog(); startupWorker = new SwingWorker<Throwable, String>() { @Override protected Throwable doInBackground() throws Exception { try { publish("Starting NodeBox"); initApplication(); checkForUpdates(); } catch (RuntimeException ex) { return ex; } return null; } @Override protected void process(List<String> strings) { final String firstString = strings.get(0); startupDialog.setMessage(firstString); } @Override protected void done() { startingUp.set(false); startupDialog.setVisible(false); // See if application startup has generated an exception. Throwable t; try { t = get(); } catch (Exception e) { t = e; } if (t != null) { ExceptionDialog ed = new ExceptionDialog(null, t); ed.setVisible(true); System.exit(-1); } if (documents.isEmpty() && filesToLoad.isEmpty()) { instance.createNewDocument(); } else { for (File f : filesToLoad) { openDocument(f); } } } }; startupWorker.execute(); }
/* * (non-Javadoc) * * @see com.intel.stl.ui.email.IEmailControl#onTest() */ @Override public void onTest() { view.showTesting(true); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { /* * (non-Javadoc) * * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Void doInBackground() throws Exception { // Should retrieve the values presently set in the view and use // these values to send the test email String testSmtpHostName = view.getSmtpServerNameStr(); String testSmtpPortNum = view.getSmtpServerPortStr(); String testToAddr = view.getToAddrStr(); String testFromAddr = view.getFromAddrStr(); // Test connection with above values... MailProperties mailProperties = new MailProperties(); mailProperties.setSmtpServer(testSmtpHostName); mailProperties.setFromAddr(testFromAddr); mailProperties.setSmtpPort(new Integer(testSmtpPortNum)); String subject = UILabels.STL92001_TEST_EMAIL_SUBJECT.getDescription(); String body = ""; subnetMgr.getConfigurationApi().sendTestMail(mailProperties, testToAddr, subject, body); return null; } /* * (non-Javadoc) * * @see javax.swing.SwingWorker#done() */ @Override protected void done() { try { get(); } catch (InterruptedException e) { } catch (ExecutionException e) { Util.showError(view, e); } finally { view.showTesting(false); } } }; worker.execute(); }
public boolean start() { makeBusy(true); worker = new SwingWorkerImpl(); worker.addPropertyChangeListener( new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { firePropertyChange(STATE_PROPERTY, null, worker.getState()); } }); worker.execute(); return true; }
// TODO: deprecate public boolean processTask( ProgressKeeper pk, ProgressDialog d, SwingWorker<Boolean, Boolean> sw) { sw.execute(); d.setVisible(true); try { return sw.get(); } catch (ExecutionException e) { handleConverterException("Exception during conversion", null, e.getCause()); return false; } catch (InterruptedException e) { handleConverterException("Conversion was cancelled or interrupted", null, e); return false; } }
void showProgressMonitor() { progressMonitor = new ProgressMonitor(DBSettings.this, "Building internal data ...", "", 0, 100); progressMonitor.setProgress(0); if (dbURL.matches("(?i:.*oracle.*)")) { task = QueryManager.instance().initFinder(QueryManager.SearchEngine.ORACLE, this); } if (dbURL.matches("(?i:.*mysql.*)")) { task = QueryManager.instance().initFinder(QueryManager.SearchEngine.MYSQL, this); } if (task != null) { task.addPropertyChangeListener(this); task.execute(); } }
/** * Multiple data-sources version of execute() method. Enqueues multiple sources inputs (Content * objects) and associated modules at once * * @param modules modules to execute on every data source * @param inputs input data sources to enqueue and execute the ingest modules on */ public void execute(final List<IngestModuleAbstract> modules, final List<Content> inputs) { logger.log( Level.INFO, "Will enqueue number of inputs: " + inputs.size() + " to " + modules.size() + " modules."); if (!isIngestRunning() && ui != null) { ui.clearMessages(); } queueWorker = new EnqueueWorker(modules, inputs); queueWorker.execute(); if (ui != null) { ui.restoreMessages(); } }
public synchronized Object startProcess( final Object obj, final java.lang.reflect.Method mtd, final Object[] params, String info, boolean is2ndMethod) { this.mtd = mtd; // ---------------- this.obj = obj; // --------------- lblMesg.setText("<html>" + info + "</html>"); pgbProcess.setIndeterminate(true); setVisible(true); // System.out.println("jasdgjasgdjagsdsa"); worker = getNewWorker(params, is2ndMethod); // ------------------- worker.execute(); // ------------------ return this.obj; }
private void printButtonActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_printButtonActionPerformed final SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected void done() {} @Override protected Void doInBackground() { ReportPrinter printer = new ReportPrinter(); printer.printPart(part); return null; } }; worker.execute(); } // GEN-LAST:event_printButtonActionPerformed
public void importFromFile(final File file) throws IOException, ImportException { frame.setBusy(); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { // Executed in background thread public Void doInBackground() { try { BufferedReader reader = new BufferedReader(new FileReader(file)); String line = reader.readLine(); Tree tree; if (line.toUpperCase().startsWith("#NEXUS")) { NexusImporter importer = new NexusImporter(reader); tree = importer.importTree(null); } else { NewickImporter importer = new NewickImporter(reader); tree = importer.importTree(null); } // TODO Add taxons from a new tree to that list and display // them in Taxa panel dataList.taxonList = tree; dataList.forestMap.put(file, new TreeModel(tree)); reader.close(); } catch (Exception e) { Utils.handleException(e); } // END: try-catch block return null; } // END: doInBackground() // Executed in event dispatch thread public void done() { frame.setIdle(); frame.fireTaxaChanged(); } // END: done }; worker.execute(); } // END: importFromFile
public void actionPerformed(ActionEvent ev) { SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { // Executed in background thread public Void doInBackground() { try { generateProcessing.setEnabled(false); progressBar.setIndeterminate(true); // drawPolygonMap.setCam(drawPolygonMap.getCam()); if (projectionParser.getSelectedIndex() == 0) { drawPolygonMap.setMercatorProjection(); } else { drawPolygonMap.setEquirrectangularProjection(); } drawPolygonMap.init(); } catch (Exception e) { e.printStackTrace(); String msg = String.format("Unexpected problem: %s", e.toString()); JOptionPane.showMessageDialog(null, msg, "Error", JOptionPane.ERROR_MESSAGE); } return null; } // END: doInBackground() // Executed in event dispatch thread public void done() { generateProcessing.setEnabled(true); progressBar.setIndeterminate(false); } }; worker.execute(); }
/** * Loads Events fro the local file system * * @param request */ public void loadEventsFromLocalFiles(final LoadFileRequest request) { SwingWorker worker = new SwingWorker<Void, Void>() { @Override public Void doInBackground() { if (request.getFilter() == null) { request.setFilter(new AllFilter()); } int count = 0; List<String> filenames = request.getFilenames(); int total = filenames.size(); for (String filename : filenames) { count++; for (EventLoaderListener l : listeners) { l.processingFile(count, total); } try (InputStream stream = loadEventFromLocalFile(filename); ) { processStream(stream, request.getFilter()); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } for (EventLoaderListener l : listeners) { l.finishedLoading(); } return null; }; }; worker.execute(); }
public void showDetails() { SwingWorker<String, Void> generateWorker = new SwingWorker<String, Void>() { Thread t; protected String doInBackground() throws Exception { t = Thread.currentThread(); ThreadMgmt.getInstance().addThread(t); createGroupDetails(); return ""; } protected void done() { ThreadMgmt.getInstance().removeThread(t); } }; generateWorker.execute(); }
@Override public void actionPerformed(ActionEvent e) { final short videoCount = (short) TABLE.getSelectedRows().length; // can't happen, but just in case. if (videoCount < 1) { return; } // get selected files before we switch to audio and loose the selection final List<File> selectedFiles = getSelectedFiles(); selectAudio(); String status = I18n.tr("Extracting audio from " + videoCount + " selected videos..."); if (videoCount == 1) { status = I18n.tr("Extracting audio from selected video..."); } LibraryMediator.instance().getLibrarySearch().pushStatus(status); SwingWorker<Void, Void> demuxWorker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { isDemuxing = true; demuxFiles(selectedFiles); isDemuxing = false; return null; } @Override protected void done() { int failed = videoCount - demuxedFiles.size(); String failedStr = (failed > 0) ? " (" + failed + " " + I18n.tr("failed") + ")" : ""; LibraryMediator.instance() .getLibrarySearch() .pushStatus(I18n.tr("Done extracting audio.") + failedStr); } }; demuxWorker.execute(); }
/** Overlays the files. */ protected void process() { SwingWorker worker; m_Processing = true; updateButtons(); worker = new SwingWorker() { protected StringBuilder m_Errors; @Override protected Object doInBackground() throws Exception { saveSetup(); m_Errors = new StringBuilder(); ScriptedPDFOverlay overlay = new ScriptedPDFOverlay( new File(m_TextPdfTemplate.getText()), new File(m_TextParams.getText()), new File(m_TextGroovy.getText()), new File(m_TextOutputDir.getText())); String errors = overlay.execute(); if (errors != null) m_Errors.append(errors); return null; } @Override protected void done() { m_Processing = false; updateButtons(); if (m_Errors.length() > 0) { JOptionPane.showMessageDialog( ScriptedPDFOverlayGUI.this, m_Errors.toString(), "Error", JOptionPane.ERROR_MESSAGE); } super.done(); } }; worker.execute(); }
/** * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) * @param e */ public void actionPerformed(ActionEvent e) { SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() { @Override protected Object doInBackground() throws Exception { boolean canContinue = RunMultiTimesAction.this.container.canContinue(); int nbTimes = Integer.parseInt(RunMultiTimesAction.this.textComponent.getText().trim()); for (int i = 0; i < nbTimes && canContinue; i++) { canContinue = RunMultiTimesAction.this.manager.nextStep(RunMultiTimesAction.this.simulation); RunMultiTimesAction.this.container.setCanContinue(canContinue); RunMultiTimesAction.this.container.modelHasChanged(); Thread.sleep(100); } return null; } }; worker.execute(); }
private void jBAtualizarActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jBAtualizarActionPerformed final Progress p = new Progress(); p.setVisible(true); SwingWorker worker = new SwingWorker() { @Override protected Object doInBackground() throws Exception { atualizaTabela(); return null; } @Override protected void done() { p.setVisible(false); } }; worker.execute(); } // GEN-LAST:event_jBAtualizarActionPerformed
/* * (non-Javadoc) * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(ActionEvent e) { this.setEnabled(false); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { if (console.getMission() == null) { GuiUtils.errorMessage( null, I18n.text("Console error"), I18n.text("Selecting Plan: no Mission Loaded in console")); return null; } String checkl = (console.getMission().getChecklistsList().size() == 0) ? null : (String) JOptionPane.showInputDialog( console, I18n.text("Choose one of the available Checklists"), I18n.text("Select Checklist"), JOptionPane.QUESTION_MESSAGE, new ImageIcon(), console.getMission().getChecklistsList().keySet().toArray(), console.getMission().getChecklistsList().keySet().iterator().next()); if (checkl != null) { ChecklistType newClone = console.getMission().getChecklistsList().get(checkl).getChecklist().createCopy(); console.executeCheckList(newClone); } return null; } }; worker.execute(); }
public HistogramChart( String name, Taskable task, BatchMatchResultSet resultSet, final SGRBatchScenario scenario, float binSize) { super(name, task); this.resultSet = resultSet; update(); chartUpdater = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { Thread.currentThread().setName("Histogram-Updater"); while (true) { try { if (!scenario.isRunning()) return null; } catch (NullPointerException e) { return null; } Thread.sleep(2000); SwingUtilities.invokeLater( new Runnable() { @Override public void run() { update(); } }); } } }; chartUpdater.execute(); }
private void requestServerSelection() { SwingWorker<String, Object> worker = new SwingWorker<String, Object>() { @Override protected String doInBackground() throws Exception { if (!requestRunning) { requestRunning = true; // set the selected server as selected in model boolean success = loginModel.selectServer(uniList.getSelectedValue()); if (!success) { errorLabel.setText(getLocalized(ERROR_SERVER_LABEL)); } else { errorLabel.setText(""); } // request RequestToken ResponseCode code = loginModel.getRequestToken(); if (code != ResponseCode.SUCCESS) { errorLabel.setText(getLocalized(ERROR_SERVER_LABEL)); } else { errorLabel.setText(""); } loginModel.openBrowser(); } return "done"; } }; errorLabel.setText(""); setBussyMouse(true); worker.execute(); }
private void compute(final Mask selectedMask) { final RasterDataNode raster = getRaster(); final AttributeDescriptor dataField = scatterPlotModel.dataField; if (raster == null || dataField == null) { return; } SwingWorker<ComputedData[], Object> swingWorker = new SwingWorker<ComputedData[], Object>() { @Override protected ComputedData[] doInBackground() throws Exception { SystemUtils.LOG.finest("start computing scatter plot data"); final List<ComputedData> computedDataList = new ArrayList<>(); final FeatureCollection<SimpleFeatureType, SimpleFeature> collection = scatterPlotModel.pointDataSource.getFeatureCollection(); final SimpleFeature[] features = collection.toArray(new SimpleFeature[collection.size()]); final int boxSize = scatterPlotModel.boxSize; final Rectangle sceneRect = new Rectangle(raster.getSceneRasterWidth(), raster.getSceneRasterHeight()); final GeoCoding geoCoding = raster.getGeoCoding(); final AffineTransform imageToModelTransform; imageToModelTransform = ImageManager.getImageToModelTransform(geoCoding); for (SimpleFeature feature : features) { final Point point = (Point) feature.getDefaultGeometryProperty().getValue(); Point2D modelPos = new Point2D.Float((float) point.getX(), (float) point.getY()); final Point2D imagePos = imageToModelTransform.inverseTransform(modelPos, null); if (!sceneRect.contains(imagePos)) { continue; } final float imagePosX = (float) imagePos.getX(); final float imagePosY = (float) imagePos.getY(); final Rectangle imageRect = sceneRect.intersection( new Rectangle( ((int) imagePosX) - boxSize / 2, ((int) imagePosY) - boxSize / 2, boxSize, boxSize)); if (imageRect.isEmpty()) { continue; } final double[] rasterValues = new double[imageRect.width * imageRect.height]; raster.readPixels( imageRect.x, imageRect.y, imageRect.width, imageRect.height, rasterValues); final int[] maskBuffer = new int[imageRect.width * imageRect.height]; Arrays.fill(maskBuffer, 1); if (selectedMask != null) { selectedMask.readPixels( imageRect.x, imageRect.y, imageRect.width, imageRect.height, maskBuffer); } final int centerIndex = imageRect.width * (imageRect.height / 2) + (imageRect.width / 2); if (maskBuffer[centerIndex] == 0) { continue; } double sum = 0; double sumSqr = 0; int n = 0; boolean valid = false; for (int y = 0; y < imageRect.height; y++) { for (int x = 0; x < imageRect.width; x++) { final int index = y * imageRect.height + x; if (raster.isPixelValid(x + imageRect.x, y + imageRect.y) && maskBuffer[index] != 0) { final double rasterValue = rasterValues[index]; sum += rasterValue; sumSqr += rasterValue * rasterValue; n++; valid = true; } } } if (!valid) { continue; } double rasterMean = sum / n; double rasterSigma = n > 1 ? Math.sqrt((sumSqr - (sum * sum) / n) / (n - 1)) : 0.0; String localName = dataField.getLocalName(); Number attribute = (Number) feature.getAttribute(localName); final Collection<org.opengis.feature.Property> featureProperties = feature.getProperties(); final float correlativeData = attribute.floatValue(); final GeoPos geoPos = new GeoPos(); if (geoCoding.canGetGeoPos()) { final PixelPos pixelPos = new PixelPos(imagePosX, imagePosY); geoCoding.getGeoPos(pixelPos, geoPos); } else { geoPos.setInvalid(); } computedDataList.add( new ComputedData( imagePosX, imagePosY, (float) geoPos.getLat(), (float) geoPos.getLon(), (float) rasterMean, (float) rasterSigma, correlativeData, featureProperties)); } return computedDataList.toArray(new ComputedData[computedDataList.size()]); } @Override public void done() { try { final ValueAxis xAxis = getPlot().getDomainAxis(); final ValueAxis yAxis = getPlot().getRangeAxis(); xAxis.setAutoRange(false); yAxis.setAutoRange(false); scatterpointsDataset.removeAllSeries(); acceptableDeviationDataset.removeAllSeries(); regressionDataset.removeAllSeries(); getPlot().removeAnnotation(r2Annotation); computedDatas = null; final ComputedData[] data = get(); if (data.length == 0) { return; } computedDatas = data; final XYIntervalSeries scatterValues = new XYIntervalSeries(getCorrelativeDataName()); for (ComputedData computedData : computedDatas) { final float rasterMean = computedData.rasterMean; final float rasterSigma = computedData.rasterSigma; final float correlativeData = computedData.correlativeData; scatterValues.add( correlativeData, correlativeData, correlativeData, rasterMean, rasterMean - rasterSigma, rasterMean + rasterSigma); } computingData = true; scatterpointsDataset.addSeries(scatterValues); xAxis.setAutoRange(true); yAxis.setAutoRange(true); xAxis.setAutoRange(false); yAxis.setAutoRange(false); xAutoRangeAxisRange = new Range(xAxis.getLowerBound(), xAxis.getUpperBound()); yAutoRangeAxisRange = new Range(yAxis.getLowerBound(), yAxis.getUpperBound()); if (xAxisRangeControl.isAutoMinMax()) { xAxisRangeControl.adjustComponents(xAxis, 3); } else { xAxisRangeControl.adjustAxis(xAxis, 3); } if (yAxisRangeControl.isAutoMinMax()) { yAxisRangeControl.adjustComponents(yAxis, 3); } else { yAxisRangeControl.adjustAxis(yAxis, 3); } computeRegressionAndAcceptableDeviationData(); computingData = false; } catch (InterruptedException | CancellationException e) { SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e); SnapDialogs.showMessage( CHART_TITLE, "Failed to compute correlative plot.\n" + "Calculation canceled.", JOptionPane.ERROR_MESSAGE, null); } catch (ExecutionException e) { SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e); SnapDialogs.showMessage( CHART_TITLE, "Failed to compute correlative plot.\n" + "An error occurred:\n" + e.getCause().getMessage(), JOptionPane.ERROR_MESSAGE, null); } } }; swingWorker.execute(); }