file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
ProductSceneViewTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/windows/ProductSceneViewTopComponent.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.esa.snap.rcp.windows; import com.bc.ceres.swing.selection.Selection; import com.bc.ceres.swing.selection.SelectionChangeEvent; import com.bc.ceres.swing.selection.SelectionChangeListener; import eu.esa.snap.netbeans.docwin.DocumentTopComponent; import eu.esa.snap.netbeans.docwin.WindowUtilities; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.core.datamodel.ProductNodeEvent; import org.esa.snap.core.datamodel.ProductNodeListenerAdapter; import org.esa.snap.rcp.actions.edit.SelectionActions; import org.esa.snap.rcp.util.ContextGlobalExtender; import org.esa.snap.ui.product.ProductSceneView; import org.openide.awt.UndoRedo; import org.openide.util.Exceptions; import org.openide.util.ImageUtilities; import org.openide.util.Utilities; import javax.swing.*; import javax.swing.plaf.LayerUI; import javax.swing.text.DefaultEditorKit; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.io.IOException; import java.util.logging.Logger; /** * A document window which displays images. * * @author Norman Fomferra */ public class ProductSceneViewTopComponent extends DocumentTopComponent<ProductNode, ProductSceneView> implements UndoRedo.Provider, SelectionChangeListener { private static final Logger LOG = Logger.getLogger(ProductSceneViewTopComponent.class.getName()); private final ProductSceneView view; private final UndoRedo undoRedo; private final ProductNodeListenerAdapter nodeRenameHandler; private Selection selection; public ProductSceneViewTopComponent(ProductSceneView view, UndoRedo undoRedo) { super(view.getRaster()); this.view = view; this.undoRedo = undoRedo != null ? undoRedo : UndoRedo.NONE; this.nodeRenameHandler = new NodeRenameHandler(); this.selection = Selection.EMPTY; setToolTipText(view.getRaster().getDescription()); setIcon(ImageUtilities.loadImage("org/esa/snap/rcp/icons/RsBandAsSwath.gif")); updateDisplayName(); setName(getDisplayName()); /* // checkme - this is ugly and not wanted (nf), the node will either passed in or we'll have // a central node factory, e.g. via an ExtensionObject Node node = null; try { if (raster instanceof Mask) { node = new MNode((Mask) raster, undoRedo); } else if (raster instanceof Band) { node = new BNode((Band) raster, undoRedo); } else if (raster instanceof TiePointGrid) { node = new TPGNode((TiePointGrid) raster, undoRedo); } } catch (IntrospectionException e) { Exceptions.printStackTrace(e); } if (node != null) { setActivatedNodes(new Node[]{node}); } */ setLayout(new BorderLayout()); add(new JLayer<>(this.view, new ProductSceneViewLayerUI()), BorderLayout.CENTER); } /** * Retrieves the ProductSceneView displayed. * * @return the scene view, never null */ public ProductSceneView getView() { return view; } @Override public UndoRedo getUndoRedo() { return undoRedo; } @Override public void selectionChanged(SelectionChangeEvent event) { setSelection(event.getSelection()); } @Override public void selectionContextChanged(SelectionChangeEvent event) { } @Override public void componentOpened() { LOG.info(">> componentOpened"); getDocument().getProduct().addProductNodeListener(nodeRenameHandler); } @Override public void componentClosed() { LOG.info(">> componentClosed"); getDocument().getProduct().removeProductNodeListener(nodeRenameHandler); } @Override public void componentSelected() { LOG.info(">> componentSelected"); updateSelectedState(); ContextGlobalExtender contextGlobalExtender = Utilities.actionsGlobalContext().lookup(ContextGlobalExtender.class); if (contextGlobalExtender != null) { contextGlobalExtender.put("view", getView()); } setSelection(getView().getFigureEditor().getSelectionContext().getSelection()); getView().getFigureEditor().getSelectionContext().addSelectionChangeListener(this); } @Override public void componentDeselected() { LOG.info(">> componentDeselected"); updateSelectedState(); getView().getFigureEditor().getSelectionContext().removeSelectionChangeListener(this); setSelection(Selection.EMPTY); ContextGlobalExtender contextGlobalExtender = Utilities.actionsGlobalContext().lookup(ContextGlobalExtender.class); if (contextGlobalExtender != null) { contextGlobalExtender.remove("view"); } } @Override public void documentClosing() { super.documentClosing(); getView().disposeLayers(); getView().dispose(); } private class ProductSceneViewLayerUI extends LayerUI<ProductSceneView> { @Override public void paint(Graphics g, JComponent c) { super.paint(g, c); if (isSelected()) { final int N = 6; final int A = 220; final Color C = new Color(255, 213, 79); for (int i = 0; i < N; i++) { g.setColor(new Color(C.getRed(), C.getGreen(), C.getBlue(), A - i * A / N)); g.drawRect(i, i, getWidth() - 2 * i, getHeight() - 2 * i); } } } } private void updateDisplayName() { setDisplayName(WindowUtilities.getUniqueTitle(getView().getSceneName(), ProductSceneViewTopComponent.class)); } private void setSelection(Selection newSelection) { Selection oldSelection = this.selection; getDynamicContent().remove(oldSelection); if (!newSelection.isEmpty()) { this.selection = newSelection.clone(); getDynamicContent().add(newSelection); } updateActionMap(newSelection); } private void updateActionMap(Selection newSelection) { ActionMap actionMap = getActionMap(); actionMap.put(SelectionActions.SELECT_ALL, new SelectAllAction()); actionMap.put(DefaultEditorKit.pasteAction, new PasteAction()); if (!newSelection.isEmpty()) { actionMap.put(DefaultEditorKit.cutAction, new CutAction()); actionMap.put(DefaultEditorKit.copyAction, new CopyAction()); actionMap.put("delete", new DeleteAction()); actionMap.put(SelectionActions.DESELECT_ALL, new DeselectAllAction()); } else { actionMap.remove(DefaultEditorKit.cutAction); actionMap.remove(DefaultEditorKit.copyAction); actionMap.remove("delete"); actionMap.remove(SelectionActions.DESELECT_ALL); } getDynamicContent().remove(actionMap); getDynamicContent().add(actionMap); } private class CutAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { Selection selection = getLookup().lookup(Selection.class); if (selection != null && !selection.isEmpty()) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable transferable = getView().getFigureEditor().getFigureSelection().createTransferable(false); clipboard.setContents(transferable, selection); getView().getFigureEditor().deleteSelection(); //JOptionPane.showMessage(WindowManager.getDefault().getMainWindow(), "Cut: " + transferable); } } } private class CopyAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { Selection selection = getLookup().lookup(Selection.class); if (selection != null && !selection.isEmpty()) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // todo - when we copy, we actually don't clone the SimpleFeature. Then, if we paste, two figures refer // to the same SimpleFeature. Transferable transferable = getView().getFigureEditor().getFigureSelection().createTransferable(true); clipboard.setContents(transferable, selection); //JOptionPane.showMessage(WindowManager.getDefault().getMainWindow(), "Copy: " + transferable); } } } private class PasteAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable contents = clipboard.getContents(getView()); //JOptionPane.showMessage(WindowManager.getDefault().getMainWindow(), "Paste: " + contents); try { getView().getSelectionContext().insert(contents); } catch (IOException | UnsupportedFlavorException ex) { Exceptions.printStackTrace(ex); } } } private class DeleteAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { getView().getFigureEditor().deleteSelection(); } } private class SelectAllAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { getView().getFigureEditor().selectAll(); } } private class DeselectAllAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { getView().getFigureEditor().setSelection(Selection.EMPTY); } } private class NodeRenameHandler extends ProductNodeListenerAdapter { @Override public void nodeChanged(final ProductNodeEvent event) { if (event.getSourceNode() == getDocument() && event.getPropertyName().equalsIgnoreCase(ProductNode.PROPERTY_NAME_NAME)) { updateDisplayName(); } } } }
10,521
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CommunityPluginVotePanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/windows/CommunityPluginVotePanel.java
package org.esa.snap.rcp.windows; import java.awt.Color; import java.awt.Container; import java.awt.Desktop; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.net.ssl.HttpsURLConnection; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.LineBorder; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.esa.snap.core.util.SystemUtils; /** * Panel containing the Community Plugin vote dialog * * @author Lucian Barbulescu * */ public class CommunityPluginVotePanel extends JPanel { /** * Generated Serial ID */ private static final long serialVersionUID = -3282916392722244406L; /** JSON deserializer. */ public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); /** * The associated plugin name; */ private String name; /** * The associated plugin version; */ private String version; /** * The stars labels */ private JLabel[] stars = new JLabel[] { new JLabel(), new JLabel(), new JLabel(), new JLabel(), new JLabel() }; /** * The vote text */ private JLabel votesText = new JLabel(); /** * The "vote" button */ private JButton vote = new JButton(); /** * Constructor. */ public CommunityPluginVotePanel() { // create the executor buildUI(); addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0x0l) { if (name == null || version == null) { return; } Container p = e.getChangedParent(); while (p != null) { if (p.toString().contains("org.netbeans.modules.autoupdate.ui.UnitTab")) { try { final ExecutorService executor = Executors.newSingleThreadExecutor(); final Method m = p.getClass().getMethod("getHelpId"); final Object result = m.invoke(p); final AsyncPluginReviewRetriever retriever = new AsyncPluginReviewRetriever(name, version, result.toString(), executor); retriever.executeAsync(); break; } catch (NoSuchMethodException ex) { // not here } catch (SecurityException ex) { SystemUtils.LOG.severe("Access error"); } catch (IllegalAccessException ex) { SystemUtils.LOG.severe("Invokation error"); } catch (IllegalArgumentException ex) { SystemUtils.LOG.severe("Invokation error"); } catch (InvocationTargetException ex) { SystemUtils.LOG.severe("Invokation error"); } } p = p.getParent(); } } } }); } /** * Invoked when the plugin data was obtained from the server * * @param plugin the plugin data or null if none found * @param helpId the help ID of the page where the dialog is opened. */ void onPluginDataRetrieved(final CommunityPluginData plugin, final String helpId) { if (plugin != null) { // update stars and review count. for (int i = 0; i < 5; i++) { this.stars[i].setVisible(true); if ((i + 1) <= plugin.getRate()) { this.stars[i].setIcon( new ImageIcon(this.getClass().getResource("/org/esa/snap/rcp/icons/FullStar.png"))); } else if (i < plugin.getRate()) { this.stars[i].setIcon( new ImageIcon(this.getClass().getResource("/org/esa/snap/rcp/icons/HalfStar.png"))); } else { this.stars[i].setIcon( new ImageIcon(this.getClass().getResource("/org/esa/snap/rcp/icons/NoStar.png"))); } } this.votesText.setText(plugin.getRate() + " / 5.0 (" + plugin.getCount() + " reviews)"); // Enable the review button only for Installed plugins if (helpId.contains("INSTALLED")) { vote.setVisible(true); } } else { this.votesText.setText("The plugin " + name + ", version " + version + " is not available online!"); } } /** * Build the UI of the component */ private void buildUI() { setSize(350, 40); setLayout(new GridBagLayout()); setBackground(Color.WHITE); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.WEST; c.weightx = 0.0; c.weighty = 0.0; c.gridy = 0; c.gridwidth = 1; c.gridheight = 1; c.insets = new Insets(1, 0, 1, 1); for (int i = 0; i < 5; i++) { c.gridx = i; this.add(this.stars[i], c); this.stars[i].setIcon( new ImageIcon(this.getClass().getResource("/org/esa/snap/rcp/icons/NoStar.png"))); this.stars[i].setVisible(false); } c.gridx = 5; c.weightx = 1.0; this.add(this.votesText, c); this.votesText.setText("Loading Plugin Reviews Data ..."); c.gridx = 6; c.weightx = 0.0; c.anchor = GridBagConstraints.EAST; this.add(this.vote, c); this.vote.addActionListener(l -> { try { final URI uri = new URI("https://step.esa.int/main/snap-community-plugins/"); Desktop d = Desktop.getDesktop(); d.browse(uri); } catch (URISyntaxException e) { // invalid URL } catch (IOException e) { // cannot open browser } }); this.vote.setVisible(false); this.vote.setText("Add Review"); } /** * Set the plugin name. * * @param name the plugin name */ public void setName(final String name) { this.name = name; } /** * Set the plugin version. * * @param name the plugin version */ public void setVersion(final String version) { this.version = version; } /** * Asynchronous retriever for plugin review data. * * @author Lucian Barbulescu */ private class AsyncPluginReviewRetriever { /** Name of the plugin. */ private final String pluginName; /** Version of the plugin. */ private final String pluginVersion; /** The help id of the page which contains this dialog. */ private final String helpId; /** Service used to obtain the plugin's review data asynchronously. */ private final ExecutorService executor; /** * Constructor. * * @param pluginName * @param pluginVersion * @param helpId * @param executor */ public AsyncPluginReviewRetriever(String pluginName, String pluginVersion, String helpId, ExecutorService executor) { this.pluginName = pluginName; this.pluginVersion = pluginVersion; this.helpId = helpId; this.executor = executor; } /** * Perform the asynchronous execution. */ void executeAsync() { this.executor.submit(() -> { final CommunityPluginResponse pluginsData = getPluginsInfo(); // check if the success field is true. if (pluginsData != null && pluginsData.isSuccess()) { for (final CommunityPluginData plugin : pluginsData.getPlugins().getResults()) { final String pluginName = plugin.getName(); final String pluginVersion = plugin.getVersion(); if (name.equals(pluginName) && version.equals(pluginVersion)) { onPluginDataRetrieved(plugin, helpId); return; } } } onPluginDataRetrieved(null, helpId); }); } /** * Get the plugins info. * * @return */ private CommunityPluginResponse getPluginsInfo() { HttpsURLConnection c = null; CommunityPluginResponse response = null; try { URL u = new URL("https://step.esa.int/communityplugins/api/plugins/all/"); c = (HttpsURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setRequestProperty("Content-length", "0"); c.setUseCaches(false); c.setAllowUserInteraction(false); c.setConnectTimeout(5000); c.setReadTimeout(5000); c.connect(); int status = c.getResponseCode(); if (status == 200 || status == 201) { BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); response = OBJECT_MAPPER.readValue(sb.toString(), new TypeReference<CommunityPluginResponse>() {}); } } catch (IOException ex) { SystemUtils.LOG.severe("Error reading server data. "); SystemUtils.LOG.info("Error message: " + ex.getMessage()); } finally { if (c != null) { try { c.disconnect(); } catch (Exception ex) { } } } return response; } } @JsonIgnoreProperties(ignoreUnknown = true) private static class CommunityPluginResponse { /** Result of the call. */ private boolean success; /** Details related to the community plugins */ private CommunityPluginList plugins; /** * Get the current value of the success. * * @return the success */ public boolean isSuccess() { return this.success; } /** * Set a new value for the success. * * @param success the success to set */ public void setSuccess(boolean success) { this.success = success; } /** * Get the current value of the plugins. * * @return the plugins */ public CommunityPluginList getPlugins() { return this.plugins; } /** * Set a new value for the plugins. * * @param plugins the plugins to set */ public void setPlugins(CommunityPluginList plugins) { this.plugins = plugins; } } @JsonIgnoreProperties(ignoreUnknown = true) private static class CommunityPluginList { /** The list of plugins. */ private List<CommunityPluginData> results; /** * Get the current value of the results. * * @return the results */ public List<CommunityPluginData> getResults() { return this.results; } /** * Set a new value for the results. * * @param results the results to set */ public void setResults(List<CommunityPluginData> results) { this.results = results; } } @JsonIgnoreProperties(ignoreUnknown = true) private static class CommunityPluginData { @JsonProperty("plugin_id") private Integer id; @JsonProperty("plugin_name") private String name; @JsonProperty("plugin_version") private String version; @JsonProperty("avg_rate") private Double rate; @JsonProperty("count_rate") private Integer count; /** * Get the current value of the id. * * @return the id */ public Integer getId() { return this.id; } /** * Set a new value for the id. * * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * Get the current value of the name. * * @return the name */ public String getName() { return this.name; } /** * Set a new value for the name. * * @param name the name to set */ public void setName(String name) { this.name = name; } /** * Get the current value of the version. * * @return the version */ public String getVersion() { return this.version; } /** * Set a new value for the version. * * @param version the version to set */ public void setVersion(String version) { this.version = version; } /** * Get the current value of the rate. * * @return the rate */ public Double getRate() { return this.rate; } /** * Set a new value for the rate. * * @param rate the rate to set */ public void setRate(Double rate) { this.rate = rate; } /** * Get the current value of the count. * * @return the count */ public Integer getCount() { return this.count; } /** * Set a new value for the count. * * @param count the count to set */ public void setCount(Integer count) { this.count = count; } } }
12,111
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AboutAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/about/AboutAction.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.esa.snap.rcp.about; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.NbBundle.Messages; import org.openide.windows.WindowManager; import javax.swing.JDialog; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * Displays the {@link AboutPanel} in a modal dialog. * * @author Norman Fomferra */ @ActionID(category = "Help", id = "org.esa.snap.rcp.about.AboutAction" ) @ActionRegistration(displayName = "#CTL_AboutAction_Name" ) @ActionReference(path = "Menu/Help", position = 1600, separatorBefore = 1550) @Messages({ "CTL_AboutAction_Name=About SNAP...", "CTL_AboutAction_Title=About SNAP", }) public final class AboutAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { JDialog dialog = new JDialog(WindowManager.getDefault().getMainWindow(), Bundle.CTL_AboutAction_Title(), true); dialog.setContentPane(new AboutPanel()); dialog.pack(); dialog.setLocationRelativeTo(WindowManager.getDefault().getMainWindow()); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } }
1,436
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ThirdPartyLicense.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/about/ThirdPartyLicense.java
package org.esa.snap.rcp.about; /** * Holder providing a description of a third party license as used in SNAP. * * @author olafd */ public class ThirdPartyLicense { // currently we use just 5 columns from the 9 columns in the csv file: private String name; private String descriptionUse; private String iprOwner; private String license; private String iprOwnerUrl; private String licenseUrl; ThirdPartyLicense(String name, String descriptionUse, String iprOwner, String license, String iprOwnerUrl, String licenseUrl) { this.name = name; this.descriptionUse = descriptionUse; this.iprOwner = iprOwner; this.license = license; this.iprOwnerUrl = iprOwnerUrl; this.licenseUrl = licenseUrl; } public String getName() { return name; } String getDescriptionUse() { return descriptionUse; } String getIprOwner() { return iprOwner; } public String getLicense() { return license; } private String getIprOwnerUrl() { return iprOwnerUrl; } private String getLicenseUrl() { return licenseUrl; } /** * Provides the correct URL related to the colunm of the corresponding {@link ThirdPartyLicensesTableModel} * * @param tableColumnName - column name * * @return String */ String getUrlByTableColumnName(String tableColumnName) { switch (tableColumnName) { case ThirdPartyLicensesTableModel.IPR_OWNER_COL_NAME: return getIprOwnerUrl(); case ThirdPartyLicensesTableModel.LICENSE_COL_NAME: return getLicenseUrl(); default: break; } return null; } }
1,921
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ThirdPartyLicensesTableModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/about/ThirdPartyLicensesTableModel.java
package org.esa.snap.rcp.about; import javax.swing.table.DefaultTableModel; /** * Table model for 3rd party licenses displayed in AboutBox * * @author olafd */ public class ThirdPartyLicensesTableModel extends DefaultTableModel { static final String IPR_OWNER_COL_NAME = "IPR owner"; static final String LICENSE_COL_NAME = "License"; private static final String NAME_COL_NAME = "Name"; private static final String DESCRIPTION_USE_COL_NAME = "Description/Use"; static final int NAME_COL_INDEX = 0; static final int DESCRIPTION_USE_COL_INDEX = 1; static final int IPR_OWNER_COL_INDEX = 2; static final int LICENSE_COL_INDEX = 3; private static final int NUMBER_OF_COLUMNS = 4; ThirdPartyLicensesTableModel(ThirdPartyLicense[] thirdPartyLicenses) { super(toArray(thirdPartyLicenses), new Object[]{NAME_COL_NAME, DESCRIPTION_USE_COL_NAME, IPR_OWNER_COL_NAME, LICENSE_COL_NAME}); } @Override public int getColumnCount() { return NUMBER_OF_COLUMNS; } @Override public String getColumnName(int columnIndex) { switch (columnIndex) { case NAME_COL_INDEX: return NAME_COL_NAME; case DESCRIPTION_USE_COL_INDEX: return DESCRIPTION_USE_COL_NAME; case IPR_OWNER_COL_INDEX: return IPR_OWNER_COL_NAME; case LICENSE_COL_INDEX: return LICENSE_COL_NAME; } throw new IllegalStateException("Should never come here"); } @Override public Class<?> getColumnClass(int columnIndex) { switch (columnIndex) { case NAME_COL_INDEX: case DESCRIPTION_USE_COL_INDEX: case LICENSE_COL_INDEX: case IPR_OWNER_COL_INDEX: return String.class; } throw new IllegalStateException(); } @Override public boolean isCellEditable(int row, int column) { return false; } /** * Checks if given column contains URLs * * @param column - column index * * @return boolean */ boolean containsURLs(int column) { return column == IPR_OWNER_COL_INDEX || column == LICENSE_COL_INDEX; } private static Object[][] toArray(ThirdPartyLicense[] thirdPartyLicenses) { Object[][] result = new Object[thirdPartyLicenses.length][NUMBER_OF_COLUMNS]; for (int i = 0; i < thirdPartyLicenses.length; i++) { // create entries result[i][NAME_COL_INDEX] = thirdPartyLicenses[i].getName(); result[i][DESCRIPTION_USE_COL_INDEX] = thirdPartyLicenses[i].getDescriptionUse(); result[i][IPR_OWNER_COL_INDEX] = thirdPartyLicenses[i].getIprOwner(); result[i][LICENSE_COL_INDEX] = thirdPartyLicenses[i].getLicense(); } return result; } }
2,911
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AboutBox.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/about/AboutBox.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.esa.snap.rcp.about; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation which generates {@code AboutBox} file objects. * * @author Norman Fomferra */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.TYPE) public @interface AboutBox { String displayName(); String iconPath() default ""; int position() default Integer.MAX_VALUE; }
691
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AboutBoxProcessor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/about/AboutBoxProcessor.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.esa.snap.rcp.about; import org.openide.filesystems.annotations.LayerBuilder.File; import org.openide.filesystems.annotations.LayerGeneratingProcessor; import org.openide.filesystems.annotations.LayerGenerationException; import org.openide.util.lookup.ServiceProvider; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import java.util.Set; /** * Processor for the {@link AboutBox} annotations. This class generates the actual {@code layer.xml} entries. * * @author Norman Fomferra */ @ServiceProvider(service = Processor.class) @SupportedAnnotationTypes("org.esa.snap.rcp.about.AboutBox") @SupportedSourceVersion(SourceVersion.RELEASE_11) public class AboutBoxProcessor extends LayerGeneratingProcessor { @Override protected boolean handleProcess(Set<? extends TypeElement> set, RoundEnvironment env) throws LayerGenerationException { Elements elements = processingEnv.getElementUtils(); for (Element element : env.getElementsAnnotatedWith(AboutBox.class)) { TypeElement clazz = (TypeElement) element; AboutBox aboutBox = clazz.getAnnotation(AboutBox.class); String teName = elements.getBinaryName(clazz).toString(); File file = layer(element) .file("AboutBox/" + teName.replace('.', '-') + ".instance") .intvalue("position", aboutBox.position()) .bundlevalue("displayName", aboutBox.displayName()); if (!aboutBox.iconPath().isEmpty()) { file.bundlevalue("iconPath", aboutBox.iconPath()); } file.write(); } return true; } }
2,167
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ThirdPartyLicensesCsvTable.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/about/ThirdPartyLicensesCsvTable.java
package org.esa.snap.rcp.about; import org.esa.snap.core.gpf.OperatorException; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * Holder for Third Party Licenses Table as provided from csv file. * * @author olafd */ public class ThirdPartyLicensesCsvTable { private List<String> name; private List<String> descrUse; private List<String> iprOwner; private List<String> iprOwnerUrl; private List<String> license; private List<String> licenseUrl; private BufferedReader bufferedReader; /** * Provides the licenses csv table from a resource file. */ ThirdPartyLicensesCsvTable(Reader licensesReader) { bufferedReader = new BufferedReader(licensesReader); loadTable(); } private void loadTable() { // currently we have 6 columns in file: this.name = new ArrayList<>(); this.descrUse = new ArrayList<>(); this.iprOwner = new ArrayList<>(); this.license = new ArrayList<>(); this.iprOwnerUrl = new ArrayList<>(); this.licenseUrl = new ArrayList<>(); readTable(); } private void readTable() { StringTokenizer st; try { int i = 0; String line; bufferedReader.readLine(); // skip header while ((line = bufferedReader.readLine()) != null) { line = line.trim(); st = new StringTokenizer(line, ";", false); if (st.hasMoreTokens()) { setName(i, st.nextToken()); } if (st.hasMoreTokens()) { setDescrUse(i, st.nextToken()); } if (st.hasMoreTokens()) { setIprOwner(i, st.nextToken()); } if (st.hasMoreTokens()) { setLicense(i, st.nextToken()); } if (st.hasMoreTokens()) { setIprOwnerUrl(i, st.nextToken()); } if (st.hasMoreTokens()) { setLicenseUrl(i, st.nextToken()); } i++; } } catch (IOException | NumberFormatException e) { throw new OperatorException("Failed to load 3rd-party license table: \n" + e.getMessage(), e); } } public List<String> getName() { return name; } private void setName(int index, String name) { this.name.add(index, name); } public String getName(int index) { return name.get(index); } private void setDescrUse(int index, String descrUse) { this.descrUse.add(index, descrUse); } String getDescrUse(int index) { return descrUse.get(index); } private void setIprOwner(int index, String iprOwner) { this.iprOwner.add(index, iprOwner); } String getIprOwner(int index) { return iprOwner.get(index); } private void setLicense(int index, String license) { this.license.add(index, license); } String getLicense(int index) { return license.get(index); } private void setIprOwnerUrl(int index, String iprOwnerUrl) { this.iprOwnerUrl.add(index, iprOwnerUrl); } String getIprOwnerUrl(int index) { return iprOwnerUrl.get(index); } private void setLicenseUrl(int index, String licenseUrl) { this.licenseUrl.add(index, licenseUrl); } String getLicenseUrl(int index) { return licenseUrl.get(index); } }
3,666
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AboutPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/about/AboutPanel.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.esa.snap.rcp.about; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.ImageUtilities; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.border.EmptyBorder; import java.awt.BorderLayout; import java.awt.Image; import java.util.Arrays; import java.util.List; /** * The UI component displayed by the {@link AboutAction}. Processes {@code AboutBox} file objects generated from * {@link AboutBox} annotations. * * @author Norman Fomferra * @author Marco Peters */ class AboutPanel extends JPanel { public AboutPanel() { setLayout(new BorderLayout(8, 8)); setBorder(new EmptyBorder(8, 8, 8, 8)); FileObject configFile = FileUtil.getConfigFile("AboutBox"); if (configFile != null) { JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.add("SNAP", new SnapAboutBox()); addAboutBoxPlugins(tabbedPane, configFile); tabbedPane.add("Licenses", new LicensesAboutBox()); add(tabbedPane, BorderLayout.CENTER); } else { add(new SnapAboutBox(), BorderLayout.CENTER); } } private void addAboutBoxPlugins(JTabbedPane tabbedPane, FileObject configFile) { FileObject aboutBoxPanels[] = configFile.getChildren(); List<FileObject> orderedAboutBoxPanels = FileUtil.getOrder(Arrays.asList(aboutBoxPanels), true); for (FileObject aboutBoxFileObject : orderedAboutBoxPanels) { JComponent panel = FileUtil.getConfigObject(aboutBoxFileObject.getPath(), JComponent.class); if (panel != null) { String displayName = (String) aboutBoxFileObject.getAttribute("displayName"); if (displayName != null && !displayName.trim().isEmpty()) { Icon icon = null; String iconPath = (String) aboutBoxFileObject.getAttribute("iconPath"); if (iconPath != null && !iconPath.trim().isEmpty()) { Image image = ImageUtilities.loadImage(iconPath, false); if (image != null) { icon = new ImageIcon(image); } } tabbedPane.addTab(displayName, icon, panel); } } } } }
2,648
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
LicensesAboutBox.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/about/LicensesAboutBox.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.esa.snap.rcp.about; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.RowSorter; import javax.swing.SortOrder; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.io.BufferedReader; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import static org.esa.snap.core.util.SystemUtils.*; /** * Provides a 'Licenses' tab in AboutBox which contains a table displaying all third party licenses * used in SNAP and the Toolboxes.. * * @author olafd */ class LicensesAboutBox extends JPanel { private static final String THIRD_PARTY_LICENSE_DEFAULT_FILE_NAME = "THIRDPARTY_LICENSES.txt"; private ThirdPartyLicense[] licenses; LicensesAboutBox() { super(new BorderLayout(4, 4)); setBorder(new EmptyBorder(4, 4, 4, 4)); createLicensesPanel(); } private void createLicensesPanel() { JLabel infoText = new JLabel("<html>" + "<b>The table below gives an overview of all 3rd-party licenses used by SNAP " + "and the ESA Toolboxes.<br>" + "The dependencies of other plugins are not considered in this list.</b>" ); JComponent licensesComponent; Path licensesFile = getApplicationHomeDir().toPath().resolve(THIRD_PARTY_LICENSE_DEFAULT_FILE_NAME); try { JTable table = createLicensesTable(licensesFile); licensesComponent = createScrollPane(table); } catch (IOException e) { String msg = "Error: Cloud not read licenses from " + licensesFile.toAbsolutePath().toString(); LOG.log(Level.WARNING, msg, e); JLabel msgLabel = new JLabel(msg); msgLabel.setVerticalAlignment(SwingConstants.TOP); licensesComponent = msgLabel; } add(infoText, BorderLayout.NORTH); add(licensesComponent, BorderLayout.CENTER); setVisible(true); } private JScrollPane createScrollPane(JTable table) { JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); Dimension d = table.getPreferredSize(); scrollPane.setPreferredSize(new Dimension(d.width, table.getRowHeight() * 10)); return scrollPane; } private JTable createLicensesTable(Path licensesFile) throws IOException { licenses = getThirdPartyLicensesFromCsvTable(licensesFile); ThirdPartyLicensesTableModel licensesTableModel = new ThirdPartyLicensesTableModel(licenses); JTable licensesTable = new JTable(licensesTableModel); // add specific properties to table final JTableHeader tableHeader = licensesTable.getTableHeader(); final int fontSize = tableHeader.getFont().getSize(); tableHeader.setFont(new Font(null, Font.BOLD, fontSize)); tableHeader.setOpaque(false); tableHeader.setBackground(Color.lightGray); for (int i = 0; i < licensesTable.getColumnCount(); i++) { licensesTable.getColumnModel().getColumn(i).setCellRenderer(new LineWrapCellRenderer()); } // set proper default column sizes final TableColumnModel tableColumnModel = licensesTable.getColumnModel(); final TableColumn nameColumn = tableColumnModel.getColumn(ThirdPartyLicensesTableModel.NAME_COL_INDEX); final TableColumn descrUseColumn = tableColumnModel.getColumn(ThirdPartyLicensesTableModel.DESCRIPTION_USE_COL_INDEX); final TableColumn iprOwnerColumn = tableColumnModel.getColumn(ThirdPartyLicensesTableModel.IPR_OWNER_COL_INDEX); final TableColumn licenseColumn = tableColumnModel.getColumn(ThirdPartyLicensesTableModel.LICENSE_COL_INDEX); // with regard to overall dialog size, a good sum of preferred widths is ~530 nameColumn.setMinWidth(10); nameColumn.setPreferredWidth(150); descrUseColumn.setMinWidth(10); descrUseColumn.setPreferredWidth(160); iprOwnerColumn.setMinWidth(10); iprOwnerColumn.setPreferredWidth(110); licenseColumn.setMinWidth(10); licenseColumn.setPreferredWidth(110); // add sorter: enable sorting by String except for Description/Use column licensesTable.setAutoCreateRowSorter(true); TableRowSorter<TableModel> sorter = new TableRowSorter<>(licensesTable.getModel()); licensesTable.setRowSorter(sorter); List<RowSorter.SortKey> sortKeys = new ArrayList<>(); sortKeys.add(new RowSorter.SortKey(ThirdPartyLicensesTableModel.NAME_COL_INDEX, SortOrder.ASCENDING)); sorter.setSortKeys(sortKeys); sorter.setSortable(ThirdPartyLicensesTableModel.DESCRIPTION_USE_COL_INDEX, false); sorter.sort(); // add mouse motion listener to set hand cursor over cells which contain a link final MouseMotionListener motionListener = new MouseMotionListener() { @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { int column = licensesTable.columnAtPoint(e.getPoint()); int row = licensesTable.rowAtPoint(e.getPoint()); final String columnName = licensesTableModel.getColumnName(column); if (licenses[row].getUrlByTableColumnName(columnName) != null) { setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } else { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } }; licensesTable.addMouseMotionListener(motionListener); // add mouse adapter to invoke external browser when clicking on a cell which contains a link final MouseAdapter mouseAdapter = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int row = licensesTable.rowAtPoint(e.getPoint()); int column = licensesTable.columnAtPoint(e.getPoint()); if (licensesTableModel.containsURLs(column)) { final String columnName = licensesTableModel.getColumnName(column); final String urlString = licenses[row].getUrlByTableColumnName(columnName); if (urlString != null) { try { URI uri = new URI(urlString); if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { try { Desktop.getDesktop().browse(uri); } catch (Throwable e2) { JOptionPane.showMessageDialog(licensesTable.getParent(), "Failed to open URL:\n" + uri + ":\n" + e2.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(licensesTable.getParent(), "The desktop command 'browse' is not supported.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (URISyntaxException e1) { JOptionPane.showMessageDialog(licensesTable.getParent(), "Cannot create URL from given String:\n" + urlString + ":\n" + e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } } }; licensesTable.addMouseListener(mouseAdapter); licensesTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS); return licensesTable; } private ThirdPartyLicense[] getThirdPartyLicensesFromCsvTable(Path licensesFile) throws IOException { try (BufferedReader licensesReader = Files.newBufferedReader(licensesFile)) { final ThirdPartyLicensesCsvTable licensesCsvTable = new ThirdPartyLicensesCsvTable(licensesReader); final int numLicenses = licensesCsvTable.getName().size(); ThirdPartyLicense[] thirdPartyLicenses = new ThirdPartyLicense[numLicenses]; for (int i = 0; i < numLicenses; i++) { if (licensesCsvTable.getName(i) != null) { String name = licensesCsvTable.getName(i); String descriptionUse = licensesCsvTable.getDescrUse(i); String iprOwner = licensesCsvTable.getIprOwner(i); String license = licensesCsvTable.getLicense(i).toUpperCase().equals("NONE") ? null : licensesCsvTable.getLicense(i); String iprOwnerUrl = licensesCsvTable.getIprOwnerUrl(i).toUpperCase().equals("NONE") ? null : licensesCsvTable.getIprOwnerUrl(i); String licenseUrl = licensesCsvTable.getLicenseUrl(i).toUpperCase().equals("NONE") ? null : licensesCsvTable.getLicenseUrl(i); thirdPartyLicenses[i] = new ThirdPartyLicense(name, descriptionUse, iprOwner, license, iprOwnerUrl, licenseUrl); } } return thirdPartyLicenses; } } /** * Class providing a proper line wrapping in table cells. */ private class LineWrapCellRenderer extends JTextArea implements TableCellRenderer { @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { this.setText((String) value); this.setWrapStyleWord(true); this.setLineWrap(true); Font boldFont = new Font(null, Font.BOLD, this.getFont().getSize()); final String columnName = table.getModel().getColumnName(column); if (licenses[row].getUrlByTableColumnName(columnName) != null) { this.setFont(boldFont); this.setForeground(Color.blue); this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } else if (column == ThirdPartyLicensesTableModel.NAME_COL_INDEX) { this.setFont(boldFont); this.setForeground(table.getForeground()); } else { this.setFont(table.getFont()); this.setForeground(table.getForeground()); } final FontMetrics fontMetrics = this.getFontMetrics(this.getFont()); int fontHeight = fontMetrics.getHeight(); int textLength = fontMetrics.stringWidth(this.getText()); final int columnWidth = table.getColumnModel().getColumn(column).getWidth(); int lines = textLength / columnWidth + 1; if (lines == 0) { lines = 1; } int height = fontHeight * lines + 5; if (height > table.getRowHeight(row)) { table.setRowHeight(row, height); } return this; } } }
13,130
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SnapAboutBox.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/about/SnapAboutBox.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.esa.snap.rcp.about; import com.bc.ceres.core.runtime.Version; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.util.BrowserUtils; import org.openide.modules.ModuleInfo; import org.openide.modules.Modules; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Font; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; /** * @author Norman */ public class SnapAboutBox extends JPanel { private final static String defaultReleaseNotesUrlString = "https://senbox.atlassian.net/issues/?filter=-4&jql=project%20%3D%20SNAP%20AND%20fixVersion%20%3D%20"; // the version is appended in the code below private final static String stepReleaseNotesUrlString = "https://step.esa.int/main/wp-content/releasenotes/SNAP/SNAP_<version>.html"; private final JLabel versionText; private final ModuleInfo engineModuleInfo; public SnapAboutBox() { super(new BorderLayout(4, 4)); ModuleInfo desktopModuleInfo = Modules.getDefault().ownerOf(SnapAboutBox.class); engineModuleInfo = Modules.getDefault().ownerOf(Product.class); ImageIcon image = new ImageIcon(SnapAboutBox.class.getResource("SNAP_Banner.jpg")); JLabel banner = new JLabel(image); versionText = new JLabel("<html><b>SNAP " + SystemUtils.getReleaseVersion() + "</b>"); JLabel infoText = new JLabel("<html>" + "This program is free software: you can redistribute it and/or modify it<br>" + "under the terms of the <b>GNU General Public License</b> as published by<br>" + "the Free Software Foundation, either version 3 of the License, or<br>" + "(at your option) any later version.<br>" + "<br>" + "<b>SNAP Desktop implementation version: </b>" + desktopModuleInfo.getImplementationVersion() + "<br>" + "<b>SNAP Engine implementation version: </b>" + engineModuleInfo.getImplementationVersion() + "<br>" /* + "<b>Home directory: </b>" + SystemUtils.getApplicationHomeDir() + "<br>" + "<b>User directory: </b>" + SystemUtils.getApplicationDataDir() + "<br>" + "<b>Cache directory: </b>" + SystemUtils.getCacheDir() + "<br>" */ + "<b>JRE: </b>" + System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version") + "<br>" + "<b>JVM: </b>" + System.getProperty("java.vm.name") + " by " + System.getProperty("java.vendor") + "<br>" + "<b>Memory: </b>" + Math.round(Runtime.getRuntime().maxMemory() / 1024. / 1024.) + " MiB<br>" ); Font font = versionText.getFont(); if (font != null) { infoText.setFont(font.deriveFont(font.getSize() * 0.9f)); } JPanel innerPanel = new JPanel(new BorderLayout(4, 4)); innerPanel.setBorder(new EmptyBorder(8, 4, 8, 4)); innerPanel.add(createVersionPanel(), BorderLayout.NORTH); innerPanel.add(infoText, BorderLayout.SOUTH); JPanel bannerPanel = new JPanel(new BorderLayout(4, 4)); bannerPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); bannerPanel.add(banner); add(bannerPanel, BorderLayout.WEST); add(innerPanel, BorderLayout.CENTER); /* final Properties properties = System.getProperties(); for (String name : properties.stringPropertyNames()) { System.out.println(name + " = " + properties.getProperty(name)); } */ } private JPanel createVersionPanel() { final JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); panel.add(versionText); Version specVersion = Version.parseVersion(engineModuleInfo.getSpecificationVersion().toString()); String versionString = String.format("%s.%s.%s", specVersion.getMajor(), specVersion.getMinor(), specVersion.getMicro()); String changelogUrl = getReleaseNotesURLString(versionString); final JLabel releaseNoteLabel = new JLabel("<html><a href=\"" + changelogUrl + "\">Release Notes</a>"); releaseNoteLabel.setCursor(new Cursor(Cursor.HAND_CURSOR)); releaseNoteLabel.addMouseListener(new BrowserUtils.URLClickAdaptor(changelogUrl)); panel.add(releaseNoteLabel); return panel; } private String getReleaseNotesURLString(String versionString){ String changelogUrl = stepReleaseNotesUrlString.replace("<version>", versionString); try { URL url = new URL(changelogUrl); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setRequestMethod("HEAD"); int responseCode = huc.getResponseCode(); if(responseCode != HttpURLConnection.HTTP_OK) { changelogUrl = defaultReleaseNotesUrlString + versionString; } } catch (IOException e) { changelogUrl = defaultReleaseNotesUrlString + versionString; } return changelogUrl; } }
5,570
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PixelPosStatusLineElementProvider.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/status/PixelPosStatusLineElementProvider.java
package org.esa.snap.rcp.status; import com.bc.ceres.glayer.support.ImageLayer; import com.bc.ceres.glayer.swing.LayerCanvas; import eu.esa.snap.netbeans.docwin.DocumentWindowManager; import org.esa.snap.core.datamodel.*; import org.esa.snap.core.util.math.SphericalDistance; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.PixelPositionListener; import org.esa.snap.ui.product.ProductSceneView; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.opengis.referencing.datum.Ellipsoid; import org.openide.awt.StatusLineElementProvider; import org.openide.util.lookup.ServiceProvider; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import java.util.prefs.Preferences; import static org.esa.snap.rcp.pixelinfo.PixelInfoView.*; /** * Displays current pixel position in the status bar. * * @author Norman Fomferra */ @ServiceProvider(service = StatusLineElementProvider.class, position = 10) public class PixelPosStatusLineElementProvider implements StatusLineElementProvider, DocumentWindowManager.Listener<Object, ProductSceneView>, PixelPositionListener, PreferenceChangeListener { private static final String GEO_POS_FORMAT = "Lat %8s Lon %8s"; private static final String PIXEL_POS_FORMAT = "X %6s Y %6s"; private static final String ZOOM_LEVEL_FORMAT = "Zoom %s Level %s"; private static final String PIXEL_SIZE_FORMAT = "Pixel Spacing: %s m %s m"; private final JLabel zoomLevelLabel; private final JLabel geoPosLabel; private final JLabel pixelPosLabel; private final JLabel pixelSpacingLabel; private final JLabel scaleLabel; private final JPanel panel; private boolean showPixelOffsetDecimals; private boolean showGeoPosOffsetDecimals; private final DecimalFormatSymbols formatSymbols; private final DecimalFormat decimalFormat; private double longitudeResolutionInMeter; private double latitudeResolutionInMeter; public PixelPosStatusLineElementProvider() { DocumentWindowManager.getDefault().addListener(DocumentWindowManager.Predicate.view(ProductSceneView.class), this); SnapApp.getDefault().getPreferences().addPreferenceChangeListener(this); updateSettings(); pixelPosLabel = new JLabel(); pixelPosLabel.setPreferredSize(new Dimension(120, 20)); pixelPosLabel.setHorizontalAlignment(SwingConstants.CENTER); geoPosLabel = new JLabel(); geoPosLabel.setPreferredSize(new Dimension(200, 20)); geoPosLabel.setHorizontalAlignment(SwingConstants.CENTER); zoomLevelLabel = new JLabel(); zoomLevelLabel.setPreferredSize(new Dimension(150, 20)); zoomLevelLabel.setHorizontalAlignment(SwingConstants.CENTER); pixelSpacingLabel = new JLabel(); pixelSpacingLabel.setPreferredSize(new Dimension(230, 20)); pixelSpacingLabel.setHorizontalAlignment(SwingConstants.CENTER); scaleLabel = new JLabel(); scaleLabel.setPreferredSize(new Dimension(180, 20)); scaleLabel.setHorizontalAlignment(SwingConstants.CENTER); panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS)); panel.add(Box.createHorizontalGlue()); panel.add(new JSeparator(SwingConstants.VERTICAL)); panel.add(pixelPosLabel); panel.add(new JSeparator(SwingConstants.VERTICAL)); panel.add(geoPosLabel); panel.add(new JSeparator(SwingConstants.VERTICAL)); panel.add(zoomLevelLabel); panel.add(new JSeparator(SwingConstants.VERTICAL)); panel.add(pixelSpacingLabel); panel.add(new JSeparator(SwingConstants.VERTICAL)); panel.add(scaleLabel); formatSymbols = new DecimalFormatSymbols(); formatSymbols.setDecimalSeparator('.'); decimalFormat = new DecimalFormat("#.##", formatSymbols); longitudeResolutionInMeter = Double.NaN; latitudeResolutionInMeter = Double.NaN; } private void computeResolution() { longitudeResolutionInMeter = Double.NaN; latitudeResolutionInMeter = Double.NaN; ProductSceneView productSceneView = SnapApp.getDefault().getSelectedProductSceneView(); if (productSceneView == null) { return; } RasterDataNode rasterDataNode = productSceneView.getRaster(); if (rasterDataNode == null) { return; } GeoCoding geoCoding = rasterDataNode.getGeoCoding(); if (geoCoding == null) { return; } if (geoCoding instanceof CrsGeoCoding) { longitudeResolutionInMeter = rasterDataNode.getImageToModelTransform().getScaleX(); latitudeResolutionInMeter = Math.abs(rasterDataNode.getImageToModelTransform().getScaleY()); } else { int width = rasterDataNode.getRasterWidth(); int height = rasterDataNode.getRasterHeight(); int minWidth = 12;//depends on checking area of the computeGeocodingAccordingDuplicatedValue if (width > minWidth && height > 2) { final DefaultGeographicCRS wgs84 = DefaultGeographicCRS.WGS84; final Ellipsoid ellipsoid = wgs84.getDatum().getEllipsoid(); final double meanEarthRadiusM = (ellipsoid.getSemiMajorAxis() + ellipsoid.getSemiMinorAxis()) * 0.5; int x1 = (int) (width * 0.5); int y1 = (int) (height * 0.5); GeoPos geoPos = geoCoding.getGeoPos(new PixelPos(x1, y1), null); double resLon = geoPos.getLon(); double resLat = geoPos.getLat(); final SphericalDistance spherDist = new SphericalDistance(resLon, resLat); //compute latitude GeoPos geoPosY = geoCoding.getGeoPos(new PixelPos(x1, y1 + 1), null); double resLonY = geoPosY.getLon(); double resLatY = geoPosY.getLat(); double latitudeDistance = spherDist.distance(resLonY, resLatY); latitudeResolutionInMeter = latitudeDistance * meanEarthRadiusM; // compute longitude with checking of duplicated geocoding longitudeResolutionInMeter = computeGeocodingAccordingDuplicatedValue(geoCoding, width, x1, y1, resLon, spherDist, meanEarthRadiusM); } } } private double computeGeocodingAccordingDuplicatedValue(GeoCoding geoCoding, int width, int xRef, int yRef, double resLon, SphericalDistance spherDist, double meanEarthRadiusM) { int step = 5; int distanceMax = 20; int diffPix = step; boolean haveAResolution = false; while (!haveAResolution && diffPix < distanceMax && xRef + diffPix < width - 1) { GeoPos geoPosX = geoCoding.getGeoPos(new PixelPos(xRef + diffPix, yRef), null); double resLonX = geoPosX.getLon(); if (resLon != resLonX) { haveAResolution = true; } else { diffPix += step; } } GeoPos geoPosX = geoCoding.getGeoPos(new PixelPos((xRef + diffPix), yRef), null); double resLonX = geoPosX.getLon(); double resLatX = geoPosX.getLat(); double longitudeDistance = spherDist.distance(resLonX, resLatX); return longitudeDistance * meanEarthRadiusM / (double) diffPix; } @Override public Component getStatusLineElement() { return panel; } @Override public void pixelPosChanged(ImageLayer imageLayer, int pixelX, int pixelY, int currentLevel, boolean pixelPosValid, MouseEvent e) { if (pixelPosValid) { AffineTransform i2mTransform = imageLayer.getImageToModelTransform(currentLevel); Point2D modelP = i2mTransform.transform(new Point2D.Double(pixelX + 0.5, pixelY + 0.5), null); AffineTransform m2iTransform = imageLayer.getModelToImageTransform(); Point2D imageP = m2iTransform.transform(modelP, null); PixelPos pixelPos = new PixelPos(imageP.getX(), imageP.getY()); ProductSceneView productSceneView = SnapApp.getDefault().getSelectedProductSceneView(); if (productSceneView == null) { setDefault(); return; } RasterDataNode rasterDataNode = productSceneView.getRaster(); if (rasterDataNode == null) { setDefault(); return; } GeoCoding geoCoding = rasterDataNode.getGeoCoding(); if (geoCoding == null) { setDefault(); return; } else { GeoPos geoPos = geoCoding.getGeoPos(pixelPos, null); if (showGeoPosOffsetDecimals) { geoPosLabel.setText(String.format("Lat %.5f Lon %.5f", geoPos.getLat(), geoPos.getLon())); } else { geoPosLabel.setText(String.format(GEO_POS_FORMAT, geoPos.getLatString(), geoPos.getLonString())); } } if (showPixelOffsetDecimals) { pixelPosLabel.setText(String.format(PIXEL_POS_FORMAT, imageP.getX(), imageP.getY())); } else { pixelPosLabel.setText(String.format(PIXEL_POS_FORMAT, (int) Math.floor(imageP.getX()), (int) Math.floor(imageP.getY()))); } LayerCanvas layerCanvas = (LayerCanvas) e.getSource(); double zoomFactor = layerCanvas.getViewport().getZoomFactor(); String scaleStr; if (zoomFactor > 1.0) { double v = Math.round(10.0 * zoomFactor) / 10.0; scaleStr = ((int) v == v ? (int) v : v) + ":1"; } else { double v = Math.round(10.0 / zoomFactor) / 10.0; scaleStr = "1:" + ((int) v == v ? (int) v : v); } zoomLevelLabel.setText(String.format(ZOOM_LEVEL_FORMAT, scaleStr, currentLevel)); if (longitudeResolutionInMeter != Double.NaN && latitudeResolutionInMeter != Double.NaN) pixelSpacingLabel.setText(String.format(PIXEL_SIZE_FORMAT, decimalFormat.format(latitudeResolutionInMeter), decimalFormat.format(longitudeResolutionInMeter))); } else { setDefault(); } } private void setDefault() { geoPosLabel.setText(String.format(GEO_POS_FORMAT, "--", "--")); pixelPosLabel.setText(String.format(PIXEL_POS_FORMAT, "--", "--")); zoomLevelLabel.setText(String.format(ZOOM_LEVEL_FORMAT, "--", "--")); pixelSpacingLabel.setText(String.format(PIXEL_SIZE_FORMAT, "--", "--")); } @Override public void pixelPosNotAvailable() { setDefault(); } @Override public void preferenceChange(PreferenceChangeEvent evt) { // Called if SNAP preferences change, adjust any status bar setting here. final String propertyName = evt.getKey(); if (PREFERENCE_KEY_SHOW_PIXEL_POS_DECIMALS.equals(propertyName) || PREFERENCE_KEY_SHOW_GEO_POS_DECIMALS.equals(propertyName)) { updateSettings(); } } @Override public void windowSelected(DocumentWindowManager.Event<Object, ProductSceneView> e) { ProductSceneView view = e.getWindow().getView(); view.addPixelPositionListener(this); computeResolution(); } @Override public void windowDeselected(DocumentWindowManager.Event<Object, ProductSceneView> e) { ProductSceneView view = e.getWindow().getView(); view.removePixelPositionListener(this); longitudeResolutionInMeter = Double.NaN; latitudeResolutionInMeter = Double.NaN; } private void updateSettings() { final Preferences preferences = SnapApp.getDefault().getPreferences(); showPixelOffsetDecimals = preferences.getBoolean( PREFERENCE_KEY_SHOW_PIXEL_POS_DECIMALS, PREFERENCE_DEFAULT_SHOW_PIXEL_POS_DECIMALS); showGeoPosOffsetDecimals = preferences.getBoolean( PREFERENCE_KEY_SHOW_GEO_POS_DECIMALS, PREFERENCE_DEFAULT_SHOW_GEO_POS_DECIMALS); } }
12,728
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
RestoredSession.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/RestoredSession.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session; import org.esa.snap.core.datamodel.Product; import org.esa.snap.ui.product.ProductNodeView; /** * A restored session comprising products and views. * * @author Norman Fomferra * @version $Revision$ $Date$ * @since BEAM 4.6 */ public class RestoredSession { private final Product[] products; private final ProductNodeView[] views; private final Exception[] problems; public RestoredSession(Product[] products, ProductNodeView[] views, Exception[] problems) { this.products = products; this.views = views; this.problems = problems; } public Product[] getProducts() { return products.clone(); } public ProductNodeView[] getViews() { return views.clone(); } public Exception[] getProblems() { return problems.clone(); } }
1,579
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ShapeConverter.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/ShapeConverter.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session; import com.bc.ceres.binding.ConversionException; import com.bc.ceres.binding.Converter; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.LinearRing; import org.locationtech.jts.geom.Polygon; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; import java.awt.Shape; import java.awt.geom.PathIterator; import java.util.ArrayList; /** * A converter for {@link Shape}s. * * @author Norman Fomferra * @version $Revision$ $Date$ * @since BEAM 4.6 */ public class ShapeConverter implements Converter { private final GeometryFactory geometryFactory; public ShapeConverter() { geometryFactory = new GeometryFactory(); } @Override public Class getValueType() { return Shape.class; } @Override public Object parse(String text) throws ConversionException { try { Geometry geometry = new WKTReader(geometryFactory).read(text); if (geometry instanceof LineString) { LineString lineString = (LineString) geometry; // todo return null; } else if (geometry instanceof Polygon) { Polygon polygon = (Polygon) geometry; // todo return null; } else { throw new ConversionException("Failed to parse shape geometry WKT."); } } catch (ParseException e) { throw new ConversionException("Failed to parse shape geometry WKT.", e); } } @Override public String format(Object value) { Shape shape = (Shape) value; PathIterator pathIterator = shape.getPathIterator(null, 1.0); ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>(); ArrayList<Geometry> geometries = new ArrayList<Geometry>(); double[] coord = new double[6]; while (!pathIterator.isDone()) { int type = pathIterator.currentSegment(coord); if (type == PathIterator.SEG_MOVETO) { coordinatesToGeometry(coordinates, geometries); coordinates.add(new Coordinate(coord[0], coord[1])); } else if (type == PathIterator.SEG_LINETO) { coordinates.add(new Coordinate(coord[0], coord[1])); } else if (type == PathIterator.SEG_CLOSE) { if (coordinates.size() > 0) { if (!coordinates.get(0).equals(coordinates.get(coordinates.size() - 1))) { coordinates.add(coordinates.get(0)); } coordinatesToGeometry(coordinates, geometries); } } pathIterator.next(); } coordinatesToGeometry(coordinates, geometries); if (geometries.isEmpty()) { return ""; } if (geometries.get(0) instanceof LinearRing) { ArrayList<LinearRing> holes = new ArrayList<LinearRing>(); for (int i = 1; i < geometries.size(); i++) { Geometry geometry = geometries.get(i); if (geometry instanceof LinearRing) { holes.add((LinearRing) geometry); } } if (holes.size() == geometries.size() - 1) { return geometryFactory.createPolygon((LinearRing) geometries.get(0), holes.toArray(new LinearRing[holes.size()])).toText(); } } if (geometries.size() == 1) { return geometries.get(0).toText(); } else { return geometryFactory.createGeometryCollection(geometries.toArray(new Geometry[geometries.size()])).toText(); } } private void coordinatesToGeometry(ArrayList<Coordinate> coordinates, ArrayList<Geometry> geometries) { if (coordinates.size() > 0) { if (coordinates.get(0).equals(coordinates.get(coordinates.size() - 1))) { LinearRing linearRing = geometryFactory.createLinearRing(coordinates.toArray(new Coordinate[coordinates.size()])); geometries.add(linearRing); } else { LineString lineString = geometryFactory.createLineString(coordinates.toArray(new Coordinate[coordinates.size()])); geometries.add(lineString); } coordinates.clear(); } } }
5,310
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SessionIO.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/SessionIO.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session; import com.bc.ceres.core.Assert; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.Reader; import java.io.Writer; /** * The Session I/O class is used to store and restore sessions. * * @author Norman Fomferra * @version $Revision$ $Date$ * @since BEAM 4.6 */ public abstract class SessionIO { static SessionIO instance = new XStreamSessionIO(); public static SessionIO getInstance() { return instance; } public static void setInstance(SessionIO instance) { Assert.notNull(instance, "instance"); SessionIO.instance = instance; } public Session readSession(File file) throws Exception { Assert.notNull(file, "file"); try (FileReader reader = new FileReader(file)) { return readSession(reader); } } public abstract Session readSession(Reader reader) throws Exception; public void writeSession(Session session, File file) throws Exception { Assert.notNull(session, "session"); Assert.notNull(file, "file"); try (FileWriter writer = new FileWriter(file)) { writeSession(session, writer); } } public abstract void writeSession(Session session, Writer writer) throws Exception; }
2,035
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SessionManager.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/SessionManager.java
package org.esa.snap.rcp.session; import org.esa.snap.core.util.io.SnapFileFilter; import java.io.File; /** * A session manager is handling the one and only active session file. * * @author Muhammad */ public class SessionManager { private static SessionManager instance = new SessionManager(); private File sessionFile; public static SessionManager getDefault() { return instance; } public SnapFileFilter getSessionFileFilter() { return new SnapFileFilter("SESSION", new String[]{".snap"}, "SNAP session files"); } public File getSessionFile() { return sessionFile; } public void setSessionFile(File sessionFile) { this.sessionFile = sessionFile; } }
805
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
XStreamSessionIO.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/XStreamSessionIO.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session; import com.bc.ceres.binding.dom.DefaultDomElement; import com.bc.ceres.binding.dom.DomElement; import com.bc.ceres.core.Assert; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.security.ExplicitTypePermission; import java.io.Reader; import java.io.Writer; /** * A Session I/O implementation which uses {@link XStream} to marshall and unmarshall {@link Session} instances * to and from XML. * <p>Clients may override the {@link #createXStream()} in order to create an appropriate {@code XStream} * for their session. * * @author Norman Fomferra * @version $Revision$ $Date$ * @since BEAM 4.6 */ public class XStreamSessionIO extends SessionIO { protected XStream createXStream() { XStream xStream = new XStream(); xStream.addPermission(new ExplicitTypePermission(new Class[]{Session.class, Session.ProductRef.class, Session.ViewRef.class})); xStream.setClassLoader(XStreamSessionIO.class.getClassLoader()); xStream.autodetectAnnotations(true); xStream.alias("session", Session.class); xStream.alias("configuration", DomElement.class, DefaultDomElement.class); return xStream; } @Override public Session readSession(Reader reader) { Assert.notNull(reader, "reader"); return (Session) createXStream().fromXML(reader); } @Override public void writeSession(Session session, Writer writer) { Assert.notNull(session, "session"); Assert.notNull(writer, "writer"); createXStream().toXML(session, writer); } }
2,324
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SaveSessionAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/SaveSessionAction.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.actions.file.SaveProductAction; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.ui.product.ProductNodeView; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.ContextAwareAction; import org.openide.util.Lookup; import org.openide.util.LookupEvent; import org.openide.util.LookupListener; import org.openide.util.NbBundle; import org.openide.util.Utilities; import org.openide.util.WeakListeners; import javax.swing.AbstractAction; import javax.swing.Action; import java.awt.event.ActionEvent; import java.io.File; import java.text.MessageFormat; import java.util.ArrayList; @ActionID( category = "File", id = "org.esa.snap.rcp.session.SaveSessionAction" ) @ActionRegistration( displayName = "#CTL_SaveSessionAction_MenuText", lazy = false ) @ActionReference(path = "Menu/File/Session", position = 20) @NbBundle.Messages({ "CTL_SaveSessionAction_MenuText=Save Session", "CTL_SaveSessionAction_ShortDescription=Save the current SNAP session." }) public class SaveSessionAction extends AbstractAction implements ContextAwareAction, LookupListener { public static final String ID = "saveSession"; private static final String TITLE = "Save Session As"; private final Lookup.Result<ProductNode> result; private final Lookup lookup; private ProductManager productManager; public SaveSessionAction() { this(Utilities.actionsGlobalContext()); } public SaveSessionAction(Lookup lookup) { super(Bundle.CTL_SaveSessionAction_MenuText()); this.lookup = lookup; result = lookup.lookupResult(ProductNode.class); ProductManager productManager = SnapApp.getDefault().getProductManager(); productManager.addListener(new SaveSessionListener()); result.addLookupListener(WeakListeners.create(LookupListener.class, this, result)); setEnabled(false); } @Override public final void actionPerformed(ActionEvent event) { saveSession(false); } @Override public Action createContextAwareInstance(Lookup actionContext) { return new SaveSessionAction(actionContext); } @Override public void resultChanged(LookupEvent ev) { ProductNode productNode = lookup.lookup(ProductNode.class); setEnabled(productNode != null); } public void saveSession(boolean saveAs) { final SessionManager app = SessionManager.getDefault(); File sessionFile = app.getSessionFile(); if (sessionFile == null || saveAs) { sessionFile = Dialogs.requestFileForSave(TITLE, false, SessionManager.getDefault().getSessionFileFilter(), SessionManager.getDefault().getSessionFileFilter().getDefaultExtension(), sessionFile != null ? sessionFile.getName() : System.getProperty("user.name", "noname"), null, OpenSessionAction.LAST_SESSION_DIR_KEY); if (sessionFile == null) { return; } } if (!saveProductsOrLetItBe(sessionFile)) { return; } app.setSessionFile(sessionFile); try { final Session session = createSession(sessionFile); SessionIO.getInstance().writeSession(session, sessionFile); Dialogs.showInformation(TITLE, "Session saved.", null); } catch (Exception e) { e.printStackTrace(); Dialogs.showError(TITLE, e.getMessage()); } finally { // app.updateState(); // to update menu entries e.g. 'Close Session' } } public void saveSessionAsQuitely(final File newSessionFile) { if (!saveProductsOrLetItBe(newSessionFile)) { return; } try { final Session session = createSession(newSessionFile); SessionIO.getInstance().writeSession(session, newSessionFile); } catch (Exception e) { e.printStackTrace(); Dialogs.showError(TITLE, e.getMessage()); } } private boolean saveProductsOrLetItBe(File sessionFile) { final Product[] products = SnapApp.getDefault().getProductManager().getProducts(); for (Product product : products) { if (product.getFileLocation() == null) { String message = MessageFormat.format( "The following product has not been saved yet:\n" + "{0}.\n" + "Do you want to save it now?\n\n" + "Note: If you select 'No', the session cannot be saved.", product.getDisplayName()); // Here: No == Cancel, its because we need a file location in the session XML Dialogs.Answer answer = Dialogs.requestDecision(TITLE, message, false, null); if (answer == Dialogs.Answer.YES) { File sessionDir = sessionFile.getAbsoluteFile().getParentFile(); product.setFileLocation(new File(sessionDir, product.getName() + ".dim")); SaveProductAction saveProductAction = new SaveProductAction(product); saveProductAction.execute(); } else { return false; } } } for (Product product : products) { if (product.isModified()) { String message = MessageFormat.format( "The following product has been modified:\n" + "{0}.\n" + "Do you want to save it now?\n\n" + "Note: It is recommended to save the product in order to \n" + "fully restore the session later.", product.getDisplayName()); // Here: Yes, No + Cancel, its because we have file location for the session XML Dialogs.Answer answer = Dialogs.requestDecision(TITLE, message, false, null); if (answer == Dialogs.Answer.YES) { SaveProductAction saveProductAction = new SaveProductAction(product); saveProductAction.execute(); } else if (answer == Dialogs.Answer.YES) { return false; } } } return true; } private static Session createSession(File sessionFile) { ArrayList<ProductNodeView> nodeViews = new ArrayList<ProductNodeView>(); // ######### 06.07.2015 ######## // Comment out by Muhammad until view persistence is solved for NetBeans platform // // final JInternalFrame[] internalFrames = app.getAllInternalFrames(); // for (JInternalFrame internalFrame : internalFrames) { // final Container contentPane = internalFrame.getContentPane(); // if (contentPane instanceof ProductNodeView) { // nodeViews.add((ProductNodeView) contentPane); // } // } return new Session(sessionFile.getParentFile().toURI(), SnapApp.getDefault().getProductManager().getProducts(), nodeViews.toArray(new ProductNodeView[nodeViews.size()])); } private class SaveSessionListener implements ProductManager.Listener { @Override public void productAdded(ProductManager.Event event) { updateEnableState(); } @Override public void productRemoved(ProductManager.Event event) { updateEnableState(); } private void updateEnableState() { setEnabled(SnapApp.getDefault().getProductManager().getProductCount() > 0); } } }
8,932
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OpenSessionAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/OpenSessionAction.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session; import com.bc.ceres.core.CanceledException; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.grender.Viewport; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import org.esa.snap.core.dataio.ProductIO; import org.esa.snap.core.datamodel.Product; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.actions.file.CloseAllProductsAction; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.ui.product.ProductNodeView; import org.esa.snap.ui.product.ProductSceneView; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.NbBundle; import javax.swing.AbstractAction; import javax.swing.JInternalFrame; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.net.URI; import java.text.MessageFormat; import java.util.concurrent.ExecutionException; @ActionID(category = "File", id = "org.esa.snap.rcp.session.OpenSessionAction") @ActionRegistration(displayName = "#CTL_OpenSessionAction_MenuText") @ActionReference(path = "Menu/File/Session", position = 15) @NbBundle.Messages({ "CTL_OpenSessionAction_MenuText=Open Session...", "CTL_OpenSessionAction_ShortDescription=Open a SNAP session." }) public class OpenSessionAction extends AbstractAction { public static final String ID = "openSession"; public static final String LAST_SESSION_DIR_KEY = "beam.lastSessionDir"; private static final String TITLE = "Open Session"; @Override public void actionPerformed(ActionEvent event) { final SessionManager manager = SessionManager.getDefault(); if (manager.getSessionFile() != null) { Dialogs.Answer answer = Dialogs.requestDecision(TITLE, "This will close or reopen the current session.\n" + "Do you want to continue?", true, null); if (answer != Dialogs.Answer.YES) { return; } } final File sessionFile = Dialogs.requestFileForOpen(TITLE, false, SessionManager.getDefault().getSessionFileFilter(), LAST_SESSION_DIR_KEY); if (sessionFile == null) { return; } openSession(sessionFile); } public void openSession(File sessionFile) { final SessionManager manager = SessionManager.getDefault(); manager.setSessionFile(sessionFile); CloseAllProductsAction closeProductAction = new CloseAllProductsAction(); closeProductAction.execute(); SwingWorker<RestoredSession, Object> worker = new OpenSessionWorker(manager, sessionFile); worker.execute(); } private static class OpenSessionWorker extends ProgressMonitorSwingWorker<RestoredSession, Object> { private final SessionManager app; private final File sessionFile; public OpenSessionWorker(SessionManager app, File sessionFile) { super(SnapApp.getDefault().getMainFrame(), TITLE); this.app = app; this.sessionFile = sessionFile; } @Override protected RestoredSession doInBackground(ProgressMonitor pm) throws Exception { final Session session = SessionIO.getInstance().readSession(sessionFile); final File parentFile = sessionFile.getParentFile(); final URI rootURI; if (parentFile != null) { rootURI = parentFile.toURI(); } else { rootURI = new File(".").toURI(); } return session.restore(SnapApp.getDefault().getAppContext(), rootURI, pm, new SessionProblemSolver()); } @Override protected void done() { final RestoredSession restoredSession; try { restoredSession = get(); } catch (InterruptedException e) { return; } catch (ExecutionException e) { if (e.getCause() instanceof CanceledException) { return; } Dialogs.showError(MessageFormat.format("An unexpected exception occurred!\nMessage: {0}", e.getCause().getMessage())); e.printStackTrace(); return; } final Exception[] problems = restoredSession.getProblems(); if (problems.length > 0) { StringBuilder sb = new StringBuilder(); sb.append("The following problem(s) occurred while opening a session:\n"); for (Exception problem : problems) { problem.printStackTrace(); sb.append(" "); sb.append(problem.getMessage()); sb.append("\n"); } Dialogs.showWarning(sb.toString()); } final Product[] products = restoredSession.getProducts(); for (Product product : products) { SnapApp.getDefault().getProductManager().addProduct(product); } // todo - Handle view persistence in a generic way. (nf - 08.05.2009) // These are the only 3 views currently known in BEAM. final ProductNodeView[] nodeViews = restoredSession.getViews(); for (ProductNodeView nodeView : nodeViews) { Rectangle bounds = nodeView.getBounds(); JInternalFrame internalFrame = null; if (nodeView instanceof ProductSceneView) { ProductSceneView sceneView = (ProductSceneView) nodeView; sceneView.getLayerCanvas().setInitiallyZoomingAll(false); Viewport viewport = sceneView.getLayerCanvas().getViewport().clone(); // ######### 06.07.2015 ######## // Comment out by Muhammad until tool window persistance is solved for SNAP on NetBeans platform. // if (sceneView.isRGB()) { // internalFrame = null;// showImageViewRGBAction.openInternalFrame(sceneView, false); // } else { // internalFrame = null;//showImageViewAction.openInternalFrame(sceneView, false); // } // sceneView.getLayerCanvas().getViewport().setTransform(viewport); // } else if (nodeView instanceof ProductMetadataView) { // ProductMetadataView metadataView = (ProductMetadataView) nodeView; // internalFrame = showMetadataViewAction.openInternalFrame(metadataView); // } // if (internalFrame != null) { // try { // internalFrame.setMaximum(false); // } catch (PropertyVetoException e) { // // ok to ignore // } // internalFrame.setBounds(bounds); // } } } } private <T> T getAction(String actionId) { T action = null; if (action == null) { throw new IllegalStateException("Action not found: actionId=" + actionId); } return action; } private class SessionProblemSolver implements Session.ProblemSolver { @Override public Product solveProductNotFound(int id, File file) throws CanceledException { final File[] newFile = new File[1]; final Dialogs.Answer[] answer = new Dialogs.Answer[1]; final String title = MessageFormat.format(TITLE + " - Resolving [{0}]", file); final String msg = MessageFormat.format("Product [{0}] has been renamed or (re-)moved.\n" + "Its location was [{1}].\n" + "Do you wish to provide its new location?\n" + "(Select ''No'' if the product shall no longer be part of the session.)", id, file); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { answer[0] = Dialogs.requestDecision(title, msg, true, null); if (answer[0] == Dialogs.Answer.YES) { newFile[0] = Dialogs.requestFileForOpen(title, false, null, null); } } }); } catch (Exception e) { throw new CanceledException(); } if (answer[0] == Dialogs.Answer.YES) { throw new CanceledException(); } if (newFile[0] != null) { try { return ProductIO.readProduct(newFile[0]); } catch (IOException e) { } } return null; } } } }
10,280
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
Session.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/Session.java
/* * Copyright (C) 2012 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session; import com.bc.ceres.binding.ConversionException; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.accessors.DefaultPropertyAccessor; import com.bc.ceres.binding.dom.DefaultDomElement; import com.bc.ceres.binding.dom.DomElement; import com.bc.ceres.binding.dom.DomElementXStreamConverter; import com.bc.ceres.core.CanceledException; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.core.SubProgressMonitor; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.LayerContext; import com.bc.ceres.glayer.LayerType; import com.bc.ceres.glayer.LayerTypeRegistry; import com.bc.ceres.grender.Viewport; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamConverter; import com.thoughtworks.xstream.converters.SingleValueConverterWrapper; import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter; import org.esa.snap.core.dataio.ProductIO; import org.esa.snap.core.dataio.ProductIOPlugInManager; import org.esa.snap.core.dataio.ProductReaderPlugIn; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.MetadataElement; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductData; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.core.datamodel.RGBImageProfile; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.VirtualBand; import org.esa.snap.core.layer.MaskCollectionLayerType; import org.esa.snap.core.util.PropertyMap; import org.esa.snap.core.util.StringUtils; import org.esa.snap.core.util.io.FileUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.metadata.MetadataViewTopComponent; import org.esa.snap.rcp.session.dom.SessionDomConverter; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.product.ProductNodeView; import org.esa.snap.ui.product.ProductSceneImage; import org.esa.snap.ui.product.ProductSceneView; import javax.swing.JComponent; import javax.swing.RootPaneContainer; import javax.swing.SwingUtilities; import java.awt.Container; import java.awt.Rectangle; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; /** * Data container used for storing/restoring BEAM sessions. * * @author Ralf Quast * @author Norman Fomferra * @version $Revision$ $Date$ * @since BEAM 4.6 */ @XStreamAlias("session") public class Session { public static String CURRENT_MODEL_VERSION = "1.0.0"; String modelVersion; @XStreamAlias("products") ProductRef[] productRefs; @XStreamAlias("views") ViewRef[] viewRefs; /** * No-arg constructor required by XStream. */ @SuppressWarnings("UnusedDeclaration") public Session() { } public Session(URI rootURI, Product[] products, ProductNodeView[] views) { modelVersion = CURRENT_MODEL_VERSION; productRefs = new ProductRef[products.length]; for (int i = 0; i < products.length; i++) { Product product = products[i]; URI relativeProductURI = getFileLocationURI(rootURI, product); final String productReaderPlugin = product.getProductReader().getReaderPlugIn().getClass().toString(); productRefs[i] = new ProductRef(product.getRefNo(), relativeProductURI, productReaderPlugin); } ProductManager productManager = new ProductManager(); for (Product product : products) { productManager.addProduct(product); } viewRefs = new ViewRef[views.length]; for (int i = 0; i < views.length; i++) { ProductNodeView view = views[i]; ViewportDef viewportDef = null; LayerRef[] layerRefs = new LayerRef[0]; if (view instanceof ProductSceneView) { ProductSceneView sceneView = (ProductSceneView) view; Viewport viewport = sceneView.getLayerCanvas().getViewport(); viewportDef = new ViewportDef(viewport.isModelYAxisDown(), viewport.getOffsetX(), viewport.getOffsetY(), viewport.getZoomFactor(), viewport.getOrientation()); List<Layer> layers = sceneView.getRootLayer().getChildren(); layerRefs = getLayerRefs(layers, productManager); } Rectangle viewBounds = new Rectangle(0, 0, 200, 200); if (view instanceof JComponent) { viewBounds = getRootPaneContainer((JComponent) view).getBounds(); } String productNodeName = null; String viewName = null; String expressionR = null; String expressionG = null; String expressionB = null; int productRefNo = 0; if (view instanceof ProductSceneView) { ProductSceneView psv = (ProductSceneView) view; if (psv.isRGB()) { viewName = psv.getSceneName(); RasterDataNode[] rasters = psv.getRasters(); expressionR = getExpression(rasters[0]); expressionG = getExpression(rasters[1]); expressionB = getExpression(rasters[2]); productRefNo = rasters[0].getProduct().getRefNo(); } else { productNodeName = view.getVisibleProductNode().getName(); productRefNo = view.getVisibleProductNode().getProduct().getRefNo(); } } // else if (view instanceof ProductMetadataView) { // ProductMetadataView metadataView = (ProductMetadataView) view; // MetadataElement metadataRoot = metadataView.getProduct().getMetadataRoot(); // MetadataElement metadataElement = metadataView.getMetadataElement(); // StringBuilder sb = new StringBuilder(metadataElement.getName()); // MetadataElement parent = metadataElement.getParentElement(); // while (parent != null && parent != metadataRoot) { // sb.append('|'); // sb.append(parent.getName()); // parent = parent.getParentElement(); // } // productNodeName = sb.toString(); // productRefNo = view.getVisibleProductNode().getProduct().getRefNo(); // // todo - flag and index coding views (rq-20100618) // } viewRefs[i] = new ViewRef(i, view.getClass().getName(), viewBounds, viewportDef, productRefNo, productNodeName, viewName, expressionR, expressionG, expressionB, layerRefs); } } // todo - code duplication in RgbImageLayerType.java (nf 10.2009) private static String getExpression(RasterDataNode raster) { Product product = raster.getProduct(); if (product != null) { if (product.containsBand(raster.getName())) { return raster.getName(); } else { if (raster instanceof VirtualBand) { return ((VirtualBand) raster).getExpression(); } } } return null; } private static URI getFileLocationURI(URI rootURI, Product product) { File file = product.getFileLocation(); return FileUtils.getRelativeUri(rootURI, file); } private static LayerRef[] getLayerRefs(List<Layer> layers, ProductManager productManager) { ArrayList<LayerRef> layerRefs = new ArrayList<LayerRef>(layers.size()); for (int i = 0; i < layers.size(); i++) { Layer layer = layers.get(i); if (isSerializableLayer(layer)) { PropertySet configuration = layer.getConfiguration(); // todo - check - why create a configuration copy here?! (nf, 10.2009) PropertySet configurationCopy = getConfigurationCopy(configuration); SessionDomConverter domConverter = new SessionDomConverter(productManager); DomElement element = new DefaultDomElement("configuration"); try { domConverter.convertValueToDom(configurationCopy, element); } catch (ConversionException e) { e.printStackTrace(); } layerRefs.add(new LayerRef(layer, i, element, getLayerRefs(layer.getChildren(), productManager))); } } return layerRefs.toArray(new LayerRef[layerRefs.size()]); } private static boolean isSerializableLayer(Layer layer) { // todo - check, this could be solved in a generic way (nf, 10.2009) return !(layer.getLayerType() instanceof MaskCollectionLayerType); } private static PropertyContainer getConfigurationCopy(PropertySet propertyContainer) { PropertyContainer configuration = new PropertyContainer(); for (Property model : propertyContainer.getProperties()) { PropertyDescriptor descriptor = new PropertyDescriptor(model.getDescriptor()); DefaultPropertyAccessor valueAccessor = new DefaultPropertyAccessor(); valueAccessor.setValue(model.getValue()); configuration.addProperty(new Property(descriptor, valueAccessor)); } return configuration; } public String getModelVersion() { return modelVersion; } public int getProductCount() { return productRefs.length; } public ProductRef getProductRef(int index) { return productRefs[index]; } public int getViewCount() { return viewRefs.length; } public ViewRef getViewRef(int index) { return viewRefs[index]; } public RestoredSession restore(AppContext appContext, URI rootURI, ProgressMonitor pm, ProblemSolver problemSolver) throws CanceledException { try { pm.beginTask("Restoring session", 100); ArrayList<Exception> problems = new ArrayList<Exception>(); ProductManager productManager = restoreProducts(rootURI, SubProgressMonitor.create(pm, 80), problemSolver, problems); // Note: ProductManager is used for the SessionDomConverter ProductNodeView[] views = restoreViews(productManager, appContext.getPreferences(), SubProgressMonitor.create(pm, 20), problems ); return new RestoredSession(productManager.getProducts(), views, problems.toArray(new Exception[problems.size()])); } finally { pm.done(); } } ProductManager restoreProducts(URI rootURI, ProgressMonitor pm, ProblemSolver problemSolver, List<Exception> problems) throws CanceledException { ProductManager productManager = new ProductManager(); try { pm.beginTask("Restoring products", productRefs.length); for (ProductRef productRef : productRefs) { try { Product product = null; File productFile = new File(rootURI.resolve(productRef.uri)); if (productFile.exists()) { final String productReaderPlugin = productRef.productReaderPlugin; if (StringUtils.isNotNullAndNotEmpty(productReaderPlugin)) { final Iterator<ProductReaderPlugIn> allReaderPlugIns = ProductIOPlugInManager.getInstance().getAllReaderPlugIns(); while (allReaderPlugIns.hasNext()) { final ProductReaderPlugIn plugIn = allReaderPlugIns.next(); if (plugIn.getClass().toString().equals(productReaderPlugin)) { product = plugIn.createReaderInstance().readProductNodes(productFile, null); break; } } if (product == null) { SnapApp.getDefault().getLogger().log(Level.WARNING, "Could not find " + productReaderPlugin + ". " + "Attempting to use other reader to open " + productFile.getName()); } } if (product == null) { product = ProductIO.readProduct(productFile); } } else { product = problemSolver.solveProductNotFound(productRef.refNo, productFile); if (product == null) { throw new IOException("Product [" + productRef.refNo + "] not found."); } } product.setRefNo(productRef.refNo); productManager.addProduct(product); } catch (IOException e) { problems.add(e); } finally { pm.worked(1); } } } finally { pm.done(); } return productManager; } private ProductNodeView[] restoreViews(ProductManager productManager, PropertyMap applicationPreferences, ProgressMonitor pm, List<Exception> problems) { ArrayList<ProductNodeView> views = new ArrayList<ProductNodeView>(); try { pm.beginTask("Restoring views", viewRefs.length); for (ViewRef viewRef : viewRefs) { try { if (ProductSceneView.class.getName().equals(viewRef.type)) { collectSceneView(viewRef, productManager, applicationPreferences, pm, problems, views); } else if (MetadataViewTopComponent.class.getName().equals(viewRef.type)) { collectMetadataView(viewRef, productManager, views); // todo - flag and index coding views (rq-20100618) } else { throw new Exception("Unknown view type: " + viewRef.type); } } catch (Exception e) { problems.add(e); } finally { pm.worked(1); } } } finally { pm.done(); } return views.toArray(new ProductNodeView[views.size()]); } private static void collectSceneView(final ViewRef viewRef, final ProductManager productManager, final PropertyMap applicationPreferences, final ProgressMonitor pm, final List<Exception> problems, final List<ProductNodeView> views) throws Exception { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { ProductSceneView view; try { view = createSceneView(viewRef, productManager, applicationPreferences, pm); } catch (Exception e) { throw new IllegalStateException("Could not create scene", e); } views.add(view); for (int i = 0; i < viewRef.getLayerCount(); i++) { LayerRef ref = viewRef.getLayerRef(i); if (isBaseImageLayerRef(view, ref)) { // The BaseImageLayer is not restored by LayerRef, so we have to adjust // transparency and visibility manually view.getBaseImageLayer().setTransparency(ref.transparency); view.getBaseImageLayer().setVisible(ref.visible); } else { try { addLayerRef(view, view.getRootLayer(), ref, productManager); } catch (Exception e) { problems.add(e); } } } } }); } private static boolean isBaseImageLayerRef(ProductSceneView view, LayerRef ref) { return view.getBaseImageLayer().getId().equals(ref.id); } private static ProductSceneView createSceneView(ViewRef viewRef, ProductManager productManager, PropertyMap applicationPreferences, ProgressMonitor pm) throws Exception { Product product = productManager.getProductByRefNo(viewRef.productRefNo); if (product == null) { throw new Exception("Unknown product reference number: " + viewRef.productRefNo); } ProductSceneImage sceneImage; if (viewRef.productNodeName != null) { RasterDataNode node = product.getRasterDataNode(viewRef.productNodeName); if (node != null) { sceneImage = new ProductSceneImage(node, applicationPreferences, SubProgressMonitor.create(pm, 1)); } else { throw new Exception("Unknown raster data source: " + viewRef.productNodeName); } } else { Band rBand = getRgbBand(product, viewRef.expressionR, RGBImageProfile.RGB_BAND_NAMES[0]); Band gBand = getRgbBand(product, viewRef.expressionG, RGBImageProfile.RGB_BAND_NAMES[1]); Band bBand = getRgbBand(product, viewRef.expressionB, RGBImageProfile.RGB_BAND_NAMES[2]); sceneImage = new ProductSceneImage(viewRef.viewName, rBand, gBand, bBand, applicationPreferences, SubProgressMonitor.create(pm, 1)); } ProductSceneView view = new ProductSceneView(sceneImage); Rectangle bounds = viewRef.bounds; if (bounds != null && !bounds.isEmpty()) { view.setBounds(bounds); } ViewportDef viewportDef = viewRef.viewportDef; if (viewportDef != null) { Viewport viewport = view.getLayerCanvas().getViewport(); viewport.setModelYAxisDown(viewportDef.modelYAxisDown); viewport.setZoomFactor(viewportDef.zoomFactor); viewport.setOrientation(viewportDef.orientation); viewport.setOffset(viewportDef.offsetX, viewportDef.offsetY); } // view.setLayerProperties(applicationPreferences); return view; } private static void collectMetadataView(ViewRef viewRef, ProductManager productManager, ArrayList<ProductNodeView> views) throws Exception { Product product = productManager.getProductByRefNo(viewRef.productRefNo); if (product != null) { String[] productNodeNames = viewRef.productNodeName.split("\\|"); MetadataElement element = product.getMetadataRoot(); for (int i = productNodeNames.length - 1; i >= 0; i--) { if (element == null) { break; } element = element.getElement(productNodeNames[i]); } // if (element != null) { // ProductMetadataView metadataView = new ProductMetadataView(element); // Rectangle bounds = viewRef.bounds; // if (bounds != null && !bounds.isEmpty()) { // metadataView.setBounds(bounds); // } // views.add(metadataView); // } } else { throw new Exception("Unknown product reference number: " + viewRef.productRefNo); } } private static void addLayerRef(LayerContext layerContext, Layer parentLayer, LayerRef layerRef, ProductManager productManager) throws ConversionException, ValidationException { LayerType type = LayerTypeRegistry.getLayerType(layerRef.layerTypeName); if (type != null) { SessionDomConverter converter = new SessionDomConverter(productManager); PropertySet template = type.createLayerConfig(layerContext); converter.convertDomToValue(layerRef.configuration, template); Layer layer = type.createLayer(layerContext, template); layer.setId(layerRef.id); layer.setVisible(layerRef.visible); layer.setTransparency(layerRef.transparency); layer.setName(layerRef.name); parentLayer.getChildren().add(layerRef.zOrder, layer); for (LayerRef child : layerRef.children) { addLayerRef(layerContext, layer, child, productManager); } } } public static Container getRootPaneContainer(JComponent component) { Container parent = component; Container lastParent; do { if (parent instanceof RootPaneContainer) { return parent; } lastParent = parent; parent = lastParent.getParent(); } while (parent != null); return lastParent; } private static Product getProductForRefNo(Product[] products, int refNo) { for (Product product : products) { if (product.getRefNo() == refNo) { return product; } } return null; } public static interface ProblemSolver { Product solveProductNotFound(int id, File file) throws CanceledException; } @XStreamAlias("product") public static class ProductRef { int refNo; @XStreamConverter(URIConverterWrapper.class) URI uri; String productReaderPlugin; /** * No-arg constructor required by XStream. */ @SuppressWarnings("UnusedDeclaration") public ProductRef() { } public ProductRef(int refNo, URI uri, String productReaderPlugin) { this.refNo = refNo; this.uri = uri; this.productReaderPlugin = productReaderPlugin; } } @XStreamAlias("view") public static class ViewRef { int id; String type; Rectangle bounds; @XStreamAlias("viewport") ViewportDef viewportDef; int productRefNo; String productNodeName; String viewName; String expressionR; String expressionG; String expressionB; @XStreamAlias("layers") LayerRef[] layerRefs; /** * No-arg constructor required by XStream. */ @SuppressWarnings("UnusedDeclaration") public ViewRef() { } public ViewRef(int id, String type, Rectangle bounds, ViewportDef viewportDef, int productRefNo, String productNodeName, String viewName, String expressionR, String expressionG, String expressionB, LayerRef[] layerRefs) { this.id = id; this.type = type; this.bounds = bounds; this.viewportDef = viewportDef; this.productRefNo = productRefNo; this.productNodeName = productNodeName; this.viewName = viewName; this.expressionR = expressionR; this.expressionG = expressionG; this.expressionB = expressionB; this.layerRefs = layerRefs; } public int getLayerCount() { return layerRefs.length; } public LayerRef getLayerRef(int index) { return layerRefs[index]; } } @XStreamAlias("layer") public static class LayerRef { @XStreamAlias("type") String layerTypeName; String id; String name; boolean visible; double transparency; int zOrder; @XStreamConverter(DomElementXStreamConverter.class) DomElement configuration; LayerRef[] children; /** * No-arg constructor required by XStream. */ @SuppressWarnings("UnusedDeclaration") public LayerRef() { } public LayerRef(Layer layer, int zOrder, DomElement configuration, LayerRef[] children) { this.layerTypeName = layer.getLayerType().getName(); this.id = layer.getId(); this.name = layer.getName(); this.visible = layer.isVisible(); this.transparency = layer.getTransparency(); this.zOrder = zOrder; this.configuration = configuration; this.children = children; } } @XStreamAlias("viewport") public static class ViewportDef { boolean modelYAxisDown; double offsetX; double offsetY; double zoomFactor; double orientation; /** * No-arg constructor required by XStream. */ @SuppressWarnings("UnusedDeclaration") public ViewportDef() { } public ViewportDef(boolean modelYAxisDown, double offsetX, double offsetY, double zoomFactor, double orientation) { this.modelYAxisDown = modelYAxisDown; this.offsetX = offsetX; this.offsetY = offsetY; this.zoomFactor = zoomFactor; this.orientation = orientation; } } private static Band getRgbBand(Product product, String expression, String bandName) { Band band = null; if (expression != null && !expression.isEmpty()) { band = product.getBand(expression); } if (band == null) { if (expression == null || expression.isEmpty()) { expression = "0.0"; } band = new Channel(bandName, product, expression); } return band; } private static class Channel extends VirtualBand { public Channel(String name, Product product, String expression) { super(name, ProductData.TYPE_FLOAT32, product.getSceneRasterWidth(), product.getSceneRasterHeight(), expression); setOwner(product); } } public static class URIConverterWrapper extends SingleValueConverterWrapper { public URIConverterWrapper() { super(new URIConverter()); } } public static class URIConverter extends AbstractSingleValueConverter { @Override public boolean canConvert(Class type) { return type.equals(URI.class); } @Override public Object fromString(String str) { try { return new URI(str); } catch (URISyntaxException e) { throw new com.thoughtworks.xstream.converters.ConversionException(e); } } } }
29,393
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CloseSessionAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/CloseSessionAction.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.actions.file.CloseAllProductsAction; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.NbBundle; import javax.swing.AbstractAction; import java.awt.event.ActionEvent; import java.io.File; @ActionID(category = "File", id = "org.esa.snap.rcp.session.CloseSessionAction") @ActionRegistration(displayName = "#CTL_CloseSessionAction_MenuText", lazy = false) @ActionReference(path = "Menu/File/Session", position = 45) @NbBundle.Messages({ "CTL_CloseSessionAction_MenuText=Close Session", "CTL_CloseSessionAction_ShortDescription=Close the current SNAP session." }) public class CloseSessionAction extends AbstractAction { public static final String ID = "closeSession"; final SessionManager sessionManager = SessionManager.getDefault(); public CloseSessionAction() { super(Bundle.CTL_CloseSessionAction_MenuText()); ProductManager productManager = SnapApp.getDefault().getProductManager(); productManager.addListener(new CloseSessionListener()); setEnabled(false); } @Override public void actionPerformed(ActionEvent event) { sessionManager.setSessionFile((File) null); CloseAllProductsAction closeProductAction = new CloseAllProductsAction(); closeProductAction.execute(); } private class CloseSessionListener implements ProductManager.Listener { @Override public void productAdded(ProductManager.Event event) { updateEnableState(); } @Override public void productRemoved(ProductManager.Event event) { updateEnableState(); } private void updateEnableState() { setEnabled(SnapApp.getDefault().getProductManager().getProductCount() > 0 || sessionManager.getSessionFile()!=null); } } }
2,752
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SaveSessionAsAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/SaveSessionAsAction.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.rcp.SnapApp; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.ContextAwareAction; import org.openide.util.Lookup; import org.openide.util.LookupEvent; import org.openide.util.LookupListener; import org.openide.util.NbBundle; import org.openide.util.Utilities; import org.openide.util.WeakListeners; import javax.swing.AbstractAction; import javax.swing.Action; import java.awt.event.ActionEvent; @ActionID(category = "File", id = "org.esa.snap.rcp.session.SaveSessionAsAction") @ActionRegistration(displayName = "#CTL_SaveSessionAsAction_MenuText", lazy = false) @ActionReference(path = "Menu/File/Session", position = 35) @NbBundle.Messages({ "CTL_SaveSessionAsAction_MenuText=Save Session As...", "CTL_SaveSessionAsAction_ShortDescription=Save the current SNAP session using a different name." }) public class SaveSessionAsAction extends AbstractAction implements ContextAwareAction, LookupListener { public static final String ID = "saveSessionAs"; private final Lookup lookup; public SaveSessionAsAction() { this(Utilities.actionsGlobalContext()); } public SaveSessionAsAction(Lookup lookup) { super(Bundle.CTL_SaveSessionAsAction_MenuText()); this.lookup = lookup; ProductManager productManager = SnapApp.getDefault().getProductManager(); productManager.addListener(new SaveAsSessionListener()); Lookup.Result<ProductNode> result = lookup.lookupResult(ProductNode.class); result.addLookupListener(WeakListeners.create(LookupListener.class, this, result)); setEnabled(false); } @Override public Action createContextAwareInstance(Lookup lookup) { return new SaveSessionAsAction(lookup); } @Override public void actionPerformed(ActionEvent e) { final SaveSessionAction action = new SaveSessionAction(); action.saveSession(true); } @Override public void resultChanged(LookupEvent ev) { ProductNode productNode = lookup.lookup(ProductNode.class); setEnabled(productNode != null || SessionManager.getDefault().getSessionFile() != null); } private class SaveAsSessionListener implements ProductManager.Listener { @Override public void productAdded(ProductManager.Event event) { updateEnableState(); } @Override public void productRemoved(ProductManager.Event event) { updateEnableState(); } private void updateEnableState() { setEnabled(SnapApp.getDefault().getProductManager().getProductCount() > 0 && SessionManager.getDefault().getSessionFile() != null); } } }
3,628
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PointConverter.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/PointConverter.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session; import com.bc.ceres.binding.ConversionException; import com.bc.ceres.binding.Converter; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; import org.locationtech.jts.io.WKTWriter; import java.awt.geom.Point2D; /** * A converter for {@link java.awt.Shape}s. * * @author Norman Fomferra * @version $Revision$ $Date$ * @since BEAM 4.6 */ public class PointConverter implements Converter { private final GeometryFactory geometryFactory; public PointConverter() { geometryFactory = new GeometryFactory(); } @Override public Class getValueType() { return Point2D.class; } @Override public Object parse(String text) throws ConversionException { try { Geometry geometry = new WKTReader(geometryFactory).read(text); if (geometry instanceof org.locationtech.jts.geom.Point) { org.locationtech.jts.geom.Point point = (org.locationtech.jts.geom.Point) geometry; return new Point2D.Double(point.getX(), point.getY()); } else { throw new ConversionException("Failed to parse point geometry WKT."); } } catch (ParseException e) { throw new ConversionException("Failed to parse point geometry WKT.", e); } } @Override public String format(Object value) { Point2D point = (Point2D) value; return new WKTWriter().write(geometryFactory.createPoint(new Coordinate(point.getX(), point.getY()))); } }
2,437
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProductDomConverter.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/dom/ProductDomConverter.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session.dom; import com.bc.ceres.binding.dom.DomElement; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductManager; class ProductDomConverter extends ProductNodeDomConverter<Product> { ProductDomConverter(ProductManager productManager) { super(Product.class, productManager); } @Override protected Product getProductNode(DomElement parentElement, Product product) { return product; } @Override protected void convertProductNodeToDom(Product product, DomElement parentElement) { } }
1,318
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SessionDomConverter.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/dom/SessionDomConverter.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session.dom; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.PropertyDescriptorFactory; import com.bc.ceres.binding.PropertySetDescriptor; import com.bc.ceres.binding.dom.DefaultDomConverter; import com.bc.ceres.binding.dom.DomConverter; import org.esa.snap.core.datamodel.PlacemarkDescriptor; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.core.datamodel.RasterDataNode; import java.util.HashMap; import java.util.Map; public class SessionDomConverter extends DefaultDomConverter { private final Map<Class<?>, DomConverter> domConverterMap; public SessionDomConverter(ProductManager productManager) { super(PropertyContainer.class); this.domConverterMap = new HashMap<>(33); setDomConverter(Product.class, new ProductDomConverter(productManager)); setDomConverter(RasterDataNode.class, new RasterDataNodeDomConverter(productManager)); setDomConverter(PlacemarkDescriptor.class, new PlacemarkDescriptorDomConverter()); } private SessionDomConverter(Class<?> valueType, PropertyDescriptorFactory propertyDescriptorFactory, PropertySetDescriptor propertySetDescriptor, Map<Class<?>, DomConverter> domConverterMap) { super(valueType, propertyDescriptorFactory, propertySetDescriptor); this.domConverterMap = domConverterMap; } final void setDomConverter(Class<?> type, DomConverter domConverter) { domConverterMap.put(type, domConverter); } @Override protected DomConverter createChildDomConverter(Class<?> valueType, PropertyDescriptorFactory propertyDescriptorFactory, PropertySetDescriptor propertySetDescriptor) { return new SessionDomConverter(valueType, getPropertyDescriptorFactory(), propertySetDescriptor, domConverterMap); } @Override protected DomConverter findChildDomConverter(PropertyDescriptor descriptor) { return findDomConverter(descriptor.getType()); } private DomConverter findDomConverter(Class<?> type) { DomConverter domConverter = domConverterMap.get(type); while (domConverter == null && type != null && type != Object.class) { type = type.getSuperclass(); domConverter = domConverterMap.get(type); } return domConverter; } }
3,144
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
RasterDataNodeDomConverter.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/dom/RasterDataNodeDomConverter.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session.dom; import com.bc.ceres.binding.dom.DomElement; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.core.datamodel.RasterDataNode; class RasterDataNodeDomConverter extends ProductNodeDomConverter<RasterDataNode> { RasterDataNodeDomConverter(ProductManager productManager) { super(RasterDataNode.class, productManager); } @Override protected RasterDataNode getProductNode(DomElement parentElement, Product product) { final DomElement rasterName = parentElement.getChild("rasterName"); return product.getRasterDataNode(rasterName.getValue()); } @Override protected void convertProductNodeToDom(RasterDataNode raster, DomElement parentElement) { final DomElement rasterName = parentElement.createChild("rasterName"); rasterName.setValue(raster.getName()); } }
1,653
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProductNodeDomConverter.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/dom/ProductNodeDomConverter.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session.dom; import com.bc.ceres.binding.ConversionException; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.dom.DomConverter; import com.bc.ceres.binding.dom.DomElement; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.core.datamodel.ProductNode; abstract class ProductNodeDomConverter<T extends ProductNode> implements DomConverter { private final Class<T> type; private final ProductManager productManager; protected ProductNodeDomConverter(Class<T> type, ProductManager productManager) { this.type = type; this.productManager = productManager; } @Override public final Class<T> getValueType() { return type; } @Override public final T convertDomToValue(DomElement parentElement, Object value) throws ConversionException, ValidationException { final DomElement refNoElement = parentElement.getChild("refNo"); if (refNoElement == null) { throw new ConversionException(String.format( "In parent element '%s': no child element 'refNo'", parentElement.getName())); } final Integer refNo; try { refNo = Integer.valueOf(refNoElement.getValue()); } catch (NumberFormatException e) { throw new ConversionException(String.format( "In parent element '%s': %s", parentElement.getName(), e.getMessage())); } final Product product = productManager.getProductByRefNo(refNo); if (product == null) { throw new ConversionException(String.format( "In parent element '%s': no product with refNo = %d", parentElement.getName(), refNo)); } return getProductNode(parentElement, product); } @Override public final void convertValueToDom(Object value, DomElement parentElement) throws ConversionException { @SuppressWarnings({"unchecked"}) final T productNode = (T) value; final Product product = productNode.getProduct(); if (product == null) { throw new ConversionException("Node does not belong to a product"); } final DomElement refNo = parentElement.createChild("refNo"); refNo.setValue(String.valueOf(product.getRefNo())); convertProductNodeToDom(productNode, parentElement); } protected abstract T getProductNode(DomElement parentElement, Product product); protected abstract void convertProductNodeToDom(T productNode, DomElement parentElement); }
3,430
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PlacemarkDescriptorDomConverter.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/session/dom/PlacemarkDescriptorDomConverter.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.session.dom; import com.bc.ceres.binding.ConversionException; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.dom.DomConverter; import com.bc.ceres.binding.dom.DomElement; import org.esa.snap.core.datamodel.PlacemarkDescriptor; import org.esa.snap.core.datamodel.PlacemarkDescriptorRegistry; class PlacemarkDescriptorDomConverter implements DomConverter { @Override public Class<?> getValueType() { return PlacemarkDescriptor.class; } @Override public PlacemarkDescriptor convertDomToValue(DomElement parentElement, Object value) throws ConversionException, ValidationException { final String type = parentElement.getAttribute("class"); PlacemarkDescriptor placemarkDescriptor = PlacemarkDescriptorRegistry.getInstance().getPlacemarkDescriptor(type); if (placemarkDescriptor == null) { throw new ConversionException(String.format("Unknown placemark descriptor class '%s'", type)); } return placemarkDescriptor; } @Override public void convertValueToDom(Object value, DomElement parentElement) throws ConversionException { parentElement.setAttribute("class", value.getClass().getName()); } }
1,988
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
RoiMaskSelector.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/RoiMaskSelector.java
/* * Copyright (C) 2012 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.util; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.ValueSet; import com.bc.ceres.core.Assert; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.Enablement; import org.esa.snap.core.datamodel.Mask; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.core.datamodel.ProductNodeEvent; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.ProductNodeListener; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.tool.ToolButtonFactory; import org.openide.util.ImageUtilities; import org.openide.windows.TopComponent; import org.openide.windows.WindowManager; import javax.swing.AbstractButton; import javax.swing.DefaultListCellRenderer; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.SwingUtilities; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.util.ArrayList; import java.util.List; public class RoiMaskSelector { public final static String PROPERTY_NAME_USE_ROI_MASK = "useRoiMask"; public final static String PROPERTY_NAME_ROI_MASK = "roiMask"; final JCheckBox useRoiMaskCheckBox; final JComboBox roiMaskComboBox; final AbstractButton showMaskManagerButton; private final BindingContext bindingContext; private final ProductNodeListener productNodeListener; private Product product; private RasterDataNode raster; private Enablement useRoiEnablement; private Enablement roiMaskEnablement; private AbstractButton createShowMaskManagerButton() { final AbstractButton showMaskManagerButton = ToolButtonFactory.createButton(ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/MaskManager24.png", false), false); showMaskManagerButton.addActionListener(e -> SwingUtilities.invokeLater(() -> { final TopComponent maskManagerTopComponent = WindowManager.getDefault().findTopComponent("MaskManagerTopComponent"); maskManagerTopComponent.open(); maskManagerTopComponent.requestActive(); })); return showMaskManagerButton; } public RoiMaskSelector(BindingContext bindingContext) { final Property useRoiMaskProperty = bindingContext.getPropertySet().getProperty(PROPERTY_NAME_USE_ROI_MASK); Assert.argument(useRoiMaskProperty != null, "bindingContext"); Assert.argument(useRoiMaskProperty.getType().equals(Boolean.class) || useRoiMaskProperty.getType() == Boolean.TYPE, "bindingContext"); Assert.argument(bindingContext.getPropertySet().getProperty(PROPERTY_NAME_ROI_MASK) != null, "bindingContext"); Assert.argument(bindingContext.getPropertySet().getProperty(PROPERTY_NAME_ROI_MASK).getType().equals(Mask.class), "bindingContext"); this.productNodeListener = new PNL(); this.bindingContext = bindingContext; useRoiMaskCheckBox = new JCheckBox("Use ROI mask:"); roiMaskComboBox = new JComboBox(); roiMaskComboBox.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { this.setText(((Mask) value).getName()); } return this; } }); this.showMaskManagerButton = createShowMaskManagerButton(); bindingContext.bind(PROPERTY_NAME_USE_ROI_MASK, useRoiMaskCheckBox); bindingContext.bind(PROPERTY_NAME_ROI_MASK, roiMaskComboBox); bindingContext.bindEnabledState(PROPERTY_NAME_USE_ROI_MASK, true, createUseRoiCondition()); bindingContext.bindEnabledState(PROPERTY_NAME_ROI_MASK, true, createEnableMaskDropDownCondition()); } public JPanel createPanel() { final JPanel roiMaskPanel = GridBagUtils.createPanel(); GridBagConstraints roiMaskPanelConstraints = GridBagUtils.createConstraints("anchor=SOUTHWEST,fill=HORIZONTAL,insets.top=2"); GridBagUtils.addToPanel(roiMaskPanel, useRoiMaskCheckBox, roiMaskPanelConstraints, ",gridy=0,gridx=0,weightx=1"); GridBagUtils.addToPanel(roiMaskPanel, roiMaskComboBox, roiMaskPanelConstraints, "gridy=1,insets.left=4"); GridBagUtils.addToPanel(roiMaskPanel, showMaskManagerButton, roiMaskPanelConstraints, "gridheight=2,gridy=0,gridx=1,weightx=0,ipadx=5,insets.left=0"); return roiMaskPanel; } public void updateMaskSource(Product newProduct, RasterDataNode newRaster) { if (product != newProduct) { if (product != null) { product.removeProductNodeListener(productNodeListener); } if (newProduct != null) { newProduct.addProductNodeListener(productNodeListener); } this.product = newProduct; } if (raster != newRaster) { this.raster = newRaster; } updateRoiMasks(); } private void updateRoiMasks() { final Property property = bindingContext.getPropertySet().getProperty(PROPERTY_NAME_ROI_MASK); if (product != null && raster != null) { //todo [multisize_products] compare scenerastertransform (or its successor) rather than size final ProductNodeGroup<Mask> maskGroup = product.getMaskGroup(); List<ProductNode> maskList = new ArrayList<>(); final Dimension refRrasterSize = raster.getRasterSize(); for (int i = 0; i < maskGroup.getNodeCount(); i++) { final Mask mask = maskGroup.get(i); if (refRrasterSize.equals(mask.getRasterSize())) { maskList.add(mask); } } property.getDescriptor().setValueSet(new ValueSet(maskList.toArray(new ProductNode[maskList.size()]))); } else { property.getDescriptor().setValueSet(new ValueSet(new Mask[0])); } useRoiEnablement.apply(); roiMaskEnablement.apply(); } private Enablement.Condition createUseRoiCondition() { return new Enablement.Condition() { @Override public boolean evaluate(BindingContext bindingContext) { return product != null && product.getMaskGroup().getNodeCount() > 0; } @Override public void install(BindingContext bindingContext, Enablement enablement) { useRoiEnablement = enablement; } @Override public void uninstall(BindingContext bindingContext, Enablement enablement) { useRoiEnablement = null; } }; } private Enablement.Condition createEnableMaskDropDownCondition() { return new Enablement.Condition() { @Override public boolean evaluate(BindingContext bindingContext) { Boolean propertyValue = bindingContext.getPropertySet().getValue(PROPERTY_NAME_USE_ROI_MASK); if (roiMaskComboBox.getItemCount() > 0 && roiMaskComboBox.getSelectedIndex() < 0) { roiMaskComboBox.setSelectedIndex(0); } return Boolean.TRUE.equals(propertyValue) && product != null && product.getMaskGroup().getNodeCount() > 0; } @Override public void install(BindingContext bindingContext, Enablement enablement) { bindingContext.addPropertyChangeListener(PROPERTY_NAME_USE_ROI_MASK, enablement); roiMaskEnablement = enablement; } @Override public void uninstall(BindingContext bindingContext, Enablement enablement) { bindingContext.removePropertyChangeListener(PROPERTY_NAME_USE_ROI_MASK, enablement); roiMaskEnablement = null; } }; } private class PNL implements ProductNodeListener { @Override public void nodeAdded(ProductNodeEvent event) { handleEvent(event); } @Override public void nodeChanged(ProductNodeEvent event) { handleEvent(event); } @Override public void nodeDataChanged(ProductNodeEvent event) { handleEvent(event); } @Override public void nodeRemoved(ProductNodeEvent event) { handleEvent(event); } private void handleEvent(ProductNodeEvent event) { ProductNode sourceNode = event.getSourceNode(); if (sourceNode instanceof Mask) { updateRoiMasks(); } } } }
9,827
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TestProducts.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/TestProducts.java
package org.esa.snap.rcp.util; import org.esa.snap.core.dataio.ProductSubsetDef; import org.esa.snap.core.datamodel.AbstractGeoCoding; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.CrsGeoCoding; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.MetadataElement; import org.esa.snap.core.datamodel.PixelPos; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductData; import org.esa.snap.core.datamodel.Scene; import org.esa.snap.core.datamodel.TiePointGrid; import org.esa.snap.core.datamodel.VirtualBand; import org.esa.snap.core.dataop.maptransf.Datum; import org.esa.snap.core.transform.AffineTransform2D; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.opengis.referencing.FactoryException; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.TransformException; import javax.media.jai.operator.ConstantDescriptor; import java.awt.Color; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.util.Random; /** * Creates product instances for testing. * * @author Norman Fomferra */ public class TestProducts { public static Product[] createProducts() { return new Product[]{createProduct1(), createProduct2(), createProduct3(), createProduct4(), createProduct5(), createProduct6() }; } public static Product createProduct1() { Product product = new Product("Test_Product_1", "Test_Type_1", 2048, 1024); product.addTiePointGrid(new TiePointGrid("Grid_A", 32, 16, 0, 0, 2048f / 32, 1024f / 16, createRandomPoints(32 * 16))); product.addTiePointGrid(new TiePointGrid("Grid_B", 32, 16, 0, 0, 2048f / 32, 1024f / 16, createRandomPoints(32 * 16))); product.addBand("Band_A", "sin(4 * PI * sqrt( sq(X/1000.0 - 1) + sq(Y/500.0 - 1) ))"); product.addBand("Band_B", "sin(4 * PI * sqrt( 2.0 * abs(X/1000.0 * Y/500.0) ))"); product.addMask("Mask_A", "Band_A > 0.5", "I am Mask A", Color.ORANGE, 0.5); product.addMask("Mask_B", "Band_B < 0.0", "I am Mask B", Color.RED, 0.5); product.getMetadataRoot().addElement(new MetadataElement("Global_Attributes")); product.getMetadataRoot().addElement(new MetadataElement("Local_Attributes")); product.setModified(false); double sx = 40.0 / product.getSceneRasterWidth(); AffineTransform at = new AffineTransform(); at.translate(-80, -30); at.rotate(0.3, 20.0, 10.0); at.scale(sx, sx); product.setSceneGeoCoding(new ATGeoCoding(at)); return product; } public static Product createProduct2() { Product product = new Product("Test_Product_2", "Test_Type_2", 1024, 2048); product.addTiePointGrid(new TiePointGrid("Grid_1", 16, 32, 0, 0, 1024f / 16, 2048f / 32, createRandomPoints(32 * 16))); product.addTiePointGrid(new TiePointGrid("Grid_2", 16, 32, 0, 0, 1024f / 16, 2048f / 32, createRandomPoints(32 * 16))); product.addBand("Band_1", "cos(X/100)-sin(Y/100)"); product.addBand("Band_2", "sin(X/100)+cos(Y/100)"); product.addBand("Band_3", "cos(X/100)*cos(Y/100)"); product.addBand("Band_1_Unc", "cos(3*X/100)-sin(3*Y/100)"); product.addBand("Band_2_Unc", "sin(3*X/100)+cos(3*Y/100)"); product.addBand("Band_3_Unc", "cos(3*X/100)*cos(3*Y/100)"); product.getBand("Band_1").addAncillaryVariable(product.getBand("Band_1_Unc"), "uncertainty"); product.getBand("Band_2").addAncillaryVariable(product.getBand("Band_2_Unc"), "uncertainty"); product.getBand("Band_3").addAncillaryVariable(product.getBand("Band_3_Unc"), "uncertainty"); product.addMask("Mask_1", "Band_1 > 0.5", "I am Mask 1", Color.GREEN, 0.5); product.addMask("Mask_2", "Band_2 < 0.0", "I am Mask 2", Color.CYAN, 0.5); product.addMask("Mask_3", "Band_3 > -0.1 && Band_3 < 0.1", "I am Mask 3", Color.BLUE, 0.5); product.getMetadataRoot().addElement(new MetadataElement("Global_Attributes")); product.getMetadataRoot().addElement(new MetadataElement("Local_Attributes")); product.setModified(false); double sx = 20.0 / product.getSceneRasterWidth(); AffineTransform at = new AffineTransform(); at.scale(sx, sx); at.rotate(-0.2, 10.0, 10.0); product.setSceneGeoCoding(new ATGeoCoding(at)); product.addBand("A", "Band_1"); product.addBand("B", "Band_1 + Band_2 + Band_3"); product.addBand("C", "Band_1 / (2.3 + Band_2 + Band_3)"); product.addBand("D", "pow(Band_1, 3) / (pow(Band_1, 3) + pow(Band_3, 3))"); return product; } public static Product createProduct3() { int size = 10 * 1024; Product product = new Product("Test_Product_3", "Test_Type_3", size, size); product.setPreferredTileSize(512, 512); Band band1 = new Band("Big_Band_1", ProductData.TYPE_FLOAT64, product.getSceneRasterWidth(), product.getSceneRasterHeight()); Band band2 = new Band("Big_Band_2", ProductData.TYPE_FLOAT64, product.getSceneRasterWidth(), product.getSceneRasterHeight()); Band band3 = new Band("Big_Band_3", ProductData.TYPE_FLOAT64, product.getSceneRasterWidth(), product.getSceneRasterHeight()); Band band4 = new Band("Big_Band_4", ProductData.TYPE_FLOAT64, product.getSceneRasterWidth(), product.getSceneRasterHeight()); Band band5 = new Band("Big_Band_5", ProductData.TYPE_FLOAT64, product.getSceneRasterWidth(), product.getSceneRasterHeight()); band1.setSourceImage(ConstantDescriptor.create(1f * size, 1F * size, new Double[]{1.0}, null)); band2.setSourceImage(ConstantDescriptor.create(1f * size, 1F * size, new Double[]{2.0}, null)); band3.setSourceImage(ConstantDescriptor.create(1f * size, 1F * size, new Double[]{3.0}, null)); band4.setSourceImage(ConstantDescriptor.create(1f * size, 1F * size, new Double[]{4.0}, null)); band5.setSourceImage(ConstantDescriptor.create(1f * size, 1F * size, new Double[]{5.0}, null)); product.addBand(band1); product.addBand(band2); product.addBand(band3); product.addBand(band4); product.addBand(band5); product.setModified(true); double sx = 30.0 / product.getSceneRasterWidth(); AffineTransform at = new AffineTransform(); at.translate(100, 0.0); at.rotate(0.1, 15.0, 15.0); at.scale(sx, sx); product.setSceneGeoCoding(new ATGeoCoding(at)); return product; } public static Product createProduct4() { Product product = new Product("Test_Product_4", "Test_Type_4", 512, 512); product.getMetadataRoot().addElement(new MetadataElement("Global_Attributes")); product.getMetadataRoot().addElement(new MetadataElement("Local_Attributes")); product.setModified(false); double sx = 10.0 / product.getSceneRasterWidth(); VirtualBand band4 = new VirtualBand("Band_4", ProductData.TYPE_FLOAT64, 512, 512, "cos(ampl((X-256)/100, (Y-256)/100))"); product.addBand(band4); AffineTransform at4 = new AffineTransform(); at4.scale(0.5 * sx, 0.5 * sx); at4.rotate(-0.2, 5.0, 5.0); at4.translate(256, 256); product.setSceneGeoCoding(new ATGeoCoding(at4)); return product; } public static Product createProduct5() { try { Product product = new Product("Test_Product_5_CRS", "Test_Type_5_CRS", 512, 512); product.getMetadataRoot().addElement(new MetadataElement("Global_Attributes")); product.getMetadataRoot().addElement(new MetadataElement("Local_Attributes")); product.setModified(false); product.addBand("Band_A", "sin(4 * PI * sqrt( sq(X/1000.0 - 1) + sq(Y/500.0 - 1) ))"); product.setSceneGeoCoding(new CrsGeoCoding(DefaultGeographicCRS.WGS84, 512, 512, 0, 10, 1, 1)); final String b_expression = "sin(4 * PI * sqrt( 2.0 * abs(X/1000.0 * Y/500.0) ))"; final VirtualBand band_b = new VirtualBand("Band_B", ProductData.TYPE_FLOAT32, 1024, 256, b_expression); band_b.setGeoCoding(new CrsGeoCoding(DefaultGeographicCRS.WGS84, 1024, 256, 0, 10, 0.5, 2.0)); band_b.setNoDataValueUsed(true); product.addBand(band_b); return product; } catch (FactoryException | TransformException e) { return null; } } public static Product createProduct6() { try { Product product = new Product("Test_Product_6_SceneRasterTransforms", "Test_Type_6_SceneRasterTransforms", 512, 512); product.getMetadataRoot().addElement(new MetadataElement("Global_Attributes")); product.getMetadataRoot().addElement(new MetadataElement("Local_Attributes")); product.setModified(false); final String a_expression = "sin(4 * PI * sqrt( sq(X/1000.0 - 1) + sq(Y/500.0 - 1) ))"; final Band band_a = new VirtualBand("Band_A", ProductData.TYPE_FLOAT32, 2048, 1024, a_expression); final AffineTransform a_forward = new AffineTransform(); a_forward.scale(0.25, 0.5); final AffineTransform a_inverse = a_forward.createInverse(); band_a.setModelToSceneTransform(new AffineTransform2D(a_forward)); band_a.setSceneToModelTransform(new AffineTransform2D(a_inverse)); product.addBand(band_a); final String b_expression = "sin(4 * PI * sqrt( 2.0 * abs(X/1000.0 * Y/500.0) ))"; final VirtualBand band_b = new VirtualBand("Band_B", ProductData.TYPE_FLOAT32, 128, 256, b_expression); final AffineTransform b_forward = new AffineTransform(); b_forward.scale(2.0, 2.0); b_forward.translate(128, 0); final AffineTransform b_inverse = b_forward.createInverse(); band_b.setModelToSceneTransform(new AffineTransform2D(b_forward)); band_b.setSceneToModelTransform(new AffineTransform2D(b_inverse)); band_b.setNoDataValue(Double.NaN); band_b.setNoDataValueUsed(true); product.addBand(band_b); return product; } catch (NoninvertibleTransformException e) { return null; } } // public static Product createProduct7() { // Product product = new Product("Test_Product_3_different_tie_point_geocodings", "Test_Type_3_different_tie_point_geocodings", 1024, 2048); // product.addTiePointGrid(new TiePointGrid("Grid_1", 16, 32, 0, 0, 1024f / 16, 2048f / 32, createRandomPoints(32 * 16))); // product.addTiePointGrid(new TiePointGrid("Grid_2", 16, 32, 0, 0, 1024f / 16, 2048f / 32, createRandomPoints(32 * 16))); // product.addBand("Band_1", "cos(X/100)-sin(Y/100)"); // product.addMask("Mask_1", "Band_1 > 0.5", "I am Mask 1", Color.GREEN, 0.5); // product.getMetadataRoot().addElement(new MetadataElement("Global_Attributes")); // product.getMetadataRoot().addElement(new MetadataElement("Local_Attributes")); // product.setModified(false); // double sx = 20.0 / product.getSceneRasterWidth(); // AffineTransform at = new AffineTransform(); // at.scale(sx, sx); // at.rotate(-0.2, 10.0, 10.0); // product.setSceneGeoCoding(new ATGeoCoding(at)); // // Band band2 = new Band("Band_2", ProductData.TYPE_FLOAT64, 512, 512); // final VirtualBandOpImage image = VirtualBandOpImage. // builder("cos(ampl((X-256)/100, (Y-256)/100))", product). // sourceSize(band2.getRasterSize()). // dataType(band2.getDataType()). // create(); // // AffineTransform at_model_2 = new AffineTransform(); // at_model_2.scale(0.5, 0.5); // at_model_2.translate(128, 128); // final DefaultMultiLevelModel targetModel = new DefaultMultiLevelModel(at_model_2, 512, 512); // final DefaultMultiLevelModel targetModel = new DefaultMultiLevelModel(at2, 512, 512); // final DefaultMultiLevelModel targetModel = new DefaultMultiLevelModel(new AffineTransform(), 512, 512); // final DefaultMultiLevelSource targetMultiLevelSource = new DefaultMultiLevelSource(image, targetModel); // band2.setSourceImage(new DefaultMultiLevelImage(targetMultiLevelSource)); // product.addBand(band2); // AffineTransform at2 = new AffineTransform(); // at2.scale(0.5 * sx, 0.5 * sx); // at2.scale(0.5, 0.5); // at2.rotate(-0.2, 5.0, 5.0); // at2.translate(256, 256); // band2.setGeoCoding(new ATGeoCoding(at2)); // band2.setNoDataValue(-1.0); // band2.setNoDataValueUsed(true); // return product; // } private static float[] createRandomPoints(int n) { Random random = new Random(987); float[] pnts = new float[n]; for (int i = 0; i < pnts.length; i++) { pnts[i] = (float) random.nextGaussian(); } return pnts; } private static class ATGeoCoding extends AbstractGeoCoding { private static final PixelPos INVALID_PIXEL_POS = new PixelPos(Double.NaN, Double.NaN); private final AffineTransform affineTransform; public ATGeoCoding(AffineTransform affineTransform) { this.affineTransform = affineTransform; } @Override public boolean transferGeoCoding(Scene srcScene, Scene destScene, ProductSubsetDef subsetDef) { return false; } @Override public boolean isCrossingMeridianAt180() { return false; } @Override public boolean canGetPixelPos() { return true; } @Override public boolean canGetGeoPos() { return true; } @Override public PixelPos getPixelPos(GeoPos geoPos, PixelPos pixelPos) { try { Point2D p = affineTransform.inverseTransform(new Point2D.Double(geoPos.lon, geoPos.lat), null); if (pixelPos == null) { pixelPos = new PixelPos(); } pixelPos.x = p.getX(); pixelPos.y = p.getY(); return pixelPos; } catch (NoninvertibleTransformException e) { return INVALID_PIXEL_POS; } } @Override public GeoPos getGeoPos(PixelPos pixelPos, GeoPos geoPos) { Point2D point2D = affineTransform.transform(pixelPos, null); if (geoPos == null) { geoPos = new GeoPos(); } geoPos.lon = point2D.getX(); geoPos.lat = point2D.getY(); return geoPos; } @Override public Datum getDatum() { return Datum.WGS_84; } @Override public MathTransform getImageToMapTransform() { return new AffineTransform2D(affineTransform); } @Override public void dispose() { } } }
15,215
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DateTimePicker.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/DateTimePicker.java
package org.esa.snap.rcp.util; import org.jdesktop.swingx.JXDatePicker; import org.jdesktop.swingx.calendar.SingleDaySelectionModel; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerDateModel; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.text.DateFormatter; import javax.swing.text.DefaultFormatterFactory; import java.awt.Color; import java.awt.FlowLayout; import java.text.DateFormat; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class DateTimePicker extends JXDatePicker { private JSpinner timeSpinner; private DateFormat timeFormat; private TimeZone timeZone; public DateTimePicker(Date d, Locale l, DateFormat dateFormat, DateFormat timeFormat) { super(d, l); if (!dateFormat.getTimeZone().equals(timeFormat.getTimeZone())) { throw new IllegalStateException(String.format("Time zone mismatch: dateFormat is [%s] but timeFormat is [%s]", dateFormat, timeFormat)); } timeZone = timeFormat.getTimeZone(); getMonthView().setSelectionModel(new SingleDaySelectionModel()); getMonthView().setTimeZone(timeZone); setLinkPanel(createTimePanel()); setFormats(dateFormat); setTimeFormat(timeFormat); setDateTime(d); } public void commitEdit() throws ParseException { commitTime(); super.commitEdit(); } public DateFormat getTimeFormat() { return timeFormat; } public void setTimeFormat(DateFormat timeFormat) { this.timeFormat = timeFormat; updateTextFieldFormat(); } public void setDateTime(Date date) { super.setDate(date); if (timeSpinner != null) { if (date != null) { timeSpinner.setValue(date); }else { Calendar calendar = Calendar.getInstance(timeZone); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); timeSpinner.setValue(calendar.getTime()); } } } private JPanel createTimePanel() { JPanel newPanel = new JPanel(); newPanel.setLayout(new FlowLayout()); Date date = getDate(); if (date == null) { Calendar calendar = Calendar.getInstance(timeZone); date = calendar.getTime(); } SpinnerDateModel dateModel = new SpinnerDateModel(date, null, null, Calendar.DAY_OF_MONTH); timeSpinner = new JSpinner(dateModel); if (timeFormat == null) { timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT); } updateTextFieldFormat(); newPanel.add(new JLabel("Time:")); newPanel.add(timeSpinner); newPanel.setBackground(Color.WHITE); return newPanel; } private void updateTextFieldFormat() { if (timeSpinner == null) { return; } JFormattedTextField tf = ((JSpinner.DefaultEditor) timeSpinner.getEditor()).getTextField(); DefaultFormatterFactory factory = (DefaultFormatterFactory) tf.getFormatterFactory(); DateFormatter formatter = (DateFormatter) factory.getDefaultFormatter(); // Change the date format to only show the hours formatter.setFormat(timeFormat); } private void commitTime() { Date date = getDate(); if (date != null) { Date time = (Date) timeSpinner.getValue(); Calendar timeCalendar = Calendar.getInstance(timeZone); timeCalendar.setTime(time); Calendar calendar = Calendar.getInstance(timeZone); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, timeCalendar.get(Calendar.HOUR_OF_DAY)); calendar.set(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE)); calendar.set(Calendar.SECOND, timeCalendar.get(Calendar.SECOND)); calendar.set(Calendar.MILLISECOND, timeCalendar.get(Calendar.MILLISECOND)); Date newDate = calendar.getTime(); setDate(newDate); } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { TimeZone utcZone = TimeZone.getTimeZone("UTC"); Calendar utc = Calendar.getInstance(utcZone); Date date = utc.getTime(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); dateFormat.setTimeZone(utcZone); DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM); timeFormat.setTimeZone(utcZone); JFrame frame = new JFrame(); frame.setTitle("Date Time Picker"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); DateTimePicker dateTimePicker = new DateTimePicker(date, Locale.ENGLISH, dateFormat, timeFormat); dateTimePicker.setFormats(dateFormat); dateTimePicker.setTimeFormat(timeFormat); dateTimePicker.setDateTime(date); frame.getContentPane().add(dateTimePicker); frame.pack(); frame.setVisible(true); }); } }
5,440
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CollapsibleItemsPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/CollapsibleItemsPanel.java
package org.esa.snap.rcp.util; import com.bc.ceres.swing.CollapsiblePane; import org.openide.util.ImageUtilities; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.util.List; import java.util.ArrayList; /** * @author Norman Fomferra * @author Tonio Fincke */ public class CollapsibleItemsPanel extends JComponent { private Item[] items; private JToggleButton[] toggleButtons; private static ImageIcon COL_ICON = ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/NodeCollapsed11.png", false); private static ImageIcon EXP_ICON = ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/NodeExpanded11.png", false); private List<CollapseListener> collapseListenerList; public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { // e.printStackTrace(); } CollapsibleItemsPanel collapsibleItemsPanel = new CollapsibleItemsPanel(createTableItem("Time", 2, 2), createTableItem("Position", 6, 2), createTableItem("Bands", 18, 3)); JFrame frame = new JFrame(CollapsiblePane.class.getSimpleName()); frame.getContentPane().add(new JScrollPane(collapsibleItemsPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER)); frame.pack(); frame.setVisible(true); } public static Item<JTable> createTableItem(String name, int rows, int columns) { JTable table = new JTable(rows, columns); table.setCellSelectionEnabled(false); table.setColumnSelectionAllowed(false); table.setRowSelectionAllowed(false); table.setShowGrid(true); return new DefaultItem<>(name, table); } public CollapsibleItemsPanel(Item... items) { this.items = items; this.toggleButtons = new JToggleButton[items.length]; setLayout(null); collapseListenerList = new ArrayList<>(); for (int i = 0; i < items.length; i++) { Item item = items[i]; JToggleButton button = new JToggleButton(item.getDisplayName()); Font font = button.getFont(); if (font != null) { button.setFont(font.deriveFont(Font.PLAIN, font.getSize())); } else { button.setFont(new Font(Font.DIALOG, Font.PLAIN, 11)); } JPanel panel = new JPanel(new BorderLayout(0, 0)); panel.add(button, BorderLayout.NORTH); panel.add(item.getComponent(), BorderLayout.CENTER); button.setHorizontalAlignment(SwingConstants.LEFT); button.setBorder(new EmptyBorder(2, 4, 2, 4)); button.setIcon(EXP_ICON); final int index = i; button.addActionListener(e -> { final boolean expand = !button.isSelected(); item.getComponent().setVisible(expand); button.setIcon(!expand ? COL_ICON : EXP_ICON); if (expand) { notifyExpand(index); } else { notifyCollapse(index); } }); toggleButtons[i] = button; add(panel); } } public Item getItem(int index) { return items[index]; } public void setCollapsed(int index, boolean collapsed) { items[index].getComponent().setVisible(!collapsed); toggleButtons[index].setSelected(collapsed); toggleButtons[index].setIcon(collapsed ? COL_ICON : EXP_ICON); } private void notifyCollapse(int index) { for (CollapseListener collapseListener : collapseListenerList) { collapseListener.collapse(index); } } private void notifyExpand(int index) { for (CollapseListener collapseListener : collapseListenerList) { collapseListener.expand(index); } } public void addCollapseListener(CollapseListener collapseListener) { collapseListenerList.add(collapseListener); } public void remove(CollapseListener collapseListener) { collapseListenerList.remove(collapseListener); } @Override public Dimension getPreferredSize() { int width = 0; int height = 0; Component[] components = getComponents(); for (Component component : components) { Dimension preferredSize = component.getPreferredSize(); width = Math.max(width, preferredSize.width); height += preferredSize.height; } return new Dimension(width, height); } @Override public void doLayout() { int y = 0; int width = getWidth(); Component[] components = getComponents(); for (Component component : components) { Dimension preferredSize = component.getPreferredSize(); component.setBounds(0, y, width, preferredSize.height); y += preferredSize.height; } } public boolean isCollapsed(int index) { return !items[index].getComponent().isVisible(); } public static interface Item<T extends JComponent> { String getDisplayName(); T getComponent(); } public static class DefaultItem<T extends JComponent> implements Item<T> { String displayName; T component; public DefaultItem(String displayName, T component) { this.displayName = displayName; this.component = component; } @Override public String getDisplayName() { return displayName; } @Override public T getComponent() { return component; } } public interface CollapseListener { void collapse(int index); void expand(int index); } }
6,146
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
BooleanPreferenceKeyAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/BooleanPreferenceKeyAction.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.esa.snap.rcp.util; import org.esa.snap.rcp.SnapApp; import org.openide.util.WeakListeners; import org.openide.util.actions.Presenter; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import java.util.prefs.Preferences; /** * An action which sets a boolean preference value. * * @author Norman */ public class BooleanPreferenceKeyAction extends AbstractAction implements PreferenceChangeListener, Presenter.Toolbar, Presenter.Menu, Presenter.Popup { private final String preferenceKey; private final boolean defaultValue; protected BooleanPreferenceKeyAction(String preferenceKey) { this(preferenceKey, false); } protected BooleanPreferenceKeyAction(String preferenceKey, boolean defaultValue) { this.preferenceKey = preferenceKey; this.defaultValue = defaultValue; Preferences preferences = SnapApp.getDefault().getPreferences(); preferences.addPreferenceChangeListener(WeakListeners.create(PreferenceChangeListener.class, this, preferences)); setSelected(getPreferenceValue()); } public String getPreferenceKey() { return preferenceKey; } public boolean isSelected() { return Boolean.TRUE.equals(getValue(SELECTED_KEY)); } public void setSelected(boolean selected) { putValue(SELECTED_KEY, selected); } @Override public void actionPerformed(ActionEvent e) { setPreferenceValue(isSelected()); } @Override public JMenuItem getMenuPresenter() { JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(this); menuItem.setIcon(null); return menuItem; } @Override public JMenuItem getPopupPresenter() { return getMenuPresenter(); } @Override public Component getToolbarPresenter() { JToggleButton toggleButton = new JToggleButton(this); toggleButton.setText(null); return toggleButton; } @Override public void preferenceChange(PreferenceChangeEvent evt) { if (getPreferenceKey().equals(evt.getKey())) { setSelected(getPreferenceValue()); } } private boolean getPreferenceValue() { return SnapApp.getDefault().getPreferences().getBoolean(getPreferenceKey(), defaultValue); } private void setPreferenceValue(boolean selected) { SnapApp.getDefault().getPreferences().putBoolean(getPreferenceKey(), selected); } }
2,751
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ContextGlobalExtender.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/ContextGlobalExtender.java
package org.esa.snap.rcp.util; /** * Allows to dynamically extend the contents of the global lookup. * <p> * This interface may be implemented by a special {@code org.openide.util.ContextGlobalProvider} which should * also register an instance of this interface so that is is accessible via the global lookup. * * @author Norman Fomferra * @since 2.0 */ public interface ContextGlobalExtender { Object get(Object key); Object put(Object key, Object value); Object remove(Object key); }
509
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ContextGlobalExtenderImpl.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/ContextGlobalExtenderImpl.java
package org.esa.snap.rcp.util; import org.netbeans.modules.openide.windows.GlobalActionContextImpl; import org.openide.util.ContextGlobalProvider; import org.openide.util.Lookup; import org.openide.util.lookup.AbstractLookup; import org.openide.util.lookup.InstanceContent; import org.openide.util.lookup.Lookups; import org.openide.util.lookup.ProxyLookup; import java.util.LinkedHashMap; import java.util.Map; import java.util.logging.Logger; /** * Default implementation of a {@link ContextGlobalExtender} which is also a {@link ContextGlobalProvider}. * <p> * In order to register {@link ContextGlobalProvider} service use the following code: * <pre> * &#64;ServiceProvider( * service = ContextGlobalProvider.class, * supersedes = "org.netbeans.modules.openide.windows.GlobalActionContextImpl" * ) * public class MyGlobalActionContextImpl extends ContextGlobalExtenderImpl { * } * </pre> * * @see org.openide.util.ContextGlobalProvider * @see org.netbeans.modules.openide.windows.GlobalActionContextImpl * @author Norman Fomferra * @since 2.0 */ public class ContextGlobalExtenderImpl implements ContextGlobalProvider, ContextGlobalExtender { private static final Logger LOG = Logger.getLogger(ContextGlobalExtenderImpl.class.getName()); private Lookup proxyLookup; private final InstanceContent constantContent; private final Map<Object, Object> constantInstances; public ContextGlobalExtenderImpl() { constantContent = new InstanceContent(); constantInstances = new LinkedHashMap<>(); } @Override public synchronized Object get(Object key) { return constantInstances.get(key); } @Override public synchronized Object put(Object key, Object value) { if (value == null) { return remove(key); } Object oldValue = constantInstances.get(key); if (oldValue != value) { constantInstances.put(key, value); if (oldValue != null) { constantContent.remove(oldValue); } constantContent.add(value); LOG.info("added: key = " + key + ", value = " + value + ", oldValue = " + oldValue); } return oldValue; } @Override public synchronized Object remove(Object key) { Object oldValue = constantInstances.remove(key); if (oldValue != null) { constantContent.remove(oldValue); } LOG.info("removed: key = " + key + ", oldValue = " + oldValue); return oldValue; } /** * Returns a ProxyLookup that adds the current extra instance to the * global selection returned by Utilities.actionsGlobalContext(). * * @return a ProxyLookup that includes the original global context lookup. */ @Override public Lookup createGlobalContext() { if (proxyLookup == null) { proxyLookup = new ProxyLookup(new GlobalActionContextImpl().createGlobalContext(), Lookups.singleton(this), new AbstractLookup(constantContent)); } return proxyLookup; } }
3,202
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
NbResourceLocator.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/NbResourceLocator.java
package org.esa.snap.rcp.util; import com.bc.ceres.core.DefaultResourceLocator; import org.openide.util.Lookup; /** * A resource locator service for the NetBeans platform. * * @author Norman */ public class NbResourceLocator extends DefaultResourceLocator { /** * Returns a class loader capable of loading resources from any enabled NetBeans module. * * See <a href="http://wiki.netbeans.org/ClassloaderTrick">NetBeans Platform ClassLoader Trick</a>. * * @return the class loader used to load resources. */ @Override protected ClassLoader getResourceClassLoader() { // see ClassLoader classLoader = Lookup.getDefault().lookup(ClassLoader.class); if (classLoader == null) { throw new IllegalStateException("failed to lookup NetBeans global class loader"); } return classLoader; } }
885
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SelectionSupport.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/SelectionSupport.java
package org.esa.snap.rcp.util; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.annotations.common.NullAllowed; /** * Utility which allows for registering handlers which are informed about single selection changes. * * @author Marco Peters * @author Norman Fomferra * @since SNAP 2.0 */ public interface SelectionSupport<T> { /** * Adds a new handler. * * @param handler The handler. */ void addHandler(@NonNull Handler<T> handler); /** * Removes an existing handler. * * @param handler The handler. */ void removeHandler(@NonNull Handler<T> handler); /** * Handles single selection changes. * * @param <T> The type of the selection */ interface Handler<T> { /** * Called if a selection changed. * * @param oldValue The old selection, or {@code null} if no such exists * @param newValue The new selection, or {@code null} if no such exists */ void selectionChange(@NullAllowed T oldValue, @NullAllowed T newValue); } }
1,105
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
Dialogs.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/Dialogs.java
package org.esa.snap.rcp.util; import com.bc.ceres.core.Assert; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.core.util.io.FileUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.SnapFileChooser; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.util.NbBundle; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.filechooser.FileFilter; import java.awt.BorderLayout; import java.io.File; import java.text.MessageFormat; import java.util.prefs.Preferences; /** * Utility class which is used to display various commonly and frequently used message dialogs. * * @author Marco, Norman * @since 2.0 */ @NbBundle.Messages({ "LBL_Information=Information", "LBL_Question=Question", "LBL_Message=Message", "LBL_Warning=Warning", "LBL_Error=Error", "LBL_DoNotShowThisMessage=Don't show this message anymore.", "LBL_QuestionRemember=Remember my decision and don't ask again." }) public class Dialogs { public static final String PREF_KEY_SUFFIX_DONTSHOW = ".dontShow"; public enum Answer { YES, NO, CANCELLED } public static final String PREF_KEY_SUFFIX_DECISION = ".decision"; private static final String PREF_VALUE_YES = "yes"; private static final String PREF_VALUE_NO = "no"; private static final String PREF_VALUE_TRUE = "true"; private Dialogs() { } /** * Displays a modal dialog with the provided information message text. * * @param message The message text to be displayed. */ public static void showInformation(String message) { showInformation(message, null); } /** * Displays a modal dialog with the provided information message text. * * @param message The message text to be displayed. * @param preferencesKey If not {@code null}, a checkbox is displayed, and if checked the dialog will not be displayed again which lets users store the answer */ public static void showInformation(String message, String preferencesKey) { showInformation(Bundle.LBL_Information(), message, preferencesKey); } /** * Displays a modal dialog with the provided information message text. * * @param title The dialog title. May be {@code null}. * @param message The information message text to be displayed. * @param preferencesKey If not {@code null}, a checkbox is displayed, and if checked the dialog will not be displayed again which lets users store the answer */ public static void showInformation(String title, String message, String preferencesKey) { showMessage(title != null ? title : Bundle.LBL_Information(), message, JOptionPane.INFORMATION_MESSAGE, preferencesKey); } /** * Displays a modal dialog with the provided warning message text. * * @param message The information message text to be displayed. */ public static void showWarning(String message) { showWarning(null, message, null); } /** * Displays a modal dialog with the provided warning message text. * * @param title The dialog title. May be {@code null}. * @param message The warning message text to be displayed. * @param preferencesKey If not {@code null}, a checkbox is displayed, and if checked the dialog will not be displayed again which lets users store the answer */ public static void showWarning(String title, String message, String preferencesKey) { showMessage(title != null ? title : Bundle.LBL_Warning(), message, JOptionPane.WARNING_MESSAGE, preferencesKey); } /** * Displays a modal dialog with the provided error message text. * * @param message The error message text to be displayed. */ public static void showError(String message) { showError(null, message); } /** * Displays a modal dialog with the provided error message text. * * @param title The dialog title. May be {@code null}. * @param message The error message text to be displayed. */ public static void showError(String title, String message) { showMessage(title != null ? title : Bundle.LBL_Error(), message, JOptionPane.ERROR_MESSAGE, null); } /** * Displays a modal dialog indicating an 'Out of Memory'-error with the * provided error message text. It also displays a hint how to solve the problem. * * @param message The error message text to be displayed. */ public static void showOutOfMemoryError(String message) { showError("Out of Memory", String.format("%s\n\n" + "You can try to release memory by closing products or image views which\n" + "you currently not really need.", message)); } /** * Displays a modal dialog with the provided message text. * * @param title The dialog title. May be {@code null}. * @param message The message text to be displayed. * @param messageType The type of the message. * @param preferencesKey If not {@code null}, a checkbox is displayed, and if checked the dialog will not be displayed again which lets users store the answer */ public static void showMessage(String title, String message, int messageType, String preferencesKey) { title = getDialogTitle(title != null ? title : Bundle.LBL_Message()); if (preferencesKey != null) { String decision = getPreferences().get(preferencesKey + PREF_KEY_SUFFIX_DONTSHOW, ""); if (decision.equals(PREF_VALUE_TRUE)) { return; } JPanel panel = new JPanel(new BorderLayout(4, 4)); panel.add(new JLabel(message), BorderLayout.CENTER); JCheckBox dontShowCheckBox = new JCheckBox(Bundle.LBL_DoNotShowThisMessage(), false); panel.add(dontShowCheckBox, BorderLayout.SOUTH); NotifyDescriptor d = new NotifyDescriptor(panel, title, JOptionPane.DEFAULT_OPTION, messageType, null, null); DialogDisplayer.getDefault().notify(d); if (d.getValue() != NotifyDescriptor.CANCEL_OPTION) { boolean storeResult = dontShowCheckBox.isSelected(); if (storeResult) { getPreferences().put(preferencesKey + PREF_KEY_SUFFIX_DONTSHOW, PREF_VALUE_TRUE); } } } else { NotifyDescriptor d = new NotifyDescriptor(message, title, JOptionPane.DEFAULT_OPTION, messageType, null, null); DialogDisplayer.getDefault().notify(d); } } /** * Displays a modal dialog which requests a decision from the user. * * @param title The dialog title. May be {@code null}. * @param message The question text to be displayed. * @param allowCancel If {@code true}, the dialog also offers a cancel button. * @param preferencesKey If not {@code null}, a checkbox is displayed, and if checked the dialog will not be displayed again which lets users store the answer * @return {@link Answer#YES}, {@link Answer#NO}, or {@link Answer#CANCELLED}. */ public static Answer requestDecision(String title, String message, boolean allowCancel, String preferencesKey) { Object result; boolean storeResult; int optionType = allowCancel ? NotifyDescriptor.YES_NO_CANCEL_OPTION : NotifyDescriptor.YES_NO_OPTION; title = getDialogTitle(title != null ? title : Bundle.LBL_Question()); if (preferencesKey != null) { String decision = getPreferences().get(preferencesKey + PREF_KEY_SUFFIX_DECISION, ""); if (decision.equals(PREF_VALUE_YES)) { return Answer.YES; } else if (decision.equals(PREF_VALUE_NO)) { return Answer.NO; } JCheckBox decisionCheckBox = new JCheckBox(Bundle.LBL_QuestionRemember(), false); NotifyDescriptor d = new NotifyDescriptor.Confirmation(new Object[]{message, decisionCheckBox}, title, optionType); result = DialogDisplayer.getDefault().notify(d); storeResult = decisionCheckBox.isSelected(); } else { NotifyDescriptor d = new NotifyDescriptor.Confirmation(message, title, optionType); result = DialogDisplayer.getDefault().notify(d); storeResult = false; } if (NotifyDescriptor.YES_OPTION.equals(result)) { if (storeResult) { getPreferences().put(preferencesKey + PREF_KEY_SUFFIX_DECISION, PREF_VALUE_YES); } return Answer.YES; } else if (NotifyDescriptor.NO_OPTION.equals(result)) { if (storeResult) { getPreferences().put(preferencesKey + PREF_KEY_SUFFIX_DECISION, PREF_VALUE_NO); } return Answer.NO; } else { return Answer.CANCELLED; } } /** * Opens question dialog asking the user whether or not to overwrite an existing file. If the given * file does not exists, the question dialog is not shown. * * @param file the file to check for existance * @return <code>True</code> if the user confirms the dialog with 'yes' or the given file does not exist.<br> * <code>False</code> if the user does not want to overwrite the existing file.<br> * <code>null</code> if the user canceled the operation.<br> */ public static Boolean requestOverwriteDecision(String title, File file) { if (!file.exists()) { return Boolean.TRUE; } Answer answer = requestDecision(getDialogTitle(title), MessageFormat.format( "The file ''{0}'' already exists.\nDo you wish to overwrite it?", file), true, null); return answer == Answer.YES ? Boolean.TRUE : answer == Answer.NO ? Boolean.FALSE : null; } /** * Opens a standard file-open dialog box. * * @param title a dialog-box title * @param dirsOnly whether or not to select only directories * @param fileFilter the file filter to be used, can be <code>null</code> * @param preferencesKey the key under which the last directory the user visited is stored * @return the file selected by the user or <code>null</code> if the user canceled file selection */ public static File requestFileForOpen(String title, boolean dirsOnly, FileFilter fileFilter, String preferencesKey) { Assert.notNull(preferencesKey, "preferencesKey"); String lastDir = getPreferences().get(preferencesKey, SystemUtils.getUserHomeDir().getPath()); File currentDir = new File(lastDir); SnapFileChooser fileChooser = new SnapFileChooser(); fileChooser.setCurrentDirectory(currentDir); if (fileFilter != null) { fileChooser.setFileFilter(fileFilter); } fileChooser.setDialogTitle(getDialogTitle(title)); fileChooser.setFileSelectionMode(dirsOnly ? JFileChooser.DIRECTORIES_ONLY : JFileChooser.FILES_ONLY); int result = fileChooser.showOpenDialog(SnapApp.getDefault().getMainFrame()); if (fileChooser.getCurrentDirectory() != null) { getPreferences().put(preferencesKey, fileChooser.getCurrentDirectory().getPath()); } if (result == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); if (file == null || file.getName().equals("")) { return null; } return file; } return null; } /** * Opens a standard save dialog box. * * @param title A dialog-box title. * @param dirsOnly Whether or not to select only directories. * @param fileFilter The file filter to be used, can be <code>null</code>. * @param defaultExtension The extension used as default. * @param fileName The initial filename. * @param accessory An accessory UI component to be shown in the {@link JFileChooser#setAccessory(JComponent) file chooser}, * can be <code>null</code>. * @param preferenceKey The key under which the last directory the user visited is stored. * @return The file selected by the user or <code>null</code> if the user cancelled the file selection. */ public static File requestFileForSave(String title, boolean dirsOnly, FileFilter fileFilter, String defaultExtension, String fileName, JComponent accessory, String preferenceKey) { // Loop while the user does not want to overwrite a selected, existing file // or if the user presses "Cancel" // File file; do { file = requestFileForSave2(title, dirsOnly, fileFilter, defaultExtension, fileName, accessory, preferenceKey); if (file == null) { return null; // Cancelled } else if (file.exists()) { Boolean overwrite = requestOverwriteDecision(title, file); if (overwrite == null) { return null; } else if (!overwrite) { file = null; // No, do not overwrite, let user select another file } } } while (file == null); return file; } private static File requestFileForSave2(String title, boolean dirsOnly, FileFilter fileFilter, String defaultExtension, final String fileName, JComponent accessory, final String preferenceKey) { Assert.notNull(preferenceKey, "preferenceKey"); String lastDir = getPreferences().get(preferenceKey, SystemUtils.getUserHomeDir().getPath()); File currentDir = new File(lastDir); SnapFileChooser fileChooser = new SnapFileChooser(); fileChooser.setCurrentDirectory(currentDir); if (fileFilter != null) { fileChooser.setFileFilter(fileFilter); } if (fileName != null) { fileChooser.setSelectedFile(new File(FileUtils.exchangeExtension(fileName, defaultExtension))); } fileChooser.setDialogTitle(getDialogTitle(title)); fileChooser.setFileSelectionMode(dirsOnly ? JFileChooser.DIRECTORIES_ONLY : JFileChooser.FILES_ONLY); if (accessory != null) { fileChooser.setAccessory(accessory); } int result = fileChooser.showSaveDialog(SnapApp.getDefault().getMainFrame()); if (fileChooser.getCurrentDirectory() != null) { getPreferences().put(preferenceKey, fileChooser.getCurrentDirectory().getPath()); } if (result == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); if (file == null || file.getName().equals("")) { return null; } String path = file.getPath(); if (defaultExtension != null) { if (!path.toLowerCase().endsWith(defaultExtension.toLowerCase())) { path = path.concat(defaultExtension); } } return new File(path); } return null; } public static String getDialogTitle(String titleText) { return MessageFormat.format("{0} - {1}", SnapApp.getDefault().getInstanceName(), titleText); } private static Preferences getPreferences() { return SnapApp.getDefault().getPreferences(); } }
16,550
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DateTimePickerCellEditor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/DateTimePickerCellEditor.java
package org.esa.snap.rcp.util; import org.esa.snap.core.datamodel.ProductData; import org.jdesktop.swingx.table.DatePickerCellEditor; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.table.DefaultTableModel; import java.awt.BorderLayout; import java.awt.Component; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * @author Marco Peters */ public class DateTimePickerCellEditor extends DatePickerCellEditor { public DateTimePickerCellEditor(DateFormat dateFormat, DateFormat timeFormat) { super(null); Date asDate = ProductData.UTC.create(new Date(), 0).getAsDate(); DateTimePicker dateTimePicker = new DateTimePicker(asDate, Locale.getDefault(), dateFormat, timeFormat); //---- this duplicates the code in the parent constructor ------------- dateTimePicker.getEditor().setBorder(BorderFactory.createEmptyBorder(0, 1, 0, 1)); dateTimePicker.addActionListener(getPickerActionListener()); datePicker = dateTimePicker; //--------------------------------------------------------------------- } private DateTimePicker getEditor() { return (DateTimePicker) datePicker; } public void setTimeFormat(DateFormat timeFormat) { getEditor().setTimeFormat(timeFormat); } public DateFormat getTimeFormat() { return getEditor().getTimeFormat(); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { ignoreAction = true; Date valueAsDate = getValueAsDate(value); getEditor().setDateTime(valueAsDate); ignoreAction = false; return datePicker; } public static void main(String[] args) { Locale.setDefault(Locale.ENGLISH); SwingUtilities.invokeLater(() -> { DateFormat dateFormat = ProductData.UTC.createDateFormat("yyyy-MM-dd'T'HH:mm:ss"); DateFormat timeFormat = ProductData.UTC.createDateFormat("HH:mm:ss"); Calendar calendar = getCalendar(); Date[] date1 = {calendar.getTime()}; calendar.roll(Calendar.DATE, 1); Date[] date2 = {(Date) calendar.getTime().clone()}; calendar.roll(Calendar.DATE, 1); calendar.roll(Calendar.HOUR, 3); Date[] date3 = {calendar.getTime()}; Date[] date4 = {null}; DefaultTableModel tableModel = new DefaultTableModel(0, 1); tableModel.addRow(date1); tableModel.addRow(date2); tableModel.addRow(date3); tableModel.addRow(date4); JTable table = new JTable(tableModel); DateTimePickerCellEditor timePickerCellEditor = new DateTimePickerCellEditor(dateFormat, timeFormat); timePickerCellEditor.setClickCountToStart(1); table.getColumnModel().getColumn(0).setPreferredWidth(250); table.getColumnModel().getColumn(0).setCellEditor(timePickerCellEditor); table.getColumnModel().getColumn(0).setCellRenderer(new DateCellRenderer(dateFormat)); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(table, BorderLayout.CENTER); JFrame frame = new JFrame("Test DateTime Picker"); frame.setContentPane(panel); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setLocationByPlatform(true); frame.pack(); frame.setVisible(true); }); } private static Calendar getCalendar() { Calendar calendar = ProductData.UTC.createCalendar(); calendar.setTimeInMillis(new Date().getTime()); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar; } }
4,118
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MultiSizeIssue.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/MultiSizeIssue.java
package org.esa.snap.rcp.util; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.Resampler; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.util.Lookup; import javax.swing.JComboBox; import javax.swing.JEditorPane; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.event.HyperlinkEvent; import javax.swing.text.html.HTMLDocument; import java.awt.BorderLayout; import java.awt.Desktop; import java.awt.Font; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * <i>This class is not part of the public API.</i> * <p> * Its purpose is to suggest to use the resampling operator when users invoke a SNAP function * that is not capable to work with multi-size products such as Sentinel-2 MSI L1C or Sentinel-3 SLSTR L1b products. * * @author Tonio Fincke */ public class MultiSizeIssue { public static Product maybeResample(Product product) { String title = Dialogs.getDialogTitle("Resampling Required"); final List<Resampler> availableResamplers = getAvailableResamplers(product); int optionType; int messageType; final StringBuilder msgTextBuilder = new StringBuilder("The functionality you have chosen is not supported for products with bands of different sizes.<br/>"); if (availableResamplers.isEmpty()) { optionType = JOptionPane.OK_CANCEL_OPTION; messageType = JOptionPane.INFORMATION_MESSAGE; } else if (availableResamplers.size() == 1) { msgTextBuilder.append("You can use the ").append(availableResamplers.get(0).getName()). append(" to resample this product so that all bands have the same size, <br/>" + "which will enable you to use this feature.<br/>" + "Do you want to resample the product now?"); optionType = JOptionPane.YES_NO_OPTION; messageType = JOptionPane.QUESTION_MESSAGE; } else { msgTextBuilder.append("You can use one of these resamplers to resample this product so that all bands have the same size, <br/>" + "which will enable you to use this feature.<br/>" + "Do you want to resample the product now?"); optionType = JOptionPane.YES_NO_OPTION; messageType = JOptionPane.QUESTION_MESSAGE; } msgTextBuilder.append("<br/>" + "<br/>" + "More info about this issue and its status can be found in the " + "<a href=\"https://senbox.atlassian.net/browse/SNAP-1\">SNAP Issue Tracker</a>." ); JPanel panel = new JPanel(new BorderLayout(4, 4)); final JEditorPane textPane = new JEditorPane("text/html", msgTextBuilder.toString()); setFont(textPane); textPane.setEditable(false); textPane.setOpaque(false); textPane.addHyperlinkListener(e -> { if (HyperlinkEvent.EventType.ACTIVATED.equals(e.getEventType())) { try { Desktop.getDesktop().browse(e.getURL().toURI()); } catch (IOException | URISyntaxException e1) { Dialogs.showWarning("Could not open URL: " + e.getDescription()); } } }); panel.add(textPane, BorderLayout.CENTER); final JComboBox<Object> resamplerBox = new JComboBox<>(); if (availableResamplers.size() > 1) { String[] resamplerNames = new String[availableResamplers.size()]; for (int i = 0; i < availableResamplers.size(); i++) { resamplerNames[i] = availableResamplers.get(i).getName(); resamplerBox.addItem(resamplerNames[i]); } panel.add(resamplerBox, BorderLayout.SOUTH); } NotifyDescriptor d = new NotifyDescriptor(panel, title, optionType, messageType, null, null); DialogDisplayer.getDefault().notify(d); if (d.getValue() == NotifyDescriptor.YES_OPTION) { Resampler selectedResampler; if (availableResamplers.size() == 1) { selectedResampler = availableResamplers.get(0); } else { selectedResampler = availableResamplers.get(resamplerBox.getSelectedIndex()); } return selectedResampler.resample(product); } return null; } public static void chooseBandsWithSameSize() { String title = Dialogs.getDialogTitle("Choose bands with same size."); int optionType = JOptionPane.OK_CANCEL_OPTION; int messageType = JOptionPane.INFORMATION_MESSAGE; final StringBuilder msgTextBuilder = new StringBuilder("The functionality you have chosen is not supported for bands of different sizes.<br/>"); JPanel panel = new JPanel(new BorderLayout(4, 4)); final JEditorPane textPane = new JEditorPane("text/html", msgTextBuilder.toString()); setFont(textPane); textPane.setEditable(false); textPane.setOpaque(false); textPane.addHyperlinkListener(e -> { if (HyperlinkEvent.EventType.ACTIVATED.equals(e.getEventType())) { try { Desktop.getDesktop().browse(e.getURL().toURI()); } catch (IOException | URISyntaxException e1) { Dialogs.showWarning("Could not open URL: " + e.getDescription()); } } }); panel.add(textPane, BorderLayout.CENTER); final JComboBox<Object> resamplerBox = new JComboBox<>(); NotifyDescriptor d = new NotifyDescriptor(panel, title, optionType, messageType, null, null); DialogDisplayer.getDefault().notify(d); } public static void warningMaskForBandsWithDifferentSize() { String title = Dialogs.getDialogTitle("Mask deleted due to bands with different sizes."); int optionType = JOptionPane.OK_OPTION; int messageType = JOptionPane.INFORMATION_MESSAGE; final StringBuilder msgTextBuilder = new StringBuilder("The current mask will be deleted as you chose bands with different sizes.<br/>"); JPanel panel = new JPanel(new BorderLayout(4, 4)); final JEditorPane textPane = new JEditorPane("text/html", msgTextBuilder.toString()); setFont(textPane); textPane.setEditable(false); textPane.setOpaque(false); // textPane.addHyperlinkListener(e -> { // if (HyperlinkEvent.EventType.ACTIVATED.equals(e.getEventType())) { // try { // Desktop.getDesktop().browse(e.getURL().toURI()); // } catch (IOException | URISyntaxException e1) { // Dialogs.showWarning("Could not open URL: " + e.getDescription()); // } // } // }); panel.add(textPane, BorderLayout.CENTER); final JComboBox<Object> resamplerBox = new JComboBox<>(); Object[] options = {"CLOSE"}; NotifyDescriptor d = new NotifyDescriptor(panel, title, optionType, messageType, options, options[0]); DialogDisplayer.getDefault().notify(d); } private static List<Resampler> getAvailableResamplers(Product product) { final Collection<? extends Resampler> allResamplers = Lookup.getDefault().lookupAll(Resampler.class); List<Resampler> availableResamplers = new ArrayList<>(); for (Resampler resampler : allResamplers) { if (resampler.canResample(product)) { availableResamplers.add(resampler); } } return availableResamplers; } public static boolean isMultiSize(Product selectedProduct) { return selectedProduct != null && selectedProduct.isMultiSize(); } private static void setFont(JEditorPane textPane) { if (textPane.getDocument() instanceof HTMLDocument) { Font font = UIManager.getFont("Label.font"); String bodyRule = "body { font-family: " + font.getFamily() + "; font-size: " + font.getSize() + "pt; }"; ((HTMLDocument) textPane.getDocument()).getStyleSheet().addRule(bodyRule); } } }
8,459
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProgressHandleMonitor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/ProgressHandleMonitor.java
package org.esa.snap.rcp.util; import com.bc.ceres.core.Assert; import com.bc.ceres.core.ProgressMonitor; import org.netbeans.api.progress.ProgressHandle; import org.netbeans.api.progress.ProgressHandleFactory; import org.openide.util.Cancellable; /** * A progress monitor that notifies a {@code ProgressHandle} instance (of the NetBeans Progress API). * <p> * Use case 1: * <pre> * ProgressHandleMonitor pm = ProgressHandleMonitor.create("Training"); * Runnable operation = () -> { * pm.beginTask("Classifier training...", 100); * try { * session.startTraining(queryPatches, pm); * } catch (Exception e) { * SnapApp.getDefault().handleError("Failed to train classifier", e); * } finally { * pm.done(); * } * }; * ProgressUtils.runOffEventThreadWithProgressDialog(operation, "Extracting Features", pm.getProgressHandle(), true, 50, 1000); * </pre> * * <p> * Use case 2: * <pre> * RequestProcessor.getDefault().post(() -> { * ProgressHandle handle = ProgressHandleFactory.createHandle("Performing time consuming task"); * ProgressMonitor pm = new ProgressHandleMonitor(handle); * performTimeConsumingTask(pm); * }); * </pre> * * @author Norman Fomferra * @since SNAP 2 */ public class ProgressHandleMonitor implements ProgressMonitor, Cancellable { private static final int F = 100; private ProgressHandle progressHandle; private Cancellable cancellable; private boolean canceled; private int totalWorkUnits; private int currentWorkUnits; private double currentWorkUnitsRational; public static ProgressHandleMonitor create(String displayName) { return create(displayName, null); } public static ProgressHandleMonitor create(String displayName, Cancellable cancellable) { ProgressHandleMonitor progressMonitor = new ProgressHandleMonitor(cancellable); ProgressHandle progressHandle = ProgressHandleFactory.createHandle(displayName, progressMonitor); progressMonitor.setProgressHandle(progressHandle); return progressMonitor; } public ProgressHandleMonitor(ProgressHandle progressHandle) { Assert.notNull(progressHandle); this.progressHandle = progressHandle; } private ProgressHandleMonitor(Cancellable cancellable) { this.cancellable = cancellable; } /** * @return The progress handle. */ public ProgressHandle getProgressHandle() { return progressHandle; } /** * @param progressHandle The progress handle. */ public void setProgressHandle(ProgressHandle progressHandle) { Assert.notNull(progressHandle); this.progressHandle = progressHandle; } @Override public void beginTask(String taskName, int totalWork) { if(totalWork < 0) { this.totalWorkUnits = 0; }else { this.totalWorkUnits = F * totalWork; } this.currentWorkUnits = 0; this.currentWorkUnitsRational = 0.0; if (progressHandle == null) { progressHandle = ProgressHandleFactory.createHandle(taskName, this); progressHandle.start(this.totalWorkUnits); } else { try { progressHandle.start(this.totalWorkUnits); } catch (java.lang.IllegalStateException e) { // if already started, use fall back progressHandle.switchToDeterminate(this.totalWorkUnits); } progressHandle.setDisplayName(taskName); } } @Override public void done() { Assert.notNull(progressHandle); progressHandle.finish(); } @Override public void internalWorked(double work) { currentWorkUnitsRational += F * work; int i = (int) currentWorkUnitsRational; if (i > currentWorkUnits) { currentWorkUnits = i; progressHandle.progress(currentWorkUnits); } } @Override public boolean isCanceled() { return canceled; } @Override public void setCanceled(boolean canceled) { this.canceled = canceled; } @Override public void setTaskName(String taskName) { Assert.notNull(progressHandle); progressHandle.setDisplayName(taskName); } @Override public void setSubTaskName(String subTaskName) { Assert.notNull(progressHandle); progressHandle.progress(subTaskName); } @Override public void worked(int work) { internalWorked(work); } @Override public boolean cancel() { if (cancellable != null) { setCanceled(cancellable.cancel()); } else { setCanceled(true); } return isCanceled(); } }
4,848
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DateCellRenderer.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/DateCellRenderer.java
package org.esa.snap.rcp.util; import javax.swing.JTable; import java.awt.Component; import java.text.DateFormat; /** * DateCellRenderer to render a date in a table cell. * It extends {@link org.jfree.ui.DateCellRenderer} to fix the selection foreground color. * * @author Marco Peters */ public class DateCellRenderer extends org.jfree.ui.DateCellRenderer { public DateCellRenderer(DateFormat dateFormat) { super(dateFormat); this.setHorizontalAlignment(LEADING); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (isSelected) { this.setForeground(table.getSelectionForeground()); } else { this.setForeground(null); } return this; } }
932
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
BrowserUtils.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/BrowserUtils.java
/* * Copyright (C) 2016 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.util; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.SnapApp; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.net.URI; import java.net.URISyntaxException; /** * Methods for opening a URL in a browser. * Handles the case that {@link Desktop} is not supporting this. */ public class BrowserUtils { public static void openInBrowser(URI uri) { boolean desktopSupported = Desktop.isDesktopSupported(); boolean browseSupported = Desktop.getDesktop().isSupported(Desktop.Action.BROWSE); if (desktopSupported && browseSupported) { try { Desktop.getDesktop().browse(uri); } catch (Throwable t) { Dialogs.showError(String.format("Failed to open URL:\n%s:\n%s", uri, t.getMessage())); } } else { SystemUtils.copyToClipboard(uri.toString()); Dialogs.showInformation("The URL has been copied to your Clipboard\n"); } } public static class URLClickAdaptor extends MouseAdapter { private final String address; public URLClickAdaptor(String address) { this.address = address; } @Override public void mouseClicked(MouseEvent event) { try { openInBrowser(new URI(address)); } catch (URISyntaxException e) { SnapApp.getDefault().handleError("Unable to follow link", e); } } } }
2,263
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FakeUncertaintyGenerator.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/FakeUncertaintyGenerator.java
package org.esa.snap.rcp.util; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.ConvolutionFilterBand; import org.esa.snap.core.datamodel.Kernel; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductData; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.core.datamodel.Stx; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.rcp.SnapApp; import org.openide.modules.OnStart; /** * @author Norman Fomferra */ public class FakeUncertaintyGenerator { public static final int UNCERTAINTY_KIND_COUNT = 2; private FakeUncertaintyGenerator() { } @OnStart public static class StartOp implements Runnable { int bandCount; @Override public void run() { if (Boolean.getBoolean("snap.uncertainty.test")) { SnapApp.getDefault().getProductManager().addListener(new ProductManager.Listener() { @Override public void productAdded(ProductManager.Event event) { bandCount = addUncertaintyBands(event.getProduct(), bandCount); } @Override public void productRemoved(ProductManager.Event event) { } }); } } } private static int addUncertaintyBands(Product product, int bandCount) { Band[] bands = product.getBands(); product.setAutoGrouping("radiance_*_variance:radiance_*_confidence:radiance_*_blur:radiance"); for (Band band : bands) { bandCount++; String bandName = band.getName(); if (bandName.startsWith("radiance") && !bandName.endsWith("_blur") && !bandName.endsWith("_variance") && !bandName.endsWith("_confidence")) { Band varianceBand = product.getBand(bandName + "_variance"); Band confidenceBand = product.getBand(bandName + "_confidence"); if (confidenceBand == null) { if (bandCount % UNCERTAINTY_KIND_COUNT == 0) { ConvolutionFilterBand blurredBand = new ConvolutionFilterBand(bandName + "_blur", band, new Kernel(11, 11, new double[]{ 0 / 720.0, 0 / 720.0, 1 / 720.0, 1 / 720.0, 2 / 720.0, 2 / 720.0, 2 / 720.0, 1 / 720.0, 1 / 720.0, 0 / 720.0, 0 / 720.0, 0 / 720.0, 1 / 720.0, 2 / 720.0, 3 / 720.0, 4 / 720.0, 5 / 720.0, 4 / 720.0, 3 / 720.0, 2 / 720.0, 1 / 720.0, 0 / 720.0, 1 / 720.0, 2 / 720.0, 4 / 720.0, 6 / 720.0, 9 / 720.0, 9 / 720.0, 9 / 720.0, 6 / 720.0, 4 / 720.0, 2 / 720.0, 1 / 720.0, 1 / 720.0, 3 / 720.0, 6 / 720.0, 11 / 720.0, 14 / 720.0, 16 / 720.0, 14 / 720.0, 11 / 720.0, 6 / 720.0, 3 / 720.0, 1 / 720.0, 2 / 720.0, 4 / 720.0, 9 / 720.0, 14 / 720.0, 20 / 720.0, 22 / 720.0, 20 / 720.0, 14 / 720.0, 9 / 720.0, 4 / 720.0, 2 / 720.0, 2 / 720.0, 5 / 720.0, 9 / 720.0, 16 / 720.0, 22 / 720.0, 24 / 720.0, 22 / 720.0, 16 / 720.0, 9 / 720.0, 5 / 720.0, 2 / 720.0, 2 / 720.0, 4 / 720.0, 9 / 720.0, 14 / 720.0, 20 / 720.0, 22 / 720.0, 20 / 720.0, 14 / 720.0, 9 / 720.0, 4 / 720.0, 2 / 720.0, 1 / 720.0, 3 / 720.0, 6 / 720.0, 11 / 720.0, 14 / 720.0, 16 / 720.0, 14 / 720.0, 11 / 720.0, 6 / 720.0, 3 / 720.0, 1 / 720.0, 1 / 720.0, 2 / 720.0, 4 / 720.0, 6 / 720.0, 9 / 720.0, 9 / 720.0, 9 / 720.0, 6 / 720.0, 4 / 720.0, 2 / 720.0, 1 / 720.0, 0 / 720.0, 1 / 720.0, 2 / 720.0, 3 / 720.0, 4 / 720.0, 5 / 720.0, 4 / 720.0, 3 / 720.0, 2 / 720.0, 1 / 720.0, 0 / 720.0, 0 / 720.0, 0 / 720.0, 1 / 720.0, 1 / 720.0, 2 / 720.0, 2 / 720.0, 2 / 720.0, 1 / 720.0, 1 / 720.0, 0 / 720.0, 0 / 720.0, }), 1); product.addBand(blurredBand); String varianceExpr = String.format("0.1 * (1 + 0.1 * min(max(random_gaussian(), 0), 10)) * %s", blurredBand.getName()); varianceBand = addVarianceBand(product, band, varianceExpr); confidenceBand = addConfidenceBand(product, band, varianceBand); } else if (bandCount % UNCERTAINTY_KIND_COUNT == 1) { int w2 = product.getSceneRasterWidth() / 2; int h2 = product.getSceneRasterHeight() / 2; int s = Math.min(w2, h2); String varianceExpr = String.format("100 * 0.5 * (1 + sin(4 * PI * sqrt(sq(X-%d) + sq(Y-%d)) / %d))", w2, h2, s); varianceBand = addVarianceBand(product, band, varianceExpr); confidenceBand = addConfidenceBand(product, band, varianceBand); } } band.addAncillaryVariable(varianceBand, "variance"); band.addAncillaryVariable(confidenceBand, "confidence"); } } return bandCount; } private static Band addVarianceBand(Product product, Band sourceBand, String varianceExpr) { Band varianceBand; varianceBand = product.addBand(sourceBand.getName() + "_variance", varianceExpr, ProductData.TYPE_FLOAT32); varianceBand.setUnit(sourceBand.getUnit()); ProductUtils.copySpectralBandProperties(sourceBand, varianceBand); return varianceBand; } private static Band addConfidenceBand(Product product, Band sourceBand, Band varianceBand) { Band confidenceBand; Stx varStx = varianceBand.getStx(); double minVar = Math.max(varStx.getMean() - 3 * varStx.getStandardDeviation(), varStx.getMinimum()); double maxVar = Math.min(varStx.getMean() + 3 * varStx.getStandardDeviation(), varStx.getMaximum()); double absVar = maxVar - minVar; confidenceBand = product.addBand(sourceBand.getName() + "_confidence", String.format("min(max((1 - (%s - %s) / %s), 0), 1)", varianceBand.getName(), minVar, absVar), ProductData.TYPE_FLOAT32); confidenceBand.setUnit("dl"); return confidenceBand; } }
6,482
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DesktopVersionCheck.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/DesktopVersionCheck.java
package org.esa.snap.rcp.util; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.core.util.VersionChecker; import org.esa.snap.rcp.SnapApp; import org.openide.awt.CheckForUpdatesProvider; import org.openide.util.Lookup; import org.openide.windows.OnShowing; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import java.awt.Cursor; /** * @author Marco Peters */ @SuppressWarnings("unused") public class DesktopVersionCheck { private static final String STEP_WEB_PAGE = SystemUtils.getApplicationHomepageUrl(); private static final String MSG_UPDATE_INFO = "<html>A new SNAP version is available for download!<br>" + "Currently installed %s, available is %s.<br>" + "Please visit the SNAP home page at"; private static final VersionChecker VERSION_CHECKER = VersionChecker.getInstance(); private DesktopVersionCheck() { } @OnShowing public static class OnStartup implements Runnable { @Override public void run() { // @OnShowing is triggered if Utilities.actionsGlobalContext() is called. This happens in some tests (which use actions). // So we need to check if the Desktop is really running. If not, we can skip the version check. if (!SnapApp.getDefault().getAppContext().getApplicationWindow().isVisible()) { return; } if (VERSION_CHECKER.mustCheck()) { if (VERSION_CHECKER.checkForNewRelease()) { VERSION_CHECKER.setChecked(); final JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); String localVersion = String.valueOf(VERSION_CHECKER.getLocalVersion()); String remoteVersion = String.valueOf(VERSION_CHECKER.getRemoteVersion()); panel.add(new JLabel(String.format(MSG_UPDATE_INFO + "", localVersion, remoteVersion))); final JLabel LinkLabel = new JLabel("<html><a href=\"" + STEP_WEB_PAGE + "\">" + STEP_WEB_PAGE + "</a>"); LinkLabel.setCursor(new Cursor(Cursor.HAND_CURSOR)); LinkLabel.addMouseListener(new BrowserUtils.URLClickAdaptor(STEP_WEB_PAGE)); panel.add(LinkLabel); JOptionPane.showMessageDialog(null, panel); return; } } final String message = "You are running the latest major version " + VERSION_CHECKER.getLocalVersion() + " of SNAP.\n" + "Please check regularly for new plugin updates (Help -> Check for Updates...) \n" + "to get the best SNAP experience.\n\n" + "Press 'Yes', if you want to check for plugin updates now.\n\n"; Dialogs.Answer decision = Dialogs.requestDecision("SNAP Update", message, false, "optional.version.check.onstartup"); if (Dialogs.Answer.YES.equals(decision)) { final CheckForUpdatesProvider checkForUpdatesProvider = Lookup.getDefault().lookup(CheckForUpdatesProvider.class); checkForUpdatesProvider.openCheckForUpdatesWizard(true); } } } }
3,370
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DefaultSelectionSupport.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/internal/DefaultSelectionSupport.java
package org.esa.snap.rcp.util.internal; import org.esa.snap.rcp.util.SelectionSupport; import org.openide.util.Lookup; import org.openide.util.LookupListener; import org.openide.util.Utilities; import org.openide.util.WeakListeners; import java.lang.reflect.Array; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.function.Predicate; import java.util.stream.Stream; public class DefaultSelectionSupport<T> implements SelectionSupport<T> { private final Class<T> type; private final Lookup.Result<T> itemResult; private final LinkedList<Handler<T>> handlerList; private final LookupListener lookupListener; private Collection<? extends T> currentlySelectedItems; private LookupListener theWeakListener; public DefaultSelectionSupport(Class<T> type) { this.type = type; currentlySelectedItems = Collections.emptyList(); itemResult = Utilities.actionsGlobalContext().lookupResult(type); handlerList = new LinkedList<>(); lookupListener = createLookupListener(); } @Override public void addHandler(Handler<T> handler) { if (handlerList.isEmpty() && theWeakListener == null) { // first listener added --> add LookupListener theWeakListener = WeakListeners.create(LookupListener.class, lookupListener, itemResult); itemResult.addLookupListener(theWeakListener); } handlerList.add(handler); } @Override public void removeHandler(Handler<T> handler) { handlerList.remove(handler); if (handlerList.isEmpty()) { // last listener removed --> remove LookupListener itemResult.removeLookupListener(theWeakListener); theWeakListener = null; } } private LookupListener createLookupListener() { return ev -> { Collection<? extends T> allItems = itemResult.allInstances(); Stream<? extends T> deselectedStream = currentlySelectedItems.stream().filter((Predicate<T>) (o) -> !allItems.contains(o)); T[] allDeselected = deselectedStream.toArray(value -> (T[]) Array.newInstance(type, value)); T firstDeselected = null; if (allDeselected.length > 0) { firstDeselected = allDeselected[0]; } Stream<? extends T> newlySelectedStream = allItems.stream().filter((Predicate<T>) (o) -> !currentlySelectedItems.contains(o)); T[] allNewlySelected = newlySelectedStream.toArray(value -> (T[]) Array.newInstance(type, value)); T firstSelected = null; if (allNewlySelected.length > 0) { firstSelected = allNewlySelected[0]; } currentlySelectedItems = allItems; // todo check if implementation is correct - ASAP! for (Handler<T> handler : handlerList) { handler.selectionChange(firstDeselected, firstSelected); } }; } }
3,001
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
RasterDataNodeDeleter.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/util/internal/RasterDataNodeDeleter.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.util.internal; import com.bc.ceres.core.Assert; import eu.esa.snap.netbeans.docwin.WindowUtilities; import org.esa.snap.core.datamodel.*; import org.esa.snap.core.datamodel.Mask.ImageType; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.rcp.windows.ProductSceneViewTopComponent; import java.text.MessageFormat; import java.util.*; import java.util.function.Consumer; /** * Confirms Raster Data Node deletion by the user and performs them. * * @author Marco Zuehlke * @version $Revision$ $Date$ * @since BEAM 4.7 */ public class RasterDataNodeDeleter { private static final String INDENT = " "; public static void deleteVectorDataNode(VectorDataNode vectorDataNode) { Assert.notNull(vectorDataNode); Product product = vectorDataNode.getProduct(); ProductNodeGroup<Mask> maskGroup = product.getMaskGroup(); Mask vectorMask = null; for (int i = 0; i < maskGroup.getNodeCount(); i++) { Mask mask = maskGroup.get(i); if (mask.getImageType() == Mask.VectorDataType.INSTANCE && Mask.VectorDataType.getVectorData(mask) == vectorDataNode) { vectorMask = mask; break; } } String message; if (vectorMask != null) { List<RasterDataNode> virtualBands = getReferencedVirtualBands(vectorMask); List<RasterDataNode> validMaskNodes = getReferencedValidMasks(vectorMask); List<RasterDataNode> masks = getReferencedMasks(vectorMask); VectorDataNode[] nodes = new VectorDataNode[]{vectorDataNode}; message = formatPromptMessage("Geometry", nodes, virtualBands, validMaskNodes, masks); } else { message = MessageFormat.format("Do you really want to delete the geometry ''{0}''?\nThis action cannot be undone.\n\n", vectorDataNode.getName()); } final Dialogs.Answer answer = Dialogs.requestDecision("Delete Vector Data", message, true, null); if (answer == Dialogs.Answer.YES) { product.getVectorDataGroup().remove(vectorDataNode); } } public static void deleteRasterDataNodes(RasterDataNode[] rasterNodes) { Assert.notNull(rasterNodes); if (rasterNodes.length == 0) { return; } Set<RasterDataNode> virtualBandsSet = new HashSet<RasterDataNode>(); Set<RasterDataNode> validMaskNodesSet = new HashSet<RasterDataNode>(); Set<RasterDataNode> masksSet = new HashSet<RasterDataNode>(); for (RasterDataNode raster : rasterNodes) { virtualBandsSet.addAll(getReferencedVirtualBands(raster)); validMaskNodesSet.addAll(getReferencedValidMasks(raster)); masksSet.addAll(getReferencedMasks(raster)); } for (RasterDataNode raster : rasterNodes) { virtualBandsSet.remove(raster); validMaskNodesSet.remove(raster); masksSet.remove(raster); } String typeName = getTypeName(rasterNodes); String message = formatPromptMessage(typeName, rasterNodes, virtualBandsSet, validMaskNodesSet, masksSet); deleteRasterDataNodesImpl(rasterNodes, message); } public static void deleteRasterDataNode(RasterDataNode raster) { Assert.notNull(raster); List<RasterDataNode> virtualBands = getReferencedVirtualBands(raster); List<RasterDataNode> validMaskNodes = getReferencedValidMasks(raster); List<RasterDataNode> masks = getReferencedMasks(raster); RasterDataNode[] rasters = new RasterDataNode[]{raster}; String typeName = getTypeName(rasters); String message = formatPromptMessage(typeName, rasters, virtualBands, validMaskNodes, masks); deleteRasterDataNodesImpl(rasters, message); } private static void deleteRasterDataNodesImpl(RasterDataNode[] rasters, String message) { final Dialogs.Answer answer = Dialogs.requestDecision("Delete Raster Data", message, true, null); if (answer == Dialogs.Answer.YES) { for (RasterDataNode raster : rasters) { WindowUtilities.getOpened(ProductSceneViewTopComponent.class). filter(topComponent -> raster == topComponent.getView().getRaster()). forEach(new Consumer<ProductSceneViewTopComponent>() { @Override public void accept(ProductSceneViewTopComponent productSceneViewTopComponent) { productSceneViewTopComponent.close(); } }); if (raster.hasRasterData()) { raster.unloadRasterData(); } final Product product = raster.getProduct(); if (raster instanceof Mask) { Mask mask = (Mask) raster; product.getMaskGroup().remove(mask); for (Band band : product.getBands()) { deleteMaskFromGroup(band.getOverlayMaskGroup(), mask); } TiePointGrid[] tiePointGrids = product.getTiePointGrids(); for (TiePointGrid tiePointGrid : tiePointGrids) { deleteMaskFromGroup(tiePointGrid.getOverlayMaskGroup(), mask); } ImageType imageType = mask.getImageType(); if (imageType == Mask.VectorDataType.INSTANCE) { VectorDataNode vectorDataNode = Mask.VectorDataType.getVectorData(mask); product.getVectorDataGroup().remove(vectorDataNode); } } else if (raster instanceof Band) { product.removeBand((Band) raster); } else if (raster instanceof TiePointGrid) { product.removeTiePointGrid((TiePointGrid) raster); } } } } private static String formatPromptMessage(String description, ProductNode[] nodes, Collection<RasterDataNode> virtualBands, Collection<RasterDataNode> validMaskNodes, Collection<RasterDataNode> masks) { String name; StringBuilder message = new StringBuilder(); if ((nodes.length > 1)) { message.append(MessageFormat.format("Do you really want to delete the following {0}:\n", description)); for (ProductNode node : nodes) { message.append(INDENT); message.append(node.getName()); message.append("\n"); } } else { name = nodes[0].getName(); message.append(MessageFormat.format("Do you really want to delete the {0} ''{1}''?\n", description, name)); } message.append("This action cannot be undone.\n\n"); if (!virtualBands.isEmpty() || !validMaskNodes.isEmpty() || !masks.isEmpty()) { if ((nodes.length > 1)) { message.append(MessageFormat.format("The {0} to be deleted are referenced by\n", description)); } else { message.append(MessageFormat.format("The {0} to be deleted is referenced by\n", description)); } } if (!virtualBands.isEmpty()) { message.append("the expression of virtual band(s):\n"); for (RasterDataNode virtualBand : virtualBands) { message.append(INDENT); message.append(virtualBand.getName()); message.append("\n"); } } if (!validMaskNodes.isEmpty()) { message.append("the valid-mask expression of band(s) or tie-point grid(s)\n"); for (RasterDataNode validMaskNode : validMaskNodes) { message.append(INDENT); message.append(validMaskNode.getName()); message.append("\n"); } } if (!masks.isEmpty()) { message.append("the mask(s):\n"); for (RasterDataNode mask : masks) { message.append(INDENT); message.append(mask.getName()); message.append("\n"); } } return message.toString(); } private static String getTypeName(RasterDataNode[] rasters) { String description = ""; if (rasters[0] instanceof Mask) { description = "mask"; } else if (rasters[0] instanceof Band) { description = "band"; } else if (rasters[0] instanceof TiePointGrid) { description = "tie-point grid"; } if (rasters.length > 1) { description += "s"; } return description; } private static void deleteMaskFromGroup(ProductNodeGroup<Mask> group, Mask mask) { if (group.contains(mask)) { group.remove(mask); } } private static List<RasterDataNode> getReferencedValidMasks(final RasterDataNode node) { final Product product = node.getProduct(); final List<RasterDataNode> rasterList = new ArrayList<RasterDataNode>(); if (product != null) { for (int i = 0; i < product.getNumBands(); i++) { final Band band = product.getBandAt(i); if (band != node) { if (isNodeReferencedByExpression(node, band.getValidPixelExpression())) { rasterList.add(band); } } } for (int i = 0; i < product.getNumTiePointGrids(); i++) { final TiePointGrid tiePointGrid = product.getTiePointGridAt(i); if (tiePointGrid != node) { if (isNodeReferencedByExpression(node, tiePointGrid.getValidPixelExpression())) { rasterList.add(tiePointGrid); } } } } return rasterList; } private static List<RasterDataNode> getReferencedMasks(final RasterDataNode node) { final Product product = node.getProduct(); final List<RasterDataNode> rasterList = new ArrayList<RasterDataNode>(); if (product != null) { final ProductNodeGroup<Mask> maskGroup = product.getMaskGroup(); final Mask[] masks = maskGroup.toArray(new Mask[maskGroup.getNodeCount()]); for (final Mask mask : masks) { final String expression; if (mask.getImageType() == Mask.BandMathsType.INSTANCE) { expression = Mask.BandMathsType.getExpression(mask); } else if (mask.getImageType() == Mask.RangeType.INSTANCE) { expression = Mask.RangeType.getRasterName(mask); } else { expression = null; } if (isNodeReferencedByExpression(node, expression)) { rasterList.add(mask); } } } return rasterList; } private static List<RasterDataNode> getReferencedVirtualBands(final RasterDataNode node) { final Product product = node.getProduct(); final List<RasterDataNode> rasterList = new ArrayList<RasterDataNode>(); if (product != null) { for (int i = 0; i < product.getNumBands(); i++) { final Band band = product.getBandAt(i); if (band instanceof VirtualBand) { final VirtualBand virtualBand = (VirtualBand) band; if (isNodeReferencedByExpression(node, virtualBand.getExpression())) { rasterList.add(virtualBand); } } } } return rasterList; } @SuppressWarnings({"SimplifiableIfStatement"}) private static boolean isNodeReferencedByExpression(RasterDataNode node, String expression) { if (expression == null || expression.trim().isEmpty()) { return false; } return expression.matches(".*\\b" + node.getName() + "\\b.*"); } }
12,967
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProductNodeNameValidator.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/bandmaths/ProductNodeNameValidator.java
package org.esa.snap.rcp.bandmaths; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.Validator; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNode; import org.openide.util.NbBundle; /** * Created by Norman on 30.06.2015. */ @NbBundle.Messages({ "CTL_PNNV_ExMsg_UniqueBandName=The band name must be unique within the product scope.\n" + "The scope comprises bands, tie-point grids and masks.", "CTL_PNNV_ExMsg_ContainedCharacter=The band name ''{0}'' is not valid.\n\n" + "Names must not start with a dot and must not\n" + "contain any of the following characters: \\/:*?\"<>|" }) class ProductNodeNameValidator implements Validator { Product targetProduct; public ProductNodeNameValidator(Product targetProduct) { this.targetProduct = targetProduct; } @Override public void validateValue(Property property, Object value) throws ValidationException { final String name = (String) value; if (!ProductNode.isValidNodeName(name)) { throw new ValidationException(Bundle.CTL_PNNV_ExMsg_ContainedCharacter(name)); } if (targetProduct.containsRasterDataNode(name)) { throw new ValidationException(Bundle.CTL_PNNV_ExMsg_UniqueBandName()); } } }
1,409
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PropagateUncertaintyDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/bandmaths/PropagateUncertaintyDialog.java
package org.esa.snap.rcp.bandmaths; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.ValueSet; import com.bc.ceres.core.Assert; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.PropertyEditor; import com.bc.ceres.swing.binding.PropertyEditorRegistry; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductData; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.VirtualBand; import org.esa.snap.core.dataop.barithm.BandArithmetic; import org.esa.snap.core.dataop.barithm.StandardUncertaintyGenerator; import org.esa.snap.core.jexp.ParseException; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.actions.window.OpenImageViewAction; import org.esa.snap.rcp.nodes.UndoableProductNodeInsertion; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.ModalDialog; import org.openide.awt.UndoRedo; import org.openide.util.NbBundle; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.Color; import java.awt.GridBagConstraints; import java.beans.PropertyChangeListener; /** * @author Norman Fomferra */ @NbBundle.Messages({ "CTL_PropagateUncertaintyDialog_Title=Propagate Uncertainty", }) public class PropagateUncertaintyDialog extends ModalDialog { private static final String PROPERTY_NAME_BAND_NAME = "bandName"; private static final String PROPERTY_NAME_ORDER = "order"; private static final String PROPERTY_NAME_RELATION = "relation"; private static final String ERROR_PREFIX = "Error: "; private static Color OK_MSG_COLOR = new Color(0, 128, 0); private static Color WARN_MSG_OLOR = new Color(128, 0, 0); private final BindingContext bindingContext; private VirtualBand sourceBand; @SuppressWarnings("UnusedDeclaration") private String bandName; @SuppressWarnings("UnusedDeclaration") private int order; @SuppressWarnings("UnusedDeclaration") private String relation; private JTextArea sourceExprArea; private JTextArea targetExprArea; private JLabel expressionIsCompatibleLabel; public PropagateUncertaintyDialog(VirtualBand virtualBand) { super(SnapApp.getDefault().getMainFrame(), Bundle.CTL_PropagateUncertaintyDialog_Title(), ID_OK_CANCEL_HELP, "propagateUncertainty"); Assert.notNull(virtualBand, "virtualBand"); this.sourceBand = virtualBand; bindingContext = createBindingContext(); bandName = virtualBand.getName() + "_unc"; order = 1; initUI(); } @Override protected void onOK() { String uncertaintyExpression = targetExprArea.getText(); Product targetProduct = sourceBand.getProduct(); int width = sourceBand.getRasterWidth(); int height = sourceBand.getRasterHeight(); ProductNodeGroup<Band> bandGroup = targetProduct.getBandGroup(); VirtualBand uncertaintyBand = new VirtualBand(getBandName(), ProductData.TYPE_FLOAT32, width, height, uncertaintyExpression); uncertaintyBand.setDescription("Uncertainty propagated from band " + sourceBand.getName() + " = " + sourceBand.getExpression()); uncertaintyBand.setUnit(sourceBand.getUnit()); uncertaintyBand.setNoDataValue(Double.NaN); uncertaintyBand.setNoDataValueUsed(true); uncertaintyBand.setValidPixelExpression(sourceBand.getValidPixelExpression()); ProductUtils.copySpectralBandProperties(sourceBand, uncertaintyBand); bandGroup.add(uncertaintyBand); sourceBand.addAncillaryVariable(uncertaintyBand, relation); UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(targetProduct); if (undoManager != null) { undoManager.addEdit(new UndoableProductNodeInsertion<>(bandGroup, uncertaintyBand)); } hide(); uncertaintyBand.setModified(true); if (SnapApp.getDefault().getPreferences().getBoolean(BandMathsDialog.PREF_KEY_AUTO_SHOW_NEW_BANDS, true)) { OpenImageViewAction.openImageView(uncertaintyBand); } } private String generateUncertaintyExpression() throws ParseException, UnsupportedOperationException { StandardUncertaintyGenerator propagator = new StandardUncertaintyGenerator(order, false); return propagator.generateUncertainty(sourceBand.getProduct(), relation, sourceBand.getExpression()); } @Override protected boolean verifyUserInput() { String uncertaintyExpression = targetExprArea.getText(); if (uncertaintyExpression == null || uncertaintyExpression.trim().isEmpty()) { Dialogs.showError("Uncertainty expression is empty."); return false; } if (uncertaintyExpression.startsWith(ERROR_PREFIX)) { Dialogs.showError(uncertaintyExpression.substring(ERROR_PREFIX.length())); return false; } if (sourceBand.getProduct().containsBand(getBandName())) { Dialogs.showError("A raster with name '" + getBandName() + "' already exists."); return false; } return super.verifyUserInput(); } private void initUI() { JComponent[] components; final JPanel panel = GridBagUtils.createPanel(); int line = 0; GridBagConstraints gbc = new GridBagConstraints(); sourceExprArea = new JTextArea(3, 40); sourceExprArea.setEditable(false); sourceExprArea.setEnabled(false); sourceExprArea.setText(sourceBand.getExpression()); targetExprArea = new JTextArea(6, 40); targetExprArea.setEditable(true); expressionIsCompatibleLabel = new JLabel(); updateTargetExprArea(); targetExprArea.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { validateTargExpression(); } @Override public void removeUpdate(DocumentEvent e) { validateTargExpression(); } @Override public void changedUpdate(DocumentEvent e) { validateTargExpression(); } }); final JComboBox<String> comboBox = new JComboBox<>(new String[]{"uncertainty", "standard_deviation", "error"}); comboBox.setEditable(true); bindingContext.bind(PROPERTY_NAME_RELATION, comboBox); gbc.gridy = ++line; components = createComponents(PROPERTY_NAME_BAND_NAME); GridBagUtils.addToPanel(panel, components[1], gbc, "weightx=0, insets.right=3, insets.top=3, gridwidth=1, fill=HORIZONTAL, anchor=WEST"); GridBagUtils.addToPanel(panel, components[0], gbc, "weightx=1, insets.right=0, insets.top=3, gridwidth=2, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; components = createComponents(PROPERTY_NAME_ORDER); GridBagUtils.addToPanel(panel, components[1], gbc, "weightx=0, insets.right=3, insets.top=3, gridwidth=1, fill=HORIZONTAL, anchor=WEST"); GridBagUtils.addToPanel(panel, components[0], gbc, "weightx=1, insets.right=0, insets.top=3, gridwidth=2, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; PropertyDescriptor relationDescriptor = bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_RELATION); GridBagUtils.addToPanel(panel, new JLabel(relationDescriptor.getDisplayName() + ":"), gbc, "weightx=0, insets.right=3, insets.top=3, gridwidth=1, fill=HORIZONTAL, anchor=WEST"); GridBagUtils.addToPanel(panel, comboBox, gbc, "weightx=1, insets.right=0, insets.top=3, gridwidth=2, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; GridBagUtils.addToPanel(panel, new JLabel("Source expression:"), gbc, "weightx=1, insets.top=8, gridwidth=3, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; GridBagUtils.addToPanel(panel, new JScrollPane(sourceExprArea), gbc, "weightx=1, insets.top=3, gridwidth=3, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; GridBagUtils.addToPanel(panel, new JLabel("Uncertainty expression:"), gbc, "weightx=1, insets.top=3, gridwidth=3, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; GridBagUtils.addToPanel(panel, new JScrollPane(targetExprArea), gbc, "weightx=1, weighty=1, insets.top=3, gridwidth=3, fill=BOTH, anchor=WEST"); gbc.gridy = ++line; GridBagUtils.addToPanel(panel, expressionIsCompatibleLabel, gbc, "weightx=0, weighty=1, insets.top=3, gridwidth=3, fill=NONE, anchor=EAST"); setContent(panel); } private void validateTargExpression() { final String targExpression = targetExprArea.getText(); final Product product = sourceBand.getProduct(); try { if (!BandArithmetic.areRastersEqualInSize(product, sourceExprArea.getText(), targExpression)) { expressionIsCompatibleLabel.setText("Referenced rasters must be of the same size"); expressionIsCompatibleLabel.setForeground(WARN_MSG_OLOR); } else { expressionIsCompatibleLabel.setText("Ok, no errors"); expressionIsCompatibleLabel.setForeground(OK_MSG_COLOR); } } catch (ParseException e) { expressionIsCompatibleLabel.setText("Expression is invalid"); expressionIsCompatibleLabel.setForeground(WARN_MSG_OLOR); } } private void updateTargetExprArea() { try { String uncertaintyExpression = generateUncertaintyExpression(); targetExprArea.setText(uncertaintyExpression); validateTargExpression(); } catch (ParseException | UnsupportedOperationException e) { targetExprArea.setText(ERROR_PREFIX + e.getMessage()); } } private JComponent[] createComponents(String propertyName) { PropertyDescriptor descriptor = bindingContext.getPropertySet().getDescriptor(propertyName); PropertyEditor propertyEditor = PropertyEditorRegistry.getInstance().findPropertyEditor(descriptor); return propertyEditor.createComponents(descriptor, bindingContext); } private BindingContext createBindingContext() { final PropertyContainer container = PropertyContainer.createObjectBacked(this); final BindingContext context = new BindingContext(container); PropertyDescriptor descriptor; descriptor = container.getDescriptor(PROPERTY_NAME_BAND_NAME); descriptor.setDisplayName("Uncertainty band name"); descriptor.setDescription("The name for the new uncertainty band."); descriptor.setNotEmpty(true); descriptor.setValidator(new ProductNodeNameValidator(sourceBand.getProduct())); descriptor.setDefaultValue(getDefaultBandName(sourceBand.getName() + "_unc")); descriptor = container.getDescriptor(PROPERTY_NAME_ORDER); descriptor.setDisplayName("Order of Taylor polynomial"); descriptor.setDescription("The number of Taylor series expansion terms used for the Standard Combined Uncertainty (GUM 1995)."); descriptor.setDefaultValue(1); descriptor.setValueSet(new ValueSet(new Integer[]{1, 2, 3})); descriptor = container.getDescriptor(PROPERTY_NAME_RELATION); descriptor.setDisplayName("Relation name of ancillary bands"); descriptor.setDescription("Relation name of ancillary variables that represent uncertainties (NetCDF-U 'rel' attribute)."); descriptor.setDefaultValue("uncertainty"); descriptor.setNotNull(true); descriptor.setNotEmpty(true); container.setDefaultValues(); PropertyChangeListener targetExprUpdater = evt -> { updateTargetExprArea(); }; context.addPropertyChangeListener(PROPERTY_NAME_ORDER, targetExprUpdater); context.addPropertyChangeListener(PROPERTY_NAME_RELATION, targetExprUpdater); return context; } private String getDefaultBandName(String nameBase) { String defaultName = nameBase; Product product = sourceBand.getProduct(); int i = 0; while (product.getRasterDataNode(defaultName) != null) { defaultName = nameBase + (++i); } return defaultName; } private String getBandName() { return bandName.trim(); } }
13,127
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
BandMathsAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/bandmaths/BandMathsAction.java
/* * Copyright (C) 2014 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.bandmaths; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.core.datamodel.ProductNodeList; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.rcp.SnapApp; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.util.HelpCtx; import org.openide.util.NbBundle.Messages; import org.openide.util.Utilities; import javax.swing.AbstractAction; import javax.swing.Action; import java.awt.event.ActionEvent; import java.util.Collection; import java.util.stream.Collectors; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.EXPLORER; @ActionID( category = "Tools", id = "BandMathsAction" ) @ActionRegistration( displayName = "#CTL_BandMathsAction_MenuText", popupText = "#CTL_BandMathsAction_MenuText", // iconBase = "org/esa/snap/rcp/icons/BandMaths.gif", // icon is not nice lazy = false ) @ActionReferences({ @ActionReference(path = "Menu/Raster", position = 0), @ActionReference(path = "Context/Product/Product", position = 10), @ActionReference(path = "Context/Product/RasterDataNode", position = 20) }) @Messages({ "CTL_BandMathsAction_MenuText=Band Maths...", "CTL_BandMathsAction_ShortDescription=Create a new band using an arbitrary mathematical expression" }) public class BandMathsAction extends AbstractAction implements HelpCtx.Provider { private static final String HELP_ID = "bandArithmetic"; public BandMathsAction() { super(Bundle.CTL_BandMathsAction_MenuText()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_BandMathsAction_ShortDescription()); final ProductManager productManager = SnapApp.getDefault().getProductManager(); setEnabled(productManager.getProductCount() > 0); productManager.addListener(new PMListener()); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(HELP_ID); } @Override public void actionPerformed(ActionEvent actionEvent) { final ProductNodeList<Product> products = new ProductNodeList<>(); Product[] openedProducts = SnapApp.getDefault().getProductManager().getProducts(); for (Product prod : openedProducts) { products.add(prod); } Product product = SnapApp.getDefault().getSelectedProduct(EXPLORER); if (product == null) { product = products.getAt(0); } Collection<? extends RasterDataNode> selectedRasters = Utilities.actionsGlobalContext().lookupAll(RasterDataNode.class); String expression = selectedRasters.stream().map(ProductNode::getName).collect(Collectors.joining(" + ")); BandMathsDialog bandMathsDialog = new BandMathsDialog(product, products, expression, HELP_ID); bandMathsDialog.show(); } private class PMListener implements ProductManager.Listener { @Override public void productAdded(ProductManager.Event event) { updateEnableState(); } @Override public void productRemoved(ProductManager.Event event) { updateEnableState(); } private void updateEnableState() { setEnabled(SnapApp.getDefault().getProductManager().getProductCount() > 0); } } }
4,225
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PropagateUncertaintyAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/bandmaths/PropagateUncertaintyAction.java
/* * Copyright (C) 2014 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.bandmaths; import org.esa.snap.core.datamodel.VirtualBand; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.util.NbBundle.Messages; import javax.swing.AbstractAction; import javax.swing.Action; import java.awt.event.ActionEvent; @ActionID(category = "Tools", id = "PropagateUncertaintyAction") @ActionRegistration(displayName = "#CTL_PropagateUncertaintyAction_MenuText", lazy = true) @ActionReferences({ @ActionReference(path = "Menu/Raster", position = 25), @ActionReference(path = "Context/Product/VirtualBand", position = 200),}) @Messages({ "CTL_PropagateUncertaintyAction_MenuText=Propagate Uncertainty...", "CTL_PropagateUncertaintyAction_ShortDescription=Perform Gaussian uncertainty propagation from virtual band according to GUM 1995, chapter 5" }) public class PropagateUncertaintyAction extends AbstractAction { private VirtualBand virtualBand; public PropagateUncertaintyAction(VirtualBand virtualBand) { super(Bundle.CTL_PropagateUncertaintyAction_MenuText()); this.virtualBand = virtualBand; putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_PropagateUncertaintyAction_ShortDescription()); } @Override public void actionPerformed(ActionEvent actionEvent) { PropagateUncertaintyDialog dialog = new PropagateUncertaintyDialog(virtualBand); dialog.show(); } }
2,244
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
BandMathsDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/bandmaths/BandMathsDialog.java
/* * Copyright (C) 2015 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.bandmaths; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.ValueSet; import com.bc.ceres.core.Assert; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.PropertyEditor; import com.bc.ceres.swing.binding.PropertyEditorRegistry; import com.bc.ceres.swing.binding.internal.CheckBoxEditor; import com.bc.ceres.swing.binding.internal.NumericEditor; import com.bc.ceres.swing.binding.internal.SingleSelectionEditor; import com.bc.ceres.swing.binding.internal.TextComponentAdapter; import com.bc.ceres.swing.binding.internal.TextFieldEditor; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductData; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.ProductNodeList; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.VirtualBand; import org.esa.snap.core.dataop.barithm.BandArithmetic; import org.esa.snap.core.dataop.barithm.RasterDataSymbol; import org.esa.snap.core.jexp.ParseException; import org.esa.snap.core.jexp.Term; import org.esa.snap.core.util.PreferencesPropertyMap; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.actions.window.OpenImageViewAction; import org.esa.snap.rcp.nodes.UndoableProductNodeInsertion; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.ModalDialog; import org.esa.snap.ui.product.ProductExpressionPane; import org.openide.awt.UndoRedo; import org.openide.util.NbBundle; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.event.ActionListener; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.prefs.Preferences; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.EXPLORER; @NbBundle.Messages({ "CTL_BandMathsDialog_Title=Band Maths", "CTL_BandMathsDialog_ErrBandNotCreated=The band could not be created.\nAn expression parse error occurred:\n", "CTL_BandMathsDialog_ErrExpressionNotValid=Please check the band maths expression you have entered.\nIt is not valid.", "CTL_BandMathsDialog_ErrBandCannotBeReferenced=You cannot reference the target band ''{0}'' within the expression.", "CTL_BandMathsDialog_LblExpression=Band maths expression:", }) class BandMathsDialog extends ModalDialog { static final String PREF_KEY_AUTO_SHOW_NEW_BANDS = "BandMaths.autoShowNewBands"; static final String PREF_KEY_LAST_EXPRESSION_PATH = "BandMaths.lastExpressionPath"; private static final String PROPERTY_NAME_PRODUCT = "productName"; private static final String PROPERTY_NAME_EXPRESSION = "expression"; private static final String PROPERTY_NAME_NO_DATA_VALUE = "noDataValue"; private static final String PROPERTY_NAME_NO_DATA_VALUE_USED = "noDataValueUsed"; private static final String PROPERTY_NAME_SAVE_EXPRESSION_ONLY = "saveExpressionOnly"; private static final String PROPERTY_NAME_GENERATE_UNCERTAINTY_BAND = "generateUncertaintyBand"; private static final String PROPERTY_NAME_BAND_NAME = "bandName"; private static final String PROPERTY_NAME_BAND_DESC = "bandDescription"; private static final String PROPERTY_NAME_BAND_UNIT = "bandUnit"; private static final String PROPERTY_NAME_BAND_WAVELENGTH = "bandWavelength"; private final ProductNodeList<Product> productsList; private final BindingContext bindingContext; private Product targetProduct; private String productName; @SuppressWarnings("FieldCanBeLocal") private String expression; @SuppressWarnings("UnusedDeclaration") private double noDataValue; @SuppressWarnings("UnusedDeclaration") private boolean noDataValueUsed; @SuppressWarnings("UnusedDeclaration") private boolean saveExpressionOnly; @SuppressWarnings("UnusedDeclaration") private boolean generateUncertaintyBand; @SuppressWarnings("UnusedDeclaration") private String bandName; @SuppressWarnings("FieldCanBeLocal") private String bandDescription; @SuppressWarnings("FieldCanBeLocal") private String bandUnit; @SuppressWarnings("UnusedDeclaration") private float bandWavelength; private static int numNewBands = 0; public BandMathsDialog(Product currentProduct, ProductNodeList<Product> productsList, String expression, String helpId) { super(SnapApp.getDefault().getMainFrame(), Bundle.CTL_BandMathsDialog_Title(), ID_OK_CANCEL_HELP, helpId); Assert.notNull(expression, "expression"); Assert.notNull(currentProduct, "currentProduct"); Assert.notNull(productsList, "productsList"); Assert.argument(productsList.size() > 0, "productsList must be not empty"); targetProduct = currentProduct; this.productsList = productsList; bindingContext = createBindingContext(); this.expression = expression; bandDescription = ""; bandUnit = ""; makeUI(); } @Override protected void onOK() { final String validMaskExpression; int width = targetProduct.getSceneRasterWidth(); int height = targetProduct.getSceneRasterHeight(); RasterDataNode prototypeRasterDataNode = null; try { Product[] products = getCompatibleProducts(); int defaultProductIndex = Arrays.asList(products).indexOf(targetProduct); validMaskExpression = BandArithmetic.getValidMaskExpression(getExpression(), products, defaultProductIndex, null); final RasterDataNode[] refRasters = BandArithmetic.getRefRasters(getExpression(), products, defaultProductIndex); if (refRasters.length > 0) { prototypeRasterDataNode = refRasters[0]; width = prototypeRasterDataNode.getRasterWidth(); height = prototypeRasterDataNode.getRasterHeight(); } } catch (ParseException e) { String errorMessage = Bundle.CTL_BandMathsDialog_ErrBandNotCreated() + e.getMessage(); Dialogs.showError(Bundle.CTL_BandMathsDialog_Title() + " - Error", errorMessage); hide(); return; } Band band; if (saveExpressionOnly) { band = new VirtualBand(getBandName(), ProductData.TYPE_FLOAT32, width, height, getExpression()); setBandProperties(band, validMaskExpression); } else { band = new Band(getBandName(), ProductData.TYPE_FLOAT32, width, height); setBandProperties(band, ""); } ProductNodeGroup<Band> bandGroup = targetProduct.getBandGroup(); bandGroup.add(band); if (prototypeRasterDataNode != null) { ProductUtils.copyImageGeometry(prototypeRasterDataNode, band, false); } if (saveExpressionOnly) { checkExpressionForExternalReferences(getExpression()); } else { String expression = getExpression(); if (validMaskExpression != null && !validMaskExpression.isEmpty()) { expression = "(" + validMaskExpression + ") ? (" + expression + ") : NaN"; } band.setSourceImage(VirtualBand.createSourceImage(band, expression)); } UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(targetProduct); if (undoManager != null) { undoManager.addEdit(new UndoableProductNodeInsertion<>(bandGroup, band)); } hide(); band.setModified(true); if (SnapApp.getDefault().getPreferences().getBoolean(PREF_KEY_AUTO_SHOW_NEW_BANDS, true)) { OpenImageViewAction.openImageView(band); } if (generateUncertaintyBand) { if (band instanceof VirtualBand) { VirtualBand virtualBand = (VirtualBand) band; PropagateUncertaintyAction uncertaintyAction = new PropagateUncertaintyAction(virtualBand); uncertaintyAction.actionPerformed(null); } } } private void setBandProperties(Band band, String validMaskExpression) { band.setDescription(bandDescription); band.setUnit(bandUnit); band.setSpectralWavelength(bandWavelength); band.setGeophysicalNoDataValue(noDataValue); band.setNoDataValueUsed(noDataValueUsed); band.setValidPixelExpression(validMaskExpression); } @Override protected boolean verifyUserInput() { if (!isValidExpression()) { showErrorDialog(Bundle.CTL_BandMathsDialog_ErrExpressionNotValid()); return false; } if (isTargetBandReferencedInExpression()) { showErrorDialog(Bundle.CTL_BandMathsDialog_ErrBandCannotBeReferenced(getBandName())); return false; } return super.verifyUserInput(); } private void makeUI() { JButton loadExpressionButton = new JButton("Load..."); loadExpressionButton.setName("loadExpressionButton"); loadExpressionButton.addActionListener(createLoadExpressionButtonListener()); JButton saveExpressionButton = new JButton("Save..."); saveExpressionButton.setName("saveExpressionButton"); saveExpressionButton.addActionListener(createSaveExpressionButtonListener()); JButton editExpressionButton = new JButton("Edit Expression..."); editExpressionButton.setName("editExpressionButton"); editExpressionButton.addActionListener(createEditExpressionButtonListener()); final JPanel panel = GridBagUtils.createPanel(); int line = 0; GridBagConstraints gbc = new GridBagConstraints(); JComponent[] components = createComponents(PROPERTY_NAME_PRODUCT, SingleSelectionEditor.class); gbc.gridy = ++line; GridBagUtils.addToPanel(panel, components[1], gbc, "gridwidth=3, fill=BOTH, weightx=1"); gbc.gridy = ++line; GridBagUtils.addToPanel(panel, components[0], gbc, "insets.top=3, gridwidth=3, fill=BOTH, anchor=WEST"); gbc.gridy = ++line; components = createComponents(PROPERTY_NAME_BAND_NAME, TextFieldEditor.class); GridBagUtils.addToPanel(panel, components[1], gbc, "weightx=0, insets.top=3, gridwidth=1, fill=HORIZONTAL, anchor=WEST"); GridBagUtils.addToPanel(panel, components[0], gbc, "weightx=1, insets.top=3, gridwidth=2, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; components = createComponents(PROPERTY_NAME_BAND_DESC, TextFieldEditor.class); GridBagUtils.addToPanel(panel, components[1], gbc, "weightx=0, insets.top=3, gridwidth=1, fill=HORIZONTAL, anchor=WEST"); GridBagUtils.addToPanel(panel, components[0], gbc, "weightx=1, insets.top=3, gridwidth=2, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; components = createComponents(PROPERTY_NAME_BAND_UNIT, TextFieldEditor.class); GridBagUtils.addToPanel(panel, components[1], gbc, "weightx=0, insets.top=3, gridwidth=1, fill=HORIZONTAL, anchor=WEST"); GridBagUtils.addToPanel(panel, components[0], gbc, "weightx=1, insets.top=3, gridwidth=2, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; components = createComponents(PROPERTY_NAME_BAND_WAVELENGTH, TextFieldEditor.class); GridBagUtils.addToPanel(panel, components[1], gbc, "weightx=0, insets.top=3, gridwidth=1, fill=HORIZONTAL, anchor=WEST"); GridBagUtils.addToPanel(panel, components[0], gbc, "weightx=1, insets.top=3, gridwidth=2, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; components = createComponents(PROPERTY_NAME_SAVE_EXPRESSION_ONLY, CheckBoxEditor.class); GridBagUtils.addToPanel(panel, components[0], gbc, "insets.top=3, gridwidth=3, fill=HORIZONTAL, anchor=EAST"); gbc.gridy = ++line; JPanel nodataPanel = new JPanel(new BorderLayout()); components = createComponents(PROPERTY_NAME_NO_DATA_VALUE_USED, CheckBoxEditor.class); nodataPanel.add(components[0], BorderLayout.WEST); components = createComponents(PROPERTY_NAME_NO_DATA_VALUE, NumericEditor.class); nodataPanel.add(components[0]); GridBagUtils.addToPanel(panel, nodataPanel, gbc, "weightx=1, insets.top=3, gridwidth=3, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; components = createComponents(PROPERTY_NAME_GENERATE_UNCERTAINTY_BAND, CheckBoxEditor.class); GridBagUtils.addToPanel(panel, components[0], gbc, "insets.top=3, gridwidth=3, fill=HORIZONTAL, anchor=EAST"); gbc.gridy = ++line; JLabel expressionLabel = new JLabel(Bundle.CTL_BandMathsDialog_LblExpression()); JTextArea expressionArea = new JTextArea(); expressionArea.setRows(3); TextComponentAdapter textComponentAdapter = new TextComponentAdapter(expressionArea); bindingContext.bind(PROPERTY_NAME_EXPRESSION, textComponentAdapter); GridBagUtils.addToPanel(panel, expressionLabel, gbc, "insets.top=3, gridwidth=3, anchor=WEST"); gbc.gridy = ++line; GridBagUtils.addToPanel(panel, expressionArea, gbc, "weighty=1, insets.top=3, gridwidth=3, fill=BOTH, anchor=WEST"); gbc.gridy = ++line; final JPanel loadSavePanel = new JPanel(); loadSavePanel.add(loadExpressionButton); loadSavePanel.add(saveExpressionButton); GridBagUtils.addToPanel(panel, loadSavePanel, gbc, "weighty=0, insets.top=3, gridwidth=2, fill=NONE, anchor=WEST"); GridBagUtils.addToPanel(panel, editExpressionButton, gbc, "weighty=1, insets.top=3, gridwidth=1, fill=HORIZONTAL, anchor=EAST"); gbc.gridy = ++line; GridBagUtils.addToPanel(panel, new JLabel(""), gbc, "insets.top=10, weightx=1, weighty=1, gridwidth=3, fill=BOTH, anchor=WEST"); setContent(panel); expressionArea.selectAll(); expressionArea.requestFocus(); } private ActionListener createLoadExpressionButtonListener() { return e -> { try { final File file = Dialogs.requestFileForOpen( "Load Band Maths Expression", false, null, PREF_KEY_LAST_EXPRESSION_PATH); if (file != null) { expression = new String(Files.readAllBytes(file.toPath())); bindingContext.getBinding(PROPERTY_NAME_EXPRESSION).setPropertyValue(expression); bindingContext.getBinding(PROPERTY_NAME_EXPRESSION).adjustComponents(); } } catch (IOException ex) { showErrorDialog(ex.getMessage()); } }; } private ActionListener createSaveExpressionButtonListener() { return e -> { try { final File file = Dialogs.requestFileForSave( "Save Band Maths Expression", false, null, ".txt", "myExpression", null, PREF_KEY_LAST_EXPRESSION_PATH); if (file != null) { final FileOutputStream out = new FileOutputStream(file.getAbsolutePath(), false); PrintStream p = new PrintStream(out); p.print(getExpression()); } } catch (IOException ex) { showErrorDialog(ex.getMessage()); } }; } private JComponent[] createComponents(String propertyName, Class<? extends PropertyEditor> editorClass) { PropertyDescriptor descriptor = bindingContext.getPropertySet().getDescriptor(propertyName); PropertyEditor editor = PropertyEditorRegistry.getInstance().getPropertyEditor(editorClass.getName()); return editor.createComponents(descriptor, bindingContext); } private BindingContext createBindingContext() { final PropertyContainer container = PropertyContainer.createObjectBacked(this); final BindingContext context = new BindingContext(container); container.addPropertyChangeListener(PROPERTY_NAME_PRODUCT, evt -> targetProduct = productsList.getByDisplayName(productName)); productName = targetProduct.getDisplayName(); PropertyDescriptor descriptor = container.getDescriptor(PROPERTY_NAME_PRODUCT); descriptor.setValueSet(new ValueSet(productsList.getDisplayNames())); descriptor.setDisplayName("Target product"); descriptor = container.getDescriptor(PROPERTY_NAME_BAND_NAME); descriptor.setDisplayName("Name"); descriptor.setDescription("The name for the new band."); descriptor.setNotEmpty(true); descriptor.setValidator(new ProductNodeNameValidator(targetProduct)); String newBandName; do { numNewBands++; newBandName = "new_band_" + numNewBands; } while (targetProduct.containsRasterDataNode(newBandName)); descriptor.setDefaultValue("new_band_" + (numNewBands)); descriptor = container.getDescriptor(PROPERTY_NAME_BAND_DESC); descriptor.setDisplayName("Description"); descriptor.setDescription("The description for the new band."); descriptor = container.getDescriptor(PROPERTY_NAME_BAND_UNIT); descriptor.setDisplayName("Unit"); descriptor.setDescription("The physical unit for the new band."); descriptor = container.getDescriptor(PROPERTY_NAME_BAND_WAVELENGTH); descriptor.setDisplayName("Spectral wavelength"); descriptor.setDescription("The physical unit for the new band."); descriptor = container.getDescriptor(PROPERTY_NAME_EXPRESSION); descriptor.setDisplayName("Band maths expression"); descriptor.setDescription("Band maths expression"); descriptor.setNotEmpty(true); descriptor = container.getDescriptor(PROPERTY_NAME_SAVE_EXPRESSION_ONLY); descriptor.setDisplayName("Virtual (save expression only, don't store data)"); descriptor.setDefaultValue(Boolean.TRUE); descriptor = container.getDescriptor(PROPERTY_NAME_NO_DATA_VALUE_USED); descriptor.setDisplayName("Replace NaN and infinity results by"); descriptor.setDefaultValue(Boolean.TRUE); descriptor = container.getDescriptor(PROPERTY_NAME_NO_DATA_VALUE); descriptor.setDefaultValue(Double.NaN); descriptor = container.getDescriptor(PROPERTY_NAME_GENERATE_UNCERTAINTY_BAND); descriptor.setDisplayName("Generate associated uncertainty band"); descriptor.setDefaultValue(Boolean.FALSE); container.setDefaultValues(); context.addPropertyChangeListener(PROPERTY_NAME_SAVE_EXPRESSION_ONLY, evt -> { final boolean saveExpressionOnly1 = (Boolean) context.getBinding( PROPERTY_NAME_SAVE_EXPRESSION_ONLY).getPropertyValue(); if (!saveExpressionOnly1) { context.getBinding(PROPERTY_NAME_NO_DATA_VALUE_USED).setPropertyValue(true); } }); context.bindEnabledState(PROPERTY_NAME_NO_DATA_VALUE_USED, false, PROPERTY_NAME_SAVE_EXPRESSION_ONLY, Boolean.FALSE); context.bindEnabledState(PROPERTY_NAME_NO_DATA_VALUE, true, PROPERTY_NAME_NO_DATA_VALUE_USED, Boolean.TRUE); context.bindEnabledState(PROPERTY_NAME_GENERATE_UNCERTAINTY_BAND, true, PROPERTY_NAME_SAVE_EXPRESSION_ONLY, Boolean.TRUE); return context; } private String getBandName() { return bandName.trim(); } private String getExpression() { return expression.trim(); } private Product[] getCompatibleProducts() { List<Product> compatibleProducts = new ArrayList<>(productsList.size()); compatibleProducts.add(targetProduct); for (int i = 0; i < productsList.size(); i++) { final Product product = productsList.getAt(i); if (targetProduct != product) { if (targetProduct.getSceneRasterWidth() == product.getSceneRasterWidth() && targetProduct.getSceneRasterHeight() == product.getSceneRasterHeight()) { compatibleProducts.add(product); } } } return compatibleProducts.toArray(new Product[compatibleProducts.size()]); } private ActionListener createEditExpressionButtonListener() { return e -> { Product[] compatibleProducts = getCompatibleProducts(); final Preferences preferences = SnapApp.getDefault().getPreferences(); final PreferencesPropertyMap preferencesPropertyMap = new PreferencesPropertyMap(preferences); ProductExpressionPane pep = ProductExpressionPane.createGeneralExpressionPane(compatibleProducts, targetProduct, preferencesPropertyMap); pep.setCode(getExpression()); int status = pep.showModalDialog(getJDialog(), "Band Maths Expression Editor"); if (status == ModalDialog.ID_OK) { bindingContext.getBinding(PROPERTY_NAME_EXPRESSION).setPropertyValue(pep.getCode()); } pep.dispose(); }; } private void checkExpressionForExternalReferences(String expression) { final Product[] compatibleProducts = getCompatibleProducts(); if (compatibleProducts.length > 1) { int defaultIndex = Arrays.asList(compatibleProducts).indexOf(targetProduct); RasterDataNode[] rasters = null; try { rasters = BandArithmetic.getRefRasters(expression, compatibleProducts, defaultIndex); } catch (ParseException ignored) { } if (rasters != null && rasters.length > 0) { Set<Product> externalProducts = new HashSet<>(compatibleProducts.length); for (RasterDataNode rdn : rasters) { Product product = rdn.getProduct(); if (product != targetProduct) { externalProducts.add(product); } } if (!externalProducts.isEmpty()) { String message = "The entered maths expression references multiple products.\n" + "It will cause problems unless the session is restored as is.\n\n" + "Note: You can save the session from the file menu."; Dialogs.showWarning(message); } } } } private boolean isValidExpression() { final Product[] products = getCompatibleProducts(); if (products.length == 0 || getExpression().isEmpty()) { return false; } final int defaultIndex = Arrays.asList(products).indexOf(targetProduct); try { BandArithmetic.parseExpression(getExpression(), products, defaultIndex == -1 ? 0 : defaultIndex); return true; } catch (ParseException e) { return false; } } private boolean isTargetBandReferencedInExpression() { final Product[] products = getCompatibleProducts(); final int defaultIndex = Arrays.asList(products).indexOf(SnapApp.getDefault().getSelectedProduct(EXPLORER)); try { final Term term = BandArithmetic.parseExpression(getExpression(), products, defaultIndex == -1 ? 0 : defaultIndex); final RasterDataSymbol[] refRasterDataSymbols = BandArithmetic.getRefRasterDataSymbols(term); String bName = getBandName(); if (targetProduct.containsRasterDataNode(bName)) { for (final RasterDataSymbol refRasterDataSymbol : refRasterDataSymbols) { final String refRasterName = refRasterDataSymbol.getRaster().getName(); if (bName.equalsIgnoreCase(refRasterName)) { return true; } } } } catch (ParseException e) { return false; } return false; } }
25,829
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
NavigationCanvas.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nav/NavigationCanvas.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.nav; import com.bc.ceres.glayer.CollectionLayer; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.LayerFilter; import com.bc.ceres.glayer.support.ImageLayer; import com.bc.ceres.glayer.swing.DefaultLayerCanvasModel; import com.bc.ceres.glayer.swing.LayerCanvas; import com.bc.ceres.glayer.swing.LayerCanvasModel; import com.bc.ceres.grender.Rendering; import com.bc.ceres.grender.Viewport; import com.bc.ceres.grender.ViewportListener; import com.bc.ceres.grender.support.DefaultViewport; import org.esa.snap.rcp.windows.NavigationTopComponent; import org.esa.snap.ui.product.ProductSceneView; import javax.swing.JPanel; import javax.swing.border.Border; import javax.swing.event.MouseInputAdapter; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; public class NavigationCanvas extends JPanel { private final NavigationTopComponent navigationWindow; private LayerCanvas thumbnailCanvas; private static final DefaultLayerCanvasModel NULL_MODEL = new DefaultLayerCanvasModel(new CollectionLayer(), new DefaultViewport()); private ObservedViewportHandler observedViewportHandler; private Rectangle2D moveSliderRect; private boolean adjustingObservedViewport; private boolean debug = false; public NavigationCanvas(NavigationTopComponent navigationWindow) { super(new BorderLayout()); setOpaque(true); this.navigationWindow = navigationWindow; thumbnailCanvas = new LayerCanvas(); thumbnailCanvas.setBackground(ProductSceneView.DEFAULT_IMAGE_BACKGROUND_COLOR); thumbnailCanvas.setLayerFilter(new LayerFilter() { @Override public boolean accept(Layer layer) { return layer instanceof ImageLayer; } }); thumbnailCanvas.addOverlay(new LayerCanvas.Overlay() { @Override public void paintOverlay(LayerCanvas canvas, Rendering rendering) { if (moveSliderRect != null && !moveSliderRect.isEmpty()) { Graphics2D g = rendering.getGraphics(); g.setColor(new Color(getForeground().getRed(), getForeground().getGreen(), getForeground().getBlue(), 82)); final Rectangle bounds = moveSliderRect.getBounds(); g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height); g.setColor(getForeground()); g.draw3DRect(bounds.x - 1, bounds.y - 1, bounds.width + 2, bounds.height + 2, true); g.draw3DRect(bounds.x, bounds.y, bounds.width, bounds.height, false); } } }); add(thumbnailCanvas, BorderLayout.CENTER); final MouseHandler mouseHandler = new MouseHandler(); addMouseListener(mouseHandler); addMouseMotionListener(mouseHandler); observedViewportHandler = new ObservedViewportHandler(); } @Override public void setBounds(int x, int y, int width, int height) { super.setBounds(x, y, width, height); thumbnailCanvas.getViewport().setViewBounds(new Rectangle(x, y, width, height)); thumbnailCanvas.zoomAll(); updateMoveSliderRect(); } /** * This method ignores the given parameter. It is an empty implementation to * prevent from setting borders on this canvas. * * @param border is ignored */ @Override public void setBorder(Border border) { } public void handleViewChanged(ProductSceneView oldView, ProductSceneView newView) { if (debug) { System.out.println("NavigationCanvas.handleViewChanged(): " + System.currentTimeMillis()); System.out.println(" oldView = " + (oldView == null ? "null" : oldView.getSceneName())); System.out.println(" newView = " + (newView == null ? "null" : newView.getSceneName())); } if (oldView != null) { Viewport observedViewport = oldView.getLayerCanvas().getViewport(); observedViewport.removeListener(observedViewportHandler); } if (newView != null) { Viewport observedViewport = newView.getLayerCanvas().getViewport(); observedViewport.addListener(observedViewportHandler); final Rectangle bounds; if (getBounds().isEmpty()) { bounds = new Rectangle(0, 0, 100, 100); } else { bounds = getBounds(); } Viewport thumbnailViewport = new DefaultViewport(bounds, observedViewport.isModelYAxisDown()); thumbnailViewport.setOrientation(observedViewport.getOrientation()); LayerCanvasModel thumbnailCanvasModel = new DefaultLayerCanvasModel(newView.getRootLayer(), thumbnailViewport); thumbnailCanvas.setModel(thumbnailCanvasModel); thumbnailCanvas.zoomAll(); } else { thumbnailCanvas.setModel(NULL_MODEL); } updateMoveSliderRect(); } private void updateMoveSliderRect() { ProductSceneView currentView = getNavigationWindow().getCurrentView(); if (currentView != null) { Viewport viewport = currentView.getLayerCanvas().getViewport(); Rectangle viewBounds = viewport.getViewBounds(); AffineTransform m2vTN = thumbnailCanvas.getViewport().getModelToViewTransform(); AffineTransform v2mVP = viewport.getViewToModelTransform(); moveSliderRect = m2vTN.createTransformedShape(v2mVP.createTransformedShape(viewBounds)).getBounds2D(); } else { moveSliderRect = new Rectangle2D.Double(); } if (debug) { System.out.println("NavigationCanvas.updateMoveSliderRect(): " + System.currentTimeMillis()); if (currentView != null) { Viewport viewport = currentView.getLayerCanvas().getViewport(); System.out.println( " currentView = " + currentView.getSceneName() + ", viewBounds = " + viewport.getViewBounds() + ", viewBounds = " + viewport.getViewBounds()); } else { System.out.println(" currentView = null"); } System.out.println(" moveSliderRect = " + moveSliderRect); } repaint(); } private void handleMoveSliderRectChanged() { ProductSceneView view = getNavigationWindow().getCurrentView(); if (view != null) { adjustingObservedViewport = true; Point2D location = new Point2D.Double(moveSliderRect.getMinX(), moveSliderRect.getMinY()); thumbnailCanvas.getViewport().getViewToModelTransform().transform(location, location); getNavigationWindow().setModelOffset(location.getX(), location.getY()); adjustingObservedViewport = false; } } private NavigationTopComponent getNavigationWindow() { return navigationWindow; } private class ObservedViewportHandler implements ViewportListener { @Override public void handleViewportChanged(Viewport observedViewport, boolean orientationChanged) { if (!adjustingObservedViewport) { if (orientationChanged) { thumbnailCanvas.getViewport().setOrientation(observedViewport.getOrientation()); thumbnailCanvas.zoomAll(); } updateMoveSliderRect(); } } } private class MouseHandler extends MouseInputAdapter { private Point pickPoint; private Point sliderPoint; @Override public void mousePressed(MouseEvent e) { pickPoint = e.getPoint(); if (!moveSliderRect.contains(pickPoint)) { final int x1 = pickPoint.x - moveSliderRect.getBounds().width / 2; final int y1 = pickPoint.y - moveSliderRect.getBounds().height / 2; moveSliderRect.setRect(x1, y1, moveSliderRect.getWidth(), moveSliderRect.getHeight()); repaint(); } sliderPoint = moveSliderRect.getBounds().getLocation(); } @Override public void mouseReleased(MouseEvent e) { repaint(); handleMoveSliderRectChanged(); } @Override public void mouseDragged(MouseEvent e) { final int x1 = sliderPoint.x + (e.getX() - pickPoint.x); final int y1 = sliderPoint.y + (e.getY() - pickPoint.y); moveSliderRect.setRect(x1, y1, moveSliderRect.getWidth(), moveSliderRect.getHeight()); repaint(); handleMoveSliderRectChanged(); } } }
9,828
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PixelInfoUpdateService.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/pixelinfo/PixelInfoUpdateService.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.pixelinfo; import org.esa.snap.ui.product.ProductSceneView; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * @author Marco Zuehlke * @version $Revision$ $Date$ * @since BEAM 4.5.2 */ public class PixelInfoUpdateService { private final PixelInfoViewModelUpdater modelUpdater; private final ScheduledExecutorService scheduledExecutorService; private ScheduledFuture<?> updaterFuture; private PixelInfoState state; private boolean needUpdate; private int numUnchangedStates; private Runnable updaterRunnable; public PixelInfoUpdateService(PixelInfoViewModelUpdater modelUpdater) { this.modelUpdater = modelUpdater; this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); state = PixelInfoState.INVALID; updaterRunnable = new UpdaterRunnable(); } synchronized void updateState(ProductSceneView view, int pixelX, int pixelY, int level, boolean pixelPosValid) { if (!state.equals(view, pixelX, pixelY, level, pixelPosValid)) { state = new PixelInfoState(view, pixelX, pixelY, level, pixelPosValid); needUpdate = true; assertTimerStarted(); } } synchronized void requestUpdate() { if (state == PixelInfoState.INVALID) { return; } needUpdate = true; assertTimerStarted(); } synchronized void clearState() { state = PixelInfoState.INVALID; } private void assertTimerStarted() { if (updaterFuture == null) { updaterFuture = scheduledExecutorService.scheduleAtFixedRate(updaterRunnable, 100, 100, TimeUnit.MILLISECONDS); } } private synchronized void stopTimer() { if (updaterFuture != null) { updaterFuture.cancel(true); updaterFuture = null; } clearState(); } private class UpdaterRunnable implements Runnable { @Override public void run() { if (state == PixelInfoState.INVALID) { return; } if (needUpdate) { numUnchangedStates = 0; needUpdate = false; try { modelUpdater.update(state); } catch (Throwable ignored) { } } else { numUnchangedStates++; if (numUnchangedStates > 100) { stopTimer(); } } } } }
3,378
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PixelInfoState.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/pixelinfo/PixelInfoState.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.pixelinfo; import org.esa.snap.ui.product.ProductSceneView; class PixelInfoState { static final PixelInfoState INVALID = new PixelInfoState(null, -1, -1, -1, false); final ProductSceneView view; final int pixelX; final int pixelY; final int level; final boolean pixelPosValid; PixelInfoState(ProductSceneView view, int pixelX, int pixelY, int level, boolean pixelPosValid) { this.view = view; this.pixelX = pixelX; this.pixelY = pixelY; this.level = level; this.pixelPosValid = pixelPosValid; } boolean equals(ProductSceneView view, int pixelX, int pixelY, int level, boolean pixelPosValid) { return this.view == view && this.pixelX == pixelX && this.pixelY == pixelY && this.level == level && this.pixelPosValid == pixelPosValid; } }
1,639
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PixelInfoViewTableModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/pixelinfo/PixelInfoViewTableModel.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.pixelinfo; import javax.swing.table.AbstractTableModel; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * * @author Marco Zuehlke * @version $Revision$ $Date$ * @since BEAM 4.5.2 */ public class PixelInfoViewTableModel extends AbstractTableModel { private final String[] columnNames; private final List<String> names; private final List<String> values; private final List<String> units; public PixelInfoViewTableModel(String[] columnNames) { this.columnNames = columnNames; names = Collections.synchronizedList(new ArrayList<>(32)); values = Collections.synchronizedList(new ArrayList<>(32)); units = Collections.synchronizedList(new ArrayList<>(32)); } @Override public Class<?> getColumnClass(int columnIndex) { return String.class; } @Override public String getColumnName(int column) { return columnNames[column]; } @Override public int getColumnCount() { return columnNames.length; } @Override public int getRowCount() { return names.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { return names.get(rowIndex); } else if (columnIndex == 1) { return values.get(rowIndex); } else if (columnIndex == 2) { return units.get(rowIndex); } return ""; } public void addRow(String name, String value, String unit) { synchronized (this) { names.add(name); values.add(value); units.add(unit); } } public void updateValue(String aValue, int row) { values.set(row, aValue); } public void clear() { synchronized (this) { names.clear(); values.clear(); units.clear(); } } }
2,699
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PixelInfoViewUtils.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/pixelinfo/PixelInfoViewUtils.java
package org.esa.snap.rcp.pixelinfo; import org.esa.snap.ui.product.ProductSceneView; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.PixelPos; import org.esa.snap.core.util.math.MathUtils; import com.bc.ceres.glevel.MultiLevelModel; import java.awt.geom.Point2D; import java.awt.geom.AffineTransform; import java.awt.image.RenderedImage; import org.opengis.referencing.operation.TransformException; /** * Utility class to compute pixel value in any raster */ public class PixelInfoViewUtils { // The following code is inspired from rcp.pixelinfo.PixelInfoViewModelUpdater /** * Compute the scene position according to the view raster * * @param view the current view * @param x the current pixel's X coordinate * @param y the current pixel's Y coordinate * @return the scene position */ public static Point2D.Double computeScenePos(final ProductSceneView view, final int x, final int y) { Point2D.Double scenePos; // Get the view raster (where the x and y where read) final RasterDataNode viewRaster = view.getRaster(); // TBN: use the better resolution possible (level = 0) final AffineTransform i2mTransform = view.getBaseImageLayer().getImageToModelTransform(0); final Point2D modelP = i2mTransform.transform(new Point2D.Double(x + 0.5, y + 0.5), null); try { final Point2D sceneP = viewRaster.getModelToSceneTransform().transform(modelP, new Point2D.Double()); scenePos = new Point2D.Double(sceneP.getX(), sceneP.getY()); } catch (TransformException te) { scenePos = new Point2D.Double(Double.NaN, Double.NaN); } return scenePos; } /** * Get the pixel value for the current raster * * @param scenePos the scene position (in another raster) * @param raster the current raster for which we want to find the pixel value * @return the pixel value for the current raster */ public static String getPixelValue(final Point2D.Double scenePos, final RasterDataNode raster) { String pixelString; Point2D.Double modelPos = new Point2D.Double(); try { raster.getSceneToModelTransform().transform(scenePos, modelPos); if (!(Double.isNaN(modelPos.getX()) || Double.isNaN(modelPos.getY()))) { final MultiLevelModel multiLevelModel = raster.getMultiLevelModel(); final PixelPos rasterPos = (PixelPos) multiLevelModel.getModelToImageTransform(0).transform(modelPos, new PixelPos()); final int pixelXForGrid = MathUtils.floorInt(rasterPos.getX()); final int pixelYForGrid = MathUtils.floorInt(rasterPos.getY()); if (coordinatesAreInRasterBounds(raster, pixelXForGrid, pixelYForGrid)) { pixelString = raster.getPixelString(pixelXForGrid, pixelYForGrid); } else { pixelString = RasterDataNode.INVALID_POS_TEXT; } } else { pixelString = RasterDataNode.INVALID_POS_TEXT; } } catch (TransformException e) { pixelString = RasterDataNode.INVALID_POS_TEXT; } return pixelString; } /** * Check if the (x,y) pixel coordinates are within the raster bounds * * @param raster the current raster * @param x the pixel x in the raster resolution * @param y the pixel y in the raster resolution * @return true if the pixel (x,y) belongs to the raster bounds, false otherwise */ private static boolean coordinatesAreInRasterBounds(final RasterDataNode raster, final int x, final int y) { final RenderedImage levelImage = raster.getSourceImage().getImage(0); return x >= 0 && y >= 0 && x < levelImage.getWidth() && y < levelImage.getHeight(); } }
3,984
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PixelInfoView.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/pixelinfo/PixelInfoView.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.pixelinfo; import eu.esa.snap.netbeans.docwin.WindowUtilities; import org.esa.snap.core.datamodel.*; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.CollapsibleItemsPanel; import org.esa.snap.rcp.windows.ProductSceneViewTopComponent; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.product.ProductSceneView; import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableModel; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Vector; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import java.util.prefs.Preferences; /** * The pixel info view component is used to display the geophysical values for the pixel at a given pixel position * (x,y). The pixel info view can simultaneously display band, tie point grid and flag values. * * @author Norman Fomferra * @author Sabine Embacher * @version 1.2 */ public class PixelInfoView extends JPanel { public static final String HELP_ID = "pixelInfoView"; /** * Preferences key for showing all band pixel values in pixel info view */ public static final String PREFERENCE_KEY_SHOW_ONLY_DISPLAYED_BAND_PIXEL_VALUES = "pixelview.showOnlyDisplayedBands"; /** * Preferences key for display style of geo-locations */ public static final String PREFERENCE_KEY_SHOW_GEO_POS_DECIMALS = "pixelview.showGeoPosDecimals"; /** * Preferences key for showing floating-point image coordinates */ public static final String PREFERENCE_KEY_SHOW_PIXEL_POS_DECIMALS = "pixelview.showPixelPosDecimals"; /** * Preferences key for coordinate system starting at (1,1) */ public static final String PREFERENCE_KEY_SHOW_PIXEL_POS_OFFSET_ONE = "pixelview.showPixelPosOffsetOne"; public static final boolean PREFERENCE_DEFAULT_SHOW_DISPLAYED_BAND_PIXEL_VALUES = true; public static final boolean PREFERENCE_DEFAULT_SHOW_GEO_POS_DECIMALS = false; public static final boolean PREFERENCE_DEFAULT_SHOW_PIXEL_POS_DECIMALS = false; public static final boolean PREFERENCE_DEFAULT_SHOW_PIXEL_POS_OFFSET_1 = false; private static final int NAME_COLUMN = 0; private static final int VALUE_COLUMN = 1; private static final int UNIT_COLUMN = 2; private boolean showGeoPosDecimals; static final int POSITION_INDEX = 0; static final int TIME_INDEX = 1; static final int BANDS_INDEX = 2; static final int TIE_POINT_GRIDS_INDEX = 3; static final int FLAGS_INDEX = 4; private final PropertyChangeListener displayFilterListener; private final ProductNodeListener productNodeListener; private boolean showPixelPosDecimals; private boolean showPixelPosOffset1; private DisplayFilter displayFilter; private final PixelInfoViewTableModel positionTableModel; private final PixelInfoViewTableModel timeTableModel; private final PixelInfoViewTableModel bandsTableModel; private final PixelInfoViewTableModel tiePointGridsTableModel; private final PixelInfoViewTableModel flagsTableModel; private final PixelInfoViewModelUpdater modelUpdater; private final PixelInfoUpdateService updateService; private CollapsibleItemsPanel collapsibleItemsPanel; /** * Constructs a new pixel info view. */ public PixelInfoView() { super(new BorderLayout()); displayFilterListener = createDisplayFilterListener(); productNodeListener = createProductNodeListener(); positionTableModel = new PixelInfoViewTableModel(new String[]{"Position", "Value", "Unit"}); timeTableModel = new PixelInfoViewTableModel(new String[]{"Time", "Value", "Unit"}); bandsTableModel = new PixelInfoViewTableModel(new String[]{"Band", "Value", "Unit"}); tiePointGridsTableModel = new PixelInfoViewTableModel(new String[]{"Tie-Point Grid", "Value", "Unit"}); flagsTableModel = new PixelInfoViewTableModel(new String[]{"Flag", "Value",}); modelUpdater = new PixelInfoViewModelUpdater(this, positionTableModel, timeTableModel, bandsTableModel, tiePointGridsTableModel, flagsTableModel ); updateService = new PixelInfoUpdateService(modelUpdater); setDisplayFilter(new DisplayFilter()); final Preferences preferences = SnapApp.getDefault().getPreferences(); preferences.addPreferenceChangeListener(new PreferenceChangeListener() { @Override public void preferenceChange(PreferenceChangeEvent evt) { final String propertyName = evt.getKey(); if (PREFERENCE_KEY_SHOW_ONLY_DISPLAYED_BAND_PIXEL_VALUES.equals(propertyName)) { setShowOnlyLoadedBands(preferences); } else if (PREFERENCE_KEY_SHOW_PIXEL_POS_DECIMALS.equals(propertyName)) { setShowPixelPosDecimals(preferences); } else if (PREFERENCE_KEY_SHOW_GEO_POS_DECIMALS.equals(propertyName)) { setShowGeoPosDecimals(preferences); } else if (PREFERENCE_KEY_SHOW_PIXEL_POS_OFFSET_ONE.equals(propertyName)) { setShowPixelPosOffset1(preferences); } } }); setShowOnlyLoadedBands(preferences); setShowPixelPosDecimals(preferences); setShowGeoPosDecimals(preferences); setShowPixelPosOffset1(preferences); createUI(); } public void reset() { modelUpdater.resetTableModels(); } ProductNodeListener getProductNodeListener() { return productNodeListener; } private ProductNodeListener createProductNodeListener() { return new ProductNodeListenerAdapter() { @Override public void nodeChanged(ProductNodeEvent event) { updateService.requestUpdate(); } @Override public void nodeAdded(ProductNodeEvent event) { updateService.requestUpdate(); } @Override public void nodeRemoved(ProductNodeEvent event) { updateService.requestUpdate(); } }; } private PropertyChangeListener createDisplayFilterListener() { return evt -> { if (getCurrentProduct() != null) { updateService.requestUpdate(); clearSelectionInRasterTables(); } }; } /** * Returns the current product * * @return the current Product */ public Product getCurrentProduct() { return modelUpdater.getCurrentProduct(); } /** * Sets the filter to be used to filter the displayed bands. <p> * * @param displayFilter the filter, can be null */ private void setDisplayFilter(DisplayFilter displayFilter) { if (this.displayFilter != displayFilter) { if (this.displayFilter != null) { this.displayFilter.removePropertyChangeListener(displayFilterListener); } this.displayFilter = displayFilter; this.displayFilter.addPropertyChangeListener(displayFilterListener); } } /** * Returns the display filter * * @return the display filter, can be null */ DisplayFilter getDisplayFilter() { return displayFilter; } private void setShowPixelPosDecimals(boolean showPixelPosDecimals) { if (this.showPixelPosDecimals != showPixelPosDecimals) { this.showPixelPosDecimals = showPixelPosDecimals; updateService.requestUpdate(); } } boolean getShowPixelPosDecimal() { return showPixelPosDecimals; } private void setShowGeoPosDecimals(boolean showGeoPosDecimals) { if (this.showGeoPosDecimals != showGeoPosDecimals) { this.showGeoPosDecimals = showGeoPosDecimals; updateService.requestUpdate(); } } boolean getShowGeoPosDecimals() { return showGeoPosDecimals; } private void setShowPixelPosOffset1(boolean showPixelPosOffset1) { if (this.showPixelPosOffset1 != showPixelPosOffset1) { this.showPixelPosOffset1 = showPixelPosOffset1; updateService.requestUpdate(); } } boolean getShowPixelPosOffset1() { return showPixelPosOffset1; } public void updatePixelValues(ProductSceneView view, int pixelX, int pixelY, int level, boolean pixelPosValid) { updateService.updateState(view, pixelX, pixelY, level, pixelPosValid); } private void createUI() { DefaultTableCellRenderer pixelValueRenderer = new ValueCellRenderer(); FlagCellRenderer flagCellRenderer = new FlagCellRenderer(); setLayout(new BorderLayout()); CollapsibleItemsPanel.Item<JTable> positionItem = CollapsibleItemsPanel.createTableItem("Position", 6, 3); positionItem.getComponent().setModel(positionTableModel); positionItem.getComponent().getColumnModel().getColumn(1).setCellRenderer(pixelValueRenderer); CollapsibleItemsPanel.Item<JTable> timeItem = CollapsibleItemsPanel.createTableItem("Time", 2, 3); timeItem.getComponent().setModel(timeTableModel); timeItem.getComponent().getColumnModel().getColumn(1).setCellRenderer(pixelValueRenderer); CollapsibleItemsPanel.Item<JTable> tiePointGridsItem = CollapsibleItemsPanel.createTableItem("Tie-Point Grids", 0, 3); tiePointGridsItem.getComponent().setModel(tiePointGridsTableModel); tiePointGridsItem.getComponent().getColumnModel().getColumn(1).setCellRenderer(pixelValueRenderer); CollapsibleItemsPanel.Item<JTable> bandsItem = CollapsibleItemsPanel.createTableItem("Bands", 18, 3); bandsItem.getComponent().setModel(bandsTableModel); bandsItem.getComponent().getColumnModel().getColumn(1).setCellRenderer(pixelValueRenderer); CollapsibleItemsPanel.Item<JTable> flagsItem = CollapsibleItemsPanel.createTableItem("Flags", 0, 2); flagsItem.getComponent().setModel(flagsTableModel); flagsItem.getComponent().getColumnModel().getColumn(1).setCellRenderer(flagCellRenderer); collapsibleItemsPanel = new CollapsibleItemsPanel( positionItem, // POSITION_INDEX = 0 timeItem, // TIME_INDEX = 1 bandsItem, // BANDS_INDEX = 2 tiePointGridsItem, // TIE_POINT_GRIDS_INDEX = 3 flagsItem // FLAGS_INDEX = 4 ); collapsibleItemsPanel.setCollapsed(POSITION_INDEX, false); collapsibleItemsPanel.setCollapsed(TIME_INDEX, true); collapsibleItemsPanel.setCollapsed(BANDS_INDEX, false); collapsibleItemsPanel.setCollapsed(TIE_POINT_GRIDS_INDEX, true); collapsibleItemsPanel.setCollapsed(FLAGS_INDEX, true); collapsibleItemsPanel.addCollapseListener(new CollapsibleItemsPanel.CollapseListener() { @Override public void collapse(int index) { //do nothing } @Override public void expand(int index) { updateService.requestUpdate(); } }); JScrollPane scrollPane = new JScrollPane(collapsibleItemsPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.getVerticalScrollBar().setUnitIncrement(20); add(scrollPane, BorderLayout.CENTER); } void clearSelectionInRasterTables() { final JTable bandsTable = (JTable) collapsibleItemsPanel.getItem(BANDS_INDEX).getComponent(); final JTable tiePointGridsTable = (JTable) collapsibleItemsPanel.getItem(TIE_POINT_GRIDS_INDEX).getComponent(); bandsTable.clearSelection(); tiePointGridsTable.clearSelection(); final RasterDataNode raster = modelUpdater.getCurrentRaster(); if (raster != null) { final String rasterName = raster.getName(); if (!selectCurrentRaster(rasterName, bandsTable)) { selectCurrentRaster(rasterName, tiePointGridsTable); } } } public void clearProductNodeRefs() { modelUpdater.clearProductNodeRefs(); updateService.clearState(); } boolean isCollapsiblePaneVisible(int index) { return !collapsibleItemsPanel.isCollapsed(index); } private boolean selectCurrentRaster(String rasterName, JTable table) { final TableModel model = table.getModel(); for (int i = 0; i < model.getRowCount(); i++) { final String s = model.getValueAt(i, NAME_COLUMN).toString(); if (rasterName.equals(s)) { table.changeSelection(i, NAME_COLUMN, false, false); return true; } } return false; } private void setShowOnlyLoadedBands(final Preferences preferences) { final boolean showOnlyLoadedOrDisplayedBands = preferences.getBoolean( PixelInfoView.PREFERENCE_KEY_SHOW_ONLY_DISPLAYED_BAND_PIXEL_VALUES, PixelInfoView.PREFERENCE_DEFAULT_SHOW_DISPLAYED_BAND_PIXEL_VALUES); displayFilter.setShowOnlyLoadedOrDisplayedBands(showOnlyLoadedOrDisplayedBands); } private void setShowPixelPosOffset1(final Preferences preferences) { setShowPixelPosOffset1(preferences.getBoolean( PREFERENCE_KEY_SHOW_PIXEL_POS_OFFSET_ONE, PREFERENCE_DEFAULT_SHOW_PIXEL_POS_OFFSET_1)); } private void setShowPixelPosDecimals(final Preferences preferences) { setShowPixelPosDecimals(preferences.getBoolean( PREFERENCE_KEY_SHOW_PIXEL_POS_DECIMALS, PREFERENCE_DEFAULT_SHOW_PIXEL_POS_DECIMALS)); } private void setShowGeoPosDecimals(final Preferences preferences) { setShowGeoPosDecimals(preferences.getBoolean( PREFERENCE_KEY_SHOW_GEO_POS_DECIMALS, PREFERENCE_DEFAULT_SHOW_GEO_POS_DECIMALS)); } private static class ValueCellRenderer extends DefaultTableCellRenderer { Font valueFont; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (valueFont == null) { Font font = getFont(); valueFont = new Font(Font.MONOSPACED, Font.PLAIN, font != null ? font.getSize() : 12); } setFont(valueFont); setHorizontalAlignment(RIGHT); return this; } } private static class FlagCellRenderer extends ValueCellRenderer { static final Color VERY_LIGHT_BLUE = new Color(230, 230, 255); static final Color VERY_LIGHT_RED = new Color(255, 230, 230); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); setForeground(Color.black); setBackground(Color.white); if (column == VALUE_COLUMN && value != null) { if (value.equals("true")) { setForeground(UIUtils.COLOR_DARK_RED); setBackground(VERY_LIGHT_BLUE); } else if (value.equals("false")) { setForeground(UIUtils.COLOR_DARK_BLUE); setBackground(VERY_LIGHT_RED); } } return this; } } public static class DisplayFilter { private final Vector<PropertyChangeListener> propertyChangeListeners = new Vector<>(); private boolean showOnlyLoadedOrDisplayedBands; public void addPropertyChangeListener(PropertyChangeListener displayFilterListener) { if (displayFilterListener != null && !propertyChangeListeners.contains(displayFilterListener)) { propertyChangeListeners.add(displayFilterListener); } } public void removePropertyChangeListener(PropertyChangeListener displayFilterListener) { if (displayFilterListener != null) { propertyChangeListeners.remove(displayFilterListener); } } protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { final PropertyChangeEvent event = new PropertyChangeEvent(this, propertyName, oldValue, newValue); for (int i = 0; i < propertyChangeListeners.size(); i++) { (propertyChangeListeners.elementAt(i)).propertyChange(event); } } void setShowOnlyLoadedOrDisplayedBands(boolean v) { if (showOnlyLoadedOrDisplayedBands != v) { final boolean oldValue = showOnlyLoadedOrDisplayedBands; showOnlyLoadedOrDisplayedBands = v; firePropertyChange("showOnlyLoadedOrDisplayedBands", oldValue, v); } } public boolean accept(ProductNode node) { if (node instanceof RasterDataNode) { final RasterDataNode rasterDataNode = (RasterDataNode) node; if (showOnlyLoadedOrDisplayedBands) { return rasterDataNode.hasRasterData() || WindowUtilities.getOpened(ProductSceneViewTopComponent.class).anyMatch( topComponent -> rasterDataNode == topComponent.getView().getRaster()); } } return true; } } }
18,884
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PixelInfoViewModelUpdater.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/pixelinfo/PixelInfoViewModelUpdater.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.pixelinfo; import com.bc.ceres.core.Assert; import com.bc.ceres.glayer.support.ImageLayer; import com.bc.ceres.glevel.MultiLevelModel; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.CrsGeoCoding; import org.esa.snap.core.datamodel.FlagCoding; import org.esa.snap.core.datamodel.GeoCoding; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.MapGeoCoding; import org.esa.snap.core.datamodel.MetadataAttribute; import org.esa.snap.core.datamodel.PixelPos; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductData; import org.esa.snap.core.datamodel.ProductNodeListener; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.TiePointGrid; import org.esa.snap.core.dataop.maptransf.MapTransform; import org.esa.snap.core.image.ImageManager; import org.esa.snap.core.util.Guardian; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.core.util.math.MathUtils; import org.esa.snap.ui.product.ProductSceneView; import org.geotools.geometry.DirectPosition2D; import org.opengis.geometry.DirectPosition; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.TransformException; import javax.media.jai.PlanarImage; import javax.swing.SwingUtilities; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.util.Calendar; import java.util.Vector; /** * @author Marco Zuehlke * @version $Revision$ $Date$ * @since BEAM 4.5.2 */ class PixelInfoViewModelUpdater { private static final String INVALID_POS_TEXT = "Invalid pos."; private final PixelInfoViewTableModel positionModel; private final PixelInfoViewTableModel timeModel; private final PixelInfoViewTableModel bandModel; private final PixelInfoViewTableModel tiePointModel; private final PixelInfoViewTableModel flagModel; private volatile Product currentProduct; private volatile RasterDataNode currentRaster; private volatile ProductSceneView currentView; private Band[] currentFlagBands; private int pixelX; private int pixelY; private int rasterLevel; private int levelZeroRasterX; private int levelZeroRasterY; private double sceneX; private double sceneY; private int levelZeroSceneX; private int levelZeroSceneY; private boolean pixelPosValidInRaster; private final PixelInfoView pixelInfoView; PixelInfoViewModelUpdater(PixelInfoView pixelInfoView, PixelInfoViewTableModel positionModel, PixelInfoViewTableModel timeModel, PixelInfoViewTableModel bandModel, PixelInfoViewTableModel tiePointModel, PixelInfoViewTableModel flagModel) { this.pixelInfoView = pixelInfoView; this.positionModel = positionModel; this.timeModel = timeModel; this.bandModel = bandModel; this.tiePointModel = tiePointModel; this.flagModel = flagModel; } Product getCurrentProduct() { return currentProduct; } RasterDataNode getCurrentRaster() { return currentRaster; } void update(PixelInfoState state) { update(state.view, state.pixelX, state.pixelY, state.level, state.pixelPosValid); } private void update(ProductSceneView view, int pixelX, int pixelY, int level, boolean pixelPosValid) { Guardian.assertNotNull("view", view); boolean clearRasterTableSelection = false; RasterDataNode raster = view.getRaster(); final Product product = raster.getProduct(); if (product == currentProduct && view.isRGB()) { resetBandTableModel(); } if (product != currentProduct) { ProductNodeListener productNodeListener = pixelInfoView.getProductNodeListener(); if (currentProduct != null) { currentProduct.removeProductNodeListener(productNodeListener); } product.addProductNodeListener(productNodeListener); currentProduct = product; } if (raster != currentRaster) { currentRaster = raster; registerFlagDatasets(); resetTableModels(); } if (bandModel.getRowCount() != getBandRowCount()) { resetTableModels(); } if (view != currentView) { currentView = view; resetTableModels(); clearRasterTableSelection = true; } this.pixelX = pixelX; this.pixelY = pixelY; this.rasterLevel = level; this.pixelPosValidInRaster = pixelPosValid; AffineTransform i2mTransform = currentView.getBaseImageLayer().getImageToModelTransform(level); Point2D modelP = i2mTransform.transform(new Point2D.Double(pixelX + 0.5, pixelY + 0.5), null); try { final Point2D sceneP = currentView.getRaster().getModelToSceneTransform().transform(modelP, new Point2D.Double()); sceneX = sceneP.getX(); sceneY = sceneP.getY(); } catch (TransformException e) { sceneX = Double.NaN; sceneY = Double.NaN; } AffineTransform m2iTransform = view.getBaseImageLayer().getModelToImageTransform(); Point2D levelZeroP = m2iTransform.transform(modelP, null); levelZeroRasterX = floor(levelZeroP.getX()); levelZeroRasterY = floor(levelZeroP.getY()); //todo [multisize_products] ask for different imagetomodeltransforms - tf 20151113 if (product.isMultiSize()) { try { final GeoCoding sceneGeoCoding = product.getSceneGeoCoding(); if (sceneGeoCoding != null) { final MathTransform imageToMapTransform = sceneGeoCoding.getImageToMapTransform(); if (imageToMapTransform instanceof AffineTransform) { final MathTransform modelToImage = imageToMapTransform.inverse(); final DirectPosition2D pos = new DirectPosition2D(sceneX, sceneY); final DirectPosition position = modelToImage.transform(pos, pos); levelZeroSceneX = floor(position.getCoordinate()[0]); levelZeroSceneY = floor(position.getCoordinate()[1]); } else { levelZeroSceneX = floor(sceneX); levelZeroSceneY = floor(sceneY); } } } catch (TransformException e) { levelZeroSceneX = levelZeroRasterX; levelZeroSceneY = levelZeroRasterY; } } updateDataDisplay(clearRasterTableSelection); } void resetTableModels() { resetPositionTableModel(); resetTimeTableModel(); resetBandTableModel(); resetTiePointGridTableModel(); resetFlagTableModel(); } private void fireTableChanged(final boolean clearRasterTableSelection) { SwingUtilities.invokeLater(() -> { if (clearRasterTableSelection) { pixelInfoView.clearSelectionInRasterTables(); } positionModel.fireTableDataChanged(); timeModel.fireTableDataChanged(); bandModel.fireTableDataChanged(); tiePointModel.fireTableDataChanged(); flagModel.fireTableDataChanged(); }); } private void updateDataDisplay(boolean clearRasterTableSelection) { if (currentRaster == null) { return; } if (pixelInfoView.isCollapsiblePaneVisible(PixelInfoView.POSITION_INDEX)) { updatePositionValues(); } if (pixelInfoView.isCollapsiblePaneVisible(PixelInfoView.TIME_INDEX)) { updateTimeValues(); } if (pixelInfoView.isCollapsiblePaneVisible(PixelInfoView.BANDS_INDEX)) { updateBandPixelValues(); } if (pixelInfoView.isCollapsiblePaneVisible(PixelInfoView.TIE_POINT_GRIDS_INDEX)) { updateTiePointGridPixelValues(); } if (pixelInfoView.isCollapsiblePaneVisible(PixelInfoView.FLAGS_INDEX)) { updateFlagPixelValues(); } fireTableChanged(clearRasterTableSelection); } private void resetPositionTableModel() { positionModel.clear(); if (currentRaster != null) { final GeoCoding geoCoding = currentRaster.getGeoCoding(); positionModel.addRow("Image-X", "", "pixel"); positionModel.addRow("Image-Y", "", "pixel"); //todo [Multisize_products] ask for something else than multisize (scenetomodeltransform) if (getCurrentProduct().isMultiSize()) { positionModel.addRow("Scene-X", "", "pixel"); positionModel.addRow("Scene-Y", "", "pixel"); } if (geoCoding != null) { positionModel.addRow("Longitude", "", "degree"); positionModel.addRow("Latitude", "", "degree"); if (geoCoding instanceof MapGeoCoding) { final MapGeoCoding mapGeoCoding = (MapGeoCoding) geoCoding; final String mapUnit = mapGeoCoding.getMapInfo().getMapProjection().getMapUnit(); positionModel.addRow("Map-X", "", mapUnit); positionModel.addRow("Map-Y", "", mapUnit); } else if (geoCoding instanceof CrsGeoCoding) { String xAxisUnit = geoCoding.getMapCRS().getCoordinateSystem().getAxis(0).getUnit().toString(); String yAxisUnit = geoCoding.getMapCRS().getCoordinateSystem().getAxis(1).getUnit().toString(); positionModel.addRow("Map-X", "", xAxisUnit); positionModel.addRow("Map-Y", "", yAxisUnit); } } } } private void updatePositionValues() { final boolean availableInRaster = pixelPosValidInRaster && coordinatesAreInRasterBounds(currentRaster, pixelX, pixelY, rasterLevel); final boolean availableInScene = isSampleValueAvailableInScene(); final double offset = 0.5 + (pixelInfoView.getShowPixelPosOffset1() ? 1.0 : 0.0); final double pX = levelZeroRasterX + offset; final double pY = levelZeroRasterY + offset; String tix, tiy, tsx, tsy, tmx, tmy, tgx, tgy; tix = tiy = tsx = tsy = tmx = tmy = tgx = tgy = INVALID_POS_TEXT; GeoCoding geoCoding = currentRaster.getGeoCoding(); if (availableInRaster) { if (pixelInfoView.getShowPixelPosDecimal()) { tix = String.valueOf(pX); tiy = String.valueOf(pY); } else { tix = String.valueOf((int) Math.floor(pX)); tiy = String.valueOf((int) Math.floor(pY)); } } if (getCurrentProduct().isMultiSize()) { if (!availableInScene) { tsx = PixelInfoViewModelUpdater.INVALID_POS_TEXT; tsy = PixelInfoViewModelUpdater.INVALID_POS_TEXT; } else { double sX = levelZeroSceneX + offset; double sY = levelZeroSceneY + offset; if (pixelInfoView.getShowPixelPosDecimal()) { tsx = String.valueOf(sX); tsy = String.valueOf(sY); } else { tsx = String.valueOf((int) Math.floor(sX)); tsy = String.valueOf((int) Math.floor(sY)); } } } if (availableInRaster && geoCoding != null) { PixelPos pixelPos = new PixelPos(pX, pY); GeoPos geoPos = geoCoding.getGeoPos(pixelPos, null); if (pixelInfoView.getShowGeoPosDecimals()) { tgx = String.format("%.6f", geoPos.getLon()); tgy = String.format("%.6f", geoPos.getLat()); } else { tgx = geoPos.getLonString(); tgy = geoPos.getLatString(); } if (geoCoding instanceof MapGeoCoding) { final MapGeoCoding mapGeoCoding = (MapGeoCoding) geoCoding; final MapTransform mapTransform = mapGeoCoding.getMapInfo().getMapProjection().getMapTransform(); Point2D mapPoint = mapTransform.forward(geoPos, null); tmx = String.valueOf(MathUtils.round(mapPoint.getX(), 10000.0)); tmy = String.valueOf(MathUtils.round(mapPoint.getY(), 10000.0)); } else if (geoCoding instanceof CrsGeoCoding) { MathTransform transform = geoCoding.getImageToMapTransform(); try { DirectPosition position = transform.transform(new DirectPosition2D(pX, pY), null); double[] coordinate = position.getCoordinate(); tmx = String.valueOf(coordinate[0]); tmy = String.valueOf(coordinate[1]); } catch (TransformException ignore) { } } } int rowCount = 0; positionModel.updateValue(tix, rowCount++); positionModel.updateValue(tiy, rowCount++); if (getCurrentProduct().isMultiSize()) { positionModel.updateValue(tsx, rowCount++); positionModel.updateValue(tsy, rowCount++); } if (geoCoding != null) { positionModel.updateValue(tgx, rowCount++); positionModel.updateValue(tgy, rowCount++); if (geoCoding instanceof MapGeoCoding || geoCoding instanceof CrsGeoCoding) { positionModel.updateValue(tmx, rowCount++); positionModel.updateValue(tmy, rowCount); } } } private void resetTimeTableModel() { timeModel.clear(); if (currentRaster != null) { timeModel.addRow("Date", "", "YYYY-MM-DD"); timeModel.addRow("Time (UTC)", "", "HH:MM:SS:mm [AM/PM]"); } } private void updateTimeValues() { final ProductData.UTC utcStartTime = currentProduct.getStartTime(); final ProductData.UTC utcEndTime = currentProduct.getEndTime(); boolean isAvailable = currentProduct.isMultiSize() ? isSampleValueAvailableInScene() : isSampleValueAvailableInRaster(); if (utcStartTime == null || utcEndTime == null || !isAvailable) { timeModel.updateValue("No date information", 0); timeModel.updateValue("No time information", 1); } else { final ProductData.UTC utcCurrentLine; if (currentProduct.isMultiSize()) { utcCurrentLine = ProductUtils.getPixelScanTime(currentProduct, levelZeroSceneX + 0.5, levelZeroSceneY + 0.5); } else { utcCurrentLine = ProductUtils.getPixelScanTime(currentRaster, levelZeroRasterX + 0.5, levelZeroRasterY + 0.5); } Assert.notNull(utcCurrentLine, "utcCurrentLine"); final Calendar currentLineTime = utcCurrentLine.getAsCalendar(); final String dateString = String.format("%1$tF", currentLineTime); final String timeString = String.format("%1$tI:%1$tM:%1$tS:%1$tL %1$Tp", currentLineTime); timeModel.updateValue(dateString, 0); timeModel.updateValue(timeString, 1); } } private void resetBandTableModel() { bandModel.clear(); if (currentRaster != null) { final int numBands = currentProduct.getNumBands(); for (int i = 0; i < numBands; i++) { final Band band = currentProduct.getBandAt(i); if (shouldDisplayBand(band)) { bandModel.addRow(band.getName(), "", band.getUnit()); } } } } private void updateBandPixelValues() { for (int i = 0; i < bandModel.getRowCount(); i++) { final String bandName = (String) bandModel.getValueAt(i, 0); bandModel.updateValue(getPixelString(currentProduct.getBand(bandName)), i); } } private int getBandRowCount() { int rowCount = 0; if (currentProduct != null) { Band[] bands = currentProduct.getBands(); for (final Band band : bands) { if (shouldDisplayBand(band)) { rowCount++; } } } return rowCount; } private boolean shouldDisplayBand(final Band band) { PixelInfoView.DisplayFilter displayFilter = pixelInfoView.getDisplayFilter(); if (displayFilter != null) { return displayFilter.accept(band); } return band.hasRasterData(); } private void resetTiePointGridTableModel() { tiePointModel.clear(); if (currentRaster != null) { final int numTiePointGrids = currentProduct.getNumTiePointGrids(); for (int i = 0; i < numTiePointGrids; i++) { final TiePointGrid tiePointGrid = currentProduct.getTiePointGridAt(i); tiePointModel.addRow(tiePointGrid.getName(), "", tiePointGrid.getUnit()); } } } private void updateTiePointGridPixelValues() { for (int i = 0; i < tiePointModel.getRowCount(); i++) { final TiePointGrid grid = currentProduct.getTiePointGrid((String) tiePointModel.getValueAt(i, 0)); tiePointModel.updateValue(getPixelString(grid), i); } } private void resetFlagTableModel() { flagModel.clear(); if (currentRaster != null) { for (Band band : currentFlagBands) { // currentFlagBands is already filtered for "equals size" in registerFlagDatasets final FlagCoding flagCoding = band.getFlagCoding(); if (flagCoding != null) { final int numFlags = flagCoding.getNumAttributes(); final String bandNameDot = band.getName() + "."; for (int j = 0; j < numFlags; j++) { String name = bandNameDot + flagCoding.getAttributeAt(j).getName(); flagModel.addRow(name, "", ""); } } } } } private void updateFlagPixelValues() { if (flagModel.getRowCount() != getFlagRowCount()) { resetFlagTableModel(); } int rowIndex = 0; for (Band band : currentFlagBands) { long pixelValue; boolean available; if (band.getImageToModelTransform().equals(currentRaster.getImageToModelTransform()) && band.getSceneToModelTransform().equals(currentRaster.getSceneToModelTransform())) { available = pixelPosValidInRaster; pixelValue = available ? ProductUtils.getGeophysicalSampleAsLong(band, pixelX, pixelY, rasterLevel) : 0; } else { PixelPos rasterPos = new PixelPos(); final Point2D.Double scenePos = new Point2D.Double(sceneX, sceneY); final Point2D modelPos; try { modelPos = band.getSceneToModelTransform().transform(scenePos, new Point2D.Double()); final MultiLevelModel multiLevelModel = band.getMultiLevelModel(); final int level = getLevel(multiLevelModel); multiLevelModel.getModelToImageTransform(level).transform(modelPos, rasterPos); final int rasterX = (int) Math.floor(rasterPos.getX()); final int rasterY = (int) Math.floor(rasterPos.getY()); available = coordinatesAreInRasterBounds(band, rasterX, rasterY, level); pixelValue = available ? ProductUtils.getGeophysicalSampleAsLong(band, rasterX, rasterY, level) : 0; } catch (TransformException e) { available = false; pixelValue = -1; } } for (int j = 0; j < band.getFlagCoding().getNumAttributes(); j++) { if (available) { MetadataAttribute attribute = band.getFlagCoding().getAttributeAt(j); final ProductData flagData = attribute.getData(); final long flagMask; final long flagValue; if (flagData.getNumElems() == 2) { flagMask = flagData.getElemUIntAt(0); flagValue = flagData.getElemUIntAt(1); } else { flagMask = flagValue = flagData.getElemUInt(); } flagModel.updateValue(String.valueOf((pixelValue & flagMask) == flagValue), rowIndex); } else { flagModel.updateValue(INVALID_POS_TEXT, rowIndex); } rowIndex++; } } } private void registerFlagDatasets() { Vector<Band> flagBandsVector = new Vector<>(); if (currentProduct != null) { final Band[] bands = currentProduct.getBands(); for (Band band : bands) { if (isFlagBand(band)) { flagBandsVector.add(band); } } } currentFlagBands = flagBandsVector.toArray(new Band[flagBandsVector.size()]); } private boolean isFlagBand(final Band band) { return band.getFlagCoding() != null; } private int getFlagRowCount() { int rowCount = 0; for (Band band : currentFlagBands) { rowCount += band.getFlagCoding().getNumAttributes(); } return rowCount; } private String getPixelString(RasterDataNode raster) { if (raster.getImageToModelTransform().equals(currentRaster.getImageToModelTransform()) && raster.getSceneToModelTransform().equals(currentRaster.getSceneToModelTransform())) { if (!pixelPosValidInRaster) { return RasterDataNode.INVALID_POS_TEXT; } return getPixelString(raster, pixelX, pixelY, rasterLevel); } final Point2D.Double scenePos = new Point2D.Double(sceneX, sceneY); Point2D.Double modelPos = new Point2D.Double(); try { raster.getSceneToModelTransform().transform(scenePos, modelPos); if (Double.isNaN(modelPos.getX()) || Double.isNaN(modelPos.getY())) { return PixelInfoViewModelUpdater.INVALID_POS_TEXT; } } catch (TransformException e) { return PixelInfoViewModelUpdater.INVALID_POS_TEXT; } final MultiLevelModel multiLevelModel = raster.getMultiLevelModel(); final int level = getLevel(multiLevelModel); final PixelPos rasterPos = (PixelPos) multiLevelModel.getModelToImageTransform(level).transform(modelPos, new PixelPos()); final int rasterX = floor(rasterPos.getX()); final int rasterY = floor(rasterPos.getY()); if (!coordinatesAreInRasterBounds(raster, rasterX, rasterY, level)) { return RasterDataNode.INVALID_POS_TEXT; } return getPixelString(raster, rasterX, rasterY, level); } //todo code duplication with spectrumtopcomponent - move to single class - tf 20151119 private int getLevel(MultiLevelModel multiLevelModel) { if (rasterLevel < multiLevelModel.getLevelCount()) { return rasterLevel; } return ImageLayer.getLevel(multiLevelModel, currentView.getViewport()); } private String getPixelString(RasterDataNode raster, int x, int y, int level) { if (isPixelValid(raster, x, y, level)) { if (raster.isScalingApplied() || ProductData.isFloatingPointType(raster.getDataType())) { int dataType = raster.getGeophysicalDataType(); if (dataType == ProductData.TYPE_FLOAT64) { double pixel = ProductUtils.getGeophysicalSampleAsDouble(raster, x, y, level); return String.format("%.10f", pixel); } else if (dataType == ProductData.TYPE_FLOAT32) { double pixel = ProductUtils.getGeophysicalSampleAsDouble(raster, x, y, level); return String.format("%.5f", pixel); } } return String.valueOf(ProductUtils.getGeophysicalSampleAsLong(raster, x, y, level)); } else { return RasterDataNode.NO_DATA_TEXT; } } //todo code duplication with spectrumtopcomponent - move to single class - tf 20151119 private boolean isPixelValid(RasterDataNode raster, int pixelX, int pixelY, int level) { if (raster.isValidMaskUsed()) { PlanarImage image = ImageManager.getInstance().getValidMaskImage(raster, level); Raster data = getRasterTile(image, pixelX, pixelY); return data.getSample(pixelX, pixelY, 0) != 0; } else { return true; } } //todo code duplication with spectrumtopcomponent - move to single class - tf 20151119 private Raster getRasterTile(PlanarImage image, int pixelX, int pixelY) { final int tileX = image.XToTileX(pixelX); final int tileY = image.YToTileY(pixelY); return image.getTile(tileX, tileY); } //todo code duplication with spectrumtopcomponent - move to single class - tf 20151119 private boolean coordinatesAreInRasterBounds(RasterDataNode raster, int x, int y, int level) { final RenderedImage levelImage = raster.getSourceImage().getImage(level); return x >= 0 && y >= 0 && x < levelImage.getWidth() && y < levelImage.getHeight(); } /** * Convenience method that gives the largest integer smaller than the double value or * -1 if value is Doubl.NaN. */ private int floor(double value) { if (Double.isNaN(value)) { return -1; } return (int) Math.floor(value); } private boolean isSampleValueAvailableInScene() { return levelZeroSceneX >= 0 && levelZeroSceneY >= 0 && levelZeroSceneX < currentProduct.getSceneRasterWidth() && levelZeroSceneY < currentProduct.getSceneRasterHeight(); } private boolean isSampleValueAvailableInRaster() { return levelZeroRasterX >= 0 && levelZeroRasterY >= 0 && levelZeroRasterX < currentRaster.getRasterWidth() && levelZeroRasterY < currentRaster.getRasterHeight(); } void clearProductNodeRefs() { currentProduct = null; currentRaster = null; currentView = null; currentFlagBands = new Band[0]; } }
27,663
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WriterOptionsPanelController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-znap-ui/src/main/java/org/esa/snap/dataio/znap/preferences/WriterOptionsPanelController.java
/* * Copyright (c) 2021. Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.dataio.znap.preferences; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import javax.swing.JComponent; import javax.swing.SwingUtilities; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.HelpCtx; import org.openide.util.Lookup; @OptionsPanelController.TopLevelRegistration( categoryName = "#AdvancedOption_DisplayName_Writer", iconBase = "org/esa/snap/dataio/znap/images/SNAP_data_32.png", keywords = "#AdvancedOption_Keywords_Writer", keywordsCategory = "ZNAP", position = 1600 ) @org.openide.util.NbBundle.Messages({ "AdvancedOption_DisplayName_Writer=ZNAP", "AdvancedOption_Keywords_Writer=data,znap,zarr,io,reader,writer" }) public final class WriterOptionsPanelController extends OptionsPanelController { private WriterPanel panel; private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); private boolean changed; public void update() { getPanel().load(); changed = false; } public void applyChanges() { SwingUtilities.invokeLater(() -> { getPanel().store(); changed = false; }); } public void cancel() { // need not do anything special, if no changes have been persisted yet } public boolean isValid() { return getPanel().valid(); } public boolean isChanged() { return changed; } public HelpCtx getHelpCtx() { return new HelpCtx("exportZnapProduct"); // new HelpCtx("...ID") if you have a help set } public JComponent getComponent(Lookup masterLookup) { return getPanel(); } public void addPropertyChangeListener(PropertyChangeListener l) { pcs.addPropertyChangeListener(l); } public void removePropertyChangeListener(PropertyChangeListener l) { pcs.removePropertyChangeListener(l); } private WriterPanel getPanel() { if (panel == null) { panel = new WriterPanel(this); } return panel; } void changed() { if (!changed) { changed = true; pcs.firePropertyChange(OptionsPanelController.PROP_CHANGED, false, true); } pcs.firePropertyChange(OptionsPanelController.PROP_VALID, null, null); } }
3,093
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WriterPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-znap-ui/src/main/java/org/esa/snap/dataio/znap/preferences/WriterPanel.java
/* * Copyright (c) 2021. Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.dataio.znap.preferences; import org.esa.snap.rcp.SnapApp; import org.esa.snap.runtime.Config; import javax.swing.GroupLayout; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.border.TitledBorder; import java.awt.event.ItemListener; import java.util.Arrays; import java.util.Vector; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import static org.esa.snap.dataio.znap.preferences.ZnapPreferencesConstants.DEFAULT_COMPRESSION_LEVEL; import static org.esa.snap.dataio.znap.preferences.ZnapPreferencesConstants.DEFAULT_COMPRESSOR_ID; import static org.esa.snap.dataio.znap.preferences.ZnapPreferencesConstants.DEFAULT_USE_ZIP_ARCHIVE; import static org.esa.snap.dataio.znap.preferences.ZnapPreferencesConstants.PROPERTY_NAME_BINARY_FORMAT; import static org.esa.snap.dataio.znap.preferences.ZnapPreferencesConstants.PROPERTY_NAME_COMPRESSION_LEVEL; import static org.esa.snap.dataio.znap.preferences.ZnapPreferencesConstants.PROPERTY_NAME_COMPRESSOR_ID; import static org.esa.snap.dataio.znap.preferences.ZnapPreferencesConstants.PROPERTY_NAME_USE_ZIP_ARCHIVE; import static org.esa.snap.dataio.znap.preferences.ZnapPreferencesConstants.ZLIB_COMPRESSION_LEVELS; final class WriterPanel extends javax.swing.JPanel { private static final String ZARR_FORMAT_NAME = "Zarr (default)"; private static final String COMPRESSOR_NULL = "null"; private static final String COMPRESSOR_ZLIB = "zlib"; private static final String DEFAULT_EXTENSION = " (default)"; private static final String[] AVAILABLE_COMPRESSORS = {COMPRESSOR_NULL, COMPRESSOR_ZLIB}; static { for (int i = 0; i < AVAILABLE_COMPRESSORS.length; i++) { AVAILABLE_COMPRESSORS[i] = appendDefaultExtensionIfItIsTheDefaultCompressorId(AVAILABLE_COMPRESSORS[i]); } } private final WriterOptionsPanelController controller; private JComponent createZipArchiveLabel; private JCheckBox createZipArchiveCheck; private JComponent binaryFormatLabel; private JComboBox<String> binaryFormatCombo; private JComponent compressorLabel; private JComboBox<String> compressorCombo; private JComponent compressionLevelLabel; private JComboBox<String> compressionLevelCombo; WriterPanel(WriterOptionsPanelController controller) { this.controller = controller; initComponents(); addListenerToComponents(controller); } void load() { Preferences preferences = Config.instance("snap").load().preferences(); final boolean useZipArchive = preferences.getBoolean(PROPERTY_NAME_USE_ZIP_ARCHIVE, DEFAULT_USE_ZIP_ARCHIVE); createZipArchiveCheck.setSelected(useZipArchive); String binaryFormat = preferences.get(PROPERTY_NAME_BINARY_FORMAT, ZARR_FORMAT_NAME); binaryFormatCombo.setSelectedItem(binaryFormat); String compressorId = preferences.get(PROPERTY_NAME_COMPRESSOR_ID, DEFAULT_COMPRESSOR_ID); final String entryToBeSelected = appendDefaultExtensionIfItIsTheDefaultCompressorId(compressorId); compressorCombo.setSelectedItem(entryToBeSelected); int compressionLevel = preferences.getInt(PROPERTY_NAME_COMPRESSION_LEVEL, DEFAULT_COMPRESSION_LEVEL); int idx = Arrays.asList(ZLIB_COMPRESSION_LEVELS).indexOf(compressionLevel); compressionLevelCombo.setSelectedIndex(idx); } void store() { Preferences preferences = Config.instance("snap").load().preferences(); try { final boolean useZipArchive = createZipArchiveCheck.isSelected(); if (useZipArchive != DEFAULT_USE_ZIP_ARCHIVE) { preferences.put(PROPERTY_NAME_USE_ZIP_ARCHIVE, String.valueOf(useZipArchive)); } else { preferences.remove(PROPERTY_NAME_USE_ZIP_ARCHIVE); } String selectedFormat = binaryFormatCombo.getItemAt(binaryFormatCombo.getSelectedIndex()); final boolean isNotZarrFormatName = !ZARR_FORMAT_NAME.equals(selectedFormat); if (binaryFormatCombo.isEnabled() && isNotZarrFormatName) { preferences.put(PROPERTY_NAME_BINARY_FORMAT, selectedFormat); } else { preferences.remove(PROPERTY_NAME_BINARY_FORMAT); } String compressorId = compressorCombo.getItemAt(compressorCombo.getSelectedIndex()); compressorId = removeDefaultExtension(compressorId); final boolean isDefaultCompressorId = DEFAULT_COMPRESSOR_ID.equals(compressorId); if (compressorCombo.isEnabled() && !isDefaultCompressorId) { preferences.put(PROPERTY_NAME_COMPRESSOR_ID, compressorId); } else { preferences.remove(PROPERTY_NAME_COMPRESSOR_ID); } if (COMPRESSOR_NULL.equals(compressorId)) { preferences.remove(PROPERTY_NAME_COMPRESSION_LEVEL); return; } int selectedIndex = compressionLevelCombo.getSelectedIndex(); int compressionLevel = ZLIB_COMPRESSION_LEVELS[selectedIndex]; final boolean isDefaultCompressionLevel = compressionLevel == DEFAULT_COMPRESSION_LEVEL; if (compressionLevelCombo.isEnabled() && !isDefaultCompressionLevel) { preferences.putInt(PROPERTY_NAME_COMPRESSION_LEVEL, compressionLevel); } else { preferences.remove(PROPERTY_NAME_COMPRESSION_LEVEL); } } finally { try { preferences.flush(); } catch (BackingStoreException e) { SnapApp.getDefault().getLogger().severe(e.getMessage()); } } } private static String appendDefaultExtensionIfItIsTheDefaultCompressorId(String compressorId) { return DEFAULT_COMPRESSOR_ID.equals(compressorId) ? compressorId + DEFAULT_EXTENSION : compressorId; } private static String removeDefaultExtension(String comboBoxEntry) { return comboBoxEntry.replace(DEFAULT_EXTENSION, ""); } boolean valid() { return true; } private void initComponents() { binaryFormatLabel = new JLabel("Binary format:"); Vector<String> formatNames = new Vector<>(); formatNames.add(ZARR_FORMAT_NAME); formatNames.add("GeoTIFF"); formatNames.add("GeoTIFF-BigTIFF"); formatNames.add("ENVI"); formatNames.add("NetCDF4-CF"); binaryFormatCombo = new JComboBox<>(formatNames); compressorLabel = new JLabel("Compressor:"); compressorCombo = new JComboBox<>(AVAILABLE_COMPRESSORS); compressionLevelLabel = new JLabel("Compression level:"); compressionLevelCombo = new JComboBox<>(); for (Integer zlibCompressionLevel : ZLIB_COMPRESSION_LEVELS) { String item = zlibCompressionLevel.toString(); if (zlibCompressionLevel == DEFAULT_COMPRESSION_LEVEL) { item += " (default)"; } compressionLevelCombo.addItem(item); } createZipArchiveLabel = new JLabel("Create zip archive:"); createZipArchiveCheck = new JCheckBox(); setBorder(new TitledBorder("ZNAP Options")); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); setLayout(layout); layout.setVerticalGroup( layout.createSequentialGroup() .addGroup( layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(createZipArchiveLabel) .addComponent(createZipArchiveCheck)) .addGroup( layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(binaryFormatLabel) .addComponent(binaryFormatCombo)) .addGroup( layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(compressorLabel) .addComponent(compressorCombo)) .addGroup( layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(compressionLevelLabel) .addComponent(compressionLevelCombo)) .addGap(0, 2000, Short.MAX_VALUE) ); layout.setHorizontalGroup( layout.createSequentialGroup() .addGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(binaryFormatLabel) .addComponent(compressorLabel) .addComponent(compressionLevelLabel) .addComponent(createZipArchiveLabel)) .addGroup( layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(binaryFormatCombo) .addComponent(compressorCombo) .addComponent(compressionLevelCombo) .addComponent(createZipArchiveCheck)) .addGap(0, 2000, Short.MAX_VALUE) ); } private void addListenerToComponents(WriterOptionsPanelController controller) { ItemListener itemListener = e -> { controller.changed(); updateState(); }; binaryFormatCombo.addItemListener(itemListener); compressorCombo.addItemListener(itemListener); compressionLevelCombo.addItemListener(itemListener); createZipArchiveCheck.addItemListener(itemListener); } private void updateState() { final boolean noZipArchive = !createZipArchiveCheck.isSelected(); binaryFormatLabel.setEnabled(noZipArchive); binaryFormatCombo.setEnabled(noZipArchive); boolean zarrFormat = binaryFormatCombo.getSelectedIndex() == 0; final boolean noArchiveAndZarrFormat = noZipArchive && zarrFormat; compressorCombo.setEnabled(noArchiveAndZarrFormat); compressorLabel.setEnabled(noArchiveAndZarrFormat); int selectedIndex = compressorCombo.getSelectedIndex(); String selectedItem = compressorCombo.getItemAt(selectedIndex); final String selectedCompressorID = removeDefaultExtension(selectedItem); boolean compressorIsSelected = !COMPRESSOR_NULL.equals(selectedCompressorID); boolean levelEnabled = noArchiveAndZarrFormat && compressorIsSelected; compressionLevelCombo.setEnabled(levelEnabled); compressionLevelLabel.setEnabled(levelEnabled); } }
11,905
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CollocationFormTest.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-collocation-ui/src/test/java/org/esa/snap/collocation/visat/CollocationFormTest.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.collocation.visat; import org.esa.snap.collocation.ResamplingType; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductData; import org.junit.Test; import javax.swing.DefaultComboBoxModel; import static org.junit.Assert.*; /** * Tests for class {@link CollocationForm}. * * @author Ralf Quast */ public class CollocationFormTest { @Test public void testAdaptResamplingComboBoxModel() { final Product product = new Product("name", "type", 10, 10); final Band band1 = product.addBand("band1", ProductData.TYPE_INT32); final Band band2 = product.addBand("band2", ProductData.TYPE_INT32); DefaultComboBoxModel<ResamplingType> resamplingComboBoxModel = new DefaultComboBoxModel<>(ResamplingType.values()); boolean validPixelExpressionUsed = CollocationForm.isValidPixelExpressionUsed(product); assertFalse(validPixelExpressionUsed); CollocationForm.adaptResamplingComboBoxModel(resamplingComboBoxModel, validPixelExpressionUsed); assertEquals(5, resamplingComboBoxModel.getSize()); band1.setValidPixelExpression("true"); validPixelExpressionUsed = CollocationForm.isValidPixelExpressionUsed(product); assertTrue(validPixelExpressionUsed); CollocationForm.adaptResamplingComboBoxModel(resamplingComboBoxModel, validPixelExpressionUsed); assertEquals(1, resamplingComboBoxModel.getSize()); assertEquals(ResamplingType.NEAREST_NEIGHBOUR, resamplingComboBoxModel.getSelectedItem()); band1.setValidPixelExpression(null); band2.setValidPixelExpression(" "); validPixelExpressionUsed = CollocationForm.isValidPixelExpressionUsed(product); assertFalse(validPixelExpressionUsed); CollocationForm.adaptResamplingComboBoxModel(resamplingComboBoxModel, validPixelExpressionUsed); assertEquals(5, resamplingComboBoxModel.getSize()); assertEquals(ResamplingType.NEAREST_NEIGHBOUR, resamplingComboBoxModel.getSelectedItem()); } }
2,822
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CollocationUI.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-collocation-ui/src/main/java/org/esa/snap/collocation/gpf/ui/CollocationUI.java
package org.esa.snap.collocation.gpf.ui; import com.bc.ceres.binding.ConversionException; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.PropertySetDescriptor; import com.bc.ceres.swing.TableLayout; import org.esa.snap.collocation.ResamplingType; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory; import org.esa.snap.core.gpf.descriptor.OperatorDescriptor; import org.esa.snap.core.gpf.descriptor.PropertySetDescriptorFactory; import org.esa.snap.graphbuilder.gpf.ui.BaseOperatorUI; import org.esa.snap.graphbuilder.gpf.ui.UIValidation; import org.esa.snap.ui.AppContext; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import java.awt.GridLayout; import java.util.Map; /** * Created by obarrile on 23/04/2019. */ public class CollocationUI extends BaseOperatorUI { private final JComboBox<String> masterCombo = new JComboBox<>(); private final JComboBox<ResamplingType> resampleTypeCombo = new JComboBox<>(); private final JTextField productTypeField = new JTextField("COLLOCATED"); private final JTextField slavePatternField = new JTextField("${ORIGINAL_NAME}_S${SLAVE_NUMBER_ID}"); private final JTextField masterPatternField = new JTextField("${ORIGINAL_NAME}_M"); private JCheckBox copySecMetadataCheckBox; private JCheckBox renameMasterCheckBox; private JCheckBox renameSlaveCheckBox; @Override public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) { OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(operatorName); if (operatorSpi == null) { throw new IllegalArgumentException("No SPI found for operator name '" + operatorName + "'"); } initializeOperatorUI(operatorName, parameterMap); final JComponent panel = createPanel(); initParameters(); return new JScrollPane(panel); } @Override public void initParameters() { for (ResamplingType resamplingType : ResamplingType.values()) { resampleTypeCombo.addItem(resamplingType); } } @Override public UIValidation validateParameters() { return new UIValidation(UIValidation.State.OK, ""); } @Override public void updateParameters() { String masterNameSelected = (String) masterCombo.getSelectedItem(); if (hasSourceProducts()) { masterCombo.removeAllItems(); for (Product product : sourceProducts) { if (!product.isMultiSize()) { masterCombo.addItem(product.getName()); } } if (masterCombo.getItemCount() > 0) { masterCombo.setSelectedItem(masterCombo.getItemAt(0)); } } if (masterNameSelected != null && masterNameSelected.length() > 0) { masterCombo.setSelectedItem(masterNameSelected); } paramMap.clear(); paramMap.put("referenceProductName", masterCombo.getSelectedItem()); paramMap.put("targetProductName", "_collocated"); paramMap.put("targetProductType", productTypeField.getText()); paramMap.put("copySecondaryMetadata", copySecMetadataCheckBox.isSelected()); paramMap.put("renameReferenceComponents", renameMasterCheckBox.isSelected()); paramMap.put("renameSecondaryComponents", renameSlaveCheckBox.isSelected()); paramMap.put("referenceComponentPattern", masterPatternField.getText()); paramMap.put("secondaryComponentPattern", slavePatternField.getText()); paramMap.put("resamplingType", resampleTypeCombo.getSelectedItem()); } protected void initializeOperatorUI(final String operatorName, final Map<String, Object> parameterMap) { this.operatorName = operatorName; this.paramMap = parameterMap; final OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(operatorName); if (operatorSpi == null) { throw new IllegalArgumentException("operator " + operatorName + " not found"); } final ParameterDescriptorFactory descriptorFactory = new ParameterDescriptorFactory(); final OperatorDescriptor operatorDescriptor = operatorSpi.getOperatorDescriptor(); final PropertySetDescriptor propertySetDescriptor; try { propertySetDescriptor = PropertySetDescriptorFactory.createForOperator(operatorDescriptor, descriptorFactory.getSourceProductMap()); } catch (ConversionException e) { throw new IllegalStateException("Not able to init OperatorParameterSupport.", e); } propertySet = PropertyContainer.createMapBacked(paramMap, propertySetDescriptor); if (paramMap.isEmpty()) { try { propertySet.setDefaultValues(); } catch (IllegalStateException e) { // todo - handle exception here e.printStackTrace(); } } } private JComponent createPanel() { final TableLayout tableLayout = new TableLayout(1); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL); tableLayout.setTableWeightX(1.0); tableLayout.setTablePadding(4, 4); JPanel masterSelectionPanel = new JPanel(new GridLayout(1, 2)); PropertyDescriptor descriptorReferenceProductName = propertySet.getProperty("referenceProductName").getDescriptor(); JLabel masterSelectionLabel = new JLabel("Reference product name"); masterSelectionLabel.setToolTipText(descriptorReferenceProductName.getAttribute("description").toString()); masterSelectionPanel.add(masterSelectionLabel); masterSelectionPanel.add(masterCombo); JPanel productTypePanel = new JPanel(new GridLayout(1, 2)); PropertyDescriptor descriptorProductType = propertySet.getProperty("targetProductType").getDescriptor(); JLabel productTypeLabel = new JLabel(descriptorProductType.getAttribute("displayName").toString()); productTypeLabel.setToolTipText(descriptorProductType.getAttribute("description").toString()); productTypePanel.add(productTypeLabel); productTypePanel.add(productTypeField); JPanel secMetaPanel = new JPanel(new GridLayout(1, 1)); PropertyDescriptor descriptorSecMetadata = propertySet.getProperty("copySecondaryMetadata").getDescriptor(); copySecMetadataCheckBox = new JCheckBox(descriptorSecMetadata.getAttribute("displayName").toString()); copySecMetadataCheckBox.setSelected(true); copySecMetadataCheckBox.setToolTipText(descriptorProductType.getAttribute("description").toString()); secMetaPanel.add(copySecMetadataCheckBox); JPanel renameMasterPanel = new JPanel(new GridLayout(1, 1)); PropertyDescriptor descriptorRenameMaster = propertySet.getProperty("renameReferenceComponents").getDescriptor(); renameMasterCheckBox = new JCheckBox(descriptorRenameMaster.getAttribute("displayName").toString()); renameMasterCheckBox.setSelected(true); renameMasterCheckBox.setToolTipText(descriptorRenameMaster.getAttribute("description").toString()); renameMasterPanel.add(renameMasterCheckBox); JPanel renameSlavePanel = new JPanel(new GridLayout(1, 1)); PropertyDescriptor descriptorRenameSlave = propertySet.getProperty("renameSecondaryComponents").getDescriptor(); renameSlaveCheckBox = new JCheckBox(descriptorRenameSlave.getAttribute("displayName").toString()); renameSlaveCheckBox.setSelected(true); renameSlaveCheckBox.setToolTipText(descriptorRenameSlave.getAttribute("description").toString()); renameSlavePanel.add(renameSlaveCheckBox); JPanel masterPatternPanel = new JPanel(new GridLayout(1, 2)); PropertyDescriptor descriptorMasterPattern = propertySet.getProperty("referenceComponentPattern").getDescriptor(); JLabel masterPatternLabel = new JLabel(descriptorMasterPattern.getAttribute("displayName").toString()); masterPatternLabel.setToolTipText(descriptorMasterPattern.getAttribute("description").toString()); masterPatternPanel.add(masterPatternLabel); masterPatternPanel.add(masterPatternField); JPanel slavePatternPanel = new JPanel(new GridLayout(1, 2)); PropertyDescriptor descriptorSlavePattern = propertySet.getProperty("secondaryComponentPattern").getDescriptor(); JLabel slavePatternLabel = new JLabel(descriptorSlavePattern.getAttribute("displayName").toString()); slavePatternLabel.setToolTipText(descriptorSlavePattern.getAttribute("description").toString()); slavePatternPanel.add(slavePatternLabel); slavePatternPanel.add(slavePatternField); JPanel resampleTypePanel = new JPanel(new GridLayout(1, 2)); PropertyDescriptor descriptorResampleType = propertySet.getProperty("resamplingType").getDescriptor(); JLabel resampleTypeLabel = new JLabel(descriptorResampleType.getAttribute("displayName").toString()); resampleTypeLabel.setToolTipText(descriptorResampleType.getAttribute("description").toString()); resampleTypePanel.add(resampleTypeLabel); resampleTypePanel.add(resampleTypeCombo); final JPanel parametersPanel = new JPanel(tableLayout); parametersPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); parametersPanel.add(masterSelectionPanel); parametersPanel.add(secMetaPanel); parametersPanel.add(renameMasterPanel); parametersPanel.add(renameSlavePanel); parametersPanel.add(masterPatternPanel); parametersPanel.add(slavePatternPanel); parametersPanel.add(resampleTypePanel); parametersPanel.add(tableLayout.createVerticalSpacer()); return parametersPanel; } }
10,318
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
package-info.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-collocation-ui/src/main/java/org/esa/snap/collocation/docs/package-info.java
@HelpSetRegistration(helpSet = "help.hs", position = 4110) package org.esa.snap.collocation.docs; import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration;
161
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CollocationForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-collocation-ui/src/main/java/org/esa/snap/collocation/visat/CollocationForm.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.collocation.visat; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.binding.accessors.DefaultPropertyAccessor; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import org.esa.snap.collocation.ResamplingType; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.ui.SourceProductSelector; import org.esa.snap.core.gpf.ui.TargetProductSelector; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.product.SourceProductList; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import java.awt.BorderLayout; import java.awt.Insets; /** * Form for geographic collocation dialog. * * @author Ralf Quast * @version $Revision$ $Date$ */ class CollocationForm extends JPanel { private static final String DEFAULT_TARGET_PRODUCT_NAME = "collocate"; private final SourceProductSelector referenceProductSelector; private final SourceProductList secondaryProductList; private final JCheckBox copySecondaryMetadata; private final JCheckBox renameReferenceComponentsCheckBox; private final JCheckBox renameSecondaryComponentsCheckBox; private final JTextField referenceComponentPatternField; private final JTextField secondaryComponentPatternField; private final JComboBox<ResamplingType> resamplingComboBox; private final DefaultComboBoxModel<ResamplingType> resamplingComboBoxModel; private final TargetProductSelector targetProductSelector; private final BindingContext sbc; public CollocationForm(PropertySet propertySet, TargetProductSelector targetProductSelector, AppContext appContext) { this.targetProductSelector = targetProductSelector; referenceProductSelector = new SourceProductSelector(appContext, "Reference (pixel values are conserved):"); ListDataListener changeListener = new ListDataListener() { @Override public void contentsChanged(ListDataEvent event) { final Product[] sourceProducts = secondaryProductList.getSourceProducts(); propertySet.setValue("sourceProducts", sourceProducts); } @Override public void intervalAdded(ListDataEvent e) { contentsChanged(e); } @Override public void intervalRemoved(ListDataEvent e) { contentsChanged(e); } }; propertySet.addProperty(createTransientProperty("sourceProducts", Product[].class)); secondaryProductList = new SourceProductList(appContext); secondaryProductList.addChangeListener(changeListener); secondaryProductList.setXAxis(false); copySecondaryMetadata = new JCheckBox("Include metadata of secondary in result"); renameReferenceComponentsCheckBox = new JCheckBox("Rename reference components:"); renameSecondaryComponentsCheckBox = new JCheckBox("Rename secondary components:"); referenceComponentPatternField = new JTextField(); secondaryComponentPatternField = new JTextField(); resamplingComboBoxModel = new DefaultComboBoxModel<>(ResamplingType.values()); resamplingComboBox = new JComboBox<>(resamplingComboBoxModel); ListDataListener myListener = new ListDataListener() { @Override public void intervalAdded(ListDataEvent e) { contentsChanged(e); } @Override public void intervalRemoved(ListDataEvent e) { contentsChanged(e); } @Override public void contentsChanged(ListDataEvent e) { boolean validPixelExpressionUsed = false; for (Product product : secondaryProductList.getSourceProducts()){ if(isValidPixelExpressionUsed(product)) { validPixelExpressionUsed = true; break; } } adaptResamplingComboBoxModel(resamplingComboBoxModel, validPixelExpressionUsed); } }; secondaryProductList.addChangeListener(myListener); createComponents(); sbc = new BindingContext(propertySet); bindComponents(propertySet); } public void prepareShow() { referenceProductSelector.initProducts(); if (referenceProductSelector.getProductCount() > 0) { referenceProductSelector.setSelectedIndex(0); } } private static Property createTransientProperty(String name, Class type) { final DefaultPropertyAccessor defaultAccessor = new DefaultPropertyAccessor(); final PropertyDescriptor descriptor = new PropertyDescriptor(name, type); descriptor.setTransient(true); descriptor.setDefaultConverter(); return new Property(descriptor, defaultAccessor); } public void prepareHide() { referenceProductSelector.releaseProducts(); } Product getMasterProduct() { return referenceProductSelector.getSelectedProduct(); } String[] getSourceProductPaths() { final Property property = sbc.getPropertySet().getProperty("sourceProductPaths"); if (property != null) { return (String[]) property.getValue(); } return null; } Product[] getSlaveProducts() { return secondaryProductList.getSourceProducts(); } private void createComponents() { //setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); final TableLayout tableLayout = new TableLayout(1); tableLayout.setTableAnchor(TableLayout.Anchor.WEST); tableLayout.setTableFill(TableLayout.Fill.BOTH); tableLayout.setTableWeightX(1.0); tableLayout.setTableWeightY(0.0); tableLayout.setTablePadding(3, 3); setLayout(tableLayout); tableLayout.setRowWeightY(0, 1.0); setLayout(tableLayout); add(createSourceProductPanel()); add(createTargetProductPanel()); add(createRenamingPanel()); add(createResamplingPanel()); } private void bindComponents(PropertySet propertySet) { //final BindingContext sbc = new BindingContext(propertySet); sbc.bind("copySecondaryMetadata", copySecondaryMetadata); sbc.bind("renameReferenceComponents", renameReferenceComponentsCheckBox); sbc.bind("renameSecondaryComponents", renameSecondaryComponentsCheckBox); sbc.bind("referenceComponentPattern", referenceComponentPatternField); sbc.bind("secondaryComponentPattern", secondaryComponentPatternField); sbc.bind("resamplingType", resamplingComboBox); sbc.bind("sourceProductPaths", secondaryProductList); sbc.bindEnabledState("referenceComponentPattern", true, "renameReferenceComponents", true); sbc.bindEnabledState("secondaryComponentPattern", true, "renameSecondaryComponents", true); } private JPanel createSourceProductPanel() { final JPanel masterPanel = new JPanel(new BorderLayout(3, 3)); masterPanel.add(referenceProductSelector.getProductNameLabel(), BorderLayout.NORTH); referenceProductSelector.getProductNameComboBox().setPrototypeDisplayValue( "MER_RR__1PPBCM20030730_071000_000003972018_00321_07389_0000.N1"); masterPanel.add(referenceProductSelector.getProductNameComboBox(), BorderLayout.CENTER); masterPanel.add(referenceProductSelector.getProductFileChooserButton(), BorderLayout.EAST); JComponent[] panels = secondaryProductList.getComponents(); JPanel listPanel = new JPanel(new BorderLayout()); listPanel.add(panels[0], BorderLayout.CENTER); BorderLayout layout1 = new BorderLayout(); final JPanel slavePanel = new JPanel(layout1); slavePanel.setBorder(BorderFactory.createTitledBorder("Secondary Products")); slavePanel.add(listPanel, BorderLayout.CENTER); slavePanel.add(panels[1], BorderLayout.EAST); slavePanel.add(copySecondaryMetadata, BorderLayout.SOUTH); final TableLayout layout = new TableLayout(1); layout.setRowWeightX(0, 1.0); layout.setRowWeightX(1, 1.0); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableFill(TableLayout.Fill.HORIZONTAL); layout.setCellPadding(0, 0, new Insets(3, 3, 3, 3)); layout.setCellPadding(1, 0, new Insets(3, 3, 3, 3)); final JPanel panel = new JPanel(layout); panel.setBorder(BorderFactory.createTitledBorder("Source Products")); panel.add(masterPanel); panel.add(slavePanel); return panel; } private JPanel createTargetProductPanel() { targetProductSelector.getModel().setProductName(DEFAULT_TARGET_PRODUCT_NAME); return targetProductSelector.createDefaultPanel(); } private JPanel createRenamingPanel() { final TableLayout layout = new TableLayout(2); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableFill(TableLayout.Fill.HORIZONTAL); layout.setColumnWeightX(0, 0.0); layout.setColumnWeightX(1, 1.0); layout.setCellPadding(0, 0, new Insets(3, 3, 3, 3)); layout.setCellPadding(1, 0, new Insets(3, 3, 3, 3)); final JPanel panel = new JPanel(layout); panel.setBorder(BorderFactory.createTitledBorder("Renaming of Source Product Components")); panel.add(renameReferenceComponentsCheckBox); panel.add(referenceComponentPatternField); panel.add(renameSecondaryComponentsCheckBox); panel.add(secondaryComponentPatternField); return panel; } private JPanel createResamplingPanel() { final TableLayout layout = new TableLayout(3); layout.setTableAnchor(TableLayout.Anchor.LINE_START); layout.setTableFill(TableLayout.Fill.HORIZONTAL); layout.setColumnWeightX(0, 0.0); layout.setColumnWeightX(1, 0.0); layout.setColumnWeightX(2, 1.0); layout.setCellPadding(0, 0, new Insets(3, 3, 3, 3)); final JPanel panel = new JPanel(layout); panel.setBorder(BorderFactory.createTitledBorder("Resampling")); panel.add(new JLabel("Method:")); panel.add(resamplingComboBox); panel.add(new JLabel()); return panel; } static void adaptResamplingComboBoxModel(DefaultComboBoxModel<ResamplingType> comboBoxModel, boolean isValidPixelExpressionUsed) { if (isValidPixelExpressionUsed) { if (comboBoxModel.getSize() == 5) { comboBoxModel.removeElement(ResamplingType.BICUBIC_CONVOLUTION); comboBoxModel.removeElement(ResamplingType.BISINC_CONVOLUTION); comboBoxModel.removeElement(ResamplingType.CUBIC_CONVOLUTION); comboBoxModel.removeElement(ResamplingType.BILINEAR_INTERPOLATION); comboBoxModel.setSelectedItem(ResamplingType.NEAREST_NEIGHBOUR); } } else { if (comboBoxModel.getSize() == 1) { comboBoxModel.addElement(ResamplingType.BILINEAR_INTERPOLATION); comboBoxModel.addElement(ResamplingType.CUBIC_CONVOLUTION); comboBoxModel.addElement(ResamplingType.BICUBIC_CONVOLUTION); comboBoxModel.addElement(ResamplingType.BISINC_CONVOLUTION); } } } static boolean isValidPixelExpressionUsed(Product product) { if (product != null) { for (final Band band : product.getBands()) { final String expression = band.getValidPixelExpression(); if (expression != null && !expression.trim().isEmpty()) { return true; } } } return false; } }
12,941
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CollocationAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-collocation-ui/src/main/java/org/esa/snap/collocation/visat/CollocationAction.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.collocation.visat; import org.esa.snap.rcp.actions.AbstractSnapAction; import org.esa.snap.ui.ModelessDialog; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.NbBundle; import java.awt.event.ActionEvent; /** * Geographic collocation action. * * @author Ralf Quast * @author Marco Peters */ @ActionID(category = "Processors", id = "org.esa.snap.collocation.visat.CollocationAction") @ActionRegistration(displayName = "#CTL_CollocationAction_Text", lazy = false) @ActionReference(path = "Menu/Raster/Geometric", position = 50) @NbBundle.Messages({ "CTL_CollocationAction_Text=Collocation", "CTL_CollocationAction_Description=Geographic collocation of two data products." }) public class CollocationAction extends AbstractSnapAction { private ModelessDialog dialog; public CollocationAction() { putValue(NAME, Bundle.CTL_CollocationAction_Text()); putValue(SHORT_DESCRIPTION, Bundle.CTL_CollocationAction_Description()); setHelpId(CollocationDialog.HELP_ID); } @Override public void actionPerformed(ActionEvent e) { if (dialog == null) { dialog = new CollocationDialog(getAppContext()); } dialog.show(); } }
2,051
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CollocationDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-collocation-ui/src/main/java/org/esa/snap/collocation/visat/CollocationDialog.java
/* * Copyright (C) 2014 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.collocation.visat; import org.esa.snap.collocation.CollocateOp; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.gpf.ui.OperatorMenu; import org.esa.snap.core.gpf.ui.OperatorParameterSupport; import org.esa.snap.core.gpf.ui.SingleTargetProductDialog; import org.esa.snap.ui.AppContext; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * @author Ralf Quast */ class CollocationDialog extends SingleTargetProductDialog { public static final String HELP_ID = "collocation"; private final OperatorParameterSupport parameterSupport; private final CollocationForm form; public CollocationDialog(AppContext appContext) { super(appContext, "Collocation", ID_APPLY_CLOSE, HELP_ID); final OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(CollocateOp.Spi.class.getName()); parameterSupport = new OperatorParameterSupport(operatorSpi.getOperatorDescriptor()); OperatorMenu operatorMenu = new OperatorMenu(this.getJDialog(), operatorSpi.getOperatorDescriptor(), parameterSupport, appContext, HELP_ID); getJDialog().setJMenuBar(operatorMenu.createDefaultMenu()); form = new CollocationForm(parameterSupport.getPropertySet(), getTargetProductSelector(), appContext); } @Override protected Product createTargetProduct() throws Exception { final Map<String, Product> productMap = new LinkedHashMap<String, Product>(5); productMap.put("reference", form.getMasterProduct()); for (int i = 0 ; i < form.getSlaveProducts().length ; i++) { productMap.put(String.format("secondary%d",i), form.getSlaveProducts()[i]); } parameterSupport.getParameterMap().put("referenceProductName",form.getMasterProduct().getName()); parameterSupport.getParameterMap().put("sourceProductPaths",form.getSourceProductPaths()); return GPF.createProduct(OperatorSpi.getOperatorAlias(CollocateOp.class), parameterSupport.getParameterMap(), productMap); } @Override public int show() { form.prepareShow(); setContent(form); return super.show(); } @Override public void hide() { form.prepareHide(); super.hide(); } }
3,359
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
EditRemoteMachineCredentialsDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/machines/EditRemoteMachineCredentialsDialog.java
package org.esa.snap.remote.execution.machines; import org.apache.commons.lang3.StringUtils; import org.esa.snap.ui.loading.AbstractModalDialog; import org.esa.snap.ui.loading.LabelListCellRenderer; import org.esa.snap.ui.loading.LoadingIndicator; import org.esa.snap.ui.loading.SwingUtils; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionListener; /** * Created by jcoravu on 17/12/2018. */ public class EditRemoteMachineCredentialsDialog extends AbstractModalDialog { private final RemoteMachineProperties remoteMachineCredentialsToEdit; private JTextField hostNameTextField; private JTextField portNumberTextField; private JTextField usernameTextField; private JPasswordField passwordTextField; private JComboBox<String> operatingSystemsComboBox; private JTextField sharedFolderPathTextField; private JTextField gptFilePathTextField; private JLabel sharedFolderPathLabel; public EditRemoteMachineCredentialsDialog(Window parent, RemoteMachineProperties remoteMachineCredentialsToEdit) { super(parent, "Remote machine", true, null); this.remoteMachineCredentialsToEdit = remoteMachineCredentialsToEdit; } @Override protected void onAboutToShow() { Dimension size = getJDialog().getPreferredSize(); getJDialog().setMinimumSize(size); } @Override protected JPanel buildContentPanel(int gapBetweenColumns, int gapBetweenRows) { Insets defaultTextFieldMargins = buildDefaultTextFieldMargins(); Insets defaultListItemMargins = buildDefaultListItemMargins(); createComponents(defaultTextFieldMargins, defaultListItemMargins); JButton testConnectionButton = new JButton("Test connection"); testConnectionButton.setFocusable(false); testConnectionButton.addActionListener(event -> testConnectionButtonPressed()); JPanel contentPanel = new JPanel(new GridBagLayout()); GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, 0, 0); contentPanel.add(new JLabel("Host name"), c); c = SwingUtils.buildConstraints(1, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns); contentPanel.add(this.hostNameTextField, c); c = SwingUtils.buildConstraints(0, 1, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); contentPanel.add(new JLabel("Port number"), c); c = SwingUtils.buildConstraints(1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); contentPanel.add(this.portNumberTextField, c); c = SwingUtils.buildConstraints(0, 2, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); contentPanel.add(new JLabel("Operating system"), c); c = SwingUtils.buildConstraints(1, 2, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); contentPanel.add(this.operatingSystemsComboBox, c); c = SwingUtils.buildConstraints(0, 3, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); contentPanel.add(new JLabel("Username"), c); c = SwingUtils.buildConstraints(1, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); contentPanel.add(this.usernameTextField, c); c = SwingUtils.buildConstraints(0, 4, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); contentPanel.add(new JLabel("Password"), c); c = SwingUtils.buildConstraints(1, 4, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); contentPanel.add(this.passwordTextField, c); c = SwingUtils.buildConstraints(0, 5, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); contentPanel.add(new JLabel("GPT file path"), c); c = SwingUtils.buildConstraints(1, 5, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); contentPanel.add(this.gptFilePathTextField, c); c = SwingUtils.buildConstraints(0, 6, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); contentPanel.add(this.sharedFolderPathLabel, c); c = SwingUtils.buildConstraints(1, 6, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); contentPanel.add(this.sharedFolderPathTextField, c); c = SwingUtils.buildConstraints(1, 7, GridBagConstraints.NONE, GridBagConstraints.EAST, 1, 1, gapBetweenRows, 0); contentPanel.add(testConnectionButton, c); c = SwingUtils.buildConstraints(1, 8, GridBagConstraints.BOTH, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns); contentPanel.add(new JLabel(), c); computePanelFirstColumn(contentPanel); if (this.remoteMachineCredentialsToEdit != null) { this.hostNameTextField.setText(this.remoteMachineCredentialsToEdit.getHostName()); this.portNumberTextField.setText(Integer.toString(this.remoteMachineCredentialsToEdit.getPortNumber())); this.operatingSystemsComboBox.setSelectedItem(this.remoteMachineCredentialsToEdit.getOperatingSystemName()); this.usernameTextField.setText(this.remoteMachineCredentialsToEdit.getUsername()); this.passwordTextField.setText(this.remoteMachineCredentialsToEdit.getPassword()); this.gptFilePathTextField.setText(this.remoteMachineCredentialsToEdit.getGPTFilePath()); this.sharedFolderPathTextField.setText(this.remoteMachineCredentialsToEdit.getSharedFolderPath()); } return contentPanel; } @Override protected JPanel buildButtonsPanel(ActionListener cancelActionListener) { ActionListener okActionListener = event -> okButtonPressed(); return buildButtonsPanel("Ok", okActionListener, "Cancel", cancelActionListener); } protected void successfullyCloseDialog(RemoteMachineProperties oldSSHServerCredentials, RemoteMachineProperties newSSHServerCredentials) { getJDialog().dispose(); } private String getLinuxSharedFolderPathLabelText() { return "Shared folder path"; } private String getWindowsSharedFolderPathLabelText() { return "Shared drive"; } private void createComponents(Insets defaultTextFieldMargins, Insets defaultListItemMargins) { this.hostNameTextField = new JTextField(); this.hostNameTextField.setMargin(defaultTextFieldMargins); this.hostNameTextField.setColumns(30); this.sharedFolderPathTextField = new JTextField(); this.sharedFolderPathTextField.setMargin(defaultTextFieldMargins); this.sharedFolderPathLabel = new JLabel(getLinuxSharedFolderPathLabelText()); this.portNumberTextField = new JTextField(); this.portNumberTextField.setMargin(defaultTextFieldMargins); this.operatingSystemsComboBox = new JComboBox<>(); this.operatingSystemsComboBox.setPreferredSize(this.hostNameTextField.getPreferredSize()); this.operatingSystemsComboBox.addItem(RemoteMachineProperties.LINUX_OPERATING_SYSTEM); this.operatingSystemsComboBox.addItem(RemoteMachineProperties.WINDOWS_OPERATING_SYSTEM); this.operatingSystemsComboBox.setSelectedItem(null); LabelListCellRenderer<String> renderer = new LabelListCellRenderer<>(defaultListItemMargins) { @Override protected String getItemDisplayText(String value) { return value; } }; this.operatingSystemsComboBox.setRenderer(renderer); this.operatingSystemsComboBox.setBackground(new Color(0, 0, 0, 0)); // set the transparent color this.operatingSystemsComboBox.setOpaque(true); this.operatingSystemsComboBox.addItemListener(event -> operatingSystemSelected()); this.usernameTextField = new JTextField(); this.usernameTextField.setMargin(defaultTextFieldMargins); this.gptFilePathTextField = new JTextField(); this.gptFilePathTextField.setMargin(defaultTextFieldMargins); this.passwordTextField = new JPasswordField(); this.passwordTextField.setMargin(defaultTextFieldMargins); } private void operatingSystemSelected() { String selectedOperatingSystemName = (String) operatingSystemsComboBox.getSelectedItem(); if (RemoteMachineProperties.LINUX_OPERATING_SYSTEM.equals(selectedOperatingSystemName)) { this.sharedFolderPathLabel.setText(getLinuxSharedFolderPathLabelText()); } else if (RemoteMachineProperties.WINDOWS_OPERATING_SYSTEM.equals(selectedOperatingSystemName)) { this.sharedFolderPathLabel.setText(getWindowsSharedFolderPathLabelText()); } else { throw new IllegalStateException("Unknown operating system name '" + selectedOperatingSystemName + "'."); } } private void okButtonPressed() { RemoteMachineProperties sshServerCredentials = buildRemoteMachineCredentialsItem(true); if (sshServerCredentials != null) { successfullyCloseDialog(this.remoteMachineCredentialsToEdit, sshServerCredentials); } } private void testConnectionButtonPressed() { RemoteMachineProperties sshServerCredentials = buildRemoteMachineCredentialsItem(false); if (sshServerCredentials != null) { LoadingIndicator loadingIndicator = getLoadingIndicator(); int threadId = getNewCurrentThreadId(); TestConnectionTimerRunnable runnable = new TestConnectionTimerRunnable(this, loadingIndicator, threadId, sshServerCredentials); runnable.executeAsync(); } } private RemoteMachineProperties buildRemoteMachineCredentialsItem(boolean validateSharedFolderPath) { RemoteMachineProperties remoteMachineCredentials = null; String hostName = this.hostNameTextField.getText(); String portNumberAsString = this.portNumberTextField.getText(); String username = this.usernameTextField.getText(); String password = new String(this.passwordTextField.getPassword()); String operatingSystemName = (String)this.operatingSystemsComboBox.getSelectedItem(); String sharedFolderPath = this.sharedFolderPathTextField.getText(); if (StringUtils.isBlank(hostName)) { showErrorDialog("Enter the host name."); this.hostNameTextField.requestFocus(); } else if (StringUtils.isBlank(portNumberAsString)) { showErrorDialog("Enter the port number."); this.portNumberTextField.requestFocus(); } else { // check if the port number is valid Integer portNumber; try { portNumber = Integer.parseInt(portNumberAsString); } catch (NumberFormatException exception) { portNumber = null; } if (portNumber == null) { showErrorDialog("The port number is not valid."); this.portNumberTextField.requestFocus(); } else { if (StringUtils.isBlank(operatingSystemName)) { showErrorDialog("Select the operating system."); this.operatingSystemsComboBox.requestFocus(); } else if (StringUtils.isBlank(username)) { showErrorDialog("Enter the username."); this.usernameTextField.requestFocus(); } else if (StringUtils.isBlank(password)) { showErrorDialog("Enter the password."); this.passwordTextField.requestFocus(); } else if (validateSharedFolderPath && StringUtils.isBlank(sharedFolderPath)) { String message; if (operatingSystemName.equals(RemoteMachineProperties.LINUX_OPERATING_SYSTEM)) { message = "Enter the shared folder path."; } else if (operatingSystemName.equals(RemoteMachineProperties.WINDOWS_OPERATING_SYSTEM)) { message = "Enter the shared drive."; } else { throw new IllegalStateException("Unknown operating system name '" + operatingSystemName + "'."); } showErrorDialog(message); this.sharedFolderPathTextField.requestFocus(); } else { remoteMachineCredentials = new RemoteMachineProperties(hostName, portNumber, username, password, operatingSystemName, sharedFolderPath); remoteMachineCredentials.setGPTFilePath(this.gptFilePathTextField.getText()); } } } return remoteMachineCredentials; } }
13,270
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TestConnectionTimerRunnable.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/machines/TestConnectionTimerRunnable.java
package org.esa.snap.remote.execution.machines; import org.esa.snap.remote.execution.utils.CommandExecutorUtils; import org.esa.snap.ui.loading.AbstractTimerRunnable; import org.esa.snap.ui.loading.GenericRunnable; import org.esa.snap.ui.loading.LoadingIndicator; import org.esa.snap.ui.loading.MessageDialog; import javax.swing.SwingUtilities; /** * Created by jcoravu on 18/12/2018. */ public class TestConnectionTimerRunnable extends AbstractTimerRunnable<RemoteMachineConnectionResult> { private final MessageDialog parentWindow; private final RemoteMachineProperties sshServer; private String loadingIndicatorMessage; public TestConnectionTimerRunnable(MessageDialog parentWindow, LoadingIndicator loadingIndicator, int threadId, RemoteMachineProperties sshServerCredentials) { super(loadingIndicator, threadId, 500); this.parentWindow = parentWindow; this.sshServer = sshServerCredentials; this.loadingIndicatorMessage = "Testing connection..."; } @Override protected void onTimerWakeUp(String messageToDisplay) { super.onTimerWakeUp(this.loadingIndicatorMessage); this.loadingIndicatorMessage = null; // reset the message } @Override protected RemoteMachineConnectionResult execute() throws Exception { ITestRemoteMachineConnection callback = new ITestRemoteMachineConnection() { @Override public void testSSHConnection() { displayLoadingIndicatorMessageLater("Testing connection..."); } @Override public void testGPTApplication() { displayLoadingIndicatorMessageLater("Testing GPT application..."); } }; return CommandExecutorUtils.canConnectToRemoteMachine(this.sshServer, callback); } @Override protected String getExceptionLoggingMessage() { return "Failed to connect to the remote machine '" + this.sshServer.getHostName()+"'."; } @Override protected void onFailed(Exception exception) { this.parentWindow.showErrorDialog("Failed to connect to the remote machine."); } @Override protected void onSuccessfullyFinish(RemoteMachineConnectionResult result) { if (result.isRemoteMachineAvailable()) { StringBuilder message = new StringBuilder(); message.append("The connection to the remote machine is successfully.") .append("\n\n"); if (result.isGPTApplicationAvailable()) { message.append("The GPT application is available on the remote machine."); this.parentWindow.showInformationDialog(message.toString()); } else { message.append("The GPT application is not available on the remote machine."); this.parentWindow.showErrorDialog(message.toString()); } } else { this.parentWindow.showErrorDialog("The connection to the remote machine has failed."); } } private void displayLoadingIndicatorMessageLater(String messageToDisplay) { GenericRunnable<String> runnable = new GenericRunnable<String>(messageToDisplay) { @Override protected void execute(String message) { onDisplayMessage(message); } }; SwingUtilities.invokeLater(runnable); } private void onDisplayMessage(String messageToDisplay) { if (this.loadingIndicatorMessage == null) { // the timer is has been activated onDisplayLoadingIndicatorMessage(messageToDisplay); } else { this.loadingIndicatorMessage = messageToDisplay; } } }
3,722
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
package-info.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/docs/package-info.java
/* * Copyright (C) 2015-2016 CS-Romania ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ /** * Created by dmihailescu on 08/11/2016. */ @HelpSetRegistration(helpSet = "help.hs", position = 5432) package org.esa.snap.remote.execution.docs; import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration;
918
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
RemoteExecutionDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/operator/RemoteExecutionDialog.java
package org.esa.snap.remote.execution.operator; import com.bc.ceres.binding.ConversionException; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.ValueSet; import com.bc.ceres.binding.dom.DomElement; import com.bc.ceres.swing.binding.Binding; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.internal.ListSelectionAdapter; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.esa.snap.core.dataio.ProductIO; import org.esa.snap.core.dataio.ProductIOPlugInManager; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.Operator; import org.esa.snap.core.gpf.OperatorException; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.gpf.descriptor.OperatorDescriptor; import org.esa.snap.core.gpf.ui.OperatorMenu; import org.esa.snap.core.gpf.ui.OperatorParameterSupport; import org.esa.snap.core.gpf.ui.ParameterUpdater; import org.esa.snap.core.gpf.ui.TargetProductSelectorModel; import org.esa.snap.rcp.actions.file.SaveProductAsAction; import org.esa.snap.remote.execution.RemoteExecutionOp; import org.esa.snap.remote.execution.converters.RemoteMachinePropertiesConverter; import org.esa.snap.remote.execution.converters.SourceProductFilesConverter; import org.esa.snap.remote.execution.local.folder.IMountLocalSharedFolderCallback; import org.esa.snap.remote.execution.local.folder.IMountLocalSharedFolderResult; import org.esa.snap.remote.execution.local.folder.IUnmountLocalSharedFolderCallback; import org.esa.snap.remote.execution.machines.EditRemoteMachineCredentialsDialog; import org.esa.snap.remote.execution.machines.RemoteMachineProperties; import org.esa.snap.remote.execution.topology.LinuxRemoteTopologyPanel; import org.esa.snap.remote.execution.topology.MacRemoteTopologyPanel; import org.esa.snap.remote.execution.topology.ReadRemoteTopologyTimerRunnable; import org.esa.snap.remote.execution.topology.RemoteTopology; import org.esa.snap.remote.execution.topology.RemoteTopologyPanel; import org.esa.snap.remote.execution.topology.WindowsRemoteTopologyPanel; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.loading.AbstractModalDialog; import org.esa.snap.ui.loading.CustomFileChooser; import org.esa.snap.ui.loading.LabelListCellRenderer; import org.esa.snap.ui.loading.LoadingIndicator; import org.esa.snap.ui.loading.SwingUtils; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListModel; import javax.swing.border.TitledBorder; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionListener; import java.io.File; import java.lang.reflect.Array; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by jcoravu on 24/12/2018. */ public class RemoteExecutionDialog extends AbstractModalDialog { private static final String SOURCE_PRODUCT_FILES_PROPERTY = "sourceProductFiles"; private static final String REMOTE_MACHINES_PROPERTY = "remoteMachines"; private static final String REMOTE_SHARED_FOLDER_PATH_PROPERTY = "remoteSharedFolderPath"; private static final String REMOTE_SHARED_FOLDER_USERNAME_PROPERTY = "remoteSharedFolderUsername"; private static final String REMOTE_SHARED_FOLDER_PASSWORD_PROPERTY = "remoteSharedFolderPassword"; public static final String LOCAL_SHARED_FOLDER_PATH_PROPERTY = "localSharedFolderPath"; public static final String LOCAL_PASSWORD_PROPERTY = "localPassword"; private static final String SLAVE_GRAPH_FILE_PATH_PROPERTY = "slaveGraphFilePath"; private static final String SLAVE_PRODUCTS_FORMAT_NAME_PROPERTY = "slaveProductsFormatName"; private static final String MASTER_GRAPH_FILE_PATH_PROPERTY = "masterGraphFilePath"; private static final String MASTER_PRODUCT_FILE_PATH_PROPERTY = "masterProductFilePath"; private static final String MASTER_PRODUCT_FOLDER_PATH_PROPERTY = "masterProductFolderPath"; private static final String MASTER_PRODUCT_FILE_NAME_PROPERTY = "masterProductFileName"; private static final String MASTER_PRODUCT_FORMAT_NAME_PROPERTY = "masterProductFormatName"; private static final String CONTINUE_ON_FAILURE_NAME_PROPERTY = "continueOnFailure"; private static final String CAN_SAVE_TARGET_PRODUCT_PROPERTY = "canSaveTargetProduct"; private static final String OPEN_TARGET_PRODUCT_PROPERTY = "openTargetProduct"; private final AppContext appContext; private final BindingContext bindingContext; private final OperatorParameterSupport parameterSupport; private JTextField slaveGraphFilePathTextField; private JTextField masterGraphFilePathTextField; private JList<String> sourceProductsList; private RemoteTopologyPanel remoteTopologyPanel; private JCheckBox continueOnFailureCheckBox; private IMountLocalSharedFolderResult mountLocalSharedFolderResult; private JCheckBox canSaveTargetProductCheckBox; private JCheckBox openTargetProductCheckBox; private JTextField masterProductFolderPathTextField; private JTextField masterProductNameTextField; private JComboBox<String> slaveProductsFormatNameComboBox; private JComboBox<String> masterProductFormatNameComboBox; private List<JComponent> masterProductEnabledComponents; private Path lastSelectedFolderPath; public RemoteExecutionDialog(AppContext appContext, Window parent) { super(parent, "Remote execution", false, "remoteExecutionProcessor"); this.appContext = appContext; String operatorName = OperatorSpi.getOperatorAlias(RemoteExecutionOp.class); OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(operatorName); if (operatorSpi == null) { throw new IllegalArgumentException("No SPI found for operator name '" + operatorName + "'."); } ParameterUpdater parameterUpdater = new ParameterUpdater() { @Override public void handleParameterSaveRequest(Map<String, Object> parameterMap) { // do nothing } @Override public void handleParameterLoadRequest(Map<String, Object> parameterMap) { // set the source products String[] files = (String[]) parameterMap.get(SOURCE_PRODUCT_FILES_PROPERTY); if (files == null) { files = new String[0]; } setListItems(files, SOURCE_PRODUCT_FILES_PROPERTY); // set the remote machines RemoteMachineProperties[] remoteMachines = (RemoteMachineProperties[]) parameterMap.get(REMOTE_MACHINES_PROPERTY); if (remoteMachines == null) { remoteMachines = new RemoteMachineProperties[0]; } setListItems(remoteMachines, REMOTE_MACHINES_PROPERTY); // refresh the target product components refreshTargetProductEnabledComponents(); Boolean canSaveTargetProduct = (Boolean) parameterMap.get(CAN_SAVE_TARGET_PRODUCT_PROPERTY); if (canSaveTargetProduct != null && canSaveTargetProduct) { refreshOpenTargetProductSelectedState(); } } }; Map<String, Object> parameterMap = new HashMap<>(); PropertySet propertySet = PropertyContainer.createMapBacked(parameterMap, CloudExploitationPlatformItem.class); propertySet.getDescriptor(REMOTE_MACHINES_PROPERTY).setConverter(new RemoteMachinePropertiesConverter()); propertySet.getDescriptor(SOURCE_PRODUCT_FILES_PROPERTY).setConverter(new SourceProductFilesConverter()); propertySet.setDefaultValues(); propertySet.addPropertyChangeListener(evt -> { String propertyName = evt.getPropertyName(); if (propertyName.equals(CAN_SAVE_TARGET_PRODUCT_PROPERTY)) { refreshTargetProductEnabledComponents(); Boolean selected = (Boolean) evt.getNewValue(); if (selected) { refreshOpenTargetProductSelectedState(); } } else if (propertyName.equals(MASTER_PRODUCT_FORMAT_NAME_PROPERTY)) { refreshOpenTargetProductEnabledState(); refreshOpenTargetProductSelectedState(); } }); OperatorDescriptor baseOperatorDescriptor = operatorSpi.getOperatorDescriptor(); OperatorDescriptor operatorDescriptor = new OperatorDescriptorWrapperImpl(baseOperatorDescriptor); this.parameterSupport = new OperatorParameterSupport(operatorDescriptor, propertySet, parameterMap, parameterUpdater) { @Override public void fromDomElement(DomElement parametersElement) throws ValidationException, ConversionException { Property remoteMachinesProperty = getPropertySet().getProperty(REMOTE_MACHINES_PROPERTY); remoteMachinesProperty.getDescriptor().setValueSet(new EmptyValueSetExtended(new RemoteMachineProperties[0])); Property sourceProductFilesProperty = getPropertySet().getProperty(SOURCE_PRODUCT_FILES_PROPERTY); sourceProductFilesProperty.getDescriptor().setValueSet(new EmptyValueSetExtended(new String[0])); try { super.fromDomElement(parametersElement); } finally { RemoteMachineProperties[] remoteMachines = (RemoteMachineProperties[]) getParameterMap().get(REMOTE_MACHINES_PROPERTY); if (remoteMachines == null) { remoteMachines = new RemoteMachineProperties[0]; } remoteMachinesProperty.getDescriptor().setValueSet(new ValueSet(remoteMachines)); String[] sourceProductFiles = (String[]) getParameterMap().get(SOURCE_PRODUCT_FILES_PROPERTY); if (sourceProductFiles == null) { sourceProductFiles = new String[0]; } sourceProductFilesProperty.getDescriptor().setValueSet(new ValueSet(sourceProductFiles)); } } }; this.bindingContext = new BindingContext(this.parameterSupport.getPropertySet()); JDialog dialog = getJDialog(); OperatorMenu operatorMenu = new OperatorMenu(dialog, operatorDescriptor, this.parameterSupport, appContext, getHelpID()); dialog.setJMenuBar(operatorMenu.createDefaultMenu()); } @Override protected void onAboutToShow() { JDialog dialog = getJDialog(); dialog.setMinimumSize(new Dimension(650, 590)); LoadingIndicator loadingIndicator = getLoadingIndicator(); int threadId = getNewCurrentThreadId(); Path remoteTopologyFilePath = getRemoteTopologyFilePath(); ReadRemoteTopologyTimerRunnable runnable = new ReadRemoteTopologyTimerRunnable(this, loadingIndicator, threadId, remoteTopologyFilePath) { @Override protected void onSuccessfullyFinish(RemoteTopology remoteTopology) { onFinishReadingRemoteTopoloy(remoteTopology); } }; runnable.executeAsync(); } @Override protected void registerEscapeKey(ActionListener cancelActionListener) { // do nothing } private static String[] getAvailableFormatNames() { String[] formatNames = ProductIOPlugInManager.getInstance().getAllProductWriterFormatStrings(); if (formatNames.length > 1) { List<String> items = new ArrayList<>(formatNames.length); Collections.addAll(items, formatNames); Comparator<String> comparator = String::compareTo; Collections.sort(items, comparator); items.toArray(formatNames); } return formatNames; } @Override protected void setEnabledComponentsWhileLoading(boolean enabled) { super.setEnabledComponentsWhileLoading(enabled); refreshTargetProductEnabledComponents(); } private static JComboBox<String> buildProductFormatNamesComboBox(Insets defaultListItemMargins, int textFieldPreferredHeight, String[] availableFormatNames) { JComboBox<String> productFormatNameComboBox = new JComboBox<>(availableFormatNames); Dimension formatNameComboBoxSize = productFormatNameComboBox.getPreferredSize(); formatNameComboBoxSize.height = textFieldPreferredHeight; productFormatNameComboBox.setPreferredSize(formatNameComboBoxSize); productFormatNameComboBox.setMinimumSize(formatNameComboBoxSize); LabelListCellRenderer<String> renderer = new LabelListCellRenderer<>(defaultListItemMargins) { @Override protected String getItemDisplayText(String value) { return value; } }; productFormatNameComboBox.setMaximumRowCount(5); productFormatNameComboBox.setRenderer(renderer); productFormatNameComboBox.setBackground(new Color(0, 0, 0, 0)); // set the transparent color productFormatNameComboBox.setOpaque(true); return productFormatNameComboBox; } @Override protected JPanel buildContentPanel(int gapBetweenColumns, int gapBetweenRows) { Insets defaultTextFieldMargins = buildDefaultTextFieldMargins(); Insets defaultListItemMargins = buildDefaultListItemMargins(); this.slaveGraphFilePathTextField = new JTextField(); this.slaveGraphFilePathTextField.setMargin(defaultTextFieldMargins); this.bindingContext.bind(SLAVE_GRAPH_FILE_PATH_PROPERTY, this.slaveGraphFilePathTextField); this.continueOnFailureCheckBox = new JCheckBox("Continue when a remote execution fails"); this.continueOnFailureCheckBox.setMargin(new Insets(0, 0, 0, 0)); this.continueOnFailureCheckBox.setFocusable(false); Binding canContinueOnFailureBinding = this.bindingContext.bind(CONTINUE_ON_FAILURE_NAME_PROPERTY, this.continueOnFailureCheckBox); canContinueOnFailureBinding.setPropertyValue(this.continueOnFailureCheckBox.isSelected()); int textFieldPreferredHeight = this.slaveGraphFilePathTextField.getPreferredSize().height; createRemoteTopologyPanel(defaultTextFieldMargins, defaultListItemMargins, textFieldPreferredHeight, gapBetweenColumns, gapBetweenRows); String[] formatNames = getAvailableFormatNames(); JPanel inputPanel = buildInputPanel(gapBetweenColumns, gapBetweenRows, textFieldPreferredHeight, defaultListItemMargins, formatNames); JPanel outputMasterProductPanel = buildOutputMasterProductPanel(gapBetweenColumns, gapBetweenRows, defaultTextFieldMargins, defaultListItemMargins, textFieldPreferredHeight, formatNames); JPanel contentPanel = new JPanel(new GridBagLayout()); GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.BOTH, GridBagConstraints.NORTHWEST, 1, 1, 0, 0); contentPanel.add(this.remoteTopologyPanel, c); c = SwingUtils.buildConstraints(0, 2, GridBagConstraints.BOTH, GridBagConstraints.NORTHWEST, 1, 1, gapBetweenRows, 0); contentPanel.add(inputPanel, c); c = SwingUtils.buildConstraints(0, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.NORTHWEST, 1, 1, gapBetweenRows, 0); contentPanel.add(outputMasterProductPanel, c); computePanelFirstColumn(contentPanel); return contentPanel; } public void setData(List<File> sourceProductFiles, File slaveGraphFile, String slaveProductsFormaName) { String[] sourceFiles = new String[sourceProductFiles.size()]; int i = 0; for (final File file : sourceProductFiles){ sourceFiles[i] = file.getPath(); ++i; } setListItems(sourceFiles, SOURCE_PRODUCT_FILES_PROPERTY); setPropertyValue(slaveGraphFile.getPath(), SLAVE_GRAPH_FILE_PATH_PROPERTY); setPropertyValue(slaveProductsFormaName, SLAVE_PRODUCTS_FORMAT_NAME_PROPERTY); } @Override public void close() { if (this.mountLocalSharedFolderResult == null) { super.close(); } else { LoadingIndicator loadingIndicator = getLoadingIndicator(); int threadId = getNewCurrentThreadId(); IUnmountLocalSharedFolderCallback callback = exception -> { RemoteExecutionDialog.this.mountLocalSharedFolderResult = null; RemoteExecutionDialog.super.close(); }; this.mountLocalSharedFolderResult.unmountLocalSharedFolderAsync(loadingIndicator, threadId, callback); } } private void addServerCredentialsButtonPressed() { EditRemoteMachineCredentialsDialog dialog = new EditRemoteMachineCredentialsDialog(getJDialog(), null) { @Override protected void successfullyCloseDialog(RemoteMachineProperties oldSSHServerCredentials, RemoteMachineProperties newSSHServerCredentials) { super.successfullyCloseDialog(oldSSHServerCredentials, newSSHServerCredentials); addSSHServerCredentialItem(newSSHServerCredentials); } }; dialog.show(); } private void addSSHServerCredentialItem(RemoteMachineProperties newSSHServerCredentials) { RemoteMachineProperties[] remoteMachines = new RemoteMachineProperties[] {newSSHServerCredentials}; addListItems(remoteMachines, RemoteMachineProperties.class, REMOTE_MACHINES_PROPERTY); } private void editSSHServerCredentialItem(RemoteMachineProperties oldSSHServerCredentials, RemoteMachineProperties newSSHServerCredentials) { ListModel<RemoteMachineProperties> listModel = this.remoteTopologyPanel.getRemoteMachinesList().getModel(); RemoteMachineProperties[] remoteMachines = new RemoteMachineProperties[listModel.getSize()]; for (int i=0; i<listModel.getSize(); i++) { RemoteMachineProperties existingRemoteMachine = listModel.getElementAt(i); remoteMachines[i] = (existingRemoteMachine == oldSSHServerCredentials) ? newSSHServerCredentials : existingRemoteMachine; } setListItems(remoteMachines, REMOTE_MACHINES_PROPERTY); } private void editServerCredentialsButtonPressed() { RemoteMachineProperties selectedSSHServerCredentials = this.remoteTopologyPanel.getRemoteMachinesList().getSelectedValue(); if (selectedSSHServerCredentials != null) { EditRemoteMachineCredentialsDialog dialog = new EditRemoteMachineCredentialsDialog(getJDialog(), selectedSSHServerCredentials) { @Override protected void successfullyCloseDialog(RemoteMachineProperties oldSSHServerCredentials, RemoteMachineProperties newSSHServerCredentials) { super.successfullyCloseDialog(oldSSHServerCredentials, newSSHServerCredentials); editSSHServerCredentialItem(oldSSHServerCredentials, newSSHServerCredentials); } }; dialog.show(); } } private void removeServerCredentialsButtonPressed() { RemoteMachineProperties selectedRemoteMachine = this.remoteTopologyPanel.getRemoteMachinesList().getSelectedValue(); if (selectedRemoteMachine != null) { ListModel<RemoteMachineProperties> listModel = this.remoteTopologyPanel.getRemoteMachinesList().getModel(); RemoteMachineProperties[] remoteMachines = new RemoteMachineProperties[listModel.getSize()-1]; for (int i=0, index = 0; i<listModel.getSize(); i++) { RemoteMachineProperties existingRemoteMachine = listModel.getElementAt(i); if (existingRemoteMachine != selectedRemoteMachine) { remoteMachines[index++] = existingRemoteMachine; } } setListItems(remoteMachines, REMOTE_MACHINES_PROPERTY); } } @Override protected JPanel buildButtonsPanel(ActionListener cancelActionListener) { ActionListener runActionListener = event -> runButtonPressed(); JButton finishButton = buildDialogButton("Run"); finishButton.addActionListener(runActionListener); JButton cancelButton = buildDialogButton("Cancel"); cancelButton.addActionListener(cancelActionListener); addComponentToAllwaysEnabledList(cancelButton); JPanel buttonsGridPanel = new JPanel(new GridLayout(1, 2, 5, 0)); buttonsGridPanel.add(finishButton); buttonsGridPanel.add(cancelButton); JPanel buttonsPanel = new JPanel(new GridBagLayout()); GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, 0, 0); buttonsPanel.add(new JLabel(), c); c = SwingUtils.buildConstraints(1, 0, GridBagConstraints.NONE, GridBagConstraints.CENTER, 1, 1, 0, 0); buttonsPanel.add(this.continueOnFailureCheckBox, c); c = SwingUtils.buildConstraints(2, 0, GridBagConstraints.NONE, GridBagConstraints.CENTER, 1, 1, 0, 5); buttonsPanel.add(buttonsGridPanel, c); return buttonsPanel; } private void createRemoteTopologyPanel(Insets defaultTextFieldMargins, Insets defaultListItemMargins, int textFieldPreferredHeight, int gapBetweenColumns, int gapBetweenRows) { if (SystemUtils.IS_OS_LINUX) { this.remoteTopologyPanel = new LinuxRemoteTopologyPanel(getJDialog(), defaultTextFieldMargins, defaultListItemMargins); } else if (SystemUtils.IS_OS_WINDOWS) { this.remoteTopologyPanel = new WindowsRemoteTopologyPanel(getJDialog(), defaultTextFieldMargins, defaultListItemMargins); } else if (SystemUtils.IS_OS_MAC) { this.remoteTopologyPanel = new MacRemoteTopologyPanel(getJDialog(), defaultTextFieldMargins, defaultListItemMargins); } else { throw new UnsupportedOperationException("Unsupported operating system '" + SystemUtils.OS_NAME + "'."); } this.remoteTopologyPanel.getRemoteSharedFolderPathTextField().setColumns(70); this.bindingContext.bind(REMOTE_SHARED_FOLDER_PATH_PROPERTY, this.remoteTopologyPanel.getRemoteSharedFolderPathTextField()); this.bindingContext.bind(REMOTE_SHARED_FOLDER_USERNAME_PROPERTY, this.remoteTopologyPanel.getRemoteUsernameTextField()); this.bindingContext.bind(REMOTE_SHARED_FOLDER_PASSWORD_PROPERTY, this.remoteTopologyPanel.getRemotePasswordTextField()); this.bindingContext.bind(LOCAL_SHARED_FOLDER_PATH_PROPERTY, this.remoteTopologyPanel.getLocalSharedFolderPathTextField()); JPasswordField localPasswordTextField = this.remoteTopologyPanel.getLocalPasswordTextField(); if (localPasswordTextField != null) { localPasswordTextField.setMargin(defaultTextFieldMargins); this.bindingContext.bind(LOCAL_PASSWORD_PROPERTY, localPasswordTextField); } ActionListener addButtonListener = event -> addServerCredentialsButtonPressed(); ActionListener editButtonListener = event -> editServerCredentialsButtonPressed(); ActionListener removeButtonListener = event -> removeServerCredentialsButtonPressed(); ActionListener browseLocalSharedFolderButtonListener = event -> selectLocalSharedFolderPath(); this.bindingContext.bind(REMOTE_MACHINES_PROPERTY, new ListSelectionAdapter(this.remoteTopologyPanel.getRemoteMachinesList())); this.remoteTopologyPanel.getRemoteMachinesList().setVisibleRowCount(5); JPanel remoteMachinesButtonsPanel = RemoteTopologyPanel.buildVerticalButtonsPanel(addButtonListener, editButtonListener, removeButtonListener, textFieldPreferredHeight, gapBetweenRows); this.remoteTopologyPanel.addComponents(gapBetweenColumns, gapBetweenRows, browseLocalSharedFolderButtonListener, remoteMachinesButtonsPanel); this.remoteTopologyPanel.setBorder(new TitledBorder("Remote execution")); } private JPanel buildInputPanel(int gapBetweenColumns, int gapBetweenRows, int textFieldPreferredHeight, Insets defaultListItemMargins, String[] availableFormatNames) { ActionListener slaveGraphBrowseButtonListener = event -> selectSlaveGraphFile(); JButton slaveGraphBrowseButton = SwingUtils.buildBrowseButton(slaveGraphBrowseButtonListener, textFieldPreferredHeight); this.sourceProductsList = new JList<>(new DefaultListModel<>()); LabelListCellRenderer<String> sourceProductsRenderer = new LabelListCellRenderer<>(defaultListItemMargins) { @Override protected String getItemDisplayText(String value) { return value;//remoteTopologyPanel.normalizeFileSeparator(value.toString()); } }; this.sourceProductsList.setCellRenderer(sourceProductsRenderer); this.sourceProductsList.setVisibleRowCount(4); this.bindingContext.bind(SOURCE_PRODUCT_FILES_PROPERTY, new ListSelectionAdapter(this.sourceProductsList)); this.slaveProductsFormatNameComboBox = buildProductFormatNamesComboBox(defaultListItemMargins, textFieldPreferredHeight, availableFormatNames); Binding formatNameBinding = this.bindingContext.bind(SLAVE_PRODUCTS_FORMAT_NAME_PROPERTY, this.slaveProductsFormatNameComboBox); if (org.esa.snap.core.util.StringUtils.contains(availableFormatNames, ProductIO.DEFAULT_FORMAT_NAME)) { formatNameBinding.setPropertyValue(ProductIO.DEFAULT_FORMAT_NAME); } else { formatNameBinding.setPropertyValue(availableFormatNames[0]); } ActionListener addSourceProductsButtonListener = event -> showDialogToSelectSourceProducts(); ActionListener removeSourceProductsButtonListener = event -> removeSelectedSourceProducts(); JPanel sourceProductButtonsPanel = RemoteTopologyPanel.buildVerticalButtonsPanel(addSourceProductsButtonListener, null, removeSourceProductsButtonListener, textFieldPreferredHeight, gapBetweenRows); JPanel inputPanel = new JPanel(new GridBagLayout()); inputPanel.setBorder(new TitledBorder("Input")); GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, 0, 0); inputPanel.add(new JLabel("Slave graph file path"), c); c = SwingUtils.buildConstraints(1, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns); inputPanel.add(this.slaveGraphFilePathTextField, c); c = SwingUtils.buildConstraints(2, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns); inputPanel.add(slaveGraphBrowseButton, c); c = SwingUtils.buildConstraints(0, 1, GridBagConstraints.NONE, GridBagConstraints.NORTHWEST, 1, 1, gapBetweenRows, 0); inputPanel.add(new JLabel("Source products"), c); c = SwingUtils.buildConstraints(1, 1, GridBagConstraints.BOTH, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); inputPanel.add(new JScrollPane(this.sourceProductsList), c); c = SwingUtils.buildConstraints(2, 1, GridBagConstraints.NONE, GridBagConstraints.NORTHWEST, 1, 1, gapBetweenRows, gapBetweenColumns); inputPanel.add(sourceProductButtonsPanel, c); c = SwingUtils.buildConstraints(0, 2, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); inputPanel.add(new JLabel("Save slave products as"), c); c = SwingUtils.buildConstraints(1, 2, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); inputPanel.add(this.slaveProductsFormatNameComboBox, c); return inputPanel; } private boolean canSaveTargetProductToFile() { return this.canSaveTargetProductCheckBox.isEnabled() && this.canSaveTargetProductCheckBox.isSelected(); } private void refreshOpenTargetProductEnabledState() { boolean enabled = (existReaderPluginForMasterProduct() && canSaveTargetProductToFile()); this.openTargetProductCheckBox.setEnabled(enabled); } private void refreshOpenTargetProductSelectedState() { this.bindingContext.getBinding(OPEN_TARGET_PRODUCT_PROPERTY).setPropertyValue(existReaderPluginForMasterProduct()); } private boolean existReaderPluginForMasterProduct() { String formatName = (String) this.bindingContext.getBinding(MASTER_PRODUCT_FORMAT_NAME_PROPERTY).getPropertyValue(); return ProductIOPlugInManager.getInstance().getReaderPlugIns(formatName).hasNext(); } private JPanel buildOutputMasterProductPanel(int gapBetweenColumns, int gapBetweenRows, Insets defaultTextFieldMargins, Insets defaultListItemMargins, int textFieldPreferredHeight, String[] availableFormatNames) { ActionListener masterGraphBrowseButtonListener = event -> selectMasterGraphFile(); JButton masterGraphFileBrowseButton = SwingUtils.buildBrowseButton(masterGraphBrowseButtonListener, textFieldPreferredHeight); Insets noMargins = new Insets(0, 0, 0, 0); this.masterGraphFilePathTextField = new JTextField(); this.masterGraphFilePathTextField.setMargin(defaultTextFieldMargins); this.bindingContext.bind(MASTER_GRAPH_FILE_PATH_PROPERTY, this.masterGraphFilePathTextField); this.canSaveTargetProductCheckBox = new JCheckBox("Save as"); this.canSaveTargetProductCheckBox.setMargin(noMargins); this.canSaveTargetProductCheckBox.setFocusable(false); Binding canSaveTargetProductBinding = this.bindingContext.bind(CAN_SAVE_TARGET_PRODUCT_PROPERTY, this.canSaveTargetProductCheckBox); this.openTargetProductCheckBox = new JCheckBox("Open in application"); this.openTargetProductCheckBox.setMargin(noMargins); this.openTargetProductCheckBox.setFocusable(false); Binding openTargetProductBinding = this.bindingContext.bind(OPEN_TARGET_PRODUCT_PROPERTY, this.openTargetProductCheckBox); this.masterProductFolderPathTextField = new JTextField(); this.masterProductFolderPathTextField.setMargin(defaultTextFieldMargins); Binding targetProductFolderPathBinding = this.bindingContext.bind(MASTER_PRODUCT_FOLDER_PATH_PROPERTY, this.masterProductFolderPathTextField); this.masterProductNameTextField = new JTextField(); this.masterProductNameTextField.setMargin(defaultTextFieldMargins); this.bindingContext.bind(MASTER_PRODUCT_FILE_NAME_PROPERTY, this.masterProductNameTextField); this.masterProductFormatNameComboBox = buildProductFormatNamesComboBox(defaultListItemMargins, textFieldPreferredHeight, availableFormatNames); Binding formatNameBinding = this.bindingContext.bind(MASTER_PRODUCT_FORMAT_NAME_PROPERTY, this.masterProductFormatNameComboBox); ActionListener targetProductBrowseButtonListener = event -> selectTargetProductFolderPath(); JButton targetProductFolderBrowseButton = SwingUtils.buildBrowseButton(targetProductBrowseButtonListener, textFieldPreferredHeight); JLabel targetProductNameLabel = new JLabel("Name"); JLabel targetProductFolderLabel = new JLabel("Directory"); JLabel masterGraphFileLabel = new JLabel("Master graph file path"); this.masterProductEnabledComponents = new ArrayList<>(); this.masterProductEnabledComponents.add(this.masterProductFormatNameComboBox); this.masterProductEnabledComponents.add(masterGraphFileLabel); this.masterProductEnabledComponents.add(this.masterGraphFilePathTextField); this.masterProductEnabledComponents.add(masterGraphFileBrowseButton); this.masterProductEnabledComponents.add(targetProductNameLabel); this.masterProductEnabledComponents.add(this.masterProductNameTextField); this.masterProductEnabledComponents.add(targetProductFolderLabel); this.masterProductEnabledComponents.add(this.masterProductFolderPathTextField); this.masterProductEnabledComponents.add(targetProductFolderBrowseButton); this.masterProductEnabledComponents.add(this.openTargetProductCheckBox); canSaveTargetProductBinding.setPropertyValue(this.canSaveTargetProductCheckBox.isSelected()); openTargetProductBinding.setPropertyValue(this.openTargetProductCheckBox.isSelected()); String homeDirPath = org.esa.snap.core.util.SystemUtils.getUserHomeDir().getPath(); String targetProductFolderPath = this.appContext.getPreferences().getPropertyString(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, homeDirPath); targetProductFolderPathBinding.setPropertyValue(targetProductFolderPath); if (org.esa.snap.core.util.StringUtils.contains(availableFormatNames, ProductIO.DEFAULT_FORMAT_NAME)) { formatNameBinding.setPropertyValue(ProductIO.DEFAULT_FORMAT_NAME); } else { formatNameBinding.setPropertyValue(availableFormatNames[0]); } refreshTargetProductEnabledComponents(); JPanel targetProductPanel = new JPanel(new GridBagLayout()); targetProductPanel.setBorder(new TitledBorder("Output")); GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, 0, 0); targetProductPanel.add(this.canSaveTargetProductCheckBox, c); c = SwingUtils.buildConstraints(1, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns); targetProductPanel.add(this.masterProductFormatNameComboBox, c); c = SwingUtils.buildConstraints(0, 1, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); targetProductPanel.add(masterGraphFileLabel, c); c = SwingUtils.buildConstraints(1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); targetProductPanel.add(this.masterGraphFilePathTextField, c); c = SwingUtils.buildConstraints(2, 1, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); targetProductPanel.add(masterGraphFileBrowseButton, c); c = SwingUtils.buildConstraints(0, 2, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); targetProductPanel.add(targetProductNameLabel, c); c = SwingUtils.buildConstraints(1, 2, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 2, 1, gapBetweenRows, gapBetweenColumns); targetProductPanel.add(this.masterProductNameTextField, c); c = SwingUtils.buildConstraints(0, 3, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); targetProductPanel.add(targetProductFolderLabel, c); c = SwingUtils.buildConstraints(1, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); targetProductPanel.add(this.masterProductFolderPathTextField, c); c = SwingUtils.buildConstraints(2, 3, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); targetProductPanel.add(targetProductFolderBrowseButton, c); c = SwingUtils.buildConstraints(0, 4, GridBagConstraints.NONE, GridBagConstraints.WEST, 3, 1, gapBetweenRows, 0); targetProductPanel.add(this.openTargetProductCheckBox, c); return targetProductPanel; } private void runOperatorAsync(Map<String, Object> parametersMap, boolean openTargetProductInApplication) { Path remoteTopologyFilePath = getRemoteTopologyFilePath(); RemoteTopology remoteTopologyToSave = this.remoteTopologyPanel.buildRemoteTopology(); LoadingIndicator loadingIndicator = getLoadingIndicator(); int threadId = getNewCurrentThreadId(); RemoteExecutionTimerRunnable runnable = new RemoteExecutionTimerRunnable(this.appContext, this, loadingIndicator, threadId, parametersMap, openTargetProductInApplication, this.mountLocalSharedFolderResult, remoteTopologyToSave, remoteTopologyFilePath) { @Override protected void onSuccessfullyUnmountLocalFolder() { RemoteExecutionDialog.this.mountLocalSharedFolderResult = null; } }; runnable.executeAsync(); } private void onFinishReadingRemoteTopoloy(RemoteTopology remoteTopology) { if (remoteTopology != null) { try { Property property = this.bindingContext.getPropertySet().getProperty(REMOTE_SHARED_FOLDER_PATH_PROPERTY); property.setValue(this.remoteTopologyPanel.normalizePath(remoteTopology.getRemoteSharedFolderURL())); property = this.bindingContext.getPropertySet().getProperty(REMOTE_SHARED_FOLDER_USERNAME_PROPERTY); property.setValue(remoteTopology.getRemoteUsername()); property = this.bindingContext.getPropertySet().getProperty(REMOTE_SHARED_FOLDER_PASSWORD_PROPERTY); property.setValue(remoteTopology.getRemotePassword()); if (remoteTopology.getLocalSharedFolderPath() != null) { property = this.bindingContext.getPropertySet().getProperty(LOCAL_SHARED_FOLDER_PATH_PROPERTY); property.setValue(this.remoteTopologyPanel.normalizePath(remoteTopology.getLocalSharedFolderPath())); } if (remoteTopology.getLocalPassword() != null) { property = this.bindingContext.getPropertySet().getProperty(LOCAL_PASSWORD_PROPERTY); property.setValue(remoteTopology.getLocalPassword()); } RemoteMachineProperties[] remoteMachines = new RemoteMachineProperties[remoteTopology.getRemoteMachines().size()]; remoteTopology.getRemoteMachines().toArray(remoteMachines); addListItems(remoteMachines, RemoteMachineProperties.class, REMOTE_MACHINES_PROPERTY); } catch (ValidationException e) { throw new IllegalStateException(e); } } } private void removeSelectedSourceProducts() { int[] selectedIndices = this.sourceProductsList.getSelectedIndices(); removeListItems(selectedIndices, String.class, SOURCE_PRODUCT_FILES_PROPERTY); } private void refreshTargetProductEnabledComponents() { boolean enabled = canSaveTargetProductToFile(); for (JComponent masterProductEnabledComponent : this.masterProductEnabledComponents) { masterProductEnabledComponent.setEnabled(enabled); } refreshOpenTargetProductEnabledState(); } private void showDialogToSelectSourceProductsNew() { CustomFileChooser fileChooser = CustomFileChooser.buildFileChooser("Select source products", false, JFileChooser.FILES_ONLY); Property property = this.bindingContext.getPropertySet().getProperty(LOCAL_SHARED_FOLDER_PATH_PROPERTY); String sharedFolder = property.getValue(); if (StringUtils.isBlank(sharedFolder)) { property = this.bindingContext.getPropertySet().getProperty(REMOTE_SHARED_FOLDER_PATH_PROPERTY); sharedFolder = property.getValue(); } Path currentDirectoryPath; if (StringUtils.isBlank(sharedFolder)) { currentDirectoryPath = this.lastSelectedFolderPath; } else { currentDirectoryPath = Paths.get(sharedFolder); } if (currentDirectoryPath != null) { fileChooser.setCurrentDirectoryPath(currentDirectoryPath); } int result = fileChooser.showDialog(getJDialog(), "Select"); if (result == JFileChooser.APPROVE_OPTION) { Path selectedFilePath = fileChooser.getSelectedPath(); this.lastSelectedFolderPath = selectedFilePath.getParent(); String[] selectedFiles = new String[] { selectedFilePath.toString() }; addListItems(selectedFiles, String.class, SOURCE_PRODUCT_FILES_PROPERTY); } } private void selectMasterGraphFile() { showDialogToSelectGraphFile("Select the master graph file", MASTER_GRAPH_FILE_PATH_PROPERTY, this.masterGraphFilePathTextField.getText()); } private void selectSlaveGraphFile() { showDialogToSelectGraphFile("Select the slave graph file", SLAVE_GRAPH_FILE_PATH_PROPERTY, this.slaveGraphFilePathTextField.getText()); } private void showDialogToSelectGraphFile(String dialogTitle, String bidingPropertyName, String graphFilePath) { CustomFileChooser fileChooser = CustomFileChooser.buildFileChooser(dialogTitle, false, JFileChooser.FILES_ONLY); fileChooser.setFileFilter(CustomFileChooser.buildFileFilter(".xml", "*.xml")); fileChooser.setAcceptAllFileFilterUsed(false); Path graphPath; Path currentDirectoryPath; if (StringUtils.isBlank(graphFilePath)) { graphPath = null; currentDirectoryPath = this.lastSelectedFolderPath; } else { graphPath = Paths.get(graphFilePath); currentDirectoryPath = graphPath.getParent(); } if (currentDirectoryPath != null) { fileChooser.setCurrentDirectoryPath(currentDirectoryPath); if (graphPath != null && Files.exists(graphPath)) { fileChooser.setSelectedPath(graphPath); } } int result = fileChooser.showDialog(getJDialog(), "Select"); if (result == JFileChooser.APPROVE_OPTION) { Path selectedFilePath = fileChooser.getSelectedPath(); this.lastSelectedFolderPath = selectedFilePath.getParent(); setPropertyValue(selectedFilePath.toString(), bidingPropertyName); } } private void setPropertyValue(String propertyValue, String bidingPropertyName) { try { Property property = this.bindingContext.getPropertySet().getProperty(bidingPropertyName); property.setValue(propertyValue); } catch (ValidationException e) { throw new IllegalStateException(e); } } private void selectTargetProductFolderPath() { showDialogToSelectFolder("Select product folder", MASTER_PRODUCT_FOLDER_PATH_PROPERTY, this.masterProductFolderPathTextField.getText()); } private void selectLocalSharedFolderPath() { showDialogToSelectFolder("Select local shared folder", LOCAL_SHARED_FOLDER_PATH_PROPERTY, this.remoteTopologyPanel.getLocalSharedFolderPathTextField().getText()); } private void showDialogToSelectFolder(String dialogTitle, String bidingPropertyName, String existingFolderPath) { CustomFileChooser fileChooser = CustomFileChooser.buildFileChooser(dialogTitle, false, JFileChooser.DIRECTORIES_ONLY); fileChooser.setAcceptAllFileFilterUsed(false); Path currentDirectoryPath; if (StringUtils.isBlank(existingFolderPath)) { currentDirectoryPath = this.lastSelectedFolderPath; } else { currentDirectoryPath = Paths.get(existingFolderPath); } if (currentDirectoryPath != null) { fileChooser.setCurrentDirectoryPath(currentDirectoryPath); } int result = fileChooser.showDialog(getJDialog(), "Select"); if (result == JFileChooser.APPROVE_OPTION) { this.lastSelectedFolderPath = fileChooser.getSelectedPath(); setPropertyValue(this.lastSelectedFolderPath.toString(), bidingPropertyName); } } private void runButtonPressed() { Map<String, Object> parameterMap = this.parameterSupport.getParameterMap(); String masterSharedFolderPath = (String) parameterMap.get(REMOTE_SHARED_FOLDER_PATH_PROPERTY); String masterSharedFolderUsername = (String) parameterMap.get(REMOTE_SHARED_FOLDER_USERNAME_PROPERTY); String masterSharedFolderPassword = (String) parameterMap.get(REMOTE_SHARED_FOLDER_PASSWORD_PROPERTY); String localSharedFolderPath = (String) parameterMap.get(LOCAL_SHARED_FOLDER_PATH_PROPERTY); String localPassword = (String) parameterMap.get(LOCAL_PASSWORD_PROPERTY); String slaveGraphFilePath = (String) parameterMap.get(SLAVE_GRAPH_FILE_PATH_PROPERTY); String slaveProductsFormatName = (String) parameterMap.get(SLAVE_PRODUCTS_FORMAT_NAME_PROPERTY); String masterGraphFilePath = (String) parameterMap.get(MASTER_GRAPH_FILE_PATH_PROPERTY); String masterProductFolderPath = (String) parameterMap.get(MASTER_PRODUCT_FOLDER_PATH_PROPERTY); String masterProductFileName = (String) parameterMap.get(MASTER_PRODUCT_FILE_NAME_PROPERTY); String masterProductFormatName = (String) parameterMap.get(MASTER_PRODUCT_FORMAT_NAME_PROPERTY); Boolean continueOnFailure = (Boolean) parameterMap.get(CONTINUE_ON_FAILURE_NAME_PROPERTY); Boolean canSaveTargetProduct = (Boolean) parameterMap.get(CAN_SAVE_TARGET_PRODUCT_PROPERTY); String[] selectedSourceProducts = (String[]) parameterMap.get(SOURCE_PRODUCT_FILES_PROPERTY); RemoteMachineProperties[] selectedRemoteMachines = (RemoteMachineProperties[]) parameterMap.get(REMOTE_MACHINES_PROPERTY); if (StringUtils.isBlank(masterSharedFolderPath)) { showErrorDialog("Enter the remote shared folder path."); this.remoteTopologyPanel.getRemoteSharedFolderPathTextField().requestFocus(); } else { if (StringUtils.isBlank(masterSharedFolderUsername)) { showErrorDialog("Enter the username of the machine containing the remote shared folder path."); this.remoteTopologyPanel.getRemoteUsernameTextField().requestFocus(); } else if (StringUtils.isBlank(masterSharedFolderPassword)) { showErrorDialog("Enter the password of the machine containing the remote shared folder path."); this.remoteTopologyPanel.getRemotePasswordTextField().requestFocus(); } else { Property property = this.bindingContext.getPropertySet().getProperty(REMOTE_MACHINES_PROPERTY); ValueSet valueSet = property.getDescriptor().getValueSet(); if (valueSet == null) { // no remote machines available to run the slave graph showErrorDialog("Add at least one remote machine to process the source products."); this.remoteTopologyPanel.getRemoteMachinesList().requestFocus(); } else if (selectedRemoteMachines == null || selectedRemoteMachines.length == 0) { // no remote machines selected to run the slave graph showErrorDialog("Select the remote machines to process the source products."); this.remoteTopologyPanel.getRemoteMachinesList().requestFocus(); } else if (StringUtils.isBlank(slaveGraphFilePath)) { showErrorDialog("Enter the slave graph file to be processed on the remote machines."); this.slaveGraphFilePathTextField.requestFocus(); } else { property = this.bindingContext.getPropertySet().getProperty(SOURCE_PRODUCT_FILES_PROPERTY); valueSet = property.getDescriptor().getValueSet(); if (valueSet == null) { showErrorDialog("Add at least one source product."); this.sourceProductsList.requestFocus(); } else if (selectedSourceProducts == null || selectedSourceProducts.length == 0) { showErrorDialog("Select the source products to be processed on the remote machines."); this.sourceProductsList.requestFocus(); } else { boolean canExecuteOperator = false; if (canSaveTargetProduct) { if (StringUtils.isBlank(masterProductFormatName)) { showErrorDialog("Select the target product format name."); this.masterProductFormatNameComboBox.requestFocus(); } else if (StringUtils.isBlank(masterGraphFilePath)) { showErrorDialog("Enter the master graph file to be processed."); this.masterGraphFilePathTextField.requestFocus(); } else if (StringUtils.isBlank(masterProductFileName)) { showErrorDialog("Enter the target product name."); this.masterProductNameTextField.requestFocus(); } else if (StringUtils.isBlank(masterProductFolderPath)) { showErrorDialog("Enter the target product folder path."); this.masterProductFolderPathTextField.requestFocus(); } else { canExecuteOperator = true; } } else { canExecuteOperator = true; } if (canExecuteOperator) { Map<String, Object> operatatorParameters = new HashMap<>(); operatatorParameters.put(REMOTE_SHARED_FOLDER_PATH_PROPERTY, masterSharedFolderPath); operatatorParameters.put(REMOTE_SHARED_FOLDER_USERNAME_PROPERTY, masterSharedFolderUsername); operatatorParameters.put(REMOTE_SHARED_FOLDER_PASSWORD_PROPERTY, masterSharedFolderPassword); operatatorParameters.put(LOCAL_SHARED_FOLDER_PATH_PROPERTY, localSharedFolderPath); operatatorParameters.put(LOCAL_PASSWORD_PROPERTY, localPassword); operatatorParameters.put(SLAVE_GRAPH_FILE_PATH_PROPERTY, slaveGraphFilePath); operatatorParameters.put(SLAVE_PRODUCTS_FORMAT_NAME_PROPERTY, slaveProductsFormatName); operatatorParameters.put(SOURCE_PRODUCT_FILES_PROPERTY, selectedSourceProducts); operatatorParameters.put(REMOTE_MACHINES_PROPERTY, selectedRemoteMachines); operatatorParameters.put(CONTINUE_ON_FAILURE_NAME_PROPERTY, continueOnFailure); boolean openTargetProductInApplication = (Boolean) parameterMap.get(OPEN_TARGET_PRODUCT_PROPERTY); if (canSaveTargetProduct) { File targetProductFile = buildTargetProductFile(masterProductFormatName, masterProductFolderPath, masterProductFileName); operatatorParameters.put(MASTER_GRAPH_FILE_PATH_PROPERTY, masterGraphFilePath); operatatorParameters.put(MASTER_PRODUCT_FILE_PATH_PROPERTY, targetProductFile.getAbsolutePath()); operatatorParameters.put(MASTER_PRODUCT_FORMAT_NAME_PROPERTY, masterProductFormatName); // save the target product folder path into the preferences this.appContext.getPreferences().setPropertyString(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, masterProductFolderPath); } else { openTargetProductInApplication = false; } runOperatorAsync(operatatorParameters, openTargetProductInApplication); } } } } } } private <ItemType> void addListItems(ItemType[] itemsToAdd, Class<? extends ItemType> arrayType, String propertyName) { Property property = this.bindingContext.getPropertySet().getProperty(propertyName); ValueSet valueSet = property.getDescriptor().getValueSet(); Object arrayItems; int offset; if (valueSet == null) { arrayItems = Array.newInstance(arrayType, itemsToAdd.length); offset = 0; } else { Object[] existingItems = valueSet.getItems(); offset = existingItems.length; arrayItems = Array.newInstance(arrayType, offset + itemsToAdd.length); System.arraycopy(existingItems, 0, arrayItems, 0, offset); } System.arraycopy(itemsToAdd, 0, arrayItems, offset, itemsToAdd.length); property.getDescriptor().setValueSet(new ValueSet((Object[]) arrayItems)); } private <ItemType> void setListItems(ItemType[] items, String propertyName) { Property property = this.bindingContext.getPropertySet().getProperty(propertyName); property.getDescriptor().setValueSet(new ValueSet(items)); } private void showDialogToSelectSourceProducts() { if (this.mountLocalSharedFolderResult == null) { // mount the local folder and then select the source product LoadingIndicator loadingIndicator = getLoadingIndicator(); int threadId = getNewCurrentThreadId(); IMountLocalSharedFolderCallback callback = result -> { RemoteExecutionDialog.this.mountLocalSharedFolderResult = result; showDialogToSelectSourceProductsNew(); }; this.remoteTopologyPanel.mountLocalSharedFolderAsync(this, loadingIndicator, threadId, callback); } else if (this.remoteTopologyPanel.hasChangedParameters(this.mountLocalSharedFolderResult.getLocalSharedDrive())) { LoadingIndicator loadingIndicator = getLoadingIndicator(); int threadId = getNewCurrentThreadId(); IUnmountLocalSharedFolderCallback callback = exception -> { RemoteExecutionDialog.this.mountLocalSharedFolderResult = null; RemoteExecutionDialog.this.showDialogToSelectSourceProducts(); // mount again the local shared folder }; this.mountLocalSharedFolderResult.unmountLocalSharedFolderAsync(loadingIndicator, threadId, callback); } else { showDialogToSelectSourceProductsNew(); } } private <ItemType> void removeListItems(int[] itemIndicesToRemove, Class<? extends ItemType> arrayType, String propertyName) { if (itemIndicesToRemove.length > 0) { Property property = this.bindingContext.getPropertySet().getProperty(propertyName); ValueSet valueSet = property.getDescriptor().getValueSet(); if (valueSet == null) { throw new NullPointerException("The valueSet is null"); } else { Object[] existingItems = valueSet.getItems(); int index = 0; Object items = Array.newInstance(arrayType, existingItems.length - itemIndicesToRemove.length); for (int i = 0; i < existingItems.length; i++) { boolean foundIndex = false; for (int k = 0; k < itemIndicesToRemove.length && !foundIndex; k++) { if (i == itemIndicesToRemove[k]) { foundIndex = true; break; } } if (!foundIndex) { Array.set(items, index++, existingItems[i]); } } if (index == Array.getLength(items)) { property.getDescriptor().setValueSet(new ValueSet((Object[]) items)); } else { throw new IllegalStateException("The remaining item count is different."); } } } } private static File buildTargetProductFile(String targetProductFormatName, String targetProductFolderPath, String targetProductFileName) { TargetProductSelectorModel targetProductSelectorModel = new TargetProductSelectorModel(); targetProductSelectorModel.setFormatName(targetProductFormatName); targetProductSelectorModel.setProductDir(new File(targetProductFolderPath)); targetProductSelectorModel.setProductName(targetProductFileName); return targetProductSelectorModel.getProductFile(); } private static Path getRemoteTopologyFilePath() { Path cepFolderPath = org.esa.snap.core.util.SystemUtils.getApplicationDataDir().toPath().resolve("cloud-exploitation-platform"); return cepFolderPath.resolve("remote-topology.json"); } public static class CloudExploitationPlatformItem extends Operator { private String remoteSharedFolderPath; private String remoteSharedFolderUsername; private String remoteSharedFolderPassword; private String localSharedFolderPath; private String localPassword; private RemoteMachineProperties[] remoteMachines; private String[] sourceProductFiles; private String slaveGraphFilePath; private String slaveProductsFormatName; private String masterGraphFilePath; private String masterProductFolderPath; private String masterProductFileName; private String masterProductFormatName; private Boolean continueOnFailure; private Boolean canSaveTargetProduct; private Boolean openTargetProduct; public CloudExploitationPlatformItem() { } @Override public void initialize() throws OperatorException { // do nothing } } private static class EmptyValueSetExtended extends ValueSet { public EmptyValueSetExtended(Object[] items) { super(items); } @Override public boolean contains(Object value) { return true;//super.contains(value); } } }
58,881
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OperatorDescriptorWrapperImpl.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/operator/OperatorDescriptorWrapperImpl.java
package org.esa.snap.remote.execution.operator; import org.esa.snap.core.gpf.Operator; import org.esa.snap.core.gpf.descriptor.OperatorDescriptor; import org.esa.snap.core.gpf.descriptor.ParameterDescriptor; import org.esa.snap.core.gpf.descriptor.SourceProductDescriptor; import org.esa.snap.core.gpf.descriptor.SourceProductsDescriptor; import org.esa.snap.core.gpf.descriptor.TargetProductDescriptor; import org.esa.snap.core.gpf.descriptor.TargetPropertyDescriptor; /** * Created by jcoravu on 11/3/2019. */ class OperatorDescriptorWrapperImpl implements OperatorDescriptor { private final OperatorDescriptor baseOperatorDescriptor; private final ParameterDescriptor[] params; private final SourceProductDescriptor[] sourceProducts; OperatorDescriptorWrapperImpl(OperatorDescriptor baseOperatorDescriptor) { this.baseOperatorDescriptor = baseOperatorDescriptor; this.params = new ParameterDescriptor[0]; this.sourceProducts = new SourceProductDescriptor[0]; } @Override public String getName() { return this.baseOperatorDescriptor.getName(); } @Override public String getAlias() { return this.baseOperatorDescriptor.getAlias(); } @Override public String getLabel() { return this.baseOperatorDescriptor.getLabel(); } @Override public String getDescription() { return this.baseOperatorDescriptor.getDescription(); } @Override public String getVersion() { return this.baseOperatorDescriptor.getVersion(); } @Override public String getAuthors() { return this.baseOperatorDescriptor.getAuthors(); } @Override public String getCopyright() { return this.baseOperatorDescriptor.getCopyright(); } @Override public boolean isInternal() { return this.baseOperatorDescriptor.isInternal(); } @Override public boolean isAutoWriteDisabled() { return this.baseOperatorDescriptor.isAutoWriteDisabled(); } @Override public Class<? extends Operator> getOperatorClass() { return RemoteExecutionDialog.CloudExploitationPlatformItem.class; } @Override public SourceProductDescriptor[] getSourceProductDescriptors() { return this.sourceProducts; } @Override public SourceProductsDescriptor getSourceProductsDescriptor() { return null; } @Override public ParameterDescriptor[] getParameterDescriptors() { return this.params; } @Override public TargetProductDescriptor getTargetProductDescriptor() { return null; } @Override public TargetPropertyDescriptor[] getTargetPropertyDescriptors() { return new TargetPropertyDescriptor[0]; } }
2,780
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
RemoteExecutionTimerRunnable.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/operator/RemoteExecutionTimerRunnable.java
package org.esa.snap.remote.execution.operator; import org.esa.snap.remote.execution.RemoteExecutionOp; import org.esa.snap.remote.execution.exceptions.OperatorExecutionException; import org.esa.snap.remote.execution.exceptions.OperatorInitializeException; import org.esa.snap.remote.execution.exceptions.WaitingTimeoutException; import org.esa.snap.remote.execution.local.folder.IMountLocalSharedFolderResult; import org.esa.snap.core.gpf.OperatorException; import org.esa.snap.remote.execution.topology.RemoteTopology; import org.esa.snap.remote.execution.topology.RemoteTopologyUtils; import org.esa.snap.ui.loading.AbstractTimerRunnable; import org.esa.snap.ui.loading.LoadingIndicator; import org.esa.snap.ui.loading.MessageDialog; import org.esa.snap.core.dataio.ProductIO; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.ui.AppContext; import javax.swing.SwingUtilities; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Map; /** * Created by jcoravu on 27/12/2018. */ public class RemoteExecutionTimerRunnable extends AbstractTimerRunnable<Product> { private final AppContext appContext; private final MessageDialog parentWindow; private final Map<String, Object> parameterMap; private final boolean openTargetProductInApplication; private final IMountLocalSharedFolderResult mountLocalSharedFolderResult; private final RemoteTopology remoteTopologyToSave; private final Path remoteTopologyFilePath; public RemoteExecutionTimerRunnable(AppContext appContext, MessageDialog parentWindow, LoadingIndicator loadingIndicator, int threadId, Map<String, Object> parameterMap, boolean openTargetProductInApplication, IMountLocalSharedFolderResult mountLocalSharedFolderResult, RemoteTopology remoteTopologyToSave, Path remoteTopologyFilePath) { super(loadingIndicator, threadId, 500); this.appContext = appContext; this.parentWindow = parentWindow; this.parameterMap = parameterMap; this.remoteTopologyToSave = remoteTopologyToSave; this.remoteTopologyFilePath = remoteTopologyFilePath; this.openTargetProductInApplication = openTargetProductInApplication; this.mountLocalSharedFolderResult = mountLocalSharedFolderResult; } @Override protected final void onTimerWakeUp(String messageToDisplay) { super.onTimerWakeUp("Processing..."); } @Override protected final Product execute() throws Exception { Path parentFolder = this.remoteTopologyFilePath.getParent(); if (!Files.exists(parentFolder)) { Files.createDirectories(parentFolder); } RemoteTopologyUtils.writeTopology(this.remoteTopologyFilePath, this.remoteTopologyToSave); if (this.mountLocalSharedFolderResult != null) { // unmount the local shared folder String localSharedFolderPath = (String) this.parameterMap.get(RemoteExecutionDialog.LOCAL_SHARED_FOLDER_PATH_PROPERTY); String localPassword = (String) this.parameterMap.get(RemoteExecutionDialog.LOCAL_PASSWORD_PROPERTY); this.mountLocalSharedFolderResult.unmountLocalSharedFolder(localSharedFolderPath, localPassword); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { onSuccessfullyUnmountLocalFolder(); } }); } Map<String, Product> sourceProducts = Collections.emptyMap(); String operatorName = OperatorSpi.getOperatorAlias(RemoteExecutionOp.class); // create the operator RemoteExecutionOp operator = (RemoteExecutionOp)GPF.getDefaultInstance().createOperator(operatorName, this.parameterMap, sourceProducts, null); // execute the operator operator.execute(null); if (operator.canCreateTargetProduct()) { return ProductIO.readProduct(operator.getMasterProductFilePath()); } return null; } @Override protected String getExceptionLoggingMessage() { return "Failed to execute the operator."; } @Override protected void onSuccessfullyFinish(Product targetProduct) { this.parentWindow.close(); if (this.openTargetProductInApplication) { if (targetProduct == null) { throw new NullPointerException("The target product cannot be null."); } else { this.appContext.getProductManager().addProduct(targetProduct); } } } @Override protected void onFailed(Exception exception) { String message; if (exception instanceof OperatorInitializeException) { message = exception.getMessage(); } else if (exception instanceof OperatorExecutionException) { message = exception.getMessage(); } else if (exception instanceof WaitingTimeoutException) { message = exception.getMessage(); } else if (exception instanceof OperatorException) { message = exception.getMessage(); } else { message = "Failed to execute the operator."; } this.parentWindow.showErrorDialog(message, "Operator execution"); } protected void onSuccessfullyUnmountLocalFolder() { } }
5,539
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
RemoteExecutionAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/operator/RemoteExecutionAction.java
package org.esa.snap.remote.execution.operator; import org.esa.snap.rcp.actions.AbstractSnapAction; import org.esa.snap.ui.AppContext; import java.awt.event.ActionEvent; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Created by jcoravu on 24/12/2018. */ public class RemoteExecutionAction extends AbstractSnapAction { private static final Set<String> KNOWN_KEYS = new HashSet<>(Arrays.asList("displayName", "operatorName", "dialogTitle", "helpId")); public RemoteExecutionAction() { } public static RemoteExecutionAction create(Map<String, Object> properties) { RemoteExecutionAction action = new RemoteExecutionAction(); for (Map.Entry<String, Object> entry : properties.entrySet()) { if (KNOWN_KEYS.contains(entry.getKey())) { action.putValue(entry.getKey(), entry.getValue()); } } return action; } @Override public void actionPerformed(ActionEvent event) { AppContext appContext = getAppContext(); RemoteExecutionDialog dialog = new RemoteExecutionDialog(appContext, appContext.getApplicationWindow()); dialog.show(); } }
1,216
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ReadRemoteTopologyTimerRunnable.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/topology/ReadRemoteTopologyTimerRunnable.java
package org.esa.snap.remote.execution.topology; import org.esa.snap.ui.loading.AbstractTimerRunnable; import org.esa.snap.ui.loading.LoadingIndicator; import org.esa.snap.ui.loading.MessageDialog; import java.nio.file.Path; /** * Created by jcoravu on 19/12/2018. */ public class ReadRemoteTopologyTimerRunnable extends AbstractTimerRunnable<RemoteTopology> { private final MessageDialog parentWindow; private final Path remoteTopologyFilePath; public ReadRemoteTopologyTimerRunnable(MessageDialog parentWindow, LoadingIndicator loadingIndicator, int threadId, Path remoteTopologyFilePath) { super(loadingIndicator, threadId, 500); this.parentWindow = parentWindow; this.remoteTopologyFilePath = remoteTopologyFilePath; } @Override protected final void onTimerWakeUp(String messageToDisplay) { super.onTimerWakeUp("Loading..."); } @Override protected RemoteTopology execute() throws Exception { return RemoteTopologyUtils.readTopology(this.remoteTopologyFilePath); } @Override protected String getExceptionLoggingMessage() { return "Failed to read the remote topology from the file."; } @Override protected final void onFailed(Exception exception) { this.parentWindow.showErrorDialog("Failed to read the remote topology from the file.", "Failed"); } }
1,384
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OperatingSystemLabelListCellRenderer.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/topology/OperatingSystemLabelListCellRenderer.java
package org.esa.snap.remote.execution.topology; import org.esa.snap.remote.execution.machines.RemoteMachineProperties; import org.esa.snap.ui.loading.LabelListCellRenderer; import javax.swing.*; import java.awt.*; import java.net.URL; /** * Created by jcoravu on 17/1/2019. */ public class OperatingSystemLabelListCellRenderer extends LabelListCellRenderer<RemoteMachineProperties> { private final Icon windowsIcon; private final Icon linuxIcon; public OperatingSystemLabelListCellRenderer(Insets margins) { super(margins); this.windowsIcon = loadImageIcon("org/esa/snap/remote/execution/windows16.png"); this.linuxIcon = loadImageIcon("org/esa/snap/remote/execution/linux16.png"); } @Override public JLabel getListCellRendererComponent(JList<? extends RemoteMachineProperties> list, RemoteMachineProperties value, int index, boolean isSelected, boolean cellHasFocus) { JLabel component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value.isWindows()) { component.setIcon(this.windowsIcon); } else if (value.isLinux()) { component.setIcon(this.linuxIcon); } else { throw new IllegalArgumentException("Uknown operating system '" + value.getOperatingSystemName() + "'."); } return component; } @Override protected String getItemDisplayText(RemoteMachineProperties value) { return value.getHostName() + ":" + value.getPortNumber(); } private static ImageIcon loadImageIcon(String imagePath) { URL imageURL = OperatingSystemLabelListCellRenderer.class.getClassLoader().getResource(imagePath); return (imageURL == null) ? null : new ImageIcon(imageURL); } }
1,787
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
RemoteTopologyPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/topology/RemoteTopologyPanel.java
package org.esa.snap.remote.execution.topology; import org.apache.commons.lang3.StringUtils; import org.esa.snap.remote.execution.local.folder.AbstractLocalSharedFolder; import org.esa.snap.remote.execution.local.folder.IMountLocalSharedFolderCallback; import org.esa.snap.remote.execution.machines.RemoteMachineProperties; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.loading.LoadingIndicator; import org.esa.snap.ui.loading.MessageDialog; import org.esa.snap.ui.loading.SwingUtils; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListModel; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionListener; import java.util.List; /** * Created by jcoravu on 9/1/2019. */ public abstract class RemoteTopologyPanel extends JPanel { private final JTextField remoteSharedFolderPathTextField; private final JTextField remoteUsernameTextField; private final JPasswordField remotePasswordTextField; private final JTextField localSharedFolderPathTextField; private final JList<RemoteMachineProperties> remoteMachinesList; public RemoteTopologyPanel(Window parentWindow, Insets defaultTextFieldMargins, Insets defaultListItemMargins) { super(new GridBagLayout()); this.remoteSharedFolderPathTextField = new JTextField(); this.remoteSharedFolderPathTextField.setMargin(defaultTextFieldMargins); this.remoteUsernameTextField = new JTextField(); this.remoteUsernameTextField.setMargin(defaultTextFieldMargins); this.remotePasswordTextField = new JPasswordField(); this.remotePasswordTextField.setMargin(defaultTextFieldMargins); this.localSharedFolderPathTextField = new JTextField(); this.localSharedFolderPathTextField.setMargin(defaultTextFieldMargins); this.remoteMachinesList = new JList<>(new DefaultListModel<>()); this.remoteMachinesList.setVisibleRowCount(15); this.remoteMachinesList.setCellRenderer(new OperatingSystemLabelListCellRenderer(defaultListItemMargins)); } public abstract String normalizePath(String path); public abstract void addComponents(int gapBetweenColumns, int gapBetweenRows, ActionListener browseLocalSharedFolderButtonListener, JPanel remoteMachinesButtonsPanel); public abstract void mountLocalSharedFolderAsync(MessageDialog parentWindow, LoadingIndicator loadingIndicator, int threadId, IMountLocalSharedFolderCallback callback); protected abstract AbstractLocalSharedFolder buildLocalSharedFolder(); public final boolean hasChangedParameters(AbstractLocalSharedFolder oldLocalSharedFolder) { AbstractLocalSharedFolder newLocalSharedFolder = buildLocalSharedFolder(); return oldLocalSharedFolder.hasChangedParameters(newLocalSharedFolder); } public JList<RemoteMachineProperties> getRemoteMachinesList() { return remoteMachinesList; } public JPasswordField getRemotePasswordTextField() { return remotePasswordTextField; } public JTextField getRemoteSharedFolderPathTextField() { return remoteSharedFolderPathTextField; } public JTextField getRemoteUsernameTextField() { return remoteUsernameTextField; } public RemoteTopology buildRemoteTopology() { String localSharedFolderPath = getLocalSharedFolderPath(); String localPassword = null; JPasswordField localPasswordTextField = getLocalPasswordTextField(); if (localPasswordTextField != null) { localPassword = new String(localPasswordTextField.getPassword()); } RemoteTopology remoteTopology = new RemoteTopology(getRemoteSharedFolderPath(), getRemoteUsername(), getRemotePassword()); remoteTopology.setLocalMachineData(localSharedFolderPath, localPassword); ListModel<RemoteMachineProperties> listModel = getRemoteMachinesList().getModel(); for (int i=0; i<listModel.getSize(); i++) { remoteTopology.addRemoteMachine(listModel.getElementAt(i)); } return remoteTopology; } protected boolean canMountLocalSharedFolder(MessageDialog parentWindow, AbstractLocalSharedFolder localSharedFolder) { if (StringUtils.isBlank(localSharedFolder.getRemoteSharedFolderPath())) { parentWindow.showErrorDialog("The remote shared folder path is not specified."); getRemoteSharedFolderPathTextField().requestFocus(); return false; } if (StringUtils.isBlank(localSharedFolder.getRemoteUsername())) { parentWindow.showErrorDialog("The remote username is not specified."); getRemoteUsernameTextField().requestFocus(); return false; } if (StringUtils.isBlank(localSharedFolder.getRemotePassword())) { parentWindow.showErrorDialog("The remote password is not specified."); getRemotePasswordTextField().requestFocus(); return false; } return true; } protected final String getRemoteSharedFolderPath() { return getRemoteSharedFolderPathTextField().getText(); } protected final String getRemoteUsername() { return getRemoteUsernameTextField().getText(); } protected final String getRemotePassword() { return new String(getRemotePasswordTextField().getPassword()); } protected final String getLocalSharedFolderPath() { return getLocalSharedFolderPathTextField().getText(); } protected void addRemoteSharedFolderPathRow(int rowIndex, int gapBetweenColumns, int gapBetweenRows) { GridBagConstraints c = SwingUtils.buildConstraints(0, rowIndex, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); add(new JLabel("Remote shared folder path"), c); c = SwingUtils.buildConstraints(1, rowIndex, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 2, 1, gapBetweenRows, gapBetweenColumns); add(this.remoteSharedFolderPathTextField, c); } public JTextField getLocalSharedFolderPathTextField() { return this.localSharedFolderPathTextField; } public JPasswordField getLocalPasswordTextField() { return null; } public void setRemoteTopology(RemoteTopology remoteTopology) { this.remoteSharedFolderPathTextField.setText(normalizePath(remoteTopology.getRemoteSharedFolderURL())); this.remoteUsernameTextField.setText(remoteTopology.getRemoteUsername()); this.remotePasswordTextField.setText(remoteTopology.getRemotePassword()); this.localSharedFolderPathTextField.setText(normalizePath(remoteTopology.getLocalSharedFolderPath())); DefaultListModel<RemoteMachineProperties> model = (DefaultListModel<RemoteMachineProperties>) this.remoteMachinesList.getModel(); model.removeAllElements(); List<RemoteMachineProperties> remoteMachines = remoteTopology.getRemoteMachines(); for (RemoteMachineProperties remoteMachine : remoteMachines) { model.addElement(remoteMachine); } } protected void addUsernameRow(int rowIndex, int gapBetweenColumns, int gapBetweenRows) { GridBagConstraints c = SwingUtils.buildConstraints(0, rowIndex, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); add(new JLabel("Remote username"), c); c = SwingUtils.buildConstraints(1, rowIndex, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 2, 1, gapBetweenRows, gapBetweenColumns); add(this.remoteUsernameTextField, c); } protected void addPasswordRow(int rowIndex, int gapBetweenColumns, int gapBetweenRows) { GridBagConstraints c = SwingUtils.buildConstraints(0, rowIndex, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); add(new JLabel("Remote password"), c); c = SwingUtils.buildConstraints(1, rowIndex, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 2, 1, gapBetweenRows, gapBetweenColumns); add(this.remotePasswordTextField, c); } protected void addRemoteMachinesRow(int rowIndex, int gapBetweenColumns, int gapBetweenRows, JPanel remoteMachinesButtonsPanel) { GridBagConstraints c = SwingUtils.buildConstraints(0, rowIndex, GridBagConstraints.NONE, GridBagConstraints.NORTHWEST, 1, 1, gapBetweenRows, 0); add(new JLabel("Remote machines"), c); c = SwingUtils.buildConstraints(2, rowIndex, GridBagConstraints.NONE, GridBagConstraints.NORTHWEST, 1, 1, gapBetweenRows, gapBetweenColumns); add(remoteMachinesButtonsPanel, c); c = SwingUtils.buildConstraints(1, rowIndex, GridBagConstraints.BOTH, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); add(new JScrollPane(this.remoteMachinesList), c); } protected int getTextFieldPreferredHeight() { return this.remoteSharedFolderPathTextField.getPreferredSize().height; } protected void addLocalSharedFolderRow(int rowIndex, int gapBetweenColumns, int gapBetweenRows, String labelText, ActionListener browseLocalSharedFolderButtonListener) { GridBagConstraints c = SwingUtils.buildConstraints(0, rowIndex, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); add(new JLabel(labelText), c); int columnSpan = 2; if (browseLocalSharedFolderButtonListener != null) { columnSpan = 1; JButton browseButton = SwingUtils.buildBrowseButton(browseLocalSharedFolderButtonListener, getTextFieldPreferredHeight()); c = SwingUtils.buildConstraints(2, rowIndex, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns); add(browseButton, c); } c = SwingUtils.buildConstraints(1, rowIndex, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, columnSpan, 1, gapBetweenRows, gapBetweenColumns); add(this.localSharedFolderPathTextField, c); } private static JButton buildButton(String resourceImagePath, ActionListener buttonListener, Dimension buttonSize) { ImageIcon icon = UIUtils.loadImageIcon(resourceImagePath); JButton button = new JButton(icon); button.setFocusable(false); button.addActionListener(buttonListener); button.setPreferredSize(buttonSize); button.setMinimumSize(buttonSize); button.setMaximumSize(buttonSize); return button; } public static JPanel buildVerticalButtonsPanel(ActionListener addButtonListener, ActionListener editButtonListener, ActionListener removeButtonListener, int textFieldPreferredHeight, int gapBetweenRows) { Dimension buttonSize = new Dimension(textFieldPreferredHeight, textFieldPreferredHeight); JPanel verticalButtonsPanel = new JPanel(); verticalButtonsPanel.setLayout(new BoxLayout(verticalButtonsPanel, BoxLayout.Y_AXIS)); JButton addButton = buildButton("icons/Add16.png", addButtonListener, buttonSize); verticalButtonsPanel.add(addButton); if (editButtonListener != null) { verticalButtonsPanel.add(Box.createVerticalStrut(gapBetweenRows)); JButton editButton = buildButton("icons/Edit16.gif", editButtonListener, buttonSize); verticalButtonsPanel.add(editButton); } verticalButtonsPanel.add(Box.createVerticalStrut(gapBetweenRows)); JButton removeButton = buildButton("icons/Remove16.png", removeButtonListener, buttonSize); verticalButtonsPanel.add(removeButton); return verticalButtonsPanel; } }
12,005
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MacRemoteTopologyPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/topology/MacRemoteTopologyPanel.java
package org.esa.snap.remote.execution.topology; import org.apache.commons.lang3.StringUtils; import org.esa.snap.remote.execution.local.folder.AbstractLocalSharedFolder; import org.esa.snap.remote.execution.local.folder.IMountLocalSharedFolderCallback; import org.esa.snap.remote.execution.local.folder.MacLocalSharedFolder; import org.esa.snap.remote.execution.local.folder.MountMacLocalFolderTimerRunnable; import org.esa.snap.ui.loading.LoadingIndicator; import org.esa.snap.ui.loading.MessageDialog; import javax.swing.JPanel; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionListener; public class MacRemoteTopologyPanel extends RemoteTopologyPanel { public MacRemoteTopologyPanel(Window parentWindow, Insets defaultTextFieldMargins, Insets defaultListItemMargins) { super(parentWindow, defaultTextFieldMargins, defaultListItemMargins); } @Override public String normalizePath(String path) { return path.replace('\\', '/'); } @Override public void mountLocalSharedFolderAsync(MessageDialog parentWindow, LoadingIndicator loadingIndicator, int threadId, IMountLocalSharedFolderCallback callback) { MacLocalSharedFolder macLocalSharedDrive = buildLocalSharedFolder(); if (canMountLocalSharedFolder(parentWindow, macLocalSharedDrive)) { MountMacLocalFolderTimerRunnable runnable = new MountMacLocalFolderTimerRunnable(parentWindow, loadingIndicator, threadId, macLocalSharedDrive, callback); runnable.executeAsync(); } } @Override protected boolean canMountLocalSharedFolder(MessageDialog parentWindow, AbstractLocalSharedFolder localSharedFolder) { boolean canMount = super.canMountLocalSharedFolder(parentWindow, localSharedFolder); if (canMount) { MacLocalSharedFolder macLocalSharedDrive = (MacLocalSharedFolder)localSharedFolder; if (StringUtils.isBlank(macLocalSharedDrive.getLocalSharedFolderPath())) { parentWindow.showErrorDialog("The local shared folder path is not specified."); getLocalSharedFolderPathTextField().requestFocus(); canMount = false; } } return canMount; } @Override protected MacLocalSharedFolder buildLocalSharedFolder() { String remoteSharedFolderPath = getRemoteSharedFolderPath(); String remoteUsername = getRemoteUsername(); String remotePassword = getRemotePassword(); String localSharedFolderPath = getLocalSharedFolderPath(); return new MacLocalSharedFolder(remoteSharedFolderPath, remoteUsername, remotePassword, localSharedFolderPath); } @Override public void addComponents(int gapBetweenColumns, int gapBetweenRows, ActionListener browseLocalSharedFolderButtonListener, JPanel remoteMachinesButtonsPanel) { addRemoteSharedFolderPathRow(0, gapBetweenColumns, 0); addUsernameRow(1, gapBetweenColumns, gapBetweenRows); addPasswordRow(2, gapBetweenColumns, gapBetweenRows); addLocalSharedFolderRow(3, gapBetweenColumns, gapBetweenRows, "Local shared folder path", browseLocalSharedFolderButtonListener); addRemoteMachinesRow(4, gapBetweenColumns, gapBetweenRows, remoteMachinesButtonsPanel); } }
3,297
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
LinuxRemoteTopologyPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/topology/LinuxRemoteTopologyPanel.java
package org.esa.snap.remote.execution.topology; import org.apache.commons.lang3.StringUtils; import org.esa.snap.remote.execution.local.folder.AbstractLocalSharedFolder; import org.esa.snap.remote.execution.local.folder.IMountLocalSharedFolderCallback; import org.esa.snap.remote.execution.local.folder.LinuxLocalSharedFolder; import org.esa.snap.remote.execution.local.folder.MountLinuxLocalFolderTimerRunnable; import org.esa.snap.ui.loading.LoadingIndicator; import org.esa.snap.ui.loading.MessageDialog; import org.esa.snap.ui.loading.SwingUtils; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionListener; public class LinuxRemoteTopologyPanel extends RemoteTopologyPanel { private final JPasswordField localPasswordTextField; public LinuxRemoteTopologyPanel(Window parentWindow, Insets defaultTextFieldMargins, Insets defaultListItemMargins) { super(parentWindow, defaultTextFieldMargins, defaultListItemMargins); this.localPasswordTextField = new JPasswordField(); this.localPasswordTextField.setMargin(defaultTextFieldMargins); } @Override public String normalizePath(String path) { return path.replace('\\', '/'); } @Override public JPasswordField getLocalPasswordTextField() { return this.localPasswordTextField; } @Override public void setRemoteTopology(RemoteTopology remoteTopology) { super.setRemoteTopology(remoteTopology); this.localPasswordTextField.setText(remoteTopology.getLocalPassword()); } @Override public void mountLocalSharedFolderAsync(MessageDialog parentWindow, LoadingIndicator loadingIndicator, int threadId, IMountLocalSharedFolderCallback callback) { LinuxLocalSharedFolder linuxLocalSharedDrive = buildLocalSharedFolder(); if (canMountLocalSharedFolder(parentWindow, linuxLocalSharedDrive)) { MountLinuxLocalFolderTimerRunnable runnable = new MountLinuxLocalFolderTimerRunnable(parentWindow, loadingIndicator, threadId, linuxLocalSharedDrive, callback); runnable.executeAsync(); } } @Override protected LinuxLocalSharedFolder buildLocalSharedFolder() { String remoteSharedFolderPath = getRemoteSharedFolderPath(); String remoteUsername = getRemoteUsername(); String remotePassword = getRemotePassword(); String localSharedFolderPath = getLocalSharedFolderPath(); String localPassword = new String(this.localPasswordTextField.getPassword()); return new LinuxLocalSharedFolder(remoteSharedFolderPath, remoteUsername, remotePassword, localSharedFolderPath, localPassword); } @Override protected boolean canMountLocalSharedFolder(MessageDialog parentWindow, AbstractLocalSharedFolder localSharedFolder) { boolean canMount = super.canMountLocalSharedFolder(parentWindow, localSharedFolder); if (canMount) { LinuxLocalSharedFolder linuxLocalSharedDrive = (LinuxLocalSharedFolder)localSharedFolder; if (StringUtils.isBlank(linuxLocalSharedDrive.getLocalSharedFolderPath())) { parentWindow.showErrorDialog("The local shared folder path is not specified."); getLocalSharedFolderPathTextField().requestFocus(); canMount = false; } else if (StringUtils.isBlank(linuxLocalSharedDrive.getLocalPassword())) { parentWindow.showErrorDialog("The local password is not specified."); this.localPasswordTextField.requestFocus(); canMount = false; } } return canMount; } @Override public void addComponents(int gapBetweenColumns, int gapBetweenRows, ActionListener browseLocalSharedFolderButtonListener, JPanel remoteMachinesButtonsPanel) { addRemoteSharedFolderPathRow(0, gapBetweenColumns, 0); addUsernameRow(1, gapBetweenColumns, gapBetweenRows); addPasswordRow(2, gapBetweenColumns, gapBetweenRows); addLocalSharedFolderRow(3, gapBetweenColumns, gapBetweenRows, "Local shared folder path", browseLocalSharedFolderButtonListener); addLocalPasswordRow(4, gapBetweenColumns, gapBetweenRows); addRemoteMachinesRow(5, gapBetweenColumns, gapBetweenRows, remoteMachinesButtonsPanel); } protected void addLocalPasswordRow(int rowIndex, int gapBetweenColumns, int gapBetweenRows) { GridBagConstraints c = SwingUtils.buildConstraints(0, rowIndex, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); add(new JLabel("Local password"), c); c = SwingUtils.buildConstraints(1, rowIndex, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 2, 1, gapBetweenRows, gapBetweenColumns); add(this.localPasswordTextField, c); } }
4,931
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WindowsRemoteTopologyPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/topology/WindowsRemoteTopologyPanel.java
package org.esa.snap.remote.execution.topology; import org.apache.commons.lang3.StringUtils; import org.esa.snap.remote.execution.local.folder.AbstractLocalSharedFolder; import org.esa.snap.remote.execution.local.folder.IMountLocalSharedFolderCallback; import org.esa.snap.remote.execution.local.folder.MountWindowsLocalDriveTimerRunnable; import org.esa.snap.remote.execution.local.folder.WindowsLocalMachineMountDrive; import org.esa.snap.remote.execution.local.folder.WindowsLocalSharedDrive; import org.esa.snap.ui.loading.LoadingIndicator; import org.esa.snap.ui.loading.MessageDialog; import javax.swing.JPanel; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionListener; public class WindowsRemoteTopologyPanel extends RemoteTopologyPanel { public WindowsRemoteTopologyPanel(Window parentWindow, Insets defaultTextFieldMargins, Insets defaultListItemMargins) { super(parentWindow, defaultTextFieldMargins, defaultListItemMargins); } @Override public String normalizePath(String path) { return path.replace('/', '\\'); } @Override public void mountLocalSharedFolderAsync(MessageDialog parentWindow, LoadingIndicator loadingIndicator, int threadId, IMountLocalSharedFolderCallback callback) { WindowsLocalSharedDrive windowsLocalSharedDrive = buildLocalSharedFolder(); if (canMountLocalSharedFolder(parentWindow, windowsLocalSharedDrive)) { if (StringUtils.isBlank(windowsLocalSharedDrive.getLocalSharedDrive())) { // no local shared drive to mount callback.onSuccessfullyFinishMountingLocalFolder(new WindowsLocalMachineMountDrive(windowsLocalSharedDrive, false)); } else { MountWindowsLocalDriveTimerRunnable runnable = new MountWindowsLocalDriveTimerRunnable(parentWindow, loadingIndicator, threadId, windowsLocalSharedDrive, callback); runnable.executeAsync(); } } } @Override protected boolean canMountLocalSharedFolder(MessageDialog parentWindow, AbstractLocalSharedFolder localSharedFolder) { boolean canMount = super.canMountLocalSharedFolder(parentWindow, localSharedFolder); if (canMount) { WindowsLocalSharedDrive windowsLocalSharedDrive = (WindowsLocalSharedDrive)localSharedFolder; if (!StringUtils.isBlank(windowsLocalSharedDrive.getLocalSharedDrive())) { char driveLetter = windowsLocalSharedDrive.getLocalSharedDrive().charAt(0); String message = null; if (Character.isLetter(driveLetter)) { String colon = windowsLocalSharedDrive.getLocalSharedDrive().substring(1); if (!":".equals(colon)) { message = "The local shared drive letter '" + driveLetter + "' is not followed by ':'."; } } else { message = "The local shared drive is invalid. \n\nThe first character '" + driveLetter + "' is not a letter."; } if (message != null) { parentWindow.showErrorDialog(message); getLocalSharedFolderPathTextField().requestFocus(); canMount = false; } } } return canMount; } @Override protected WindowsLocalSharedDrive buildLocalSharedFolder() { String remoteSharedFolderPath = getRemoteSharedFolderPath(); String remoteUsername = getRemoteUsername(); String remotePassword = getRemotePassword(); String localSharedDrive = getLocalSharedFolderPath(); return new WindowsLocalSharedDrive(remoteSharedFolderPath, remoteUsername, remotePassword, localSharedDrive); } @Override public void addComponents(int gapBetweenColumns, int gapBetweenRows, ActionListener browseLocalSharedFolderButtonListener, JPanel remoteMachinesButtonsPanel) { addRemoteSharedFolderPathRow(0, gapBetweenColumns, 0); addUsernameRow(1, gapBetweenColumns, gapBetweenRows); addPasswordRow(2, gapBetweenColumns, gapBetweenRows); addLocalSharedFolderRow(3, gapBetweenColumns, gapBetweenRows, "Local shared drive", null); addRemoteMachinesRow(4, gapBetweenColumns, gapBetweenRows, remoteMachinesButtonsPanel); } }
4,356
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
IMountLocalSharedFolderCallback.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/IMountLocalSharedFolderCallback.java
package org.esa.snap.remote.execution.local.folder; /** * Created by jcoravu on 1/3/2019. */ public interface IMountLocalSharedFolderCallback { public void onSuccessfullyFinishMountingLocalFolder(IMountLocalSharedFolderResult result); }
245
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WindowsLocalMachineMountDrive.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/WindowsLocalMachineMountDrive.java
package org.esa.snap.remote.execution.local.folder; import org.apache.commons.lang3.StringUtils; import org.esa.snap.remote.execution.utils.CommandExecutorUtils; import org.esa.snap.ui.loading.LoadingIndicator; import java.io.IOException; /** * Created by jcoravu on 1/3/2019. */ public class WindowsLocalMachineMountDrive implements IMountLocalSharedFolderResult { private final WindowsLocalSharedDrive windowsLocalSharedDrive; private final boolean mountedSharedDrive; public WindowsLocalMachineMountDrive(WindowsLocalSharedDrive windowsLocalSharedDrive, boolean mountedSharedDrive) { this.windowsLocalSharedDrive = windowsLocalSharedDrive; this.mountedSharedDrive = mountedSharedDrive; } @Override public void unmountLocalSharedFolderAsync(LoadingIndicator loadingIndicator, int threadId, IUnmountLocalSharedFolderCallback callback) { if (canUnmountLocalSharedDrive()) { UnmountWindowsLocalDriveTimerRunnable runnable = new UnmountWindowsLocalDriveTimerRunnable(loadingIndicator, threadId, this.windowsLocalSharedDrive.getLocalSharedDrive(), callback); runnable.executeAsync(); } else { callback.onFinishUnmountingLocalFolder(null); } } @Override public void unmountLocalSharedFolder(String currentLocalSharedDrive, String currentLocalPassword) throws IOException { if (canUnmountLocalSharedDrive()) { CommandExecutorUtils.unmountWindowsLocalDrive(this.windowsLocalSharedDrive.getLocalSharedDrive()); } } @Override public WindowsLocalSharedDrive getLocalSharedDrive() { return windowsLocalSharedDrive; } private boolean canUnmountLocalSharedDrive() { return (!StringUtils.isBlank(this.windowsLocalSharedDrive.getLocalSharedDrive()) && this.mountedSharedDrive); } }
1,859
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WindowsLocalSharedDrive.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/WindowsLocalSharedDrive.java
package org.esa.snap.remote.execution.local.folder; import org.apache.commons.lang3.StringUtils; /** * Created by jcoravu on 23/5/2019. */ public class WindowsLocalSharedDrive extends AbstractLocalSharedFolder { private final String localSharedDrive; public WindowsLocalSharedDrive(String remoteSharedFolderPath, String remoteUsername, String remotePassword, String localSharedDrive) { super(remoteSharedFolderPath, remoteUsername, remotePassword); this.localSharedDrive = localSharedDrive; } public String getLocalSharedDrive() { return localSharedDrive; } @Override public boolean hasChangedParameters(AbstractLocalSharedFolder newLocalSharedFolder) { boolean changedParameters = super.hasChangedParameters(newLocalSharedFolder); if (!changedParameters) { WindowsLocalSharedDrive newWindowsLocalSharedDrive = (WindowsLocalSharedDrive)newLocalSharedFolder; String localDrive = StringUtils.isBlank(this.localSharedDrive) ? "" : this.localSharedDrive; String newLocalDrive = StringUtils.isBlank(newWindowsLocalSharedDrive.getLocalSharedDrive()) ? "" : newWindowsLocalSharedDrive.getLocalSharedDrive(); changedParameters = !localDrive.equals(newLocalDrive); } return changedParameters; } }
1,334
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
IMountLocalSharedFolderResult.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/IMountLocalSharedFolderResult.java
package org.esa.snap.remote.execution.local.folder; import org.esa.snap.ui.loading.LoadingIndicator; import java.io.IOException; /** * Created by jcoravu on 1/3/2019. */ public interface IMountLocalSharedFolderResult { public AbstractLocalSharedFolder getLocalSharedDrive(); public void unmountLocalSharedFolderAsync(LoadingIndicator loadingIndicator, int threadId, IUnmountLocalSharedFolderCallback callback); public void unmountLocalSharedFolder(String currentLocalSharedFolderPath, String currentLocalPassword) throws IOException; }
556
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MountLinuxLocalFolderTimerRunnable.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/MountLinuxLocalFolderTimerRunnable.java
package org.esa.snap.remote.execution.local.folder; import org.esa.snap.remote.execution.utils.CommandExecutorUtils; import org.esa.snap.remote.execution.utils.UnixMountLocalFolderResult; import org.esa.snap.ui.loading.LoadingIndicator; import org.esa.snap.ui.loading.MessageDialog; public class MountLinuxLocalFolderTimerRunnable extends MountMacLocalFolderTimerRunnable { public MountLinuxLocalFolderTimerRunnable(MessageDialog parentWindow, LoadingIndicator loadingIndicator, int threadId, LinuxLocalSharedFolder linuxLocalSharedDrive, IMountLocalSharedFolderCallback callback) { super(parentWindow, loadingIndicator, threadId, linuxLocalSharedDrive, callback); } @Override protected void onSuccessfullyFinish(UnixMountLocalFolderResult result) { if (result.isSharedFolderMounted()) { LinuxLocalSharedFolder linuxLocalSharedDrive = (LinuxLocalSharedFolder)this.macLocalSharedDrive; LinuxLocalMachineMountFolder mountFolder = new LinuxLocalMachineMountFolder(linuxLocalSharedDrive, result); this.callback.onSuccessfullyFinishMountingLocalFolder(mountFolder); } else { showErrorDialog(); } } @Override protected UnixMountLocalFolderResult execute() throws Exception { LinuxLocalSharedFolder linuxLocalSharedDrive = (LinuxLocalSharedFolder)this.macLocalSharedDrive; return CommandExecutorUtils.mountLinuxLocalFolder(linuxLocalSharedDrive.getRemoteSharedFolderPath(), linuxLocalSharedDrive.getRemoteUsername(), linuxLocalSharedDrive.getRemotePassword(), linuxLocalSharedDrive.getLocalSharedFolderPath(), linuxLocalSharedDrive.getLocalPassword()); } }
1,860
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
LinuxLocalMachineMountFolder.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/LinuxLocalMachineMountFolder.java
package org.esa.snap.remote.execution.local.folder; import org.esa.snap.remote.execution.utils.CommandExecutorUtils; import org.esa.snap.remote.execution.utils.UnixMountLocalFolderResult; import org.esa.snap.ui.loading.LoadingIndicator; import java.io.IOException; /** * Created by jcoravu on 1/3/2019. */ public class LinuxLocalMachineMountFolder implements IMountLocalSharedFolderResult { private final LinuxLocalSharedFolder linuxLocalSharedDrive; private final UnixMountLocalFolderResult localMachineLinuxMountFolder; public LinuxLocalMachineMountFolder(LinuxLocalSharedFolder linuxLocalSharedDrive, UnixMountLocalFolderResult localMachineLinuxMountFolder) { this.linuxLocalSharedDrive = linuxLocalSharedDrive; this.localMachineLinuxMountFolder = localMachineLinuxMountFolder; } @Override public LinuxLocalSharedFolder getLocalSharedDrive() { return this.linuxLocalSharedDrive; } @Override public void unmountLocalSharedFolderAsync(LoadingIndicator loadingIndicator, int threadId, IUnmountLocalSharedFolderCallback callback) { if (canUnmountLocalSharedFolder()) { UnmountLinuxLocalFolderTimerRunnable runnable = new UnmountLinuxLocalFolderTimerRunnable(loadingIndicator, threadId, this.linuxLocalSharedDrive.getLocalSharedFolderPath(), this.linuxLocalSharedDrive.getLocalPassword(), this.localMachineLinuxMountFolder, callback); runnable.executeAsync(); } else { callback.onFinishUnmountingLocalFolder(null); } } @Override public void unmountLocalSharedFolder(String currentLocalSharedFolderPath, String currentLocalPassword) throws IOException { if (canUnmountLocalSharedFolder()) { CommandExecutorUtils.unmountLinuxLocalFolder(this.linuxLocalSharedDrive.getLocalSharedFolderPath(), this.linuxLocalSharedDrive.getLocalPassword(), this.localMachineLinuxMountFolder); } } private boolean canUnmountLocalSharedFolder() { return (this.localMachineLinuxMountFolder.isSharedFolderCreated() || this.localMachineLinuxMountFolder.isSharedFolderMounted()); } }
2,287
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MacLocalMachineMountFolder.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/MacLocalMachineMountFolder.java
package org.esa.snap.remote.execution.local.folder; import org.esa.snap.remote.execution.utils.CommandExecutorUtils; import org.esa.snap.remote.execution.utils.UnixMountLocalFolderResult; import org.esa.snap.ui.loading.LoadingIndicator; import java.io.IOException; /** * Created by jcoravu on 1/3/2019. */ public class MacLocalMachineMountFolder implements IMountLocalSharedFolderResult { private final MacLocalSharedFolder macLocalSharedDrive; private final UnixMountLocalFolderResult localMachineLinuxMountFolder; public MacLocalMachineMountFolder(MacLocalSharedFolder macLocalSharedDrive, UnixMountLocalFolderResult localMachineLinuxMountFolder) { this.macLocalSharedDrive = macLocalSharedDrive; this.localMachineLinuxMountFolder = localMachineLinuxMountFolder; } @Override public MacLocalSharedFolder getLocalSharedDrive() { return this.macLocalSharedDrive; } @Override public void unmountLocalSharedFolderAsync(LoadingIndicator loadingIndicator, int threadId, IUnmountLocalSharedFolderCallback callback) { if (canUnmountLocalSharedFolder()) { UnmountMacLocalFolderTimerRunnable runnable = new UnmountMacLocalFolderTimerRunnable(loadingIndicator, threadId, this.macLocalSharedDrive.getLocalSharedFolderPath(), this.localMachineLinuxMountFolder, callback); runnable.executeAsync(); } else { callback.onFinishUnmountingLocalFolder(null); } } @Override public void unmountLocalSharedFolder(String currentLocalSharedFolderPath, String currentLocalPassword) throws IOException { if (canUnmountLocalSharedFolder()) { CommandExecutorUtils.unmountMacLocalFolder(this.macLocalSharedDrive.getLocalSharedFolderPath(), this.localMachineLinuxMountFolder); } } private boolean canUnmountLocalSharedFolder() { return (this.localMachineLinuxMountFolder.isSharedFolderCreated() || this.localMachineLinuxMountFolder.isSharedFolderMounted()); } }
2,120
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
LinuxLocalSharedFolder.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/LinuxLocalSharedFolder.java
package org.esa.snap.remote.execution.local.folder; /** * Created by jcoravu on 23/5/2019. */ public class LinuxLocalSharedFolder extends MacLocalSharedFolder { private final String localPassword; public LinuxLocalSharedFolder(String remoteSharedFolderPath, String remoteUsername, String remotePassword, String localSharedFolderPath, String localPassword) { super(remoteSharedFolderPath, remoteUsername, remotePassword, localSharedFolderPath); this.localPassword = localPassword; } @Override public boolean hasChangedParameters(AbstractLocalSharedFolder newLocalSharedFolder) { boolean changedParameters = super.hasChangedParameters(newLocalSharedFolder); if (!changedParameters) { LinuxLocalSharedFolder newLinuxLocalSharedDrive = (LinuxLocalSharedFolder)newLocalSharedFolder; changedParameters = !this.localPassword.equals(newLinuxLocalSharedDrive.getLocalPassword()); } return changedParameters; } public String getLocalPassword() { return localPassword; } }
1,083
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MacLocalSharedFolder.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/MacLocalSharedFolder.java
package org.esa.snap.remote.execution.local.folder; /** * Created by jcoravu on 23/5/2019. */ public class MacLocalSharedFolder extends AbstractLocalSharedFolder { private final String localSharedFolderPath; public MacLocalSharedFolder(String remoteSharedFolderPath, String remoteUsername, String remotePassword, String localSharedFolderPath) { super(remoteSharedFolderPath, remoteUsername, remotePassword); this.localSharedFolderPath = localSharedFolderPath; } @Override public boolean hasChangedParameters(AbstractLocalSharedFolder newLocalSharedFolder) { boolean changedParameters = super.hasChangedParameters(newLocalSharedFolder); if (!changedParameters) { MacLocalSharedFolder newMacLocalSharedDrive = (MacLocalSharedFolder)newLocalSharedFolder; changedParameters = !this.localSharedFolderPath.equals(newMacLocalSharedDrive.getLocalSharedFolderPath()); } return changedParameters; } public String getLocalSharedFolderPath() { return localSharedFolderPath; } }
1,087
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
IUnmountLocalSharedFolderCallback.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/IUnmountLocalSharedFolderCallback.java
package org.esa.snap.remote.execution.local.folder; /** * Created by jcoravu on 1/3/2019. */ public interface IUnmountLocalSharedFolderCallback { public void onFinishUnmountingLocalFolder(Exception exception); }
220
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AbstractLocalSharedFolder.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/AbstractLocalSharedFolder.java
package org.esa.snap.remote.execution.local.folder; /** * Created by jcoravu on 23/5/2019. */ public abstract class AbstractLocalSharedFolder { private final String remoteSharedFolderPath; private final String remoteUsername; private final String remotePassword; protected AbstractLocalSharedFolder(String remoteSharedFolderPath, String remoteUsername, String remotePassword) { this.remoteSharedFolderPath = remoteSharedFolderPath; this.remoteUsername = remoteUsername; this.remotePassword = remotePassword; } public String getRemoteSharedFolderPath() { return remoteSharedFolderPath; } public String getRemotePassword() { return remotePassword; } public String getRemoteUsername() { return remoteUsername; } public boolean hasChangedParameters(AbstractLocalSharedFolder newLocalSharedFolder) { if (this.remoteSharedFolderPath.equals(newLocalSharedFolder.getRemoteSharedFolderPath())) { if (this.remoteUsername.equals(newLocalSharedFolder.getRemoteUsername())) { if (this.remotePassword.equals(newLocalSharedFolder.getRemotePassword())) { return false; } } } return true; // the parameters has changed } }
1,315
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
UnmountMacLocalFolderTimerRunnable.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/UnmountMacLocalFolderTimerRunnable.java
package org.esa.snap.remote.execution.local.folder; import org.esa.snap.remote.execution.utils.CommandExecutorUtils; import org.esa.snap.remote.execution.utils.UnixMountLocalFolderResult; import org.esa.snap.ui.loading.AbstractTimerRunnable; import org.esa.snap.ui.loading.LoadingIndicator; public class UnmountMacLocalFolderTimerRunnable extends AbstractTimerRunnable<Void> { protected final String localSharedFolderPath; protected final UnixMountLocalFolderResult localMachineLinuxMountFolder; private final IUnmountLocalSharedFolderCallback callback; public UnmountMacLocalFolderTimerRunnable(LoadingIndicator loadingIndicator, int threadId, String localSharedFolderPath, UnixMountLocalFolderResult localMachineLinuxMountFolder, IUnmountLocalSharedFolderCallback callback) { super(loadingIndicator, threadId, 500); this.localSharedFolderPath = localSharedFolderPath; this.localMachineLinuxMountFolder = localMachineLinuxMountFolder; this.callback = callback; } @Override protected final void onTimerWakeUp(String messageToDisplay) { super.onTimerWakeUp("Unmounting local shared folder..."); } @Override protected final String getExceptionLoggingMessage() { return "Failed to unmount the local shared folder '"+this.localSharedFolderPath+"'."; } @Override protected final void onSuccessfullyFinish(Void result) { this.callback.onFinishUnmountingLocalFolder(null); } @Override protected final void onFailed(Exception exception) { this.callback.onFinishUnmountingLocalFolder(exception); } @Override protected Void execute() throws Exception { CommandExecutorUtils.unmountMacLocalFolder(this.localSharedFolderPath, this.localMachineLinuxMountFolder); return null; } }
1,885
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MountWindowsLocalDriveTimerRunnable.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/MountWindowsLocalDriveTimerRunnable.java
package org.esa.snap.remote.execution.local.folder; import org.esa.snap.remote.execution.utils.CommandExecutorUtils; import org.esa.snap.ui.loading.AbstractTimerRunnable; import org.esa.snap.ui.loading.LoadingIndicator; import org.esa.snap.ui.loading.MessageDialog; public class MountWindowsLocalDriveTimerRunnable extends AbstractTimerRunnable<Boolean> { private final MessageDialog parentWindow; private final WindowsLocalSharedDrive windowsLocalSharedDrive; private final IMountLocalSharedFolderCallback callback; public MountWindowsLocalDriveTimerRunnable(MessageDialog parentWindow, LoadingIndicator loadingIndicator, int threadId, WindowsLocalSharedDrive windowsLocalSharedDrive, IMountLocalSharedFolderCallback callback) { super(loadingIndicator, threadId, 500); this.parentWindow = parentWindow; this.windowsLocalSharedDrive = windowsLocalSharedDrive; this.callback = callback; } @Override protected final void onTimerWakeUp(String messageToDisplay) { super.onTimerWakeUp("Mounting local shared drive..."); } @Override protected String getExceptionLoggingMessage() { return "Failed to mount the local shared drive '"+this.windowsLocalSharedDrive.getLocalSharedDrive()+"'."; } @Override protected final void onFailed(Exception exception) { showErrorDialog(); } @Override protected void onSuccessfullyFinish(Boolean mountedSharedDrive) { if (mountedSharedDrive.booleanValue()) { this.callback.onSuccessfullyFinishMountingLocalFolder(new WindowsLocalMachineMountDrive(this.windowsLocalSharedDrive, mountedSharedDrive)); } else { showErrorDialog(); } } @Override protected Boolean execute() throws Exception { return CommandExecutorUtils.mountWindowsLocalDrive(this.windowsLocalSharedDrive.getRemoteSharedFolderPath(), this.windowsLocalSharedDrive.getRemoteUsername(), this.windowsLocalSharedDrive.getRemotePassword(), this.windowsLocalSharedDrive.getLocalSharedDrive()); } private void showErrorDialog() { this.parentWindow.showErrorDialog("Failed to mount the local shared drive '"+this.windowsLocalSharedDrive.getLocalSharedDrive()+"'.", "Failed"); } }
2,393
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
UnmountWindowsLocalDriveTimerRunnable.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/UnmountWindowsLocalDriveTimerRunnable.java
package org.esa.snap.remote.execution.local.folder; import org.esa.snap.remote.execution.utils.CommandExecutorUtils; import org.esa.snap.ui.loading.AbstractTimerRunnable; import org.esa.snap.ui.loading.LoadingIndicator; public class UnmountWindowsLocalDriveTimerRunnable extends AbstractTimerRunnable<Void> { private final String localSharedDrive; private final IUnmountLocalSharedFolderCallback callback; public UnmountWindowsLocalDriveTimerRunnable(LoadingIndicator loadingIndicator, int threadId, String localSharedDrive, IUnmountLocalSharedFolderCallback callback) { super(loadingIndicator, threadId, 500); this.localSharedDrive = localSharedDrive; this.callback = callback; } @Override protected final void onTimerWakeUp(String messageToDisplay) { super.onTimerWakeUp("Unmounting local shared drive..."); } @Override protected String getExceptionLoggingMessage() { return "Failed to unmount the local shared drive '"+this.localSharedDrive +"'."; } @Override protected void onSuccessfullyFinish(Void result) { this.callback.onFinishUnmountingLocalFolder(null); } @Override protected void onFailed(Exception exception) { this.callback.onFinishUnmountingLocalFolder(exception); } @Override protected Void execute() throws Exception { CommandExecutorUtils.unmountWindowsLocalDrive(this.localSharedDrive); return null; } }
1,481
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MountMacLocalFolderTimerRunnable.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/MountMacLocalFolderTimerRunnable.java
package org.esa.snap.remote.execution.local.folder; import org.esa.snap.remote.execution.utils.CommandExecutorUtils; import org.esa.snap.remote.execution.utils.UnixMountLocalFolderResult; import org.esa.snap.ui.loading.AbstractTimerRunnable; import org.esa.snap.ui.loading.LoadingIndicator; import org.esa.snap.ui.loading.MessageDialog; public class MountMacLocalFolderTimerRunnable extends AbstractTimerRunnable<UnixMountLocalFolderResult> { private final MessageDialog parentWindow; protected final MacLocalSharedFolder macLocalSharedDrive; protected final IMountLocalSharedFolderCallback callback; public MountMacLocalFolderTimerRunnable(MessageDialog parentWindow, LoadingIndicator loadingIndicator, int threadId, MacLocalSharedFolder macLocalSharedDrive, IMountLocalSharedFolderCallback callback) { super(loadingIndicator, threadId, 500); this.parentWindow = parentWindow; this.macLocalSharedDrive = macLocalSharedDrive; this.callback = callback; } @Override protected final void onTimerWakeUp(String messageToDisplay) { super.onTimerWakeUp("Mounting local shared folder..."); } @Override protected final String getExceptionLoggingMessage() { return "Failed to mount the local shared folder '"+this.macLocalSharedDrive.getLocalSharedFolderPath()+"'."; } @Override protected final void onFailed(Exception exception) { showErrorDialog(); } @Override protected void onSuccessfullyFinish(UnixMountLocalFolderResult result) { if (result.isSharedFolderMounted()) { this.callback.onSuccessfullyFinishMountingLocalFolder(new MacLocalMachineMountFolder(this.macLocalSharedDrive, result)); } else { showErrorDialog(); } } @Override protected UnixMountLocalFolderResult execute() throws Exception { return CommandExecutorUtils.mountMacLocalFolder(this.macLocalSharedDrive.getRemoteSharedFolderPath(), this.macLocalSharedDrive.getRemoteUsername(), this.macLocalSharedDrive.getRemotePassword(), this.macLocalSharedDrive.getLocalSharedFolderPath()); } protected final void showErrorDialog() { this.parentWindow.showErrorDialog("Failed to mount the local shared folder '"+this.macLocalSharedDrive.getLocalSharedFolderPath()+"'.", "Failed"); } }
2,527
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
UnmountLinuxLocalFolderTimerRunnable.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-remote-execution-ui/src/main/java/org/esa/snap/remote/execution/local/folder/UnmountLinuxLocalFolderTimerRunnable.java
package org.esa.snap.remote.execution.local.folder; import org.esa.snap.remote.execution.utils.CommandExecutorUtils; import org.esa.snap.remote.execution.utils.UnixMountLocalFolderResult; import org.esa.snap.ui.loading.LoadingIndicator; public class UnmountLinuxLocalFolderTimerRunnable extends UnmountMacLocalFolderTimerRunnable { private final String localPassword; public UnmountLinuxLocalFolderTimerRunnable(LoadingIndicator loadingIndicator, int threadId, String localSharedFolderPath, String localPassword, UnixMountLocalFolderResult localMachineLinuxMountFolder, IUnmountLocalSharedFolderCallback callback) { super(loadingIndicator, threadId, localSharedFolderPath, localMachineLinuxMountFolder, callback); this.localPassword = localPassword; } @Override protected Void execute() throws Exception { CommandExecutorUtils.unmountLinuxLocalFolder(this.localSharedFolderPath, this.localPassword, this.localMachineLinuxMountFolder); return null; } }
1,063
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TargetProductSelectorModelTest.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/test/java/org/esa/snap/core/gpf/ui/TargetProductSelectorModelTest.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.core.gpf.ui; import com.bc.ceres.core.ProgressMonitor; import org.esa.snap.core.dataio.AbstractProductWriter; import org.esa.snap.core.dataio.EncodeQualification; import org.esa.snap.core.dataio.ProductIOPlugInManager; import org.esa.snap.core.dataio.ProductWriter; import org.esa.snap.core.dataio.ProductWriterPlugIn; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductData; import org.esa.snap.core.util.io.SnapFileFilter; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.Locale; import static org.junit.Assert.*; /** * Tests for class {@link TargetProductSelectorModel}. * * @author Ralf Quast * @version $Revision$ $Date$ */ public class TargetProductSelectorModelTest { private TargetProductSelectorModel model; private DummyTestProductWriterPlugIn writerPlugIn; @Before public void setUp() throws Exception { writerPlugIn = new DummyTestProductWriterPlugIn(); ProductIOPlugInManager.getInstance().addWriterPlugIn(writerPlugIn); model = new TargetProductSelectorModel(); } @Test public void testSetGetProductName() { model.setProductName("Obelix"); assertEquals("Obelix", model.getProductName()); } @Test public void testSetGetInvalidProductName() { assertNull(model.getProductName()); try { model.setProductName("Obel/x"); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().startsWith("The product name 'Obel/x' is not valid")); } assertNull(model.getProductName()); } @Test public void testSetGetFormatName() { model.setFormatName("Majestix"); assertEquals("Majestix", model.getFormatName()); } @Test public void testGetFileName() { model.setProductName("Obelix"); assertEquals("Obelix", model.getProductName()); assertEquals("Obelix.dim", model.getProductFileName()); // other format model.setFormatName(writerPlugIn.getFormatNames()[0]); assertEquals("Obelix.x", model.getProductFileName()); model.setProductName("Idefix.dim"); assertEquals("Idefix.dim.x", model.getProductFileName()); model.setProductName("Idefix.x"); assertEquals("Idefix.x", model.getProductFileName()); } @Test public void testSetGetDirectory() { final File directory = new File("Gallien"); model.setProductDir(directory); assertEquals(directory, model.getProductDir()); model.setProductName("Obelix"); assertEquals(new File("Gallien", "Obelix.dim"), model.getProductFile()); // other format model.setFormatName(writerPlugIn.getFormatNames()[0]); assertEquals(new File("Gallien", "Obelix.x"), model.getProductFile()); } @Test public void testSelections() { assertTrue(model.isSaveToFileSelected()); assertTrue(model.isOpenInAppSelected()); model.setOpenInAppSelected(false); assertFalse(model.isOpenInAppSelected()); assertTrue(model.isSaveToFileSelected()); model.setSaveToFileSelected(false); assertFalse(model.isSaveToFileSelected()); assertTrue(model.isOpenInAppSelected()); model.setOpenInAppSelected(false); assertFalse(model.isOpenInAppSelected()); assertTrue(model.isSaveToFileSelected()); } private class DummyTestProductWriter extends AbstractProductWriter { public DummyTestProductWriter(ProductWriterPlugIn writerPlugIn) { super(writerPlugIn); } @Override protected void writeProductNodesImpl() throws IOException { } public void writeBandRasterData(Band sourceBand, int sourceOffsetX, int sourceOffsetY, int sourceWidth, int sourceHeight, ProductData sourceBuffer, ProgressMonitor pm) throws IOException { } public void flush() throws IOException { } public void close() throws IOException { } public void deleteOutput() throws IOException { } } private class DummyTestProductWriterPlugIn implements ProductWriterPlugIn { @Override public EncodeQualification getEncodeQualification(Product product) { return EncodeQualification.FULL; } public Class[] getOutputTypes() { return new Class[]{String.class}; } public ProductWriter createWriterInstance() { return new DummyTestProductWriter(this); } public String[] getFormatNames() { return new String[]{"Dummy"}; } public String[] getDefaultFileExtensions() { return new String[]{".x"}; } public String getDescription(Locale locale) { return ""; } public SnapFileFilter getProductFileFilter() { return new SnapFileFilter(); } } }
5,868
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DefaultSingleTargetProductDialogTest.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/test/java/org/esa/snap/core/gpf/ui/DefaultSingleTargetProductDialogTest.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.core.gpf.ui; import com.bc.ceres.core.ProgressMonitor; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductData; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.Operator; import org.esa.snap.core.gpf.OperatorException; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.gpf.Tile; import org.esa.snap.core.gpf.annotations.Parameter; import org.esa.snap.core.gpf.annotations.SourceProduct; import org.esa.snap.core.gpf.annotations.TargetProduct; import org.esa.snap.core.util.converters.GeneralExpressionConverter; import org.esa.snap.ui.DefaultAppContext; import javax.swing.UIManager; public class DefaultSingleTargetProductDialogTest { private static final TestOp.Spi SPI = new TestOp.Spi(); public static void main(String[] args) throws Exception { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); GPF.getDefaultInstance().getOperatorSpiRegistry().addOperatorSpi(SPI); try { DefaultAppContext app = new DefaultAppContext("Killer App"); app.getApplicationWindow().setSize(200, 200); final DefaultSingleTargetProductDialog dialog = (DefaultSingleTargetProductDialog) DefaultSingleTargetProductDialog.createDefaultDialog( TestOp.Spi.class.getName(), app); dialog.setTargetProductNameSuffix("_test"); dialog.getJDialog().setTitle("TestOp GUI"); dialog.show(); } finally { GPF.getDefaultInstance().getOperatorSpiRegistry().removeOperatorSpi(SPI); } } public static class TestOp extends Operator { @SourceProduct Product masterProduct; @SourceProduct Product slaveProduct; @TargetProduct Product target; @Parameter(defaultValue = "true") boolean copyTiePointGrids; @Parameter(defaultValue = "false") Boolean copyMetadata; @Parameter(interval = "[-1,+1]", defaultValue = "-0.1") double threshold; @Parameter(valueSet = {"ME-203", "ME-208", "ME-002"}, defaultValue = "ME-208") String method; @Parameter(description = "Mask expression", label = "Mask expression", converter = GeneralExpressionConverter.class) String validExpression; @Override public void initialize() throws OperatorException { Product product = new Product("N", "T", 16, 16); product.addBand("B1", ProductData.TYPE_FLOAT32); product.addBand("B2", ProductData.TYPE_FLOAT32); product.setPreferredTileSize(4, 4); //System.out.println("product = " + product); target = product; } @Override public void computeTile(Band targetBand, Tile targetTile, ProgressMonitor pm) throws OperatorException { } public static class Spi extends OperatorSpi { public Spi() { super(TestOp.class); } } } }
3,795
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SourceProductSelectorTest.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/test/java/org/esa/snap/core/gpf/ui/SourceProductSelectorTest.java
/* * Copyright (C) 2014 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.core.gpf.ui; import org.esa.snap.core.datamodel.Product; import com.bc.ceres.test.LongTestRunner; import org.esa.snap.ui.DefaultAppContext; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import javax.swing.JComboBox; import java.awt.GraphicsEnvironment; import java.io.File; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; /** * @author Ralf Quast */ @RunWith(LongTestRunner.class) public class SourceProductSelectorTest { private Product[] defaultProducts; private DefaultAppContext appContext; @Before public void setUp() { Assume.assumeFalse("Cannot run in headless", GraphicsEnvironment.isHeadless()); appContext = new DefaultAppContext("CrazyApp!"); defaultProducts = new Product[4]; for (int i = 0; i < defaultProducts.length; i++) { defaultProducts[i] = new Product("P" + i, "T" + i, 10, 10); appContext.getProductManager().addProduct(defaultProducts[i]); } appContext.setSelectedProduct(defaultProducts[0]); } @Test public void testCreatedUIComponentsNotNull() { SourceProductSelector selector = new SourceProductSelector(appContext, "Source:"); selector.initProducts(); Assert.assertNotNull(selector.getProductNameLabel()); Assert.assertNotNull(selector.getProductNameComboBox()); Assert.assertNotNull(selector.getProductFileChooserButton()); } @Test public void testCreatedUIComponentsAreSame() { SourceProductSelector selector = new SourceProductSelector(appContext, "Source:"); selector.initProducts(); assertSame(selector.getProductNameLabel(), selector.getProductNameLabel()); assertSame(selector.getProductNameComboBox(), selector.getProductNameComboBox()); assertSame(selector.getProductFileChooserButton(), selector.getProductFileChooserButton()); } @Test public void testThatComboboxContains_4_EntriesIfEmptySelectionIsDisabled() { boolean enableEmptySelection = false; SourceProductSelector selector = new SourceProductSelector(appContext, "Source", enableEmptySelection); selector.initProducts(); final JComboBox<Object> comboBox = selector.getProductNameComboBox(); assertEquals(4, comboBox.getItemCount()); assertEquals(comboBox.getItemAt(0), defaultProducts[0]); assertEquals(comboBox.getItemAt(1), defaultProducts[1]); assertEquals(comboBox.getItemAt(2), defaultProducts[2]); assertEquals(comboBox.getItemAt(3), defaultProducts[3]); assertEquals(4, selector.getProductCount()); } @Test public void testThatComboboxContains_5_EntriesIfEmptySelectionIsEnabled() { boolean enableEmptySelection = true; SourceProductSelector selector = new SourceProductSelector(appContext, "Source", enableEmptySelection); selector.initProducts(); final JComboBox<Object> comboBox = selector.getProductNameComboBox(); assertEquals(5, comboBox.getItemCount()); assertNull(comboBox.getItemAt(0)); assertEquals(comboBox.getItemAt(1), defaultProducts[0]); assertEquals(comboBox.getItemAt(2), defaultProducts[1]); assertEquals(comboBox.getItemAt(3), defaultProducts[2]); assertEquals(comboBox.getItemAt(4), defaultProducts[3]); assertEquals(4, selector.getProductCount()); } @Test public void testSetSelectedProduct() { SourceProductSelector selector = new SourceProductSelector(appContext, "Source"); selector.initProducts(); Product selectedProduct = selector.getSelectedProduct(); assertSame(appContext.getSelectedProduct(), selectedProduct); selector.setSelectedProduct(defaultProducts[1]); selectedProduct = selector.getSelectedProduct(); assertSame(defaultProducts[1], selectedProduct); Product oldProduct = new Product("new", "T1", 0, 0); oldProduct.setFileLocation(new File("")); selector.setSelectedProduct(oldProduct); selectedProduct = selector.getSelectedProduct(); assertSame(oldProduct, selectedProduct); Product newProduct = new Product("new", "T2", 0, 0); selector.setSelectedProduct(newProduct); selectedProduct = selector.getSelectedProduct(); assertSame(newProduct, selectedProduct); Assert.assertNull(oldProduct.getFileLocation()); // assert that old product is disposed } @Test public void testSelectedProductIsRemoved() { SourceProductSelector selector = new SourceProductSelector(appContext, "Source"); selector.initProducts(); appContext.getProductManager().removeProduct(defaultProducts[0]); Assert.assertEquals(defaultProducts.length - 1, selector.getProductCount()); } @Test public void testNotSelectedProductIsRemoved() { SourceProductSelector selector = new SourceProductSelector(appContext, "Source"); selector.initProducts(); appContext.getProductManager().removeProduct(defaultProducts[2]); Assert.assertEquals(defaultProducts.length - 1, selector.getProductCount()); } @Test public void testNewProductIsDisposed() { SourceProductSelector selector = new SourceProductSelector(appContext, "Source"); selector.initProducts(); Product newProduct = new Product("new", "T1", 0, 0); newProduct.setFileLocation(new File("")); selector.setSelectedProduct(newProduct); assertSame(newProduct, selector.getSelectedProduct()); selector.setSelectedProduct(defaultProducts[0]); assertSame(defaultProducts[0], selector.getSelectedProduct()); Assert.assertNotNull(newProduct.getFileLocation()); selector.releaseProducts(); Assert.assertNull(newProduct.getFileLocation()); // assert that new product is disposed, because it is not selected } @Test public void testNewProductIsNotDisposed() { SourceProductSelector selector = new SourceProductSelector(appContext, "Source"); selector.initProducts(); selector.setSelectedProduct(defaultProducts[0]); assertSame(defaultProducts[0], selector.getSelectedProduct()); Product newProduct = new Product("new", "T1", 0, 0); newProduct.setFileLocation(new File("")); selector.setSelectedProduct(newProduct); assertSame(newProduct, selector.getSelectedProduct()); Assert.assertNotNull(newProduct.getFileLocation()); selector.releaseProducts(); Assert.assertNotNull(newProduct.getFileLocation()); // assert that new product is not disposed while it is selected } @Test public void testSetSelectedIndex() { SourceProductSelector selector = new SourceProductSelector(appContext, "Source"); selector.initProducts(); assertSame(defaultProducts[0], selector.getSelectedProduct()); selector.setSelectedIndex(1); assertSame(defaultProducts[1], selector.getSelectedProduct()); selector.setSelectedIndex(2); assertSame(defaultProducts[2], selector.getSelectedProduct()); } }
8,047
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OperatorParameterSupportTest.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/test/java/org/esa/snap/core/gpf/ui/OperatorParameterSupportTest.java
/* * Copyright (C) 2011 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.core.gpf.ui; import com.bc.ceres.binding.ConversionException; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.dom.DomElement; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.Operator; import org.esa.snap.core.gpf.OperatorException; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.gpf.annotations.OperatorMetadata; import org.esa.snap.core.gpf.annotations.Parameter; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.*; public class OperatorParameterSupportTest { private static TestOpSpi testOpSpi; @BeforeClass public static void beforeClass() { testOpSpi = new TestOpSpi(); GPF.getDefaultInstance().getOperatorSpiRegistry().addOperatorSpi(testOpSpi); } @AfterClass public static void afterClass() { GPF.getDefaultInstance().getOperatorSpiRegistry().removeOperatorSpi(testOpSpi); } @Test public void testStoreAndLoadParameter() throws IOException, ValidationException, ConversionException { final OperatorParameterSupport support = new OperatorParameterSupport(new TestOpSpi().getOperatorDescriptor()); PropertySet container = support.getPropertySet(); container.setValue("paramDouble", 0.42); container.setValue("paramString", "A String!"); container.setValue("paramComplex", new Complex(25)); final DomElement domElement = support.toDomElement(); assertEquals("parameters", domElement.getName()); assertEquals(3, domElement.getChildCount()); assertNotNull(domElement.getChild("paramDouble")); assertEquals("0.42", domElement.getChild("paramDouble").getValue()); assertNotNull(domElement.getChild("paramString")); assertEquals("A String!", domElement.getChild("paramString").getValue()); assertNotNull(domElement.getChild("paramComplex")); assertNotNull(domElement.getChild("paramComplex").getChild("complexInt")); assertEquals("25", domElement.getChild("paramComplex").getChild("complexInt").getValue()); // change container container.setValue("paramDouble", 23.67); container.setValue("paramString", "Another String"); container.setValue("paramComplex", new Complex(17)); support.fromDomElement(domElement); assertEquals(0.42, (double)support.getPropertySet().getValue("paramDouble"), 1.0e-6); assertEquals("A String!", support.getPropertySet().getValue("paramString")); assertEquals(new Complex(25), support.getPropertySet().getValue("paramComplex")); } @Test public void testStoreAndLoadParameterWhenNotAllParamsAreGiven() throws IOException, ValidationException, ConversionException { final OperatorParameterSupport support = new OperatorParameterSupport(new TestOpSpi().getOperatorDescriptor()); PropertySet container = support.getPropertySet(); container.setValue("paramDouble", 0.42); final DomElement domElement = support.toDomElement(); // change container container.setValue("paramDouble", 23.67); container.setValue("paramString", "Another String"); container.setValue("paramComplex", new Complex(17)); support.fromDomElement(domElement); assertEquals(0.42, (double)support.getPropertySet().getValue("paramDouble"), 1.0e-6); assertEquals(null, support.getPropertySet().getValue("paramString")); assertEquals(null, support.getPropertySet().getValue("paramComplex")); } @OperatorMetadata(alias = "Tester", authors = "Nobody", version = "42", description = "This is very stupid operator.") public class TestOp extends Operator { @Parameter private double paramDouble; @Parameter private String paramString; @Parameter private Complex paramComplex; @Override public void initialize() throws OperatorException { } } public static class TestOpSpi extends OperatorSpi { protected TestOpSpi() { super(TestOp.class); } } public static class Complex { public Complex() { this(-1); } private Complex(int complexInt) { this.complexInt = complexInt; } @Parameter private int complexInt; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Complex complex = (Complex) o; if (complexInt != complex.complexInt) { return false; } return true; } @Override public int hashCode() { return complexInt; } } }
5,786
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z