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 |
---|---|---|---|---|---|---|---|---|---|---|---|
package-info.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-virtual-file-system-preferences-ui/src/main/java/org/esa/snap/ui/vfs/docs/package-info.java | @HelpSetRegistration(helpSet = "help.hs", position = 2481)
package org.esa.snap.ui.vfs.docs;
import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration; | 155 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TestFilterOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/test/java/org/esa/snap/raster/gpf/TestFilterOpUI.java | /*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.gpf;
import org.esa.snap.engine_utilities.util.TestUtils;
import org.esa.snap.raster.gpf.ui.FilterOpUI;
import org.junit.Test;
import javax.swing.JComponent;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
/**
* Unit test for SingleTileOperator.
*/
public class TestFilterOpUI {
static {
TestUtils.initTestEnvironment();
}
private final static String operatorName = "Image-Filter";
private FilterOpUI filterOpUI = new FilterOpUI();
private final Map<String, Object> parameterMap = new HashMap<>(5);
@Test
public void testCreateOpTab() {
JComponent component = filterOpUI.CreateOpTab(operatorName, parameterMap, null);
assertNotNull(component);
}
@Test
public void testLoadParameters() {
parameterMap.put("selectedFilterName", "High-Pass 5x5");
JComponent component = filterOpUI.CreateOpTab(operatorName, parameterMap, null);
assertNotNull(component);
FilterOperator.Filter filter = FilterOpUI.getSelectedFilter(filterOpUI.getTree());
assertNotNull(filter);
filterOpUI.setSelectedFilter("Arithmetic 5x5 Mean");
filterOpUI.updateParameters();
Object o = parameterMap.get("selectedFilterName");
assertTrue(o.equals("Arithmetic 5x5 Mean"));
}
}
| 2,082 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TestLinearTodB.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/test/java/org/esa/snap/raster/dat/TestLinearTodB.java | /*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.dat;
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.TiePointGrid;
import org.esa.snap.engine_utilities.datamodel.Unit;
import org.esa.snap.engine_utilities.gpf.OperatorUtils;
import org.esa.snap.engine_utilities.util.TestUtils;
import org.esa.snap.raster.rcp.actions.LinearTodBAction;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertTrue;
/**
* Unit test for LinearTodB.
*/
public class TestLinearTodB {
private static final String dBStr = "_" + Unit.DB;
@Test
public void testLinearTodB() {
final Product product = createTestProduct(16, 4);
final Band band1 = product.getBandAt(0);
LinearTodBAction.convert(product, band1, true);
assertTrue(product.getNumBands() == 2);
final Band band2 = product.getBandAt(1);
assertTrue(band2.getUnit().endsWith(dBStr));
assertTrue(band2.getName().endsWith(dBStr));
}
@Test
public void testdBToLinear() {
final Product product = createTestProduct(16, 4);
final Band band1 = product.getBandAt(0);
band1.setName(band1.getName() + dBStr);
band1.setUnit(band1.getUnit() + dBStr);
LinearTodBAction.convert(product, band1, false);
assertTrue(product.getNumBands() == 2);
final Band band2 = product.getBandAt(1);
assertTrue(band2.getUnit().equals(Unit.AMPLITUDE));
assertTrue(band2.getName().equals("Amplitude"));
}
/**
* @param w width
* @param h height
* @return the created product
*/
private static Product createTestProduct(int w, int h) {
final Product testProduct = TestUtils.createProduct("ASA_APG_1P", w, h);
// create a Band: band1
final Band band1 = testProduct.addBand("Amplitude", ProductData.TYPE_INT32);
band1.setUnit(Unit.AMPLITUDE);
final int[] intValues = new int[w * h];
for (int i = 0; i < w * h; i++) {
intValues[i] = i + 1;
}
band1.setData(ProductData.createInstance(intValues));
final float[] incidence_angle = new float[64];
Arrays.fill(incidence_angle, 30.0f);
testProduct.addTiePointGrid(new TiePointGrid(OperatorUtils.TPG_INCIDENT_ANGLE, 16, 4, 0, 0, 1, 1, incidence_angle));
return testProduct;
}
}
| 3,180 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TestAmplitudeToIntensity.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/test/java/org/esa/snap/raster/dat/TestAmplitudeToIntensity.java | /*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.dat;
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.TiePointGrid;
import org.esa.snap.engine_utilities.datamodel.Unit;
import org.esa.snap.engine_utilities.gpf.OperatorUtils;
import org.esa.snap.engine_utilities.util.TestUtils;
import org.esa.snap.raster.rcp.actions.AmplitudeToIntensityAction;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertTrue;
/**
* Unit test for AmplitudeToIntensity.
*/
public class TestAmplitudeToIntensity {
@Test
public void testAmplitudeToIntensity() {
final Product product = createTestProduct("Amplitude", Unit.AMPLITUDE, 16, 4);
final Band band1 = product.getBandAt(0);
AmplitudeToIntensityAction.convert(product, band1, false);
assertTrue(product.getNumBands() == 2);
final Band band2 = product.getBandAt(1);
assertTrue(band2.getUnit().contains(Unit.INTENSITY));
assertTrue(band2.getName().endsWith("Intensity"));
}
@Test
public void testdIntensityToAmplitude() {
final Product product = createTestProduct("Intensity", Unit.INTENSITY, 16, 4);
final Band band1 = product.getBandAt(0);
AmplitudeToIntensityAction.convert(product, band1, true);
assertTrue(product.getNumBands() == 2);
final Band band2 = product.getBandAt(1);
assertTrue(band2.getUnit().equals(Unit.AMPLITUDE));
assertTrue(band2.getName().equals("Amplitude"));
}
/**
* @param w width
* @param h height
* @return the created product
*/
private static Product createTestProduct(String name, String unit, int w, int h) {
final Product testProduct = TestUtils.createProduct("ASA_APG_1P", w, h);
// create a Band: band1
final Band band1 = testProduct.addBand(name, ProductData.TYPE_INT32);
band1.setUnit(unit);
final int[] intValues = new int[w * h];
for (int i = 0; i < w * h; i++) {
intValues[i] = i + 1;
}
band1.setData(ProductData.createInstance(intValues));
final float[] incidence_angle = new float[64];
Arrays.fill(incidence_angle, 30.0f);
testProduct.addTiePointGrid(new TiePointGrid(OperatorUtils.TPG_INCIDENT_ANGLE, 16, 4, 0, 0, 1, 1, incidence_angle));
return testProduct;
}
}
| 3,181 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RasterModule.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/RasterModule.java | package org.esa.snap.raster;
/**
* Created by fdouziech on 25/02/2021.
*/
import org.esa.snap.engine_utilities.util.ResourceUtils;
import org.openide.modules.OnStart;
public class RasterModule {
@OnStart
public static class StartOp implements Runnable {
@Override
public void run() {
ResourceUtils.installGraphs(this.getClass(), "org/esa/snap/raster/graphs/");
}
}
}
| 422 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CreateLandMaskOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/gpf/ui/CreateLandMaskOpUI.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.gpf.ui;
import org.esa.snap.core.gpf.OperatorException;
import org.esa.snap.graphbuilder.gpf.ui.BaseOperatorUI;
import org.esa.snap.graphbuilder.gpf.ui.OperatorUIUtils;
import org.esa.snap.graphbuilder.gpf.ui.UIValidation;
import org.esa.snap.graphbuilder.rcp.utils.DialogUtils;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AppContext;
import org.opengis.filter.temporal.Before;
import org.openide.util.lookup.Lookups;
import javax.swing.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Map;
/**
* User interface for CreateLandMaskOp
*/
public class CreateLandMaskOpUI extends BaseOperatorUI {
private final JList bandList = new JList();
private final JComboBox<String> geometries = new JComboBox();
private final JRadioButton landMask = new JRadioButton("Mask out the Land");
private final JRadioButton seaMask = new JRadioButton("Mask out the Sea");
private final JCheckBox useSRTMCheckBox = new JCheckBox("Use SRTM 3sec");
private final JRadioButton geometryMask = new JRadioButton("Use Vector as Mask");
private final JCheckBox invertGeometryCheckBox = new JCheckBox("Invert Vector");
private final JTextField shorelineExtensionTextField = new JTextField();
private boolean invertGeometry = false;
private boolean useSRTM = true;
@Override
public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) {
initializeOperatorUI(operatorName, parameterMap);
final JComponent panel = createPanel();
initParameters();
useSRTMCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
useSRTM = (e.getStateChange() == ItemEvent.SELECTED);
}
});
invertGeometryCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
invertGeometry = (e.getStateChange() == ItemEvent.SELECTED);
}
});
final RadioListener myListener = new RadioListener();
landMask.addActionListener(myListener);
seaMask.addActionListener(myListener);
geometryMask.addActionListener(myListener);
return new JScrollPane(panel);
}
@Override
public void initParameters() {
OperatorUIUtils.initParamList(bandList, getBandNames());
final Boolean doLandMask = (Boolean) paramMap.get("landMask");
if (doLandMask != null && doLandMask) {
landMask.setSelected(true);
} else {
seaMask.setSelected(true);
}
geometries.removeAllItems();
final String[] geometryNames = getGeometries();
for (String g : geometryNames) {
geometries.addItem(g);
}
final String selectedGeometry = (String) paramMap.get("geometry");
if (selectedGeometry != null) {
geometryMask.setSelected(true);
geometries.setSelectedItem(selectedGeometry);
}
useSRTM = (Boolean) paramMap.get("useSRTM");
useSRTMCheckBox.setSelected(useSRTM);
Integer shorelineExtension = (Integer) paramMap.get("shorelineExtension");
shorelineExtensionTextField.setText(shorelineExtension == null ? "0" : shorelineExtension.toString());
if(hasSourceProducts()){
boolean isMultiSizeProducts = hasMultiSizeProducts();
if(isMultiSizeProducts) {
Dialogs.showError("The multi-size source product is not supported."
+"Please, use resampling processor before. Or use the default graph 'Raster/Land Sea Mask For Multi-size Source.xml'"
+"in the graph builder.");
}
}
}
@Override
public UIValidation validateParameters() {
return new UIValidation(UIValidation.State.OK, "");
}
@Override
public void updateParameters() {
OperatorUIUtils.updateParamList(bandList, paramMap, OperatorUIUtils.SOURCE_BAND_NAMES);
paramMap.put("landMask", landMask.isSelected());
if (geometryMask.isSelected()) {
paramMap.put("geometry", geometries.getSelectedItem());
paramMap.put("invertGeometry", invertGeometry);
}
Integer shorelineExtension = 0;
try {
shorelineExtension = Integer.parseInt(shorelineExtensionTextField.getText());
}catch (Exception e) {
shorelineExtension = 0;
}
paramMap.put("shorelineExtension", shorelineExtension);
paramMap.put("useSRTM", useSRTM);
if(hasSourceProducts()){
boolean isMultiSizeProducts = hasMultiSizeProducts();
if(isMultiSizeProducts) {
throw new IllegalArgumentException("The multi-size source product is not supported."
+"Please, use resampling processor before. Or use the default graph 'Raster/Land Sea Mask For Multi-size Source.xml'"
+"in the graph builder.");
}
}
}
private JComponent createPanel() {
final JPanel contentPane = new JPanel(new GridBagLayout());
final GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
DialogUtils.addComponent(contentPane, gbc, "Source Bands:", new JScrollPane(bandList));
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy++;
contentPane.add(landMask, gbc);
gbc.gridy++;
contentPane.add(seaMask, gbc);
gbc.gridy++;
contentPane.add(useSRTMCheckBox, gbc);
gbc.gridy++;
contentPane.add(geometryMask, gbc);
gbc.gridy++;
gbc.gridx = 1;
contentPane.add(geometries, gbc);
gbc.gridy++;
contentPane.add(invertGeometryCheckBox, gbc);
gbc.gridx = 0;
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, "Extend shoreline by [pixels]:", shorelineExtensionTextField);
final ButtonGroup group = new ButtonGroup();
group.add(landMask);
group.add(seaMask);
group.add(geometryMask);
geometries.setEnabled(false);
invertGeometryCheckBox.setEnabled(false);
DialogUtils.fillPanel(contentPane, gbc);
return contentPane;
}
private class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
boolean b = geometryMask.isSelected();
geometries.setEnabled(b);
invertGeometryCheckBox.setEnabled(b);
}
}
}
| 7,467 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LinearTodBOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/gpf/ui/LinearTodBOpUI.java | /*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.gpf.ui;
import org.esa.snap.graphbuilder.gpf.ui.BaseOperatorUI;
import org.esa.snap.graphbuilder.gpf.ui.OperatorUIUtils;
import org.esa.snap.graphbuilder.gpf.ui.UIValidation;
import org.esa.snap.graphbuilder.rcp.utils.DialogUtils;
import org.esa.snap.ui.AppContext;
import javax.swing.*;
import java.awt.*;
import java.util.Map;
/**
* User interface for LinearTodBOp
*/
public class LinearTodBOpUI extends BaseOperatorUI {
private final JList bandList = new JList();
private final JScrollPane bandListPane = new JScrollPane(bandList);
private final JLabel bandListLabel = new JLabel("Source Bands:");
@Override
public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) {
initializeOperatorUI(operatorName, parameterMap);
final JComponent panel = createPanel();
initParameters();
return new JScrollPane(panel);
}
@Override
public void initParameters() {
OperatorUIUtils.initParamList(bandList, getBandNames());
if (sourceProducts != null) {
DialogUtils.enableComponents(bandListLabel, bandListPane, true);
}
}
@Override
public UIValidation validateParameters() {
return new UIValidation(UIValidation.State.OK, "");
}
@Override
public void updateParameters() {
OperatorUIUtils.updateParamList(bandList, paramMap, OperatorUIUtils.SOURCE_BAND_NAMES);
}
private JComponent createPanel() {
final JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
final GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
contentPane.add(new JLabel("Source Bands:"), gbc);
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 1;
contentPane.add(new JScrollPane(bandList), gbc);
DialogUtils.fillPanel(contentPane, gbc);
return contentPane;
}
}
| 2,699 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FilterOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/gpf/ui/FilterOpUI.java | /*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.gpf.ui;
import org.esa.snap.graphbuilder.gpf.ui.BaseOperatorUI;
import org.esa.snap.graphbuilder.gpf.ui.OperatorUIUtils;
import org.esa.snap.graphbuilder.gpf.ui.UIValidation;
import org.esa.snap.graphbuilder.rcp.utils.DialogUtils;
import org.esa.snap.raster.gpf.FilterOperator;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AppContext;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Enumeration;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
* User: lveci
* Date: Feb 12, 2008
* Time: 1:52:49 PM
* To change this template use File | Settings | File Templates.
*/
public class FilterOpUI extends BaseOperatorUI {
private final JList bandList = new JList();
private JTree tree = null;
private DefaultMutableTreeNode root = null;
private final JLabel filterLabel = new JLabel("Filters:");
private final JLabel kernelFileLabel = new JLabel("User Defined Kernel File:");
private final JTextField kernelFile = new JTextField("");
private final JButton kernelFileBrowseButton = new JButton("...");
public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) {
initializeOperatorUI(operatorName, parameterMap);
JComponent panel = createPanel();
initParameters();
kernelFile.setColumns(30);
kernelFileBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final File file = Dialogs.requestFileForOpen("User Defined Kernel File", false, null, "snap.filterDir");
kernelFile.setText(file.getAbsolutePath());
}
});
return panel;
}
public void initParameters() {
OperatorUIUtils.initParamList(bandList, getBandNames());
final String filterName = (String) paramMap.get("selectedFilterName");
if (filterName != null) {
setSelectedFilter(filterName);
}
final File kFile = (File) paramMap.get("userDefinedKernelFile");
if (kFile != null) {
kernelFile.setText(kFile.getAbsolutePath());
}
}
public UIValidation validateParameters() {
if (sourceProducts != null) {
if (getSelectedFilter(tree) == null && kernelFile.getText().equals(""))
return new UIValidation(UIValidation.State.ERROR, "Filter not selected");
}
return new UIValidation(UIValidation.State.OK, "");
}
public void updateParameters() {
OperatorUIUtils.updateParamList(bandList, paramMap, OperatorUIUtils.SOURCE_BAND_NAMES);
final FilterOperator.Filter filter = getSelectedFilter(tree);
if (filter != null) {
paramMap.put("selectedFilterName", filter.toString());
}
final String kernelFileStr = kernelFile.getText();
if (!kernelFileStr.isEmpty()) {
paramMap.put("userDefinedKernelFile", new File(kernelFileStr));
}
}
private static DefaultMutableTreeNode findItem(DefaultMutableTreeNode parentItem, String filterName) {
if (!parentItem.isLeaf()) {
final Enumeration enumeration = parentItem.children();
while (enumeration.hasMoreElements()) {
final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) enumeration.nextElement();
final DefaultMutableTreeNode found = findItem(treeNode, filterName);
if (found != null)
return found;
}
}
if (parentItem.toString().equals(filterName))
return parentItem;
return null;
}
private JComponent createPanel() {
tree = createTree();
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
final JScrollPane treeView = new JScrollPane(tree);
final JPanel contentPane = new JPanel(new BorderLayout(4, 4));
contentPane.setLayout(new GridBagLayout());
final GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
contentPane.add(new JLabel("Source Bands:"), gbc);
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 1;
gbc.weighty = 2;
contentPane.add(new JScrollPane(bandList), gbc);
gbc.weighty = 4;
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, filterLabel, treeView);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, kernelFileLabel, kernelFile);
DialogUtils.enableComponents(kernelFileLabel, kernelFile, true);
gbc.gridx = 2;
contentPane.add(kernelFileBrowseButton, gbc);
DialogUtils.fillPanel(contentPane, gbc);
return contentPane;
}
private JTree createTree() {
root = new DefaultMutableTreeNode("@root");
root.add(createNodes("Detect Lines", FilterOperator.LINE_DETECTION_FILTERS));
root.add(createNodes("Detect Gradients (Emboss)", FilterOperator.GRADIENT_DETECTION_FILTERS));
root.add(createNodes("Smooth and Blurr", FilterOperator.SMOOTHING_FILTERS));
root.add(createNodes("Sharpen", FilterOperator.SHARPENING_FILTERS));
root.add(createNodes("Enhance Discontinuities", FilterOperator.LAPLACIAN_FILTERS));
root.add(createNodes("Non-Linear Filters", FilterOperator.NON_LINEAR_FILTERS));
root.add(createNodes("Morphology Filters", FilterOperator.MORPHOLOGY_FILTERS));
final JTree tree = new JTree(root);
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
tree.setCellRenderer(new MyDefaultTreeCellRenderer());
tree.putClientProperty("JTree.lineStyle", "Angled");
expandAll(tree);
return tree;
}
public JTree getTree() {
return tree;
}
public void setSelectedFilter(String filterName) {
final DefaultMutableTreeNode item = findItem(root, filterName);
if (item != null) {
tree.setSelectionPath(new TreePath(item.getPath()));
}
}
public static FilterOperator.Filter getSelectedFilter(final JTree tree) {
final TreePath selectionPath = tree.getSelectionPath();
if (selectionPath == null) {
return null;
}
final Object[] path = selectionPath.getPath();
if (path != null && path.length > 0) {
final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) path[path.length - 1];
if (treeNode.getUserObject() instanceof FilterOperator.Filter) {
return (FilterOperator.Filter) treeNode.getUserObject();
}
}
return null;
}
private static DefaultMutableTreeNode createNodes(String categoryName, FilterOperator.Filter[] filters) {
final DefaultMutableTreeNode category = new DefaultMutableTreeNode(categoryName);
for (FilterOperator.Filter filter : filters) {
final DefaultMutableTreeNode item = new DefaultMutableTreeNode(filter);
category.add(item);
}
return category;
}
private static void expandAll(JTree tree) {
DefaultMutableTreeNode actNode = (DefaultMutableTreeNode) tree.getModel().getRoot();
while (actNode != null) {
if (!actNode.isLeaf()) {
final TreePath actPath = new TreePath(actNode.getPath());
tree.expandRow(tree.getRowForPath(actPath));
}
actNode = actNode.getNextNode();
}
}
private static class MyDefaultTreeCellRenderer extends DefaultTreeCellRenderer {
private Font _plainFont;
private Font _boldFont;
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
final JLabel c = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row,
hasFocus);
if (_plainFont == null) {
_plainFont = c.getFont().deriveFont(Font.PLAIN);
_boldFont = c.getFont().deriveFont(Font.BOLD);
}
c.setFont(leaf ? _plainFont : _boldFont);
c.setIcon(null);
return c;
}
}
}
| 9,760 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SearchMetadataValueAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/rcp/actions/SearchMetadataValueAction.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.rcp.actions;
import org.esa.snap.core.datamodel.MetadataAttribute;
import org.esa.snap.core.datamodel.MetadataElement;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.graphbuilder.rcp.dialogs.PromptDialog;
import org.esa.snap.rcp.util.Dialogs;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
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.*;
import java.awt.event.ActionEvent;
@ActionID(category = "Metadata", id = "SearchMetadataValueAction")
@ActionRegistration(
displayName = "#CTL_SearchMetadataValueAction_MenuText",
popupText = "#CTL_SearchMetadataValueAction_MenuText"
)
@ActionReferences({
@ActionReference(path = "Context/Product/MetadataElement", position = 120),
@ActionReference(path = "Menu/Tools/Metadata", position = 65)
})
@NbBundle.Messages({
"CTL_SearchMetadataValueAction_MenuText=Search Metadata Value",
"CTL_SearchMetadataValueAction_ShortDescription=Search metadata by value"
})
/**
* This action searches the Metadata by value
*
*/
public class SearchMetadataValueAction extends AbstractAction implements ContextAwareAction, LookupListener {
private final Lookup lkp;
private Product product;
public SearchMetadataValueAction() {
this(Utilities.actionsGlobalContext());
}
public SearchMetadataValueAction(Lookup lkp) {
super(Bundle.CTL_SearchMetadataValueAction_MenuText());
this.lkp = lkp;
Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class);
lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext));
setEnableState();
putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_SearchMetadataValueAction_ShortDescription());
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new SearchMetadataValueAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
}
private void setEnableState() {
ProductNode productNode = lkp.lookup(ProductNode.class);
boolean state = false;
if (productNode != null) {
product = productNode.getProduct();
state = product.getMetadataRoot() != null;
}
setEnabled(state);
}
@Override
public void actionPerformed(final ActionEvent event) {
final PromptDialog dlg = new PromptDialog("Search Metadata", "Value", "", PromptDialog.TYPE.TEXTFIELD);
dlg.show();
if (dlg.IsOK()) {
try {
final String value = dlg.getValue("Value").toUpperCase();
final MetadataElement resultElem = new MetadataElement("Search result (" + value + ')');
final boolean isModified = product.isModified();
final MetadataElement root = product.getMetadataRoot();
resultElem.setOwner(product);
searchMetadataValue(resultElem, root, value);
product.setModified(isModified);
if (resultElem.getNumElements() > 0 || resultElem.getNumAttributes() > 0) {
SearchMetadataAction.openMetadataWindow(resultElem);
} else {
// no attributes found
Dialogs.showError("Search Metadata", value + " not found in the Metadata");
}
} catch (Exception ex) {
Dialogs.showError(ex.getMessage());
}
}
}
private static void searchMetadataValue(final MetadataElement resultElem, final MetadataElement elem, final String value) {
final MetadataElement[] elemList = elem.getElements();
for (MetadataElement e : elemList) {
searchMetadataValue(resultElem, e, value);
}
final MetadataAttribute[] attribList = elem.getAttributes();
for (MetadataAttribute attrib : attribList) {
if (attrib.getData().getElemString().toUpperCase().contains(value)) {
final MetadataAttribute newAttrib = attrib.createDeepClone();
newAttrib.setDescription(SearchMetadataAction.getAttributePath(attrib));
resultElem.addAttribute(newAttrib);
}
}
}
}
| 5,401 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ScaleDataAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/rcp/actions/ScaleDataAction.java | /*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.rcp.actions;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import java.awt.event.ActionEvent;
import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.EXPLORER;
/*
@ActionID(category = "Raster", id = "eu.esa.microwave.dat.ScaleDataAction" )
@ActionRegistration(displayName = "#CTL_ScaleDataAction_Text")
@ActionReference(path = "Menu/Raster/Data Conversion", position = 300 )
@NbBundle.Messages({"CTL_ScaleDataAction_Text=Scale Data"})
*/
/**
* ScaleData action.
*/
public class ScaleDataAction extends AbstractSnapAction {
@Override
public void actionPerformed(ActionEvent event) {
final ProductNode node = SnapApp.getDefault().getSelectedProductNode(EXPLORER);
if (node instanceof Band) {
final Band band = (Band) node;
final Product product = band.getProduct();
ScaleDataDialog dlg = new ScaleDataDialog("Scaling Data", product, band);
dlg.show();
}
}
// Code removed by nf, lv to review
// public void updateState(CommandEvent event) {
// final ProductNode node = SnapApp.getDefault().getSelectedProductNode();
// if (node instanceof Band) {
// final Band band = (Band) node;
// final String unit = band.getUnit();
// if (unit != null && !unit.contains(Unit.PHASE)) {
// event.getCommand().setEnabled(true);
// return;
// }
// }
// event.getCommand().setEnabled(false);
// }
}
| 2,409 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SearchMetadataAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/rcp/actions/SearchMetadataAction.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.rcp.actions;
import eu.esa.snap.netbeans.docwin.DocumentWindowManager;
import org.esa.snap.core.datamodel.MetadataAttribute;
import org.esa.snap.core.datamodel.MetadataElement;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.graphbuilder.rcp.dialogs.PromptDialog;
import org.esa.snap.rcp.metadata.MetadataViewTopComponent;
import org.esa.snap.rcp.util.Dialogs;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
@ActionID(category = "Metadata", id = "SearchMetadataAction")
@ActionRegistration(
displayName = "#CTL_SearchMetadataAction_MenuText",
popupText = "#CTL_SearchMetadataAction_MenuText"
)
@ActionReferences({
@ActionReference(path = "Context/Product/MetadataElement", position = 110),
@ActionReference(path = "Menu/Tools/Metadata", position = 60)
})
@NbBundle.Messages({
"CTL_SearchMetadataAction_MenuText=Search Metadata",
"CTL_SearchMetadataAction_ShortDescription=Search Metadata"
})
/**
* This action searches the Metadata by name
*
*/
public class SearchMetadataAction extends AbstractAction implements ContextAwareAction, LookupListener {
private final Lookup lkp;
private Product product;
public SearchMetadataAction() {
this(Utilities.actionsGlobalContext());
}
public SearchMetadataAction(Lookup lkp) {
super(Bundle.CTL_SearchMetadataAction_MenuText());
this.lkp = lkp;
Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class);
lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext));
setEnableState();
putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_SearchMetadataAction_ShortDescription());
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new SearchMetadataAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
}
private void setEnableState() {
ProductNode productNode = lkp.lookup(ProductNode.class);
boolean state = false;
if (productNode != null) {
product = productNode.getProduct();
state = product.getMetadataRoot() != null;
}
setEnabled(state);
}
@Override
public void actionPerformed(final ActionEvent event) {
final PromptDialog dlg = new PromptDialog("Search Metadata", "Item Name", "", PromptDialog.TYPE.TEXTFIELD);
dlg.show();
if (dlg.IsOK()) {
try {
final String tag = dlg.getValue("Item Name").toUpperCase();
final MetadataElement resultElem = new MetadataElement("Search result (" + tag + ')');
final boolean isModified = product.isModified();
final MetadataElement root = product.getMetadataRoot();
resultElem.setOwner(product);
searchMetadata(resultElem, root, tag);
product.setModified(isModified);
if (resultElem.getNumElements() > 0 || resultElem.getNumAttributes() > 0) {
openMetadataWindow(resultElem);
} else {
// no attributes found
Dialogs.showError("Search Metadata", tag + " not found in the Metadata");
}
} catch (Exception ex) {
Dialogs.showError(ex.getMessage());
}
}
}
static MetadataViewTopComponent openMetadataWindow(final MetadataElement element) {
final MetadataViewTopComponent metadataViewTopComponent = new MetadataViewTopComponent(element);
DocumentWindowManager.getDefault().openWindow(metadataViewTopComponent);
metadataViewTopComponent.requestSelected();
return metadataViewTopComponent;
}
private static void searchMetadata(final MetadataElement resultElem, final MetadataElement elem, final String tag) {
final MetadataElement[] elemList = elem.getElements();
for (MetadataElement e : elemList) {
searchMetadata(resultElem, e, tag);
}
final MetadataAttribute[] attribList = elem.getAttributes();
for (MetadataAttribute attrib : attribList) {
if (attrib.getName().toUpperCase().contains(tag)) {
final MetadataAttribute newAttrib = attrib.createDeepClone();
newAttrib.setDescription(getAttributePath(attrib));
resultElem.addAttribute(newAttrib);
}
}
}
static String getAttributePath(final MetadataAttribute attrib) {
MetadataElement parentElem = attrib.getParentElement();
String path = parentElem.getName();
while (parentElem != null && !parentElem.getName().equals("metadata")) {
parentElem = parentElem.getParentElement();
if (parentElem != null)
path = parentElem.getName() + "/" + path;
}
return path;
}
}
| 5,954 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ScaleDataDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/rcp/actions/ScaleDataDialog.java | /*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.rcp.actions;
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.VirtualBand;
import org.esa.snap.graphbuilder.rcp.utils.DialogUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.ModelessDialog;
import javax.swing.*;
import java.awt.*;
/**
* Scale data action dialog
*/
class ScaleDataDialog extends ModelessDialog {
private final JTextField gainField = new JTextField("1");
private final JTextField biasField = new JTextField("0");
private final JTextField expField = new JTextField("1");
private final JCheckBox logCheck = new JCheckBox();
private final Product _product;
private final Band _band;
public ScaleDataDialog(final String title, final Product product, final Band band) {
super(SnapApp.getDefault().getMainFrame(), title, ModalDialog.ID_OK_CANCEL, null);
this._product = product;
this._band = band;
setContent(createEditPanel());
}
private JPanel createEditPanel() {
final JPanel editPanel = new JPanel();
editPanel.setPreferredSize(new Dimension(400, 200));
editPanel.setLayout(new GridBagLayout());
final GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
gbc.ipady = 5;
gbc.weightx = 1;
gbc.gridy++;
DialogUtils.addComponent(editPanel, gbc, "Gain:", gainField);
gbc.gridy++;
DialogUtils.addComponent(editPanel, gbc, "Bias:", biasField);
gbc.gridy++;
DialogUtils.addComponent(editPanel, gbc, "Exponential Scaling:", expField);
gbc.gridy++;
DialogUtils.addComponent(editPanel, gbc, "Logarithmic Scaling:", logCheck);
gbc.gridy++;
DialogUtils.fillPanel(editPanel, gbc);
return editPanel;
}
@Override
protected void onOK() {
try {
final double gain = Double.parseDouble(gainField.getText());
final double bias = Double.parseDouble(biasField.getText());
final double exp = Double.parseDouble(expField.getText());
final boolean isLog = logCheck.isSelected();
applyScaling(_product, _band, gain, bias, exp, isLog);
hide();
} catch (Exception e) {
Dialogs.showError(e.getMessage());
}
}
private static void applyScaling(final Product product, final Band band,
final double gain, final double bias, final double exp, final boolean isLog) {
final String bandName = band.getName();
final String unit = band.getUnit();
String expression = gain + " * " + bandName + " + " + bias;
String targetName = bandName + "_Scaled";
int cnt = 0;
while (product.getBand(targetName) != null) {
++cnt;
targetName = bandName + "_Scaled" + cnt;
}
if (exp != 1) {
expression = "pow( " + expression + ", " + exp + " )";
}
if (isLog) {
expression = bandName + "==0 ? 0 : " + "log10( " + expression + " )";
}
final VirtualBand virtBand = new VirtualBand(targetName,
ProductData.TYPE_FLOAT32,
band.getRasterWidth(),
band.getRasterHeight(),
expression);
virtBand.setUnit(unit);
virtBand.setDescription(band.getDescription());
virtBand.setNoDataValueUsed(true);
product.addBand(virtBand);
}
}
| 4,375 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ComplexToIntensityAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/rcp/actions/ComplexToIntensityAction.java | /*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.rcp.actions;
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.ProductNode;
import org.esa.snap.core.datamodel.VirtualBand;
import org.esa.snap.engine_utilities.datamodel.Unit;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.rcp.util.Dialogs;
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.*;
import java.awt.event.ActionEvent;
@ActionID(category = "Raster", id = "org.esa.snap.raster.rcp.actions.ComplexToIntensityAction")
@ActionRegistration(displayName = "#CTL_ComplexToIntensityAction_Text")
@ActionReference(path = "Menu/Raster/Data Conversion", position = 400)
@NbBundle.Messages({
"CTL_ComplexToIntensityAction_Text=Complex i and q to Intensity",
"CTL_ComplexToIntensityAction_Description=Creates a virtual intensity band from i and q complex bands."
})
/**
* ComplexToIntensity action.
*/
public class ComplexToIntensityAction extends AbstractSnapAction implements ContextAwareAction, LookupListener {
private final Lookup lkp;
public ComplexToIntensityAction() {
this(Utilities.actionsGlobalContext());
}
public ComplexToIntensityAction(Lookup lkp) {
this.lkp = lkp;
Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class);
lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext));
setEnableState();
putValue(NAME, Bundle.CTL_ComplexToIntensityAction_Text());
putValue(SHORT_DESCRIPTION, Bundle.CTL_ComplexToIntensityAction_Description());
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new ComplexToIntensityAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
}
@Override
public void actionPerformed(ActionEvent event) {
final ProductNode productNode = lkp.lookup(ProductNode.class);
if (productNode != null && productNode instanceof Band) {
final Band band = (Band) productNode;
final Product product = band.getProduct();
String bandName = band.getName();
final String unit = band.getUnit();
String iBandName, qBandName, intensityBandName;
if (unit != null && unit.contains(Unit.REAL)) {
iBandName = bandName;
qBandName = bandName.replaceFirst("i_", "q_");
intensityBandName = bandName.replaceFirst("i_", "Intensity_");
} else if (unit != null && unit.contains(Unit.IMAGINARY)) {
iBandName = bandName.replaceFirst("q_", "i_");
qBandName = bandName;
intensityBandName = bandName.replaceFirst("q_", "Intensity_");
} else {
return;
}
if (product.getBand(iBandName) == null) {
Dialogs.showWarning(product.getName() + " missing " + iBandName + " band");
return;
}
if (product.getBand(qBandName) == null) {
Dialogs.showWarning(product.getName() + " missing " + qBandName + " band");
return;
}
if (product.getBand(intensityBandName) != null) {
Dialogs.showWarning(product.getName() + " already contains a " + intensityBandName + " band");
return;
}
if (Dialogs.requestDecision("Convert to Intensity", "Would you like to convert i and q bands " +
" to Intensity in a new virtual band?", true, null) == Dialogs.Answer.YES) {
convert(product, iBandName, qBandName, intensityBandName);
}
}
}
public void setEnableState() {
final ProductNode productNode = lkp.lookup(ProductNode.class);
if (productNode != null && productNode instanceof Band) {
final Band band = (Band) productNode;
final String unit = band.getUnit();
if (unit != null && (unit.contains(Unit.REAL) || unit.contains(Unit.IMAGINARY))) {
setEnabled(true);
return;
}
}
setEnabled(false);
}
public static void convert(final Product product,
final String iBandName, final String qBandName, final String targetBandName) {
final Band iBand = product.getBand(iBandName);
final String expression = iBandName + " * " + iBandName + " + " + qBandName + " * " + qBandName;
final VirtualBand virtBand = new VirtualBand(targetBandName,
ProductData.TYPE_FLOAT32,
iBand.getRasterWidth(),
iBand.getRasterHeight(),
expression);
virtBand.setUnit(Unit.INTENSITY);
virtBand.setDescription("Intensity from complex data");
virtBand.setNoDataValueUsed(true);
virtBand.setOwner(product);
product.addBand(virtBand);
}
}
| 6,310 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ComplexToPhaseAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/rcp/actions/ComplexToPhaseAction.java | /*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.rcp.actions;
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.ProductNode;
import org.esa.snap.core.datamodel.VirtualBand;
import org.esa.snap.engine_utilities.datamodel.Unit;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.rcp.util.Dialogs;
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.*;
import java.awt.event.ActionEvent;
@ActionID(category = "Raster", id = "org.esa.snap.raster.rcp.actions.ComplexToPhaseAction")
@ActionRegistration(displayName = "#CTL_ComplexToPhaseAction_Text")
@ActionReference(path = "Menu/Raster/Data Conversion", position = 410)
@NbBundle.Messages({
"CTL_ComplexToPhaseAction_Text=Complex i and q to Phase",
"CTL_ComplexToPhaseAction_Description=Creates a virtual phase band from i and q complex bands."
})
/**
* ComplexToPhase action.
*/
public class ComplexToPhaseAction extends AbstractSnapAction implements ContextAwareAction, LookupListener {
private final Lookup lkp;
public ComplexToPhaseAction() {
this(Utilities.actionsGlobalContext());
}
public ComplexToPhaseAction(Lookup lkp) {
this.lkp = lkp;
Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class);
lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext));
setEnableState();
putValue(NAME, Bundle.CTL_ComplexToPhaseAction_Text());
putValue(SHORT_DESCRIPTION, Bundle.CTL_ComplexToPhaseAction_Description());
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new ComplexToPhaseAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
}
@Override
public void actionPerformed(ActionEvent event) {
final ProductNode productNode = lkp.lookup(ProductNode.class);
if (productNode != null && productNode instanceof Band) {
final Band band = (Band) productNode;
final Product product = band.getProduct();
String bandName = band.getName();
final String unit = band.getUnit();
String iBandName, qBandName, phaseBandName;
if (unit != null && unit.contains(Unit.REAL)) {
iBandName = bandName;
qBandName = bandName.replaceFirst("i_", "q_");
phaseBandName = bandName.replaceFirst("i_", "Phase_");
} else if (unit != null && unit.contains(Unit.IMAGINARY)) {
iBandName = bandName.replaceFirst("q_", "i_");
qBandName = bandName;
phaseBandName = bandName.replaceFirst("q_", "Phase_");
} else {
return;
}
if (product.getBand(iBandName) == null) {
Dialogs.showWarning(product.getName() + " missing " + iBandName + " band");
return;
}
if (product.getBand(qBandName) == null) {
Dialogs.showWarning(product.getName() + " missing " + qBandName + " band");
return;
}
if (product.getBand(phaseBandName) != null) {
Dialogs.showWarning(product.getName() + " already contains a " + phaseBandName + " band");
return;
}
if (Dialogs.requestDecision("Convert to Phase", "Would you like to convert i and q bands " +
" to Phase in a new virtual band?", true, null) == Dialogs.Answer.YES) {
convert(product, iBandName, qBandName, phaseBandName);
}
}
}
public void setEnableState() {
final ProductNode productNode = lkp.lookup(ProductNode.class);
if (productNode != null && productNode instanceof Band) {
final Band band = (Band) productNode;
final String unit = band.getUnit();
if (unit != null && (unit.contains(Unit.REAL) || unit.contains(Unit.IMAGINARY))) {
setEnabled(true);
return;
}
}
setEnabled(false);
}
public static void convert(final Product product,
final String iBandName, final String qBandName, final String phaseBandName) {
final Band iBand = product.getBand(iBandName);
final String expression = "atan2(" + qBandName + ',' + iBandName + ')';
final VirtualBand virtBand = new VirtualBand(phaseBandName,
ProductData.TYPE_FLOAT32,
iBand.getRasterWidth(),
iBand.getRasterHeight(),
expression);
virtBand.setUnit(Unit.PHASE);
virtBand.setDescription("Phase from complex data");
virtBand.setNoDataValueUsed(true);
virtBand.setOwner(product);
product.addBand(virtBand);
}
}
| 6,183 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AmplitudeToIntensityAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/rcp/actions/AmplitudeToIntensityAction.java | /*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.rcp.actions;
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.ProductNode;
import org.esa.snap.core.datamodel.VirtualBand;
import org.esa.snap.engine_utilities.datamodel.Unit;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.rcp.util.Dialogs;
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.Action;
import java.awt.event.ActionEvent;
@ActionID(category = "Raster", id = "org.esa.snap.raster.rcp.actions.AmplitudeToIntensityAction")
@ActionRegistration(displayName = "#CTL_AmplitudeToIntensityAction_Text")
@ActionReference(path = "Menu/Raster/Data Conversion", position = 250)
@NbBundle.Messages({
"CTL_AmplitudeToIntensityAction_Text=Amplitude to/from Intensity",
"CTL_AmplitudeToIntensityAction_Description=Creates a virtual band from an Amplitude or Intensity band"
})
/**
* AmplitudeToIntensity action.
*/
public class AmplitudeToIntensityAction extends AbstractSnapAction implements ContextAwareAction, LookupListener {
private final Lookup lkp;
public AmplitudeToIntensityAction() {
this(Utilities.actionsGlobalContext());
}
public AmplitudeToIntensityAction(Lookup lkp) {
this.lkp = lkp;
Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class);
lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext));
setEnableState();
putValue(NAME, Bundle.CTL_AmplitudeToIntensityAction_Text());
putValue(SHORT_DESCRIPTION, Bundle.CTL_AmplitudeToIntensityAction_Description());
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new AmplitudeToIntensityAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
}
@Override
public void actionPerformed(ActionEvent event) {
final ProductNode productNode = lkp.lookup(ProductNode.class);
if (productNode != null && productNode instanceof Band) {
final Band band = (Band) productNode;
final Product product = band.getProduct();
String bandName = band.getName();
final String unit = band.getUnit();
if (unit != null && unit.contains(Unit.DB)) {
Dialogs.showWarning("Please convert band " + bandName + " from dB to linear first");
return;
}
if (unit != null && unit.contains(Unit.AMPLITUDE)) {
bandName = replaceName(bandName, "Amplitude", "Intensity");
if (product.getBand(bandName) != null) {
Dialogs.showWarning(product.getName() + " already contains an "
+ bandName + " band");
return;
}
if (Dialogs.requestDecision("Convert to Intensity", "Would you like to convert band "
+ band.getName() + " into Intensity in a new virtual band?", true, null) == Dialogs.Answer.YES) {
convert(product, band, false);
}
} else if (unit != null && unit.contains(Unit.INTENSITY)) {
bandName = replaceName(bandName, "Intensity", "Amplitude");
if (product.getBand(bandName) != null) {
Dialogs.showWarning(product.getName() + " already contains an "
+ bandName + " band");
return;
}
if (Dialogs.requestDecision("Convert to Amplitude", "Would you like to convert band "
+ band.getName() + " into Amplitude in a new virtual band?", true, null) == Dialogs.Answer.YES) {
convert(product, band, true);
}
}
}
}
public void setEnableState() {
final ProductNode productNode = lkp.lookup(ProductNode.class);
if (productNode != null && productNode instanceof Band) {
final Band band = (Band) productNode;
final String unit = band.getUnit();
if (unit != null && (unit.contains(Unit.AMPLITUDE) || unit.contains(Unit.INTENSITY))) {
setEnabled(true);
return;
}
}
setEnabled(false);
}
private static String replaceName(String bandName, final String fromName, final String toName) {
if (bandName.contains(fromName)) {
bandName = bandName.replace(fromName, toName);
} else if (bandName.contains("Sigma0")) {
bandName = bandName.replace("Sigma0", toName);
} else if (bandName.contains("Gamma0")) {
bandName = bandName.replace("Gamma0", toName);
} else if (bandName.contains("Beta0")) {
bandName = bandName.replace("Beta0", toName);
} else {
bandName = toName + '_' + bandName;
}
return bandName;
}
public static void convert(final Product product, final Band band, final boolean toAmplitude) {
String bandName = band.getName();
String unit;
String expression;
if (toAmplitude) {
expression = "sqrt(" + bandName + ')';
bandName = replaceName(bandName, "Intensity", "Amplitude");
unit = Unit.AMPLITUDE;
} else {
expression = bandName + " * " + bandName;
bandName = replaceName(bandName, "Amplitude", "Intensity");
unit = Unit.INTENSITY;
}
final VirtualBand virtBand = new VirtualBand(bandName,
ProductData.TYPE_FLOAT32,
band.getRasterWidth(),
band.getRasterHeight(),
expression);
virtBand.setUnit(unit);
virtBand.setDescription(band.getDescription());
virtBand.setNoDataValueUsed(true);
product.addBand(virtBand);
}
}
| 7,078 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ReplaceMetadataAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/rcp/actions/ReplaceMetadataAction.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.rcp.actions;
import org.esa.snap.core.datamodel.MetadataElement;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.engine_utilities.datamodel.AbstractMetadata;
import org.esa.snap.engine_utilities.datamodel.metadata.AbstractMetadataIO;
import org.esa.snap.raster.gpf.ReplaceMetadataOp;
import org.esa.snap.raster.rcp.dialogs.StringSelectorDialog;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.rcp.util.Dialogs;
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.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
@ActionID(category = "Processing", id = "org.esa.snap.raster.rcp.actions.ReplaceMetadataAction")
@ActionRegistration(displayName = "#CTL_ReplaceMetadataAction_Text")
@ActionReference(path = "Menu/Tools/Metadata", position = 400)
@NbBundle.Messages({"CTL_ReplaceMetadataAction_Text=Replace Metadata"})
/**
* This action replaces the Metadata with that of another product
*
*/
public class ReplaceMetadataAction extends AbstractSnapAction implements ContextAwareAction, LookupListener {
private final Lookup lkp;
private Product product;
public ReplaceMetadataAction() {
this(Utilities.actionsGlobalContext());
}
public ReplaceMetadataAction(Lookup lkp) {
this.lkp = lkp;
Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class);
lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext));
setEnableState();
putValue(Action.NAME, Bundle.CTL_ReplaceMetadataAction_Text());
//putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_SearchMetadataValueAction_ShortDescription());
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new ReplaceMetadataAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
}
private void setEnableState() {
ProductNode productNode = lkp.lookup(ProductNode.class);
boolean state = false;
if (productNode != null) {
product = productNode.getProduct();
state = product.getMetadataRoot() != null;
}
setEnabled(state);
}
@Override
public void actionPerformed(final ActionEvent event) {
final String[] compatibleProductNames = getCompatibleProducts(product);
if (compatibleProductNames.length == 0) {
Dialogs.showError("There are not any compatible products currently opened\nDimensions must be the same");
return;
}
final StringSelectorDialog dlg = new StringSelectorDialog("Replace Metadata with", compatibleProductNames);
dlg.show();
if (dlg.IsOK()) {
try {
final MetadataElement origAbsRoot = AbstractMetadata.getAbstractedMetadata(product);
final int isPolsar = origAbsRoot.getAttributeInt(AbstractMetadata.polsarData, 0);
final int isCalibrated = origAbsRoot.getAttributeInt(AbstractMetadata.abs_calibration_flag, 0);
final String srcProductName = dlg.getSelectedItem();
final Product[] products = SnapApp.getDefault().getProductManager().getProducts();
Product srcProduct = null;
for (Product prod : products) {
if (prod.getDisplayName().equals(srcProductName)) {
srcProduct = prod;
break;
}
}
final MetadataElement srcAbsRoot = AbstractMetadata.getAbstractedMetadata(srcProduct);
final File tmpMetadataFile = new File(SystemUtils.getCacheDir(),
srcProduct.getName() + "_metadata.xml");
AbstractMetadataIO.Save(srcProduct, srcAbsRoot, tmpMetadataFile);
String origName = product.getName();
clearProductMetadata(product);
final MetadataElement destAbsRoot = AbstractMetadata.getAbstractedMetadata(product);
AbstractMetadataIO.Load(product, destAbsRoot, tmpMetadataFile);
product.setName(origName);
ReplaceMetadataOp.resetPolarizations(AbstractMetadata.getAbstractedMetadata(product),
isPolsar, isCalibrated);
tmpMetadataFile.delete();
} catch (Exception e) {
Dialogs.showError("Unable to save or load metadata\n" + e.getMessage());
}
}
}
private static String[] getCompatibleProducts(final Product destProduct) {
final List<String> prodList = new ArrayList<>();
final Product[] products = SnapApp.getDefault().getProductManager().getProducts();
for (Product p : products) {
if (p != destProduct &&
p.getSceneRasterWidth() == destProduct.getSceneRasterWidth() &&
p.getSceneRasterHeight() == destProduct.getSceneRasterHeight()) {
prodList.add(p.getDisplayName());
}
}
return prodList.toArray(new String[prodList.size()]);
}
private static void clearProductMetadata(final Product product) {
final String[] tpgNames = product.getTiePointGridNames();
for (String tpg : tpgNames) {
product.removeTiePointGrid(product.getTiePointGrid(tpg));
}
final MetadataElement root = product.getMetadataRoot();
final MetadataElement[] elems = root.getElements();
for (MetadataElement e : elems) {
root.removeElement(e);
}
AbstractMetadata.addAbstractedMetadataHeader(product.getMetadataRoot());
}
}
| 6,965 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LinearTodBAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/rcp/actions/LinearTodBAction.java | /*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.rcp.actions;
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.ProductNode;
import org.esa.snap.core.datamodel.VirtualBand;
import org.esa.snap.engine_utilities.datamodel.Unit;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.rcp.util.Dialogs;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
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.*;
import java.awt.event.ActionEvent;
@ActionID(category = "Raster", id = "org.esa.snap.raster.rcp.actions.LinearTodBAction")
@ActionRegistration(displayName = "#CTL_LinearTodBAction_Text")
@ActionReferences({
@ActionReference(
path = "Menu/Raster/Data Conversion", position = 300
),
@ActionReference(
path = "Context/Product/RasterDataNode",
position = 42
)
})
@NbBundle.Messages({
"CTL_LinearTodBAction_Text=Linear to/from dB",
"CTL_LinearTodBAction_Description=Creates a dB or linear virtual band from a linear or dB band"
})
/**
* LinearTodB action.
*/
public class LinearTodBAction extends AbstractSnapAction implements ContextAwareAction, LookupListener {
private static final String dBStr = "_" + Unit.DB;
private final Lookup lkp;
public LinearTodBAction() {
this(Utilities.actionsGlobalContext());
}
public LinearTodBAction(Lookup lkp) {
this.lkp = lkp;
Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class);
lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext));
setEnableState();
putValue(NAME, Bundle.CTL_LinearTodBAction_Text());
putValue(SHORT_DESCRIPTION, Bundle.CTL_LinearTodBAction_Description());
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new LinearTodBAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
}
@Override
public void actionPerformed(ActionEvent event) {
final ProductNode productNode = lkp.lookup(ProductNode.class);
if (productNode != null && productNode instanceof Band) {
final Band band = (Band) productNode;
final Product product = band.getProduct();
final String unit = band.getUnit();
if (!unit.contains(Unit.DB)) {
if (Dialogs.requestDecision("Convert to dB", "Would you like to convert band "
+ band.getName() + " into dB in a new virtual band?", true, null) == Dialogs.Answer.YES) {
convert(product, band, true);
}
} else {
if (Dialogs.requestDecision("Convert to linear", "Would you like to convert band "
+ band.getName() + " into linear in a new virtual band?", true, null) == Dialogs.Answer.YES) {
convert(product, band, false);
}
}
}
}
public void setEnableState() {
final ProductNode productNode = lkp.lookup(ProductNode.class);
if (productNode != null && productNode instanceof Band) {
final Band band = (Band) productNode;
final String unit = band.getUnit();
if (unit != null && !unit.contains(Unit.PHASE)) {
setEnabled(true);
return;
}
}
setEnabled(false);
}
public static void convert(final Product product, final Band band, final boolean todB) {
String bandName = band.getName();
String unit = band.getUnit();
String expression;
String newBandName;
if (todB) {
expression = bandName + "==0 ? 0 : 10 * log10(abs(" + bandName + "))";
bandName += dBStr;
unit += dBStr;
} else {
expression = "pow(10," + bandName + "/10.0)";
if (bandName.contains(dBStr))
bandName = bandName.substring(0, bandName.indexOf(dBStr));
if (unit.contains(dBStr))
unit = unit.substring(0, unit.indexOf(dBStr));
}
newBandName = bandName;
int i = 2;
while (product.getBand(newBandName) != null) {
newBandName = bandName + i;
++i;
}
final VirtualBand virtBand = new VirtualBand(newBandName,
ProductData.TYPE_FLOAT32,
band.getRasterWidth(),
band.getRasterHeight(),
expression);
virtBand.setUnit(unit);
virtBand.setDescription(band.getDescription());
virtBand.setNoDataValueUsed(true);
product.addBand(virtBand);
}
}
| 5,901 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
StringSelectorDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-raster-ui/src/main/java/org/esa/snap/raster/rcp/dialogs/StringSelectorDialog.java | /*
* Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca
*
* 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.raster.rcp.dialogs;
import org.esa.snap.graphbuilder.rcp.utils.DialogUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.ModalDialog;
import javax.swing.*;
import java.awt.*;
/**
* Created by IntelliJ IDEA.
* User: lveci
* Date: Jun 5, 2008
* To change this template use File | Settings | File Templates.
*/
public class StringSelectorDialog extends ModalDialog {
private final JComboBox list;
private boolean ok = false;
public StringSelectorDialog(final String title, final String[] itemNames) {
super(SnapApp.getDefault().getMainFrame(), title, ModalDialog.ID_OK_CANCEL, null);
final JPanel content = new JPanel(new GridBagLayout());
final GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
list = new JComboBox(itemNames);
list.setMinimumSize(new Dimension(50, 4));
content.add(list, gbc);
getJDialog().setMinimumSize(new Dimension(200, 100));
setContent(content);
}
public String getSelectedItem() {
Object selection = list.getSelectedItem();
if (selection == null) {
if (list.getModel().getSize() > 0) {
selection = list.getModel().getElementAt(0);
}
}
return (String) selection;
}
protected void onOK() {
ok = true;
hide();
}
public boolean IsOK() {
return ok;
}
}
| 2,158 | 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-raster-ui/src/main/java/org/esa/snap/raster/docs/package-info.java | @HelpSetRegistration(helpSet = "help.hs", position = 5310)
package org.esa.snap.raster.docs;
import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration; | 155 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PatchTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/nbexec/src/test/java/org/esa/snap/nbexec/PatchTest.java | package org.esa.snap.nbexec;
import org.junit.Test;
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
public class PatchTest {
@Test
public void testParseOkWin() {
assumeTrue("Runs only on Windows", System.getProperty("os.name").startsWith("Win"));
Launcher.Patch patch = Launcher.Patch.parse("C:\\Users\\Norman\\Projects\\my-snap-module\\$\\target\\classes");
assertEquals(Paths.get("C:\\Users\\Norman\\Projects\\my-snap-module"), patch.getDir());
assertEquals("target\\classes", patch.getSubPath());
}
@Test
public void testParseOkNoneWin() {
assumeTrue("Runs not Windows", !System.getProperty("os.name").startsWith("Win"));
Launcher.Patch patch = Launcher.Patch.parse("/home/norman/projects/my-snap-module/$/target/classes");
assertEquals(Paths.get("/home/norman/projects/my-snap-module"), patch.getDir());
assertEquals("target/classes", patch.getSubPath());
}
@Test
public void testParseErrorsWin() {
assumeTrue("Runs only on Windows", System.getProperty("os.name").startsWith("Win"));
try {
Launcher.Patch.parse("C:\\Users\\Norman\\Projects\\my-snap-module\\target\\classes");
fail();
} catch (IllegalArgumentException e) {
// ok
}
try {
Launcher.Patch.parse("C:\\Users\\Norman\\Projects\\my-snap-module\\$\\target\\classes\\$");
fail();
} catch (IllegalArgumentException e) {
// ok
}
}
@Test
public void testParseErrorsNoneWin() {
assumeTrue("Runs not Windows", !System.getProperty("os.name").startsWith("Win"));
try {
Launcher.Patch.parse("/home/norman/projects/snap-module/target/classes");
fail();
} catch (IllegalArgumentException e) {
// ok
}
try {
Launcher.Patch.parse("/home/norman/projects/snap-module/$/target/classes/$");
fail();
} catch (IllegalArgumentException e) {
// ok
}
}
}
| 2,176 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
Launcher.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/nbexec/src/main/java/org/esa/snap/nbexec/Launcher.java | package org.esa.snap.nbexec;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.lang.management.ManagementFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* A plain Java NetBeans Platform launcher which mimics the core functionality of the NB's native launcher
* {@code nbexec}. Can be used for easy debugging of NB Platform (Maven) applications when using the NB IDE is not
* an option.
* <p>
* <i>IMPORTANT NOTE: This launcher only implements a subset of the functionality the native NetBeans
* launcher {@code nbexec} provides. For example, you cannot update plugins and then let the application
* restart itself.<br>
* The recommended way to run/debug applications build on the NetBeans platform is either using the NetBeans
* Maven plugin (via {@code nbm:run-platform}) or directly using the NetBeans IDE.
* </i>
* <p>
* Usage:
* <pre>
* Launcher [--patches <patches>] [--clusters <clusters>] [--branding <app>]
* [--userdir <userdir>] [--cachedir <cachedir>] <args>
* </pre>
* where the {@code clusters}, {@code branding}, {@code userdir}, and {@code cachedir} options are the same as
* for the native launcher.
* The current working directory must be the target deployment directory, {@code $appmodule/target/$app}.
* <p>
* The Launcher takes care of any changed code in modules indicated by the <i>patches</i> patterns given by the
* {@code patches} option. the <i>patches</i> patterns may contain multiple patterns separated by a semicolon (;)
* on Windows systems and a colon (:) on Unixes. Every patch pattern must contain a single wildcard character ($).
* The default patch pattern is {@code $appmodule/../../../$/target/classes}<br> and is always included.
* <p>
* So, In IntelliJ IDEA we can hit CTRL+F9
* and then run/debug the Launcher.
* <p>
* This is enabled for all modules which are
* <ul>
* <li>(a) found in the applications target cluster (e.g. modules with {@code nbm} packaging) and </li>
* <li>(b) have a valid target/classes output directory.</li>
* </ul>
* We may later want to be able to further configure this default behaviour. See code for how the current
* strategy is implemented.
*
* @author Norman Fomferra
* @version 1.0
*/
public class Launcher {
private static final String CLUSTERS_EXT = ".clusters";
// Command-line arguments
private final String[] args;
// Contains all environment variables and all variables from ${some-dir}/${app-name}/etc/${app-name}.conf
private final Map<String, String> configuration;
public static void main(String[] args) {
new Launcher(args).run();
}
private Launcher(String[] args) {
this.args = args;
this.configuration = new HashMap<>();
}
private void run() {
Path installationDir = Paths.get("").toAbsolutePath();
Path etcDir = installationDir.resolve("etc");
Path platformDir = installationDir.resolve("platform");
if (!Files.isDirectory(etcDir) || !Files.isDirectory(platformDir)) {
throw new IllegalStateException("Not a valid installation directory: " + installationDir);
}
LinkedList<String> argList = new LinkedList<>(Arrays.asList(args));
String clusterDirs = parseArg(argList, "--clusters");
String brandingToken = parseArg(argList, "--branding");
String userDir = parseArg(argList, "--userdir");
String cacheDir = parseArg(argList, "--cachedir");
// Collect project dirs.
// Default is "../../../$/target/classes" which refers to a Maven specific directory layout:
//
// ${parent-1}/
// pom.xml
// ${nb-app-module-dir}/
// pom.xml
// src/
// target/
// ${app} // -> must be current working directory
// ${nb-nbm-module-dir-1}/
// ${nb-nbm-module-dir-2}/
// ${nb-nbm-module-dir-3}/
// ...
// ${parent-2}/
// pom.xml
// ${nb-nbm-module-dir-1}/
// ${nb-nbm-module-dir-2}/
// ...
//
Set<Patch> patches = parseClusterPatches(argList);
Stream<Path> etcFiles;
try {
etcFiles = Files.list(etcDir);
} catch (IOException e) {
throw new IllegalStateException(e);
}
List<Path> clustersFiles = etcFiles
.filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(CLUSTERS_EXT))
.collect(Collectors.toList());
if (clustersFiles.isEmpty()) {
throw new IllegalStateException(String.format("no '*.clusters' file found in '%s'", etcDir));
} else if (clustersFiles.size() > 1) {
throw new IllegalStateException(String.format("multiple '*.clusters' files found in '%s'", etcDir));
}
Path clustersFile = clustersFiles.get(0);
String clustersFileName = clustersFile.getFileName().toString();
String appName = clustersFileName.substring(0, clustersFileName.length() - CLUSTERS_EXT.length());
Path confFile = etcDir.resolve(appName + ".conf");
configuration.putAll(System.getenv());
setConfigurationVariableIfNotSet("APPNAME", appName);
setConfigurationVariableIfNotSet("HOME", System.getProperty("user.home"));
if (Files.isRegularFile(confFile)) {
loadConf(confFile);
}
// Parse "default_options"
List<String> defaultOptionList = new LinkedList<>();
String defaultOptions = getVar("default_options");
String defaultClusterDirs = null;
String defaultBrandingToken = null;
String defaultUserDir = null;
String defaultCacheDir = null;
if (defaultOptions != null) {
defaultOptionList = parseOptions(defaultOptions);
defaultClusterDirs = parseArg(defaultOptionList, "--clusters");
defaultBrandingToken = parseArg(defaultOptionList, "--branding");
defaultUserDir = parseArg(defaultOptionList, "--userdir");
defaultCacheDir = parseArg(defaultOptionList, "--cachedir");
}
if (defaultUserDir == null) {
// From nbexec:
if ("Darwin".equals(System.getProperty("os.name"))) {
defaultUserDir = getVar("default_mac_userdir");
} else {
defaultUserDir = getVar("default_userdir");
}
// .. but not used here because our default is the nbm standard location
if (defaultUserDir == null) {
defaultUserDir = installationDir.resolve("..").resolve("userdir").toString();
}
}
if (clusterDirs == null) {
clusterDirs = defaultClusterDirs;
}
if (userDir == null) {
userDir = defaultUserDir;
}
if (defaultCacheDir == null) {
defaultCacheDir = path(userDir, "var", "cache");
}
if (brandingToken == null) {
brandingToken = defaultBrandingToken;
}
if (cacheDir == null) {
cacheDir = defaultCacheDir;
}
List<String> clusterList = readLines(clustersFile);
clusterList = toAbsolutePaths(clusterList);
String extraClusterPaths = getVar("extra_clusters");
if (extraClusterPaths != null) {
clusterList.add(extraClusterPaths);
}
if (clusterDirs != null) {
clusterList.addAll(toAbsolutePaths(Arrays.asList(clusterDirs.split(File.pathSeparator))));
}
String clusterPaths = toPathsString(clusterList);
List<URL> classPathList = new ArrayList<>();
buildClasspath(userDir, classPathList);
buildClasspath(platformDir.toString(), classPathList);
if ("true".equals(getVar("KDE_FULL_SESSION"))) {
setSystemPropertyIfNotSet("netbeans.running.environment", "kde");
} else if (getVar("GNOME_DESKTOP_SESSION_ID") != null) {
setSystemPropertyIfNotSet("netbeans.running.environment", "gnome");
}
// todo - address following warning:
// WARNING [org.netbeans.modules.autoupdate.ui.actions.AutoupdateSettings]: The property "netbeans.default_userdir_root" was not set!
if (getVar("DEFAULT_USERDIR_ROOT") != null) {
setSystemPropertyIfNotSet("netbeans.default_userdir_root", getVar("DEFAULT_USERDIR_ROOT"));
}
setSystemPropertyIfNotSet("netbeans.home", platformDir.toString());
setSystemPropertyIfNotSet("netbeans.dirs", clusterPaths);
setSystemPropertyIfNotSet("netbeans.logger.console", "true");
setSystemPropertyIfNotSet("com.apple.mrj.application.apple.menu.about.name", brandingToken);
List<String> remainingDefaultOptions = parseJavaOptions(defaultOptionList, false);
List<String> remainingArgs = parseJavaOptions(argList, true);
setPatchModules(clusterList, patches);
List<String> newArgList = new ArrayList<>();
newArgList.add("--branding");
newArgList.add(brandingToken);
newArgList.add("--userdir");
newArgList.add(userDir);
newArgList.add("--cachedir");
newArgList.add(cacheDir);
newArgList.addAll(remainingArgs);
newArgList.addAll(remainingDefaultOptions);
Path restartMarkerFile = Paths.get(userDir, "var", "restart");
try {
Files.deleteIfExists(restartMarkerFile);
} catch (IOException e) {
// So what?
}
final String _userDir = userDir;
Path restartExeFile;
try {
Optional<Path> restartFileResult = Files.list(installationDir.resolve("bin"))
.filter(Files::isExecutable)
.filter(p -> p.getFileName().toString().startsWith("restart."))
.findFirst();
restartExeFile = restartFileResult.get();
} catch (Exception e) {
restartExeFile = null;
}
final Path _restartExeFile = restartExeFile;
if (_restartExeFile != null) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
if (Files.exists(restartMarkerFile)) {
String processName = ManagementFactory.getRuntimeMXBean().getName();
Logger.getLogger("").info("Shut down: " + processName);
String pid = processName.split("@")[0];
try {
new ProcessBuilder().command(_restartExeFile.toString(), pid).start();
} catch (IOException e) {
Logger.getLogger("").log(Level.SEVERE, "Failed to restart: " + _restartExeFile.toString(), e);
//SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(null, "Failed to restart:\n" + e.getMessage()));
}
}
}));
}
runMain(classPathList, newArgList);
}
private Set<Patch> parseClusterPatches(LinkedList<String> argList) {
Set<Patch> patches = new LinkedHashSet<>();
// Add Maven-specific output directory for application module
patches.add(Patch.parse("../../../$/target/classes"));
while (true) {
String patchPatterns = parseArg(argList, "--patches");
if (patchPatterns != null) {
String[] patterns = patchPatterns.split(File.pathSeparator);
for (String pattern : patterns) {
patches.add(Patch.parse(pattern));
}
} else {
break;
}
}
return patches;
}
private List<String> parseJavaOptions(List<String> defaultOptionList, boolean fail) {
List<String> remainingDefaultOptions = new ArrayList<>();
for (String option : defaultOptionList) {
if (option.startsWith("-J")) {
if (option.startsWith("-J-D")) {
String kv = option.substring(4);
int i = kv.indexOf("=");
if (i > 0) {
setSystemPropertyIfNotSet(kv.substring(0, i), kv.substring(i + 1));
}
} else {
String msg = String.format("configured option '%s' will be ignored, because the JVM is already running", option);
if (fail) {
throw new IllegalArgumentException(msg);
}
warn(msg);
}
} else {
remainingDefaultOptions.add(option);
}
}
return remainingDefaultOptions;
}
int patchCount = 0;
/*
* scan appDir for modules and set system property netbeans.patches.<module>=<module-classes-dir> for each module
*/
private void setPatchModules(List<String> clusterList, Set<Patch> patches) {
String JAR_EXT = ".jar";
List<String> moduleNames = new ArrayList<>();
for (String clusterDir : clusterList) {
Path clusterModulesDir = Paths.get(clusterDir).resolve("modules");
try {
Files.list(clusterModulesDir).forEach(path -> {
String fileName = path.getFileName().toString();
if (fileName.endsWith(JAR_EXT)) {
String moduleName = fileName.substring(0, fileName.length() - JAR_EXT.length());
//info("candidate patch-providing module in development: " + moduleName);
moduleNames.add(moduleName);
}
});
} catch (IOException e) {
warn("failed to list entries of " + clusterModulesDir);
}
}
for (Patch patch : patches) {
patchCount = 0;
Path parentSourceDir = patch.dir;
if (Files.isDirectory(parentSourceDir)) {
try {
List<Path> moduleSourceDirs = Files.list(parentSourceDir)
.filter(moduleSourceDir -> Files.isDirectory(moduleSourceDir))
.collect(Collectors.toList());
for (Path moduleSourceDir : moduleSourceDirs) {
addPatchForModuleSourceDir(moduleSourceDir, moduleNames, patch);
}
} catch (IOException e) {
warn("failed to list entries of " + parentSourceDir);
}
if (patchCount == 0 && parentSourceDir.getFileName() != null) {
// Maybe patch points to single-module project directory, so let's see
addPatchForModuleSourceDir(parentSourceDir, moduleNames, patch);
}
}
if (patchCount == 0) {
warn("no module patches found for pattern " + patch);
} else {
info(patchCount + " module patch(es) found for pattern " + patch);
}
}
}
private boolean addPatchForModuleSourceDir(Path moduleSourceDir, List<String> moduleNames, Patch patch) {
String moduleSourceName = moduleSourceDir.getFileName().toString();
if (!moduleSourceName.startsWith(".")) {
//info("checking '" + moduleSourceDir + "'");
Path modulePatchDir = moduleSourceDir.resolve(patch.subPath);
if (Files.isDirectory(modulePatchDir)) {
//info("checking if artifact '" + artifactName + "' has output directory " + classesDir);
for (String moduleName : moduleNames) {
if (moduleName.endsWith(moduleSourceName)) {
addPatch(moduleName, modulePatchDir);
return true;
}
}
for (String moduleName : moduleNames) {
if (moduleName.contains(moduleSourceName)) {
addPatch(moduleName, modulePatchDir);
return true;
}
}
}
}
return false;
}
private void addPatch(String moduleName, Path classesDir) {
String propertyName = "netbeans.patches." + moduleName.replace("-", ".");
setSystemPropertyIfNotSet(propertyName, classesDir.toString());
patchCount++;
}
private List<String> parseOptions(String defaultOptions) {
LinkedList<String> defaultOptionList = new LinkedList<>();
StreamTokenizer st = new StreamTokenizer(new StringReader(defaultOptions));
st.resetSyntax();
st.wordChars(' ' + 1, 255);
st.whitespaceChars(0, ' ');
st.quoteChar('"');
st.quoteChar('\'');
boolean firstArgQuoted;
try {
int tt = st.nextToken();
firstArgQuoted = tt == '\'' || tt == '"';
if (tt != StreamTokenizer.TT_EOF) {
do {
if (st.sval != null) {
defaultOptionList.add(st.sval);
}
tt = st.nextToken();
} while (tt != StreamTokenizer.TT_EOF);
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
if (defaultOptionList.size() == 1 && firstArgQuoted) {
return parseOptions(defaultOptionList.get(0));
}
return defaultOptionList;
}
private static void runMain(List<URL> classPathList, List<String> argList) {
URLClassLoader classLoader = new URLClassLoader(classPathList.toArray(new URL[classPathList.size()]));
try {
Class<?> nbMainClass = classLoader.loadClass("org.netbeans.Main");
Method nbMainMethod = nbMainClass.getDeclaredMethod("main", String[].class);
nbMainMethod.invoke(null, (Object) argList.toArray(new String[argList.size()]));
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
private void buildClasspath(String base, List<URL> classPathList) {
appendToClasspath(path(base, "lib", "patches"), classPathList);
appendToClasspath(path(base, "lib"), classPathList);
appendToClasspath(path(base, "locale", "locale"), classPathList);
}
private void appendToClasspath(String path, List<URL> classPathList) {
try {
Files.list(Paths.get(path)).forEach(file -> {
if (Files.isDirectory(file)) {
appendToClasspath(file.toString(), classPathList);
} else if (Files.isRegularFile(file)) {
String s = file.getFileName().toString().toLowerCase();
if (s.endsWith(".jar") || s.endsWith(".zip")) {
try {
URL url = file.toUri().toURL();
classPathList.add(url);
info("added to application classpath: " + file);
} catch (MalformedURLException e) {
throw new IllegalStateException(e);
}
}
}
});
} catch (IOException e) {
warn("failed to list entries of " + path);
}
}
private void setConfigurationVariableIfNotSet(String varName, String varValue) {
if (!configuration.containsKey(varName)) {
configuration.put(varName, varValue);
}
}
private void setSystemPropertyIfNotSet(String name, String value) {
String oldValue = System.getProperty(name);
if (oldValue == null) {
info("setting system property: " + name + " = " + value);
System.setProperty(name, value);
} else {
warn("not overriding existing system property: " + name + " = " + oldValue + "(new value: " + value + ")");
}
}
private static String toPathsString(List<String> paths) {
StringBuilder sb = new StringBuilder();
for (String path : paths) {
if (sb.length() > 0) {
sb.append(File.pathSeparatorChar);
}
sb.append(path);
}
return sb.toString();
}
private static List<String> toAbsolutePaths(List<String> paths) {
return paths.stream()
.map(path -> Paths.get(path).toAbsolutePath().toString())
.collect(Collectors.toList());
}
private static List<String> readLines(Path path) {
try {
return Files.readAllLines(path);
} catch (IOException e) {
return Collections.emptyList();
}
}
private String parseArg(List<String> argList, String name) {
String value = null;
int i = argList.indexOf(name);
if (i >= 0 && i + 1 < argList.size()) {
value = argList.get(i + 1);
argList.remove(i);
argList.remove(i);
}
return value;
}
private String getVar(String name) {
String value = configuration.get(name);
if (value != null) {
return resolveString(value, configuration);
}
return null;
}
private void loadConf(Path path) {
info("reading configuration from " + path);
try {
Properties properties = new Properties();
try (Reader reader = Files.newBufferedReader(path)) {
properties.load(reader);
}
Set<String> propertyNames = properties.stringPropertyNames();
for (String propertyName : propertyNames) {
String propertyValue = properties.getProperty(propertyName);
if (propertyValue.startsWith("\"") && propertyValue.endsWith("\"")) {
propertyValue = propertyValue.substring(1, propertyValue.length() - 1);
}
configuration.put(propertyName, propertyValue);
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private void info(String msg) {
System.out.printf("INFO: %s: %s%n", getClass(), msg);
}
private void warn(String msg) {
System.err.printf("WARNING: %s: %s%n", getClass(), msg);
}
private static String resolveString(String text, Map<String, String> variables) {
for (Map.Entry<String, String> entry : variables.entrySet()) {
text = text.replace("$" + entry.getKey(), entry.getValue());
text = text.replace("${" + entry.getKey() + "}", entry.getValue());
}
return text;
}
private static String path(String first, String... more) {
return Paths.get(first, more).toString();
}
public static class Patch {
public static final char WILDCARD_CHAR = '$';
private final Path dir;
private final String subPath;
public static Patch parse(String pattern) {
int wcPos = pattern.indexOf(WILDCARD_CHAR);
if (wcPos >= 0) {
String subPath = pattern.substring(wcPos + 1);
if (subPath.startsWith(File.separator) || subPath.startsWith("/")) {
subPath = subPath.substring(1);
}
if (subPath.indexOf(WILDCARD_CHAR) > 0) {
throw new IllegalArgumentException(String.format("patch pattern must contain a single wildcard '%s': %s",
WILDCARD_CHAR, pattern));
}
return new Patch(Paths.get(pattern.substring(0, wcPos)).toAbsolutePath().normalize(), subPath);
} else {
throw new IllegalArgumentException(String.format("patch pattern must contain wildcard '%s': %s",
WILDCARD_CHAR, pattern));
}
}
private Patch(Path dir, String subPath) {
this.dir = dir;
this.subPath = subPath;
}
public Path getDir() {
return dir;
}
public String getSubPath() {
return subPath;
}
@Override
public String toString() {
if (subPath.isEmpty()) {
return dir + File.separator + WILDCARD_CHAR;
}
return dir + File.separator + WILDCARD_CHAR + File.separator + subPath;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Patch patch = (Patch) o;
return dir.equals(patch.dir) && subPath.equals(patch.subPath);
}
@Override
public int hashCode() {
int result = dir.hashCode();
result = 31 * result + subPath.hashCode();
return result;
}
}
}
| 25,965 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TangoIconsTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-tango/src/test/java/org/esa/snap/tango/TangoIconsTest.java | package org.esa.snap.tango;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
/**
* @author Norman Fomferra
*/
public class TangoIconsTest {
@Test
public void testAll() {
assertNotNull(TangoIcons.actions_address_book_new(TangoIcons.R16));
assertNotNull(TangoIcons.actions_address_book_new(TangoIcons.R22));
assertNotNull(TangoIcons.actions_address_book_new(TangoIcons.R32));
assertNotNull(TangoIcons.actions_appointment_new(TangoIcons.R16));
assertNotNull(TangoIcons.actions_appointment_new(TangoIcons.R22));
assertNotNull(TangoIcons.actions_appointment_new(TangoIcons.R32));
assertNotNull(TangoIcons.actions_bookmark_new(TangoIcons.R16));
assertNotNull(TangoIcons.actions_bookmark_new(TangoIcons.R22));
assertNotNull(TangoIcons.actions_bookmark_new(TangoIcons.R32));
assertNotNull(TangoIcons.actions_contact_new(TangoIcons.R16));
assertNotNull(TangoIcons.actions_contact_new(TangoIcons.R22));
assertNotNull(TangoIcons.actions_contact_new(TangoIcons.R32));
assertNotNull(TangoIcons.actions_document_new(TangoIcons.R16));
assertNotNull(TangoIcons.actions_document_new(TangoIcons.R22));
assertNotNull(TangoIcons.actions_document_new(TangoIcons.R32));
assertNotNull(TangoIcons.actions_document_open(TangoIcons.R16));
assertNotNull(TangoIcons.actions_document_open(TangoIcons.R22));
assertNotNull(TangoIcons.actions_document_open(TangoIcons.R32));
assertNotNull(TangoIcons.actions_document_print_preview(TangoIcons.R16));
assertNotNull(TangoIcons.actions_document_print_preview(TangoIcons.R22));
assertNotNull(TangoIcons.actions_document_print_preview(TangoIcons.R32));
assertNotNull(TangoIcons.actions_document_print(TangoIcons.R16));
assertNotNull(TangoIcons.actions_document_print(TangoIcons.R22));
assertNotNull(TangoIcons.actions_document_print(TangoIcons.R32));
assertNotNull(TangoIcons.actions_document_properties(TangoIcons.R16));
assertNotNull(TangoIcons.actions_document_properties(TangoIcons.R22));
assertNotNull(TangoIcons.actions_document_properties(TangoIcons.R32));
assertNotNull(TangoIcons.actions_document_save_as(TangoIcons.R16));
assertNotNull(TangoIcons.actions_document_save_as(TangoIcons.R22));
assertNotNull(TangoIcons.actions_document_save_as(TangoIcons.R32));
assertNotNull(TangoIcons.actions_document_save(TangoIcons.R16));
assertNotNull(TangoIcons.actions_document_save(TangoIcons.R22));
assertNotNull(TangoIcons.actions_document_save(TangoIcons.R32));
assertNotNull(TangoIcons.actions_edit_clear(TangoIcons.R16));
assertNotNull(TangoIcons.actions_edit_clear(TangoIcons.R22));
assertNotNull(TangoIcons.actions_edit_clear(TangoIcons.R32));
assertNotNull(TangoIcons.actions_edit_copy(TangoIcons.R16));
assertNotNull(TangoIcons.actions_edit_copy(TangoIcons.R22));
assertNotNull(TangoIcons.actions_edit_copy(TangoIcons.R32));
assertNotNull(TangoIcons.actions_edit_cut(TangoIcons.R16));
assertNotNull(TangoIcons.actions_edit_cut(TangoIcons.R22));
assertNotNull(TangoIcons.actions_edit_cut(TangoIcons.R32));
assertNotNull(TangoIcons.actions_edit_delete(TangoIcons.R16));
assertNotNull(TangoIcons.actions_edit_delete(TangoIcons.R22));
assertNotNull(TangoIcons.actions_edit_delete(TangoIcons.R32));
assertNotNull(TangoIcons.actions_edit_find_replace(TangoIcons.R16));
assertNotNull(TangoIcons.actions_edit_find_replace(TangoIcons.R22));
assertNotNull(TangoIcons.actions_edit_find_replace(TangoIcons.R32));
assertNotNull(TangoIcons.actions_edit_find(TangoIcons.R16));
assertNotNull(TangoIcons.actions_edit_find(TangoIcons.R22));
assertNotNull(TangoIcons.actions_edit_find(TangoIcons.R32));
assertNotNull(TangoIcons.actions_edit_paste(TangoIcons.R16));
assertNotNull(TangoIcons.actions_edit_paste(TangoIcons.R22));
assertNotNull(TangoIcons.actions_edit_paste(TangoIcons.R32));
assertNotNull(TangoIcons.actions_edit_redo(TangoIcons.R16));
assertNotNull(TangoIcons.actions_edit_redo(TangoIcons.R22));
assertNotNull(TangoIcons.actions_edit_redo(TangoIcons.R32));
assertNotNull(TangoIcons.actions_edit_select_all(TangoIcons.R16));
assertNotNull(TangoIcons.actions_edit_select_all(TangoIcons.R22));
assertNotNull(TangoIcons.actions_edit_select_all(TangoIcons.R32));
assertNotNull(TangoIcons.actions_edit_undo(TangoIcons.R16));
assertNotNull(TangoIcons.actions_edit_undo(TangoIcons.R22));
assertNotNull(TangoIcons.actions_edit_undo(TangoIcons.R32));
assertNotNull(TangoIcons.actions_folder_new(TangoIcons.R16));
assertNotNull(TangoIcons.actions_folder_new(TangoIcons.R22));
assertNotNull(TangoIcons.actions_folder_new(TangoIcons.R32));
assertNotNull(TangoIcons.actions_format_indent_less(TangoIcons.R16));
assertNotNull(TangoIcons.actions_format_indent_less(TangoIcons.R22));
assertNotNull(TangoIcons.actions_format_indent_less(TangoIcons.R32));
assertNotNull(TangoIcons.actions_format_indent_more(TangoIcons.R16));
assertNotNull(TangoIcons.actions_format_indent_more(TangoIcons.R22));
assertNotNull(TangoIcons.actions_format_indent_more(TangoIcons.R32));
assertNotNull(TangoIcons.actions_format_justify_center(TangoIcons.R16));
assertNotNull(TangoIcons.actions_format_justify_center(TangoIcons.R22));
assertNotNull(TangoIcons.actions_format_justify_center(TangoIcons.R32));
assertNotNull(TangoIcons.actions_format_justify_fill(TangoIcons.R16));
assertNotNull(TangoIcons.actions_format_justify_fill(TangoIcons.R22));
assertNotNull(TangoIcons.actions_format_justify_fill(TangoIcons.R32));
assertNotNull(TangoIcons.actions_format_justify_left(TangoIcons.R16));
assertNotNull(TangoIcons.actions_format_justify_left(TangoIcons.R22));
assertNotNull(TangoIcons.actions_format_justify_left(TangoIcons.R32));
assertNotNull(TangoIcons.actions_format_justify_right(TangoIcons.R16));
assertNotNull(TangoIcons.actions_format_justify_right(TangoIcons.R22));
assertNotNull(TangoIcons.actions_format_justify_right(TangoIcons.R32));
assertNotNull(TangoIcons.actions_format_text_bold(TangoIcons.R16));
assertNotNull(TangoIcons.actions_format_text_bold(TangoIcons.R22));
assertNotNull(TangoIcons.actions_format_text_bold(TangoIcons.R32));
assertNotNull(TangoIcons.actions_format_text_italic(TangoIcons.R16));
assertNotNull(TangoIcons.actions_format_text_italic(TangoIcons.R22));
assertNotNull(TangoIcons.actions_format_text_italic(TangoIcons.R32));
assertNotNull(TangoIcons.actions_format_text_strikethrough(TangoIcons.R16));
assertNotNull(TangoIcons.actions_format_text_strikethrough(TangoIcons.R22));
assertNotNull(TangoIcons.actions_format_text_strikethrough(TangoIcons.R32));
assertNotNull(TangoIcons.actions_format_text_underline(TangoIcons.R16));
assertNotNull(TangoIcons.actions_format_text_underline(TangoIcons.R22));
assertNotNull(TangoIcons.actions_format_text_underline(TangoIcons.R32));
assertNotNull(TangoIcons.actions_go_bottom(TangoIcons.R16));
assertNotNull(TangoIcons.actions_go_bottom(TangoIcons.R22));
assertNotNull(TangoIcons.actions_go_bottom(TangoIcons.R32));
assertNotNull(TangoIcons.actions_go_down(TangoIcons.R16));
assertNotNull(TangoIcons.actions_go_down(TangoIcons.R22));
assertNotNull(TangoIcons.actions_go_down(TangoIcons.R32));
assertNotNull(TangoIcons.actions_go_first(TangoIcons.R16));
assertNotNull(TangoIcons.actions_go_first(TangoIcons.R22));
assertNotNull(TangoIcons.actions_go_first(TangoIcons.R32));
assertNotNull(TangoIcons.actions_go_home(TangoIcons.R16));
assertNotNull(TangoIcons.actions_go_home(TangoIcons.R22));
assertNotNull(TangoIcons.actions_go_home(TangoIcons.R32));
assertNotNull(TangoIcons.actions_go_jump(TangoIcons.R16));
assertNotNull(TangoIcons.actions_go_jump(TangoIcons.R22));
assertNotNull(TangoIcons.actions_go_jump(TangoIcons.R32));
assertNotNull(TangoIcons.actions_go_last(TangoIcons.R16));
assertNotNull(TangoIcons.actions_go_last(TangoIcons.R22));
assertNotNull(TangoIcons.actions_go_last(TangoIcons.R32));
assertNotNull(TangoIcons.actions_go_next(TangoIcons.R16));
assertNotNull(TangoIcons.actions_go_next(TangoIcons.R22));
assertNotNull(TangoIcons.actions_go_next(TangoIcons.R32));
assertNotNull(TangoIcons.actions_go_previous(TangoIcons.R16));
assertNotNull(TangoIcons.actions_go_previous(TangoIcons.R22));
assertNotNull(TangoIcons.actions_go_previous(TangoIcons.R32));
assertNotNull(TangoIcons.actions_go_top(TangoIcons.R16));
assertNotNull(TangoIcons.actions_go_top(TangoIcons.R22));
assertNotNull(TangoIcons.actions_go_top(TangoIcons.R32));
assertNotNull(TangoIcons.actions_go_up(TangoIcons.R16));
assertNotNull(TangoIcons.actions_go_up(TangoIcons.R22));
assertNotNull(TangoIcons.actions_go_up(TangoIcons.R32));
assertNotNull(TangoIcons.actions_list_add(TangoIcons.R16));
assertNotNull(TangoIcons.actions_list_add(TangoIcons.R22));
assertNotNull(TangoIcons.actions_list_add(TangoIcons.R32));
assertNotNull(TangoIcons.actions_list_remove(TangoIcons.R16));
assertNotNull(TangoIcons.actions_list_remove(TangoIcons.R22));
assertNotNull(TangoIcons.actions_list_remove(TangoIcons.R32));
assertNotNull(TangoIcons.actions_mail_forward(TangoIcons.R16));
assertNotNull(TangoIcons.actions_mail_forward(TangoIcons.R22));
assertNotNull(TangoIcons.actions_mail_forward(TangoIcons.R32));
assertNotNull(TangoIcons.actions_mail_mark_junk(TangoIcons.R16));
assertNotNull(TangoIcons.actions_mail_mark_junk(TangoIcons.R22));
assertNotNull(TangoIcons.actions_mail_mark_junk(TangoIcons.R32));
assertNotNull(TangoIcons.actions_mail_mark_not_junk(TangoIcons.R16));
assertNotNull(TangoIcons.actions_mail_mark_not_junk(TangoIcons.R22));
assertNotNull(TangoIcons.actions_mail_mark_not_junk(TangoIcons.R32));
assertNotNull(TangoIcons.actions_mail_message_new(TangoIcons.R16));
assertNotNull(TangoIcons.actions_mail_message_new(TangoIcons.R22));
assertNotNull(TangoIcons.actions_mail_message_new(TangoIcons.R32));
assertNotNull(TangoIcons.actions_mail_reply_all(TangoIcons.R16));
assertNotNull(TangoIcons.actions_mail_reply_all(TangoIcons.R22));
assertNotNull(TangoIcons.actions_mail_reply_all(TangoIcons.R32));
assertNotNull(TangoIcons.actions_mail_reply_sender(TangoIcons.R16));
assertNotNull(TangoIcons.actions_mail_reply_sender(TangoIcons.R22));
assertNotNull(TangoIcons.actions_mail_reply_sender(TangoIcons.R32));
assertNotNull(TangoIcons.actions_mail_send_receive(TangoIcons.R16));
assertNotNull(TangoIcons.actions_mail_send_receive(TangoIcons.R22));
assertNotNull(TangoIcons.actions_mail_send_receive(TangoIcons.R32));
assertNotNull(TangoIcons.actions_media_eject(TangoIcons.R16));
assertNotNull(TangoIcons.actions_media_eject(TangoIcons.R22));
assertNotNull(TangoIcons.actions_media_eject(TangoIcons.R32));
assertNotNull(TangoIcons.actions_media_playback_pause(TangoIcons.R16));
assertNotNull(TangoIcons.actions_media_playback_pause(TangoIcons.R22));
assertNotNull(TangoIcons.actions_media_playback_pause(TangoIcons.R32));
assertNotNull(TangoIcons.actions_media_playback_start(TangoIcons.R16));
assertNotNull(TangoIcons.actions_media_playback_start(TangoIcons.R22));
assertNotNull(TangoIcons.actions_media_playback_start(TangoIcons.R32));
assertNotNull(TangoIcons.actions_media_playback_stop(TangoIcons.R16));
assertNotNull(TangoIcons.actions_media_playback_stop(TangoIcons.R22));
assertNotNull(TangoIcons.actions_media_playback_stop(TangoIcons.R32));
assertNotNull(TangoIcons.actions_media_record(TangoIcons.R16));
assertNotNull(TangoIcons.actions_media_record(TangoIcons.R22));
assertNotNull(TangoIcons.actions_media_record(TangoIcons.R32));
assertNotNull(TangoIcons.actions_media_seek_backward(TangoIcons.R16));
assertNotNull(TangoIcons.actions_media_seek_backward(TangoIcons.R22));
assertNotNull(TangoIcons.actions_media_seek_backward(TangoIcons.R32));
assertNotNull(TangoIcons.actions_media_seek_forward(TangoIcons.R16));
assertNotNull(TangoIcons.actions_media_seek_forward(TangoIcons.R22));
assertNotNull(TangoIcons.actions_media_seek_forward(TangoIcons.R32));
assertNotNull(TangoIcons.actions_media_skip_backward(TangoIcons.R16));
assertNotNull(TangoIcons.actions_media_skip_backward(TangoIcons.R22));
assertNotNull(TangoIcons.actions_media_skip_backward(TangoIcons.R32));
assertNotNull(TangoIcons.actions_media_skip_forward(TangoIcons.R16));
assertNotNull(TangoIcons.actions_media_skip_forward(TangoIcons.R22));
assertNotNull(TangoIcons.actions_media_skip_forward(TangoIcons.R32));
assertNotNull(TangoIcons.actions_process_stop(TangoIcons.R16));
assertNotNull(TangoIcons.actions_process_stop(TangoIcons.R22));
assertNotNull(TangoIcons.actions_process_stop(TangoIcons.R32));
assertNotNull(TangoIcons.actions_system_lock_screen(TangoIcons.R16));
assertNotNull(TangoIcons.actions_system_lock_screen(TangoIcons.R22));
assertNotNull(TangoIcons.actions_system_lock_screen(TangoIcons.R32));
assertNotNull(TangoIcons.actions_system_log_out(TangoIcons.R16));
assertNotNull(TangoIcons.actions_system_log_out(TangoIcons.R22));
assertNotNull(TangoIcons.actions_system_log_out(TangoIcons.R32));
assertNotNull(TangoIcons.actions_system_search(TangoIcons.R16));
assertNotNull(TangoIcons.actions_system_search(TangoIcons.R22));
assertNotNull(TangoIcons.actions_system_search(TangoIcons.R32));
assertNotNull(TangoIcons.actions_system_shutdown(TangoIcons.R16));
assertNotNull(TangoIcons.actions_system_shutdown(TangoIcons.R22));
assertNotNull(TangoIcons.actions_system_shutdown(TangoIcons.R32));
assertNotNull(TangoIcons.actions_tab_new(TangoIcons.R16));
assertNotNull(TangoIcons.actions_tab_new(TangoIcons.R22));
assertNotNull(TangoIcons.actions_tab_new(TangoIcons.R32));
assertNotNull(TangoIcons.actions_view_fullscreen(TangoIcons.R16));
assertNotNull(TangoIcons.actions_view_fullscreen(TangoIcons.R22));
assertNotNull(TangoIcons.actions_view_fullscreen(TangoIcons.R32));
assertNotNull(TangoIcons.actions_view_refresh(TangoIcons.R16));
assertNotNull(TangoIcons.actions_view_refresh(TangoIcons.R22));
assertNotNull(TangoIcons.actions_view_refresh(TangoIcons.R32));
assertNotNull(TangoIcons.actions_window_new(TangoIcons.R16));
assertNotNull(TangoIcons.actions_window_new(TangoIcons.R22));
assertNotNull(TangoIcons.actions_window_new(TangoIcons.R32));
assertNotNull(TangoIcons.animations_process_working(TangoIcons.R16));
assertNotNull(TangoIcons.animations_process_working(TangoIcons.R22));
assertNotNull(TangoIcons.animations_process_working(TangoIcons.R32));
assertNotNull(TangoIcons.apps_accessories_calculator(TangoIcons.R16));
assertNotNull(TangoIcons.apps_accessories_calculator(TangoIcons.R22));
assertNotNull(TangoIcons.apps_accessories_calculator(TangoIcons.R32));
assertNotNull(TangoIcons.apps_accessories_character_map(TangoIcons.R16));
assertNotNull(TangoIcons.apps_accessories_character_map(TangoIcons.R22));
assertNotNull(TangoIcons.apps_accessories_character_map(TangoIcons.R32));
assertNotNull(TangoIcons.apps_accessories_text_editor(TangoIcons.R16));
assertNotNull(TangoIcons.apps_accessories_text_editor(TangoIcons.R22));
assertNotNull(TangoIcons.apps_accessories_text_editor(TangoIcons.R32));
assertNotNull(TangoIcons.apps_help_browser(TangoIcons.R16));
assertNotNull(TangoIcons.apps_help_browser(TangoIcons.R22));
assertNotNull(TangoIcons.apps_help_browser(TangoIcons.R32));
assertNotNull(TangoIcons.apps_internet_group_chat(TangoIcons.R16));
assertNotNull(TangoIcons.apps_internet_group_chat(TangoIcons.R22));
assertNotNull(TangoIcons.apps_internet_group_chat(TangoIcons.R32));
assertNotNull(TangoIcons.apps_internet_mail(TangoIcons.R16));
assertNotNull(TangoIcons.apps_internet_mail(TangoIcons.R22));
assertNotNull(TangoIcons.apps_internet_mail(TangoIcons.R32));
assertNotNull(TangoIcons.apps_internet_news_reader(TangoIcons.R16));
assertNotNull(TangoIcons.apps_internet_news_reader(TangoIcons.R22));
assertNotNull(TangoIcons.apps_internet_news_reader(TangoIcons.R32));
assertNotNull(TangoIcons.apps_internet_web_browser(TangoIcons.R16));
assertNotNull(TangoIcons.apps_internet_web_browser(TangoIcons.R22));
assertNotNull(TangoIcons.apps_internet_web_browser(TangoIcons.R32));
assertNotNull(TangoIcons.apps_office_calendar(TangoIcons.R16));
assertNotNull(TangoIcons.apps_office_calendar(TangoIcons.R22));
assertNotNull(TangoIcons.apps_office_calendar(TangoIcons.R32));
assertNotNull(TangoIcons.apps_preferences_desktop_accessibility(TangoIcons.R16));
assertNotNull(TangoIcons.apps_preferences_desktop_accessibility(TangoIcons.R22));
assertNotNull(TangoIcons.apps_preferences_desktop_accessibility(TangoIcons.R32));
assertNotNull(TangoIcons.apps_preferences_desktop_assistive_technology(TangoIcons.R16));
assertNotNull(TangoIcons.apps_preferences_desktop_assistive_technology(TangoIcons.R22));
assertNotNull(TangoIcons.apps_preferences_desktop_assistive_technology(TangoIcons.R32));
assertNotNull(TangoIcons.apps_preferences_desktop_font(TangoIcons.R16));
assertNotNull(TangoIcons.apps_preferences_desktop_font(TangoIcons.R22));
assertNotNull(TangoIcons.apps_preferences_desktop_font(TangoIcons.R32));
assertNotNull(TangoIcons.apps_preferences_desktop_keyboard_shortcuts(TangoIcons.R16));
assertNotNull(TangoIcons.apps_preferences_desktop_keyboard_shortcuts(TangoIcons.R22));
assertNotNull(TangoIcons.apps_preferences_desktop_keyboard_shortcuts(TangoIcons.R32));
assertNotNull(TangoIcons.apps_preferences_desktop_locale(TangoIcons.R16));
assertNotNull(TangoIcons.apps_preferences_desktop_locale(TangoIcons.R22));
assertNotNull(TangoIcons.apps_preferences_desktop_locale(TangoIcons.R32));
assertNotNull(TangoIcons.apps_preferences_desktop_multimedia(TangoIcons.R16));
assertNotNull(TangoIcons.apps_preferences_desktop_multimedia(TangoIcons.R22));
assertNotNull(TangoIcons.apps_preferences_desktop_multimedia(TangoIcons.R32));
assertNotNull(TangoIcons.apps_preferences_desktop_remote_desktop(TangoIcons.R16));
assertNotNull(TangoIcons.apps_preferences_desktop_remote_desktop(TangoIcons.R22));
assertNotNull(TangoIcons.apps_preferences_desktop_remote_desktop(TangoIcons.R32));
assertNotNull(TangoIcons.apps_preferences_desktop_screensaver(TangoIcons.R16));
assertNotNull(TangoIcons.apps_preferences_desktop_screensaver(TangoIcons.R22));
assertNotNull(TangoIcons.apps_preferences_desktop_screensaver(TangoIcons.R32));
assertNotNull(TangoIcons.apps_preferences_desktop_theme(TangoIcons.R16));
assertNotNull(TangoIcons.apps_preferences_desktop_theme(TangoIcons.R22));
assertNotNull(TangoIcons.apps_preferences_desktop_theme(TangoIcons.R32));
assertNotNull(TangoIcons.apps_preferences_desktop_wallpaper(TangoIcons.R16));
assertNotNull(TangoIcons.apps_preferences_desktop_wallpaper(TangoIcons.R22));
assertNotNull(TangoIcons.apps_preferences_desktop_wallpaper(TangoIcons.R32));
assertNotNull(TangoIcons.apps_preferences_system_network_proxy(TangoIcons.R16));
assertNotNull(TangoIcons.apps_preferences_system_network_proxy(TangoIcons.R22));
assertNotNull(TangoIcons.apps_preferences_system_network_proxy(TangoIcons.R32));
assertNotNull(TangoIcons.apps_preferences_system_session(TangoIcons.R16));
assertNotNull(TangoIcons.apps_preferences_system_session(TangoIcons.R22));
assertNotNull(TangoIcons.apps_preferences_system_session(TangoIcons.R32));
assertNotNull(TangoIcons.apps_preferences_system_windows(TangoIcons.R16));
assertNotNull(TangoIcons.apps_preferences_system_windows(TangoIcons.R22));
assertNotNull(TangoIcons.apps_preferences_system_windows(TangoIcons.R32));
assertNotNull(TangoIcons.apps_system_file_manager(TangoIcons.R16));
assertNotNull(TangoIcons.apps_system_file_manager(TangoIcons.R22));
assertNotNull(TangoIcons.apps_system_file_manager(TangoIcons.R32));
assertNotNull(TangoIcons.apps_system_installer(TangoIcons.R16));
assertNotNull(TangoIcons.apps_system_installer(TangoIcons.R22));
assertNotNull(TangoIcons.apps_system_installer(TangoIcons.R32));
assertNotNull(TangoIcons.apps_system_software_update(TangoIcons.R16));
assertNotNull(TangoIcons.apps_system_software_update(TangoIcons.R22));
assertNotNull(TangoIcons.apps_system_software_update(TangoIcons.R32));
assertNotNull(TangoIcons.apps_system_users(TangoIcons.R16));
assertNotNull(TangoIcons.apps_system_users(TangoIcons.R22));
assertNotNull(TangoIcons.apps_system_users(TangoIcons.R32));
assertNotNull(TangoIcons.apps_utilities_system_monitor(TangoIcons.R16));
assertNotNull(TangoIcons.apps_utilities_system_monitor(TangoIcons.R22));
assertNotNull(TangoIcons.apps_utilities_system_monitor(TangoIcons.R32));
assertNotNull(TangoIcons.apps_utilities_terminal(TangoIcons.R16));
assertNotNull(TangoIcons.apps_utilities_terminal(TangoIcons.R22));
assertNotNull(TangoIcons.apps_utilities_terminal(TangoIcons.R32));
assertNotNull(TangoIcons.categories_applications_accessories(TangoIcons.R16));
assertNotNull(TangoIcons.categories_applications_accessories(TangoIcons.R22));
assertNotNull(TangoIcons.categories_applications_accessories(TangoIcons.R32));
assertNotNull(TangoIcons.categories_applications_development(TangoIcons.R16));
assertNotNull(TangoIcons.categories_applications_development(TangoIcons.R22));
assertNotNull(TangoIcons.categories_applications_development(TangoIcons.R32));
assertNotNull(TangoIcons.categories_applications_games(TangoIcons.R16));
assertNotNull(TangoIcons.categories_applications_games(TangoIcons.R22));
assertNotNull(TangoIcons.categories_applications_games(TangoIcons.R32));
assertNotNull(TangoIcons.categories_applications_graphics(TangoIcons.R16));
assertNotNull(TangoIcons.categories_applications_graphics(TangoIcons.R22));
assertNotNull(TangoIcons.categories_applications_graphics(TangoIcons.R32));
assertNotNull(TangoIcons.categories_applications_internet(TangoIcons.R16));
assertNotNull(TangoIcons.categories_applications_internet(TangoIcons.R22));
assertNotNull(TangoIcons.categories_applications_internet(TangoIcons.R32));
assertNotNull(TangoIcons.categories_applications_multimedia(TangoIcons.R16));
assertNotNull(TangoIcons.categories_applications_multimedia(TangoIcons.R22));
assertNotNull(TangoIcons.categories_applications_multimedia(TangoIcons.R32));
assertNotNull(TangoIcons.categories_applications_office(TangoIcons.R16));
assertNotNull(TangoIcons.categories_applications_office(TangoIcons.R22));
assertNotNull(TangoIcons.categories_applications_office(TangoIcons.R32));
assertNotNull(TangoIcons.categories_applications_other(TangoIcons.R16));
assertNotNull(TangoIcons.categories_applications_other(TangoIcons.R22));
assertNotNull(TangoIcons.categories_applications_other(TangoIcons.R32));
assertNotNull(TangoIcons.categories_applications_system(TangoIcons.R16));
assertNotNull(TangoIcons.categories_applications_system(TangoIcons.R22));
assertNotNull(TangoIcons.categories_applications_system(TangoIcons.R32));
assertNotNull(TangoIcons.categories_preferences_desktop_peripherals(TangoIcons.R16));
assertNotNull(TangoIcons.categories_preferences_desktop_peripherals(TangoIcons.R22));
assertNotNull(TangoIcons.categories_preferences_desktop_peripherals(TangoIcons.R32));
assertNotNull(TangoIcons.categories_preferences_desktop(TangoIcons.R16));
assertNotNull(TangoIcons.categories_preferences_desktop(TangoIcons.R22));
assertNotNull(TangoIcons.categories_preferences_desktop(TangoIcons.R32));
assertNotNull(TangoIcons.categories_preferences_system(TangoIcons.R16));
assertNotNull(TangoIcons.categories_preferences_system(TangoIcons.R22));
assertNotNull(TangoIcons.categories_preferences_system(TangoIcons.R32));
assertNotNull(TangoIcons.devices_audio_card(TangoIcons.R16));
assertNotNull(TangoIcons.devices_audio_card(TangoIcons.R22));
assertNotNull(TangoIcons.devices_audio_card(TangoIcons.R32));
assertNotNull(TangoIcons.devices_audio_input_microphone(TangoIcons.R16));
assertNotNull(TangoIcons.devices_audio_input_microphone(TangoIcons.R22));
assertNotNull(TangoIcons.devices_audio_input_microphone(TangoIcons.R32));
assertNotNull(TangoIcons.devices_battery(TangoIcons.R16));
assertNotNull(TangoIcons.devices_battery(TangoIcons.R22));
assertNotNull(TangoIcons.devices_battery(TangoIcons.R32));
assertNotNull(TangoIcons.devices_camera_photo(TangoIcons.R16));
assertNotNull(TangoIcons.devices_camera_photo(TangoIcons.R22));
assertNotNull(TangoIcons.devices_camera_photo(TangoIcons.R32));
assertNotNull(TangoIcons.devices_camera_video(TangoIcons.R16));
assertNotNull(TangoIcons.devices_camera_video(TangoIcons.R22));
assertNotNull(TangoIcons.devices_camera_video(TangoIcons.R32));
assertNotNull(TangoIcons.devices_computer(TangoIcons.R16));
assertNotNull(TangoIcons.devices_computer(TangoIcons.R22));
assertNotNull(TangoIcons.devices_computer(TangoIcons.R32));
assertNotNull(TangoIcons.devices_drive_harddisk(TangoIcons.R16));
assertNotNull(TangoIcons.devices_drive_harddisk(TangoIcons.R22));
assertNotNull(TangoIcons.devices_drive_harddisk(TangoIcons.R32));
assertNotNull(TangoIcons.devices_drive_optical(TangoIcons.R16));
assertNotNull(TangoIcons.devices_drive_optical(TangoIcons.R22));
assertNotNull(TangoIcons.devices_drive_optical(TangoIcons.R32));
assertNotNull(TangoIcons.devices_drive_removable_media(TangoIcons.R16));
assertNotNull(TangoIcons.devices_drive_removable_media(TangoIcons.R22));
assertNotNull(TangoIcons.devices_drive_removable_media(TangoIcons.R32));
assertNotNull(TangoIcons.devices_input_gaming(TangoIcons.R16));
assertNotNull(TangoIcons.devices_input_gaming(TangoIcons.R22));
assertNotNull(TangoIcons.devices_input_gaming(TangoIcons.R32));
assertNotNull(TangoIcons.devices_input_keyboard(TangoIcons.R16));
assertNotNull(TangoIcons.devices_input_keyboard(TangoIcons.R22));
assertNotNull(TangoIcons.devices_input_keyboard(TangoIcons.R32));
assertNotNull(TangoIcons.devices_input_mouse(TangoIcons.R16));
assertNotNull(TangoIcons.devices_input_mouse(TangoIcons.R22));
assertNotNull(TangoIcons.devices_input_mouse(TangoIcons.R32));
assertNotNull(TangoIcons.devices_media_flash(TangoIcons.R16));
assertNotNull(TangoIcons.devices_media_flash(TangoIcons.R22));
assertNotNull(TangoIcons.devices_media_flash(TangoIcons.R32));
assertNotNull(TangoIcons.devices_media_floppy(TangoIcons.R16));
assertNotNull(TangoIcons.devices_media_floppy(TangoIcons.R22));
assertNotNull(TangoIcons.devices_media_floppy(TangoIcons.R32));
assertNotNull(TangoIcons.devices_media_optical(TangoIcons.R16));
assertNotNull(TangoIcons.devices_media_optical(TangoIcons.R22));
assertNotNull(TangoIcons.devices_media_optical(TangoIcons.R32));
assertNotNull(TangoIcons.devices_multimedia_player(TangoIcons.R16));
assertNotNull(TangoIcons.devices_multimedia_player(TangoIcons.R22));
assertNotNull(TangoIcons.devices_multimedia_player(TangoIcons.R32));
assertNotNull(TangoIcons.devices_network_wired(TangoIcons.R16));
assertNotNull(TangoIcons.devices_network_wired(TangoIcons.R22));
assertNotNull(TangoIcons.devices_network_wired(TangoIcons.R32));
assertNotNull(TangoIcons.devices_network_wireless(TangoIcons.R16));
assertNotNull(TangoIcons.devices_network_wireless(TangoIcons.R22));
assertNotNull(TangoIcons.devices_network_wireless(TangoIcons.R32));
assertNotNull(TangoIcons.devices_printer(TangoIcons.R16));
assertNotNull(TangoIcons.devices_printer(TangoIcons.R22));
assertNotNull(TangoIcons.devices_printer(TangoIcons.R32));
assertNotNull(TangoIcons.devices_video_display(TangoIcons.R16));
assertNotNull(TangoIcons.devices_video_display(TangoIcons.R22));
assertNotNull(TangoIcons.devices_video_display(TangoIcons.R32));
assertNotNull(TangoIcons.emblems_emblem_favorite(TangoIcons.R16));
assertNotNull(TangoIcons.emblems_emblem_favorite(TangoIcons.R22));
assertNotNull(TangoIcons.emblems_emblem_favorite(TangoIcons.R32));
assertNotNull(TangoIcons.emblems_emblem_important(TangoIcons.R16));
assertNotNull(TangoIcons.emblems_emblem_important(TangoIcons.R22));
assertNotNull(TangoIcons.emblems_emblem_important(TangoIcons.R32));
assertNotNull(TangoIcons.emblems_emblem_photos(TangoIcons.R16));
assertNotNull(TangoIcons.emblems_emblem_photos(TangoIcons.R22));
assertNotNull(TangoIcons.emblems_emblem_photos(TangoIcons.R32));
assertNotNull(TangoIcons.emblems_emblem_readonly(TangoIcons.R16));
assertNotNull(TangoIcons.emblems_emblem_readonly(TangoIcons.R22));
assertNotNull(TangoIcons.emblems_emblem_readonly(TangoIcons.R32));
assertNotNull(TangoIcons.emblems_emblem_symbolic_link(TangoIcons.R16));
assertNotNull(TangoIcons.emblems_emblem_symbolic_link(TangoIcons.R22));
assertNotNull(TangoIcons.emblems_emblem_symbolic_link(TangoIcons.R32));
assertNotNull(TangoIcons.emblems_emblem_system(TangoIcons.R16));
assertNotNull(TangoIcons.emblems_emblem_system(TangoIcons.R22));
assertNotNull(TangoIcons.emblems_emblem_system(TangoIcons.R32));
assertNotNull(TangoIcons.emblems_emblem_unreadable(TangoIcons.R16));
assertNotNull(TangoIcons.emblems_emblem_unreadable(TangoIcons.R22));
assertNotNull(TangoIcons.emblems_emblem_unreadable(TangoIcons.R32));
assertNotNull(TangoIcons.emotes_face_angel(TangoIcons.R16));
assertNotNull(TangoIcons.emotes_face_angel(TangoIcons.R22));
assertNotNull(TangoIcons.emotes_face_angel(TangoIcons.R32));
assertNotNull(TangoIcons.emotes_face_crying(TangoIcons.R16));
assertNotNull(TangoIcons.emotes_face_crying(TangoIcons.R22));
assertNotNull(TangoIcons.emotes_face_crying(TangoIcons.R32));
assertNotNull(TangoIcons.emotes_face_devilish(TangoIcons.R16));
assertNotNull(TangoIcons.emotes_face_devilish(TangoIcons.R22));
assertNotNull(TangoIcons.emotes_face_devilish(TangoIcons.R32));
assertNotNull(TangoIcons.emotes_face_glasses(TangoIcons.R16));
assertNotNull(TangoIcons.emotes_face_glasses(TangoIcons.R22));
assertNotNull(TangoIcons.emotes_face_glasses(TangoIcons.R32));
assertNotNull(TangoIcons.emotes_face_grin(TangoIcons.R16));
assertNotNull(TangoIcons.emotes_face_grin(TangoIcons.R22));
assertNotNull(TangoIcons.emotes_face_grin(TangoIcons.R32));
assertNotNull(TangoIcons.emotes_face_kiss(TangoIcons.R16));
assertNotNull(TangoIcons.emotes_face_kiss(TangoIcons.R22));
assertNotNull(TangoIcons.emotes_face_kiss(TangoIcons.R32));
assertNotNull(TangoIcons.emotes_face_monkey(TangoIcons.R16));
assertNotNull(TangoIcons.emotes_face_monkey(TangoIcons.R22));
assertNotNull(TangoIcons.emotes_face_monkey(TangoIcons.R32));
assertNotNull(TangoIcons.emotes_face_plain(TangoIcons.R16));
assertNotNull(TangoIcons.emotes_face_plain(TangoIcons.R22));
assertNotNull(TangoIcons.emotes_face_plain(TangoIcons.R32));
assertNotNull(TangoIcons.emotes_face_sad(TangoIcons.R16));
assertNotNull(TangoIcons.emotes_face_sad(TangoIcons.R22));
assertNotNull(TangoIcons.emotes_face_sad(TangoIcons.R32));
assertNotNull(TangoIcons.emotes_face_smile_big(TangoIcons.R16));
assertNotNull(TangoIcons.emotes_face_smile_big(TangoIcons.R22));
assertNotNull(TangoIcons.emotes_face_smile_big(TangoIcons.R32));
assertNotNull(TangoIcons.emotes_face_smile(TangoIcons.R16));
assertNotNull(TangoIcons.emotes_face_smile(TangoIcons.R22));
assertNotNull(TangoIcons.emotes_face_smile(TangoIcons.R32));
assertNotNull(TangoIcons.emotes_face_surprise(TangoIcons.R16));
assertNotNull(TangoIcons.emotes_face_surprise(TangoIcons.R22));
assertNotNull(TangoIcons.emotes_face_surprise(TangoIcons.R32));
assertNotNull(TangoIcons.emotes_face_wink(TangoIcons.R16));
assertNotNull(TangoIcons.emotes_face_wink(TangoIcons.R22));
assertNotNull(TangoIcons.emotes_face_wink(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_application_certificate(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_application_certificate(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_application_certificate(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_application_x_executable(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_application_x_executable(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_application_x_executable(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_audio_x_generic(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_audio_x_generic(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_audio_x_generic(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_font_x_generic(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_font_x_generic(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_font_x_generic(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_image_x_generic(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_image_x_generic(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_image_x_generic(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_package_x_generic(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_package_x_generic(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_package_x_generic(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_text_html(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_text_html(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_text_html(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_text_x_generic_template(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_text_x_generic_template(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_text_x_generic_template(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_text_x_generic(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_text_x_generic(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_text_x_generic(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_text_x_script(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_text_x_script(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_text_x_script(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_video_x_generic(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_video_x_generic(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_video_x_generic(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_x_office_address_book(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_x_office_address_book(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_x_office_address_book(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_x_office_calendar(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_x_office_calendar(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_x_office_calendar(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_x_office_document_template(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_x_office_document_template(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_x_office_document_template(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_x_office_document(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_x_office_document(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_x_office_document(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_x_office_drawing_template(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_x_office_drawing_template(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_x_office_drawing_template(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_x_office_drawing(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_x_office_drawing(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_x_office_drawing(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_x_office_presentation_template(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_x_office_presentation_template(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_x_office_presentation_template(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_x_office_presentation(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_x_office_presentation(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_x_office_presentation(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_x_office_spreadsheet_template(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_x_office_spreadsheet_template(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_x_office_spreadsheet_template(TangoIcons.R32));
assertNotNull(TangoIcons.mimetypes_x_office_spreadsheet(TangoIcons.R16));
assertNotNull(TangoIcons.mimetypes_x_office_spreadsheet(TangoIcons.R22));
assertNotNull(TangoIcons.mimetypes_x_office_spreadsheet(TangoIcons.R32));
assertNotNull(TangoIcons.places_folder_remote(TangoIcons.R16));
assertNotNull(TangoIcons.places_folder_remote(TangoIcons.R22));
assertNotNull(TangoIcons.places_folder_remote(TangoIcons.R32));
assertNotNull(TangoIcons.places_folder_saved_search(TangoIcons.R16));
assertNotNull(TangoIcons.places_folder_saved_search(TangoIcons.R22));
assertNotNull(TangoIcons.places_folder_saved_search(TangoIcons.R32));
assertNotNull(TangoIcons.places_folder(TangoIcons.R16));
assertNotNull(TangoIcons.places_folder(TangoIcons.R22));
assertNotNull(TangoIcons.places_folder(TangoIcons.R32));
assertNotNull(TangoIcons.places_network_server(TangoIcons.R16));
assertNotNull(TangoIcons.places_network_server(TangoIcons.R22));
assertNotNull(TangoIcons.places_network_server(TangoIcons.R32));
assertNotNull(TangoIcons.places_network_workgroup(TangoIcons.R16));
assertNotNull(TangoIcons.places_network_workgroup(TangoIcons.R22));
assertNotNull(TangoIcons.places_network_workgroup(TangoIcons.R32));
assertNotNull(TangoIcons.places_start_here(TangoIcons.R16));
assertNotNull(TangoIcons.places_start_here(TangoIcons.R22));
assertNotNull(TangoIcons.places_start_here(TangoIcons.R32));
assertNotNull(TangoIcons.places_user_desktop(TangoIcons.R16));
assertNotNull(TangoIcons.places_user_desktop(TangoIcons.R22));
assertNotNull(TangoIcons.places_user_desktop(TangoIcons.R32));
assertNotNull(TangoIcons.places_user_home(TangoIcons.R16));
assertNotNull(TangoIcons.places_user_home(TangoIcons.R22));
assertNotNull(TangoIcons.places_user_home(TangoIcons.R32));
assertNotNull(TangoIcons.places_user_trash(TangoIcons.R16));
assertNotNull(TangoIcons.places_user_trash(TangoIcons.R22));
assertNotNull(TangoIcons.places_user_trash(TangoIcons.R32));
assertNotNull(TangoIcons.status_audio_volume_high(TangoIcons.R16));
assertNotNull(TangoIcons.status_audio_volume_high(TangoIcons.R22));
assertNotNull(TangoIcons.status_audio_volume_high(TangoIcons.R32));
assertNotNull(TangoIcons.status_audio_volume_low(TangoIcons.R16));
assertNotNull(TangoIcons.status_audio_volume_low(TangoIcons.R22));
assertNotNull(TangoIcons.status_audio_volume_low(TangoIcons.R32));
assertNotNull(TangoIcons.status_audio_volume_medium(TangoIcons.R16));
assertNotNull(TangoIcons.status_audio_volume_medium(TangoIcons.R22));
assertNotNull(TangoIcons.status_audio_volume_medium(TangoIcons.R32));
assertNotNull(TangoIcons.status_audio_volume_muted(TangoIcons.R16));
assertNotNull(TangoIcons.status_audio_volume_muted(TangoIcons.R22));
assertNotNull(TangoIcons.status_audio_volume_muted(TangoIcons.R32));
assertNotNull(TangoIcons.status_battery_caution(TangoIcons.R16));
assertNotNull(TangoIcons.status_battery_caution(TangoIcons.R22));
assertNotNull(TangoIcons.status_battery_caution(TangoIcons.R32));
assertNotNull(TangoIcons.status_dialog_error(TangoIcons.R16));
assertNotNull(TangoIcons.status_dialog_error(TangoIcons.R22));
assertNotNull(TangoIcons.status_dialog_error(TangoIcons.R32));
assertNotNull(TangoIcons.status_dialog_information(TangoIcons.R16));
assertNotNull(TangoIcons.status_dialog_information(TangoIcons.R22));
assertNotNull(TangoIcons.status_dialog_information(TangoIcons.R32));
assertNotNull(TangoIcons.status_dialog_warning(TangoIcons.R16));
assertNotNull(TangoIcons.status_dialog_warning(TangoIcons.R22));
assertNotNull(TangoIcons.status_dialog_warning(TangoIcons.R32));
assertNotNull(TangoIcons.status_folder_drag_accept(TangoIcons.R16));
assertNotNull(TangoIcons.status_folder_drag_accept(TangoIcons.R22));
assertNotNull(TangoIcons.status_folder_drag_accept(TangoIcons.R32));
assertNotNull(TangoIcons.status_folder_open(TangoIcons.R16));
assertNotNull(TangoIcons.status_folder_open(TangoIcons.R22));
assertNotNull(TangoIcons.status_folder_open(TangoIcons.R32));
assertNotNull(TangoIcons.status_folder_visiting(TangoIcons.R16));
assertNotNull(TangoIcons.status_folder_visiting(TangoIcons.R22));
assertNotNull(TangoIcons.status_folder_visiting(TangoIcons.R32));
assertNotNull(TangoIcons.status_image_loading(TangoIcons.R16));
assertNotNull(TangoIcons.status_image_loading(TangoIcons.R22));
assertNotNull(TangoIcons.status_image_loading(TangoIcons.R32));
assertNotNull(TangoIcons.status_image_missing(TangoIcons.R16));
assertNotNull(TangoIcons.status_image_missing(TangoIcons.R22));
assertNotNull(TangoIcons.status_image_missing(TangoIcons.R32));
assertNotNull(TangoIcons.status_mail_attachment(TangoIcons.R16));
assertNotNull(TangoIcons.status_mail_attachment(TangoIcons.R22));
assertNotNull(TangoIcons.status_mail_attachment(TangoIcons.R32));
assertNotNull(TangoIcons.status_network_error(TangoIcons.R16));
assertNotNull(TangoIcons.status_network_error(TangoIcons.R22));
assertNotNull(TangoIcons.status_network_error(TangoIcons.R32));
assertNotNull(TangoIcons.status_network_idle(TangoIcons.R16));
assertNotNull(TangoIcons.status_network_idle(TangoIcons.R22));
assertNotNull(TangoIcons.status_network_idle(TangoIcons.R32));
assertNotNull(TangoIcons.status_network_offline(TangoIcons.R16));
assertNotNull(TangoIcons.status_network_offline(TangoIcons.R22));
assertNotNull(TangoIcons.status_network_offline(TangoIcons.R32));
assertNotNull(TangoIcons.status_network_receive(TangoIcons.R16));
assertNotNull(TangoIcons.status_network_receive(TangoIcons.R22));
assertNotNull(TangoIcons.status_network_receive(TangoIcons.R32));
assertNotNull(TangoIcons.status_network_transmit_receive(TangoIcons.R16));
assertNotNull(TangoIcons.status_network_transmit_receive(TangoIcons.R22));
assertNotNull(TangoIcons.status_network_transmit_receive(TangoIcons.R32));
assertNotNull(TangoIcons.status_network_transmit(TangoIcons.R16));
assertNotNull(TangoIcons.status_network_transmit(TangoIcons.R22));
assertNotNull(TangoIcons.status_network_transmit(TangoIcons.R32));
assertNotNull(TangoIcons.status_network_wireless_encrypted(TangoIcons.R16));
assertNotNull(TangoIcons.status_network_wireless_encrypted(TangoIcons.R22));
assertNotNull(TangoIcons.status_network_wireless_encrypted(TangoIcons.R32));
assertNotNull(TangoIcons.status_printer_error(TangoIcons.R16));
assertNotNull(TangoIcons.status_printer_error(TangoIcons.R22));
assertNotNull(TangoIcons.status_printer_error(TangoIcons.R32));
assertNotNull(TangoIcons.status_software_update_available(TangoIcons.R16));
assertNotNull(TangoIcons.status_software_update_available(TangoIcons.R22));
assertNotNull(TangoIcons.status_software_update_available(TangoIcons.R32));
assertNotNull(TangoIcons.status_software_update_urgent(TangoIcons.R16));
assertNotNull(TangoIcons.status_software_update_urgent(TangoIcons.R22));
assertNotNull(TangoIcons.status_software_update_urgent(TangoIcons.R32));
assertNotNull(TangoIcons.status_user_trash_full(TangoIcons.R16));
assertNotNull(TangoIcons.status_user_trash_full(TangoIcons.R22));
assertNotNull(TangoIcons.status_user_trash_full(TangoIcons.R32));
assertNotNull(TangoIcons.status_weather_clear_night(TangoIcons.R16));
assertNotNull(TangoIcons.status_weather_clear_night(TangoIcons.R22));
assertNotNull(TangoIcons.status_weather_clear_night(TangoIcons.R32));
assertNotNull(TangoIcons.status_weather_clear(TangoIcons.R16));
assertNotNull(TangoIcons.status_weather_clear(TangoIcons.R22));
assertNotNull(TangoIcons.status_weather_clear(TangoIcons.R32));
assertNotNull(TangoIcons.status_weather_few_clouds_night(TangoIcons.R16));
assertNotNull(TangoIcons.status_weather_few_clouds_night(TangoIcons.R22));
assertNotNull(TangoIcons.status_weather_few_clouds_night(TangoIcons.R32));
assertNotNull(TangoIcons.status_weather_few_clouds(TangoIcons.R16));
assertNotNull(TangoIcons.status_weather_few_clouds(TangoIcons.R22));
assertNotNull(TangoIcons.status_weather_few_clouds(TangoIcons.R32));
assertNotNull(TangoIcons.status_weather_overcast(TangoIcons.R16));
assertNotNull(TangoIcons.status_weather_overcast(TangoIcons.R22));
assertNotNull(TangoIcons.status_weather_overcast(TangoIcons.R32));
assertNotNull(TangoIcons.status_weather_severe_alert(TangoIcons.R16));
assertNotNull(TangoIcons.status_weather_severe_alert(TangoIcons.R22));
assertNotNull(TangoIcons.status_weather_severe_alert(TangoIcons.R32));
assertNotNull(TangoIcons.status_weather_showers_scattered(TangoIcons.R16));
assertNotNull(TangoIcons.status_weather_showers_scattered(TangoIcons.R22));
assertNotNull(TangoIcons.status_weather_showers_scattered(TangoIcons.R32));
assertNotNull(TangoIcons.status_weather_showers(TangoIcons.R16));
assertNotNull(TangoIcons.status_weather_showers(TangoIcons.R22));
assertNotNull(TangoIcons.status_weather_showers(TangoIcons.R32));
assertNotNull(TangoIcons.status_weather_snow(TangoIcons.R16));
assertNotNull(TangoIcons.status_weather_snow(TangoIcons.R22));
assertNotNull(TangoIcons.status_weather_snow(TangoIcons.R32));
assertNotNull(TangoIcons.status_weather_storm(TangoIcons.R16));
assertNotNull(TangoIcons.status_weather_storm(TangoIcons.R22));
assertNotNull(TangoIcons.status_weather_storm(TangoIcons.R32));
}
} | 49,439 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TangoIcons.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-tango/src/main/java/org/esa/snap/tango/TangoIcons.java | package org.esa.snap.tango;
import org.openide.util.ImageUtilities;
import javax.swing.ImageIcon;
/**
* This class has been automatically generated.
*
* @author Norman Fomferra
*/
@SuppressWarnings("UnusedDeclaration")
public final class TangoIcons {
public enum Res {
R16("16x16"),
R22("22x22"),
R32("32x32");
private final String name;
Res(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public final static Res R16 = Res.R16;
public final static Res R22 = Res.R22;
public final static Res R32 = Res.R32;
public static ImageIcon actions_address_book_new(Res res) { return getIcon("actions/address-book-new.png", res); }
public static ImageIcon actions_appointment_new(Res res) { return getIcon("actions/appointment-new.png", res); }
public static ImageIcon actions_bookmark_new(Res res) { return getIcon("actions/bookmark-new.png", res); }
public static ImageIcon actions_contact_new(Res res) { return getIcon("actions/contact-new.png", res); }
public static ImageIcon actions_document_new(Res res) { return getIcon("actions/document-new.png", res); }
public static ImageIcon actions_document_open(Res res) { return getIcon("actions/document-open.png", res); }
public static ImageIcon actions_document_print_preview(Res res) { return getIcon("actions/document-print-preview.png", res); }
public static ImageIcon actions_document_print(Res res) { return getIcon("actions/document-print.png", res); }
public static ImageIcon actions_document_properties(Res res) { return getIcon("actions/document-properties.png", res); }
public static ImageIcon actions_document_save_as(Res res) { return getIcon("actions/document-save-as.png", res); }
public static ImageIcon actions_document_save(Res res) { return getIcon("actions/document-save.png", res); }
public static ImageIcon actions_edit_clear(Res res) { return getIcon("actions/edit-clear.png", res); }
public static ImageIcon actions_edit_copy(Res res) { return getIcon("actions/edit-copy.png", res); }
public static ImageIcon actions_edit_cut(Res res) { return getIcon("actions/edit-cut.png", res); }
public static ImageIcon actions_edit_delete(Res res) { return getIcon("actions/edit-delete.png", res); }
public static ImageIcon actions_edit_find_replace(Res res) { return getIcon("actions/edit-find-replace.png", res); }
public static ImageIcon actions_edit_find(Res res) { return getIcon("actions/edit-find.png", res); }
public static ImageIcon actions_edit_paste(Res res) { return getIcon("actions/edit-paste.png", res); }
public static ImageIcon actions_edit_redo(Res res) { return getIcon("actions/edit-redo.png", res); }
public static ImageIcon actions_edit_select_all(Res res) { return getIcon("actions/edit-select-all.png", res); }
public static ImageIcon actions_edit_undo(Res res) { return getIcon("actions/edit-undo.png", res); }
public static ImageIcon actions_folder_new(Res res) { return getIcon("actions/folder-new.png", res); }
public static ImageIcon actions_format_indent_less(Res res) { return getIcon("actions/format-indent-less.png", res); }
public static ImageIcon actions_format_indent_more(Res res) { return getIcon("actions/format-indent-more.png", res); }
public static ImageIcon actions_format_justify_center(Res res) { return getIcon("actions/format-justify-center.png", res); }
public static ImageIcon actions_format_justify_fill(Res res) { return getIcon("actions/format-justify-fill.png", res); }
public static ImageIcon actions_format_justify_left(Res res) { return getIcon("actions/format-justify-left.png", res); }
public static ImageIcon actions_format_justify_right(Res res) { return getIcon("actions/format-justify-right.png", res); }
public static ImageIcon actions_format_text_bold(Res res) { return getIcon("actions/format-text-bold.png", res); }
public static ImageIcon actions_format_text_italic(Res res) { return getIcon("actions/format-text-italic.png", res); }
public static ImageIcon actions_format_text_strikethrough(Res res) { return getIcon("actions/format-text-strikethrough.png", res); }
public static ImageIcon actions_format_text_underline(Res res) { return getIcon("actions/format-text-underline.png", res); }
public static ImageIcon actions_go_bottom(Res res) { return getIcon("actions/go-bottom.png", res); }
public static ImageIcon actions_go_down(Res res) { return getIcon("actions/go-down.png", res); }
public static ImageIcon actions_go_first(Res res) { return getIcon("actions/go-first.png", res); }
public static ImageIcon actions_go_home(Res res) { return getIcon("actions/go-home.png", res); }
public static ImageIcon actions_go_jump(Res res) { return getIcon("actions/go-jump.png", res); }
public static ImageIcon actions_go_last(Res res) { return getIcon("actions/go-last.png", res); }
public static ImageIcon actions_go_next(Res res) { return getIcon("actions/go-next.png", res); }
public static ImageIcon actions_go_previous(Res res) { return getIcon("actions/go-previous.png", res); }
public static ImageIcon actions_go_top(Res res) { return getIcon("actions/go-top.png", res); }
public static ImageIcon actions_go_up(Res res) { return getIcon("actions/go-up.png", res); }
public static ImageIcon actions_list_add(Res res) { return getIcon("actions/list-add.png", res); }
public static ImageIcon actions_list_remove(Res res) { return getIcon("actions/list-remove.png", res); }
public static ImageIcon actions_mail_forward(Res res) { return getIcon("actions/mail-forward.png", res); }
public static ImageIcon actions_mail_mark_junk(Res res) { return getIcon("actions/mail-mark-junk.png", res); }
public static ImageIcon actions_mail_mark_not_junk(Res res) { return getIcon("actions/mail-mark-not-junk.png", res); }
public static ImageIcon actions_mail_message_new(Res res) { return getIcon("actions/mail-message-new.png", res); }
public static ImageIcon actions_mail_reply_all(Res res) { return getIcon("actions/mail-reply-all.png", res); }
public static ImageIcon actions_mail_reply_sender(Res res) { return getIcon("actions/mail-reply-sender.png", res); }
public static ImageIcon actions_mail_send_receive(Res res) { return getIcon("actions/mail-send-receive.png", res); }
public static ImageIcon actions_media_eject(Res res) { return getIcon("actions/media-eject.png", res); }
public static ImageIcon actions_media_playback_pause(Res res) { return getIcon("actions/media-playback-pause.png", res); }
public static ImageIcon actions_media_playback_start(Res res) { return getIcon("actions/media-playback-start.png", res); }
public static ImageIcon actions_media_playback_stop(Res res) { return getIcon("actions/media-playback-stop.png", res); }
public static ImageIcon actions_media_record(Res res) { return getIcon("actions/media-record.png", res); }
public static ImageIcon actions_media_seek_backward(Res res) { return getIcon("actions/media-seek-backward.png", res); }
public static ImageIcon actions_media_seek_forward(Res res) { return getIcon("actions/media-seek-forward.png", res); }
public static ImageIcon actions_media_skip_backward(Res res) { return getIcon("actions/media-skip-backward.png", res); }
public static ImageIcon actions_media_skip_forward(Res res) { return getIcon("actions/media-skip-forward.png", res); }
public static ImageIcon actions_process_stop(Res res) { return getIcon("actions/process-stop.png", res); }
public static ImageIcon actions_system_lock_screen(Res res) { return getIcon("actions/system-lock-screen.png", res); }
public static ImageIcon actions_system_log_out(Res res) { return getIcon("actions/system-log-out.png", res); }
public static ImageIcon actions_system_search(Res res) { return getIcon("actions/system-search.png", res); }
public static ImageIcon actions_system_shutdown(Res res) { return getIcon("actions/system-shutdown.png", res); }
public static ImageIcon actions_tab_new(Res res) { return getIcon("actions/tab-new.png", res); }
public static ImageIcon actions_view_fullscreen(Res res) { return getIcon("actions/view-fullscreen.png", res); }
public static ImageIcon actions_view_refresh(Res res) { return getIcon("actions/view-refresh.png", res); }
public static ImageIcon actions_window_new(Res res) { return getIcon("actions/window-new.png", res); }
public static ImageIcon animations_process_working(Res res) { return getIcon("animations/process-working.png", res); }
public static ImageIcon apps_accessories_calculator(Res res) { return getIcon("apps/accessories-calculator.png", res); }
public static ImageIcon apps_accessories_character_map(Res res) { return getIcon("apps/accessories-character-map.png", res); }
public static ImageIcon apps_accessories_text_editor(Res res) { return getIcon("apps/accessories-text-editor.png", res); }
public static ImageIcon apps_help_browser(Res res) { return getIcon("apps/help-browser.png", res); }
public static ImageIcon apps_internet_group_chat(Res res) { return getIcon("apps/internet-group-chat.png", res); }
public static ImageIcon apps_internet_mail(Res res) { return getIcon("apps/internet-mail.png", res); }
public static ImageIcon apps_internet_news_reader(Res res) { return getIcon("apps/internet-news-reader.png", res); }
public static ImageIcon apps_internet_web_browser(Res res) { return getIcon("apps/internet-web-browser.png", res); }
public static ImageIcon apps_office_calendar(Res res) { return getIcon("apps/office-calendar.png", res); }
public static ImageIcon apps_preferences_desktop_accessibility(Res res) { return getIcon("apps/preferences-desktop-accessibility.png", res); }
public static ImageIcon apps_preferences_desktop_assistive_technology(Res res) { return getIcon("apps/preferences-desktop-assistive-technology.png", res); }
public static ImageIcon apps_preferences_desktop_font(Res res) { return getIcon("apps/preferences-desktop-font.png", res); }
public static ImageIcon apps_preferences_desktop_keyboard_shortcuts(Res res) { return getIcon("apps/preferences-desktop-keyboard-shortcuts.png", res); }
public static ImageIcon apps_preferences_desktop_locale(Res res) { return getIcon("apps/preferences-desktop-locale.png", res); }
public static ImageIcon apps_preferences_desktop_multimedia(Res res) { return getIcon("apps/preferences-desktop-multimedia.png", res); }
public static ImageIcon apps_preferences_desktop_remote_desktop(Res res) { return getIcon("apps/preferences-desktop-remote-desktop.png", res); }
public static ImageIcon apps_preferences_desktop_screensaver(Res res) { return getIcon("apps/preferences-desktop-screensaver.png", res); }
public static ImageIcon apps_preferences_desktop_theme(Res res) { return getIcon("apps/preferences-desktop-theme.png", res); }
public static ImageIcon apps_preferences_desktop_wallpaper(Res res) { return getIcon("apps/preferences-desktop-wallpaper.png", res); }
public static ImageIcon apps_preferences_system_network_proxy(Res res) { return getIcon("apps/preferences-system-network-proxy.png", res); }
public static ImageIcon apps_preferences_system_session(Res res) { return getIcon("apps/preferences-system-session.png", res); }
public static ImageIcon apps_preferences_system_windows(Res res) { return getIcon("apps/preferences-system-windows.png", res); }
public static ImageIcon apps_system_file_manager(Res res) { return getIcon("apps/system-file-manager.png", res); }
public static ImageIcon apps_system_installer(Res res) { return getIcon("apps/system-installer.png", res); }
public static ImageIcon apps_system_software_update(Res res) { return getIcon("apps/system-software-update.png", res); }
public static ImageIcon apps_system_users(Res res) { return getIcon("apps/system-users.png", res); }
public static ImageIcon apps_utilities_system_monitor(Res res) { return getIcon("apps/utilities-system-monitor.png", res); }
public static ImageIcon apps_utilities_terminal(Res res) { return getIcon("apps/utilities-terminal.png", res); }
public static ImageIcon categories_applications_accessories(Res res) { return getIcon("categories/applications-accessories.png", res); }
public static ImageIcon categories_applications_development(Res res) { return getIcon("categories/applications-development.png", res); }
public static ImageIcon categories_applications_games(Res res) { return getIcon("categories/applications-games.png", res); }
public static ImageIcon categories_applications_graphics(Res res) { return getIcon("categories/applications-graphics.png", res); }
public static ImageIcon categories_applications_internet(Res res) { return getIcon("categories/applications-internet.png", res); }
public static ImageIcon categories_applications_multimedia(Res res) { return getIcon("categories/applications-multimedia.png", res); }
public static ImageIcon categories_applications_office(Res res) { return getIcon("categories/applications-office.png", res); }
public static ImageIcon categories_applications_other(Res res) { return getIcon("categories/applications-other.png", res); }
public static ImageIcon categories_applications_system(Res res) { return getIcon("categories/applications-system.png", res); }
public static ImageIcon categories_preferences_desktop_peripherals(Res res) { return getIcon("categories/preferences-desktop-peripherals.png", res); }
public static ImageIcon categories_preferences_desktop(Res res) { return getIcon("categories/preferences-desktop.png", res); }
public static ImageIcon categories_preferences_system(Res res) { return getIcon("categories/preferences-system.png", res); }
public static ImageIcon devices_audio_card(Res res) { return getIcon("devices/audio-card.png", res); }
public static ImageIcon devices_audio_input_microphone(Res res) { return getIcon("devices/audio-input-microphone.png", res); }
public static ImageIcon devices_battery(Res res) { return getIcon("devices/battery.png", res); }
public static ImageIcon devices_camera_photo(Res res) { return getIcon("devices/camera-photo.png", res); }
public static ImageIcon devices_camera_video(Res res) { return getIcon("devices/camera-video.png", res); }
public static ImageIcon devices_computer(Res res) { return getIcon("devices/computer.png", res); }
public static ImageIcon devices_drive_harddisk(Res res) { return getIcon("devices/drive-harddisk.png", res); }
public static ImageIcon devices_drive_optical(Res res) { return getIcon("devices/drive-optical.png", res); }
public static ImageIcon devices_drive_removable_media(Res res) { return getIcon("devices/drive-removable-media.png", res); }
public static ImageIcon devices_input_gaming(Res res) { return getIcon("devices/input-gaming.png", res); }
public static ImageIcon devices_input_keyboard(Res res) { return getIcon("devices/input-keyboard.png", res); }
public static ImageIcon devices_input_mouse(Res res) { return getIcon("devices/input-mouse.png", res); }
public static ImageIcon devices_media_flash(Res res) { return getIcon("devices/media-flash.png", res); }
public static ImageIcon devices_media_floppy(Res res) { return getIcon("devices/media-floppy.png", res); }
public static ImageIcon devices_media_optical(Res res) { return getIcon("devices/media-optical.png", res); }
public static ImageIcon devices_multimedia_player(Res res) { return getIcon("devices/multimedia-player.png", res); }
public static ImageIcon devices_network_wired(Res res) { return getIcon("devices/network-wired.png", res); }
public static ImageIcon devices_network_wireless(Res res) { return getIcon("devices/network-wireless.png", res); }
public static ImageIcon devices_printer(Res res) { return getIcon("devices/printer.png", res); }
public static ImageIcon devices_video_display(Res res) { return getIcon("devices/video-display.png", res); }
public static ImageIcon emblems_emblem_favorite(Res res) { return getIcon("emblems/emblem-favorite.png", res); }
public static ImageIcon emblems_emblem_important(Res res) { return getIcon("emblems/emblem-important.png", res); }
public static ImageIcon emblems_emblem_photos(Res res) { return getIcon("emblems/emblem-photos.png", res); }
public static ImageIcon emblems_emblem_readonly(Res res) { return getIcon("emblems/emblem-readonly.png", res); }
public static ImageIcon emblems_emblem_symbolic_link(Res res) { return getIcon("emblems/emblem-symbolic-link.png", res); }
public static ImageIcon emblems_emblem_system(Res res) { return getIcon("emblems/emblem-system.png", res); }
public static ImageIcon emblems_emblem_unreadable(Res res) { return getIcon("emblems/emblem-unreadable.png", res); }
public static ImageIcon emotes_face_angel(Res res) { return getIcon("emotes/face-angel.png", res); }
public static ImageIcon emotes_face_crying(Res res) { return getIcon("emotes/face-crying.png", res); }
public static ImageIcon emotes_face_devilish(Res res) { return getIcon("emotes/face-devilish.png", res); }
public static ImageIcon emotes_face_glasses(Res res) { return getIcon("emotes/face-glasses.png", res); }
public static ImageIcon emotes_face_grin(Res res) { return getIcon("emotes/face-grin.png", res); }
public static ImageIcon emotes_face_kiss(Res res) { return getIcon("emotes/face-kiss.png", res); }
public static ImageIcon emotes_face_monkey(Res res) { return getIcon("emotes/face-monkey.png", res); }
public static ImageIcon emotes_face_plain(Res res) { return getIcon("emotes/face-plain.png", res); }
public static ImageIcon emotes_face_sad(Res res) { return getIcon("emotes/face-sad.png", res); }
public static ImageIcon emotes_face_smile_big(Res res) { return getIcon("emotes/face-smile-big.png", res); }
public static ImageIcon emotes_face_smile(Res res) { return getIcon("emotes/face-smile.png", res); }
public static ImageIcon emotes_face_surprise(Res res) { return getIcon("emotes/face-surprise.png", res); }
public static ImageIcon emotes_face_wink(Res res) { return getIcon("emotes/face-wink.png", res); }
public static ImageIcon mimetypes_application_certificate(Res res) { return getIcon("mimetypes/application-certificate.png", res); }
public static ImageIcon mimetypes_application_x_executable(Res res) { return getIcon("mimetypes/application-x-executable.png", res); }
public static ImageIcon mimetypes_audio_x_generic(Res res) { return getIcon("mimetypes/audio-x-generic.png", res); }
public static ImageIcon mimetypes_font_x_generic(Res res) { return getIcon("mimetypes/font-x-generic.png", res); }
public static ImageIcon mimetypes_image_x_generic(Res res) { return getIcon("mimetypes/image-x-generic.png", res); }
public static ImageIcon mimetypes_package_x_generic(Res res) { return getIcon("mimetypes/package-x-generic.png", res); }
public static ImageIcon mimetypes_text_html(Res res) { return getIcon("mimetypes/text-html.png", res); }
public static ImageIcon mimetypes_text_x_generic_template(Res res) { return getIcon("mimetypes/text-x-generic-template.png", res); }
public static ImageIcon mimetypes_text_x_generic(Res res) { return getIcon("mimetypes/text-x-generic.png", res); }
public static ImageIcon mimetypes_text_x_script(Res res) { return getIcon("mimetypes/text-x-script.png", res); }
public static ImageIcon mimetypes_video_x_generic(Res res) { return getIcon("mimetypes/video-x-generic.png", res); }
public static ImageIcon mimetypes_x_office_address_book(Res res) { return getIcon("mimetypes/x-office-address-book.png", res); }
public static ImageIcon mimetypes_x_office_calendar(Res res) { return getIcon("mimetypes/x-office-calendar.png", res); }
public static ImageIcon mimetypes_x_office_document_template(Res res) { return getIcon("mimetypes/x-office-document-template.png", res); }
public static ImageIcon mimetypes_x_office_document(Res res) { return getIcon("mimetypes/x-office-document.png", res); }
public static ImageIcon mimetypes_x_office_drawing_template(Res res) { return getIcon("mimetypes/x-office-drawing-template.png", res); }
public static ImageIcon mimetypes_x_office_drawing(Res res) { return getIcon("mimetypes/x-office-drawing.png", res); }
public static ImageIcon mimetypes_x_office_presentation_template(Res res) { return getIcon("mimetypes/x-office-presentation-template.png", res); }
public static ImageIcon mimetypes_x_office_presentation(Res res) { return getIcon("mimetypes/x-office-presentation.png", res); }
public static ImageIcon mimetypes_x_office_spreadsheet_template(Res res) { return getIcon("mimetypes/x-office-spreadsheet-template.png", res); }
public static ImageIcon mimetypes_x_office_spreadsheet(Res res) { return getIcon("mimetypes/x-office-spreadsheet.png", res); }
public static ImageIcon places_folder_remote(Res res) { return getIcon("places/folder-remote.png", res); }
public static ImageIcon places_folder_saved_search(Res res) { return getIcon("places/folder-saved-search.png", res); }
public static ImageIcon places_folder(Res res) { return getIcon("places/folder.png", res); }
public static ImageIcon places_network_server(Res res) { return getIcon("places/network-server.png", res); }
public static ImageIcon places_network_workgroup(Res res) { return getIcon("places/network-workgroup.png", res); }
public static ImageIcon places_start_here(Res res) { return getIcon("places/start-here.png", res); }
public static ImageIcon places_user_desktop(Res res) { return getIcon("places/user-desktop.png", res); }
public static ImageIcon places_user_home(Res res) { return getIcon("places/user-home.png", res); }
public static ImageIcon places_user_trash(Res res) { return getIcon("places/user-trash.png", res); }
public static ImageIcon status_audio_volume_high(Res res) { return getIcon("status/audio-volume-high.png", res); }
public static ImageIcon status_audio_volume_low(Res res) { return getIcon("status/audio-volume-low.png", res); }
public static ImageIcon status_audio_volume_medium(Res res) { return getIcon("status/audio-volume-medium.png", res); }
public static ImageIcon status_audio_volume_muted(Res res) { return getIcon("status/audio-volume-muted.png", res); }
public static ImageIcon status_battery_caution(Res res) { return getIcon("status/battery-caution.png", res); }
public static ImageIcon status_dialog_error(Res res) { return getIcon("status/dialog-error.png", res); }
public static ImageIcon status_dialog_information(Res res) { return getIcon("status/dialog-information.png", res); }
public static ImageIcon status_dialog_warning(Res res) { return getIcon("status/dialog-warning.png", res); }
public static ImageIcon status_folder_drag_accept(Res res) { return getIcon("status/folder-drag-accept.png", res); }
public static ImageIcon status_folder_open(Res res) { return getIcon("status/folder-open.png", res); }
public static ImageIcon status_folder_visiting(Res res) { return getIcon("status/folder-visiting.png", res); }
public static ImageIcon status_image_loading(Res res) { return getIcon("status/image-loading.png", res); }
public static ImageIcon status_image_missing(Res res) { return getIcon("status/image-missing.png", res); }
public static ImageIcon status_mail_attachment(Res res) { return getIcon("status/mail-attachment.png", res); }
public static ImageIcon status_network_error(Res res) { return getIcon("status/network-error.png", res); }
public static ImageIcon status_network_idle(Res res) { return getIcon("status/network-idle.png", res); }
public static ImageIcon status_network_offline(Res res) { return getIcon("status/network-offline.png", res); }
public static ImageIcon status_network_receive(Res res) { return getIcon("status/network-receive.png", res); }
public static ImageIcon status_network_transmit_receive(Res res) { return getIcon("status/network-transmit-receive.png", res); }
public static ImageIcon status_network_transmit(Res res) { return getIcon("status/network-transmit.png", res); }
public static ImageIcon status_network_wireless_encrypted(Res res) { return getIcon("status/network-wireless-encrypted.png", res); }
public static ImageIcon status_printer_error(Res res) { return getIcon("status/printer-error.png", res); }
public static ImageIcon status_software_update_available(Res res) { return getIcon("status/software-update-available.png", res); }
public static ImageIcon status_software_update_urgent(Res res) { return getIcon("status/software-update-urgent.png", res); }
public static ImageIcon status_user_trash_full(Res res) { return getIcon("status/user-trash-full.png", res); }
public static ImageIcon status_weather_clear_night(Res res) { return getIcon("status/weather-clear-night.png", res); }
public static ImageIcon status_weather_clear(Res res) { return getIcon("status/weather-clear.png", res); }
public static ImageIcon status_weather_few_clouds_night(Res res) { return getIcon("status/weather-few-clouds-night.png", res); }
public static ImageIcon status_weather_few_clouds(Res res) { return getIcon("status/weather-few-clouds.png", res); }
public static ImageIcon status_weather_overcast(Res res) { return getIcon("status/weather-overcast.png", res); }
public static ImageIcon status_weather_severe_alert(Res res) { return getIcon("status/weather-severe-alert.png", res); }
public static ImageIcon status_weather_showers_scattered(Res res) { return getIcon("status/weather-showers-scattered.png", res); }
public static ImageIcon status_weather_showers(Res res) { return getIcon("status/weather-showers.png", res); }
public static ImageIcon status_weather_snow(Res res) { return getIcon("status/weather-snow.png", res); }
public static ImageIcon status_weather_storm(Res res) { return getIcon("status/weather-storm.png", res); }
private TangoIcons() {
}
private static ImageIcon getIcon(String name, Res res) {
String resourceName = "tango/" + res + "/" + name;
return ImageUtilities.loadImageIcon(resourceName, false);
}
} | 26,486 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CodeGenerator.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-tango/src/main/java/org/esa/snap/tango/internal/CodeGenerator.java | package org.esa.snap.tango.internal;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
/**
* Generates the {@link org.esa.snap.tango.TangoIcons} class.
*
* @author Norman Fomferra
*/
public class CodeGenerator {
public static void main(String[] args) throws URISyntaxException, IOException {
Path mainTemplateFile = Paths.get("src", "main", "resources", "org", "esa", "snap", "tango", "internal", "TangoIcons.vm");
Path testTemplateFile = Paths.get("src", "main", "resources", "org", "esa", "snap", "tango", "internal", "TangoIconsTest.vm");
Path mainClassFile = Paths.get("src", "main", "java", "org", "esa", "snap", "tango", "TangoIcons.java");
Path testClassFile = Paths.get("src", "test", "java", "org", "esa", "snap", "tango", "TangoIconsTest.java");
String mainTemplate = new String(Files.readAllBytes(mainTemplateFile));
String testTemplate = new String(Files.readAllBytes(testTemplateFile));
Files.createDirectories(mainClassFile.getParent());
Files.createDirectories(testClassFile.getParent());
File dir16 = Paths.get("src", "main", "resources", "tango", "16x16").toFile();
StringBuilder mainCode = new StringBuilder();
StringBuilder testCode = new StringBuilder();
File[] subDirs = dir16.listFiles(File::isDirectory);
for (File subDir : subDirs) {
//System.out.println("subDir = " + subDir);
File[] iconFiles = subDir.listFiles(pathname -> pathname.isFile() && pathname.getName().endsWith(".png"));
String dirName = subDir.getName();
for (File iconFile : iconFiles) {
String fileName = iconFile.getName();
String methodName = dirName.toLowerCase() + "_" + fileName.substring(0, fileName.length() - 4).replace("-", "_");
mainCode.append(String.format(" public static ImageIcon %s(Res res) { return getIcon(\"%s/%s\", res); }\n", methodName, dirName, fileName));
testCode.append(String.format(" assertNotNull(TangoIcons.%s(TangoIcons.R16));\n", methodName));
testCode.append(String.format(" assertNotNull(TangoIcons.%s(TangoIcons.R22));\n", methodName));
testCode.append(String.format(" assertNotNull(TangoIcons.%s(TangoIcons.R32));\n", methodName));
testCode.append("\n");
}
}
mainTemplate = mainTemplate.replace("${code}", mainCode.toString());
testTemplate = testTemplate.replace("${code}", testCode.toString());
Files.write(mainClassFile, mainTemplate.getBytes(), StandardOpenOption.TRUNCATE_EXISTING);
System.out.println("Written " + mainClassFile);
Files.write(testClassFile, testTemplate.getBytes(), StandardOpenOption.TRUNCATE_EXISTING);
System.out.println("Written " + testClassFile);
}
}
| 3,067 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BinningVariablesPanelTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/test/java/org/esa/snap/binning/operator/ui/BinningVariablesPanelTest.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.binning.operator.ui;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Thomas Storm
*/
public class BinningVariablesPanelTest {
@Test
public void testGetResolutionString() throws Exception {
assertEquals("9.28", BinningConfigurationPanel.getResolutionString(2160));
assertEquals("5.86", BinningConfigurationPanel.getResolutionString(3420));
assertEquals("2.1", BinningConfigurationPanel.getResolutionString(9544));
assertEquals("15.81", BinningConfigurationPanel.getResolutionString(1268));
}
}
| 1,311 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BinningFormModelTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/test/java/org/esa/snap/binning/operator/ui/BinningFormModelTest.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.binning.operator.ui;
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 org.esa.snap.binning.AggregatorConfig;
import org.esa.snap.binning.aggregators.AggregatorAverage;
import org.esa.snap.binning.operator.BinningOp;
import org.esa.snap.binning.operator.VariableConfig;
import org.esa.snap.core.datamodel.Product;
import org.junit.Test;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import static org.esa.snap.binning.operator.ui.BinningFormModel.*;
import static org.junit.Assert.*;
/**
* @author Thomas Storm
*/
public class BinningFormModelTest {
@Test
public void testSetGetProperty() throws Exception {
final BinningFormModel binningFormModel = new BinningFormModel();
PropertySet propertySet = binningFormModel.getBindingContext().getPropertySet();
propertySet.addProperty(createProperty("key", Float[].class));
propertySet.addProperty(createProperty("key2", Integer[].class));
binningFormModel.setProperty("key", new Float[]{2.0f, 3.0f});
binningFormModel.setProperty("key2", new Integer[]{10, 20, 30});
assertArrayEquals(new Product[0], binningFormModel.getSourceProducts());
assertArrayEquals(new Float[]{2.0f, 3.0f}, binningFormModel.getPropertyValue("key"));
assertArrayEquals(new Integer[]{10, 20, 30}, binningFormModel.getPropertyValue("key2"));
}
@Test
public void testAggregatorConfigsProperty() throws Exception {
final BinningFormModel binningFormModel = new BinningFormModel();
assertArrayEquals(new AggregatorConfig[0], binningFormModel.getAggregatorConfigs());
final AggregatorConfig aggConf1 = new AggregatorAverage.Config("x", "y", 0.4, true, false);
final AggregatorConfig aggConf2 = new AggregatorAverage.Config("a", "b", 0.6, false, null);
binningFormModel.setProperty(PROPERTY_KEY_AGGREGATOR_CONFIGS, new AggregatorConfig[]{aggConf1, aggConf2});
assertArrayEquals(new AggregatorConfig[]{aggConf1, aggConf2}, binningFormModel.getAggregatorConfigs());
}
@Test
public void testVariableConfigsProperty() throws Exception {
final BinningFormModel binningFormModel = new BinningFormModel();
assertArrayEquals(new VariableConfig[0], binningFormModel.getVariableConfigs());
final VariableConfig varConf = new VariableConfig();
varConf.setName("prefix");
varConf.setExpr("NOT algal_2");
binningFormModel.setProperty(PROPERTY_KEY_VARIABLE_CONFIGS, new VariableConfig[]{varConf});
assertArrayEquals(new VariableConfig[]{varConf}, binningFormModel.getVariableConfigs());
}
@Test
public void testListening() throws Exception {
final BinningFormModel binningFormModel = new BinningFormModel();
PropertySet propertySet = binningFormModel.getBindingContext().getPropertySet();
propertySet.addProperty(createProperty("key1", String.class));
propertySet.addProperty(createProperty("key2", String.class));
final MyPropertyChangeListener listener = new MyPropertyChangeListener();
binningFormModel.addPropertyChangeListener(listener);
binningFormModel.setProperty("key1", "value1");
binningFormModel.setProperty("key2", "value2");
assertEquals("value1", listener.targetMap.get("key1"));
assertEquals("value2", listener.targetMap.get("key2"));
}
@Test
public void testGetStartDate() throws Exception {
final BinningFormModel binningFormModel = new BinningFormModel();
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_TIME_FILTER_METHOD, BinningOp.TimeFilterMethod.NONE);
assertNull(binningFormModel.getStartDateTime());
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_TIME_FILTER_METHOD, BinningOp.TimeFilterMethod.TIME_RANGE);
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_START_DATE_TIME, "2000-01-01");
assertNotNull(binningFormModel.getStartDateTime());
SimpleDateFormat dateFormat = new SimpleDateFormat(BinningOp.DATE_INPUT_PATTERN);
String expectedString = dateFormat.format(new GregorianCalendar(2000, 0, 1).getTime());
assertEquals(expectedString, binningFormModel.getStartDateTime());
}
@Test
public void testGetValidExpression() throws Exception {
final BinningFormModel binningFormModel = new BinningFormModel();
assertTrue(Boolean.parseBoolean(binningFormModel.getMaskExpr()));
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_MASK_EXPR, "some_expression");
assertEquals("some_expression", binningFormModel.getMaskExpr());
}
@Test
public void testGetSuperSampling() throws Exception {
final BinningFormModel binningFormModel = new BinningFormModel();
assertEquals(1, binningFormModel.getSuperSampling());
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_SUPERSAMPLING, 10);
assertEquals(10, binningFormModel.getSuperSampling());
}
@Test
public void testGetNumRows() throws Exception {
final BinningFormModel binningFormModel = new BinningFormModel();
assertEquals(2160, binningFormModel.getNumRows());
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_NUM_ROWS, 2000);
assertEquals(2000, binningFormModel.getNumRows());
}
@Test(expected = IllegalStateException.class)
public void testGetRegion_Fail() throws Exception {
final BinningFormModel binningFormModel = new BinningFormModel();
binningFormModel.getRegion();
}
@Test
public void testGetRegion_Global() throws Exception {
final BinningFormModel binningFormModel = new BinningFormModel();
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_GLOBAL, true);
assertEquals("POLYGON ((-180 -90, 180 -90, 180 90, -180 90, -180 -90))", binningFormModel.getRegion().toText());
}
@Test
public void testGetRegion_Compute() throws Exception {
final BinningFormModel binningFormModel = new BinningFormModel();
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_COMPUTE_REGION, true);
assertNull(binningFormModel.getRegion());
}
@Test
public void testGetRegion_WithSpecifiedRegion() throws Exception {
final BinningFormModel binningFormModel = new BinningFormModel();
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_BOUNDS, true);
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_NORTH_BOUND, 50.0);
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_EAST_BOUND, 15.0);
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_WEST_BOUND, 10.0);
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_SOUTH_BOUND, 40.0);
assertEquals("POLYGON ((10 40, 10 50, 15 50, 15 40, 10 40))", binningFormModel.getRegion().toText());
}
private Property createProperty(String propertyName, Class<?> type) {
return new Property(new PropertyDescriptor(propertyName, type), new DefaultPropertyAccessor());
}
private static class MyPropertyChangeListener implements PropertyChangeListener {
Map<String, Object> targetMap = new HashMap<>();
@Override
public void propertyChange(PropertyChangeEvent evt) {
targetMap.put(evt.getPropertyName(), evt.getNewValue());
}
}
}
| 8,465 | 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-binning-ui/src/main/java/org/esa/snap/binning/docs/package-info.java | @HelpSetRegistration(helpSet = "help.hs", position = 4300)
package org.esa.snap.binning.docs;
import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration;
| 157 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BinningIOPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/main/java/org/esa/snap/binning/operator/ui/BinningIOPanel.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.binning.operator.ui;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.swing.TableLayout;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.gpf.ui.TargetProductSelector;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.WildcardMatcher;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.product.SourceProductList;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import java.awt.BorderLayout;
import java.awt.Insets;
import java.io.File;
import java.io.IOException;
import java.util.TreeSet;
import java.util.logging.Logger;
/**
* The panel in the binning operator UI which allows for setting input products and the path of the output product.
*/
class BinningIOPanel extends JPanel {
private final AppContext appContext;
private final BinningFormModel binningFormModel;
private final TargetProductSelector targetProductSelector;
private SourceProductList sourceProductList;
BinningIOPanel(AppContext appContext, BinningFormModel binningFormModel, TargetProductSelector targetProductSelector) {
this.appContext = appContext;
this.binningFormModel = binningFormModel;
this.targetProductSelector = targetProductSelector;
init();
}
void prepareClose() {
sourceProductList.clear();
}
private void init() {
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);
add(createSourceProductsPanel());
targetProductSelector.getModel().setProductName("level-3");
add(targetProductSelector.createDefaultPanel());
}
private JPanel createSourceProductsPanel() {
BorderLayout layout = new BorderLayout();
final JPanel sourceProductPanel = new JPanel(layout);
sourceProductPanel.setBorder(BorderFactory.createTitledBorder("Source Products"));
ListDataListener changeListener = new ListDataListener() {
@Override
public void contentsChanged(ListDataEvent event) {
final Product[] sourceProducts = sourceProductList.getSourceProducts();
try {
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_SOURCE_PRODUCTS, sourceProducts);
} catch (ValidationException e) {
appContext.handleError("Unable to set source products.", e);
}
if (sourceProducts.length > 0) {
binningFormModel.useAsContextProduct(sourceProducts[0]);
return;
}
String[] sourceProductPaths = binningFormModel.getSourceProductPaths();
if (sourceProductPaths != null && sourceProductPaths.length > 0) {
openFirstProduct(sourceProductPaths);
return;
}
binningFormModel.useAsContextProduct(null);
}
@Override
public void intervalAdded(ListDataEvent e) {
contentsChanged(e);
}
@Override
public void intervalRemoved(ListDataEvent e) {
contentsChanged(e);
}
};
sourceProductList = new SourceProductList(appContext);
sourceProductList.setPropertyNameLastOpenInputDir("org.esa.snap.binning.lastDir");
sourceProductList.setPropertyNameLastOpenedFormat("org.esa.snap.binning.lastFormat");
sourceProductList.addChangeListener(changeListener);
sourceProductList.setXAxis(false);
binningFormModel.getBindingContext().bind(BinningFormModel.PROPERTY_KEY_SOURCE_PRODUCT_PATHS, sourceProductList);
JComboBox<String> sourceFormatComboBox = new JComboBox<>();
binningFormModel.getBindingContext().bind(BinningFormModel.PROPERTY_KEY_SOURCE_PRODUCT_FORMAT, sourceFormatComboBox);
JLabel formatLabel = new JLabel("Source format:");
TableLayout formatLayout = new TableLayout(2);
formatLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST);
formatLayout.setTablePadding(new Insets(4, 10, 0, 0));
formatLayout.setTableFill(TableLayout.Fill.BOTH);
formatLayout.setColumnWeightX(1, 2.0);
JPanel formatPanel = new JPanel(formatLayout);
formatPanel.add(formatLabel);
formatPanel.add(sourceFormatComboBox);
JComponent[] panels = sourceProductList.getComponents();
JPanel listPanel = new JPanel(new BorderLayout());
listPanel.add(panels[0], BorderLayout.CENTER);
listPanel.add(formatPanel, BorderLayout.SOUTH);
sourceProductPanel.add(listPanel, BorderLayout.CENTER);
sourceProductPanel.add(panels[1], BorderLayout.EAST);
return sourceProductPanel;
}
private void openFirstProduct(final String[] inputPaths) {
final SwingWorker<Product, Void> worker = new SwingWorker<Product, Void>() {
@Override
protected Product doInBackground() throws Exception {
for (String inputPath : inputPaths) {
if (inputPath == null || inputPath.trim().length() == 0) {
continue;
}
try {
final TreeSet<File> fileSet = new TreeSet<>();
WildcardMatcher.glob(inputPath, fileSet);
for (File file : fileSet) {
final Product product = ProductIO.readProduct(file);
if (product != null) {
return product;
}
}
} catch (IOException e) {
Logger logger = SystemUtils.LOG;
logger.severe("I/O problem occurred while scanning source product files: " + e.getMessage());
}
}
return null;
}
@Override
protected void done() {
try {
Product firstProduct = get();
if (firstProduct != null) {
binningFormModel.useAsContextProduct(firstProduct);
firstProduct.dispose();
}
} catch (Exception ex) {
String msg = String.format("Cannot open source products.\n%s", ex.getMessage());
appContext.handleError(msg, ex);
}
}
};
worker.execute();
}
}
| 7,829 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AggregatorItemDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/main/java/org/esa/snap/binning/operator/ui/AggregatorItemDialog.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.binning.operator.ui;
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.swing.binding.PropertyPane;
import org.esa.snap.binning.AggregatorConfig;
import org.esa.snap.binning.AggregatorDescriptor;
import org.esa.snap.binning.TypedDescriptor;
import org.esa.snap.binning.TypedDescriptorsRegistry;
import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory;
import org.esa.snap.ui.ModalDialog;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
class AggregatorItemDialog extends ModalDialog {
private final AggregatorItem aggregatorItem;
private final String[] sourceVarNames;
private AggregatorConfig aggregatorConfig;
private AggregatorDescriptor aggregatorDescriptor;
private PropertySet aggregatorPropertySet;
private JComboBox<String> aggregatorComboBox;
public AggregatorItemDialog(Window parent, String[] sourceVarNames, AggregatorItem aggregatorItem, boolean initWithDefaults) {
super(parent, "Edit Aggregator", ID_OK | ID_CANCEL, null);
this.sourceVarNames = sourceVarNames;
this.aggregatorItem = aggregatorItem;
aggregatorConfig = aggregatorItem.aggregatorConfig;
aggregatorDescriptor = aggregatorItem.aggregatorDescriptor;
aggregatorPropertySet = createPropertySet(aggregatorConfig);
if (initWithDefaults) {
aggregatorPropertySet.setDefaultValues();
} else {
PropertySet objectPropertySet = PropertyContainer.createObjectBacked(aggregatorConfig);
Property[] objectProperties = objectPropertySet.getProperties();
for (Property objectProperty : objectProperties) {
aggregatorPropertySet.setValue(objectProperty.getName(), objectProperty.getValue());
}
}
}
@Override
public int show() {
setContent(createUI());
this.getJDialog().getRootPane().registerKeyboardAction(e -> close(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
getJDialog().setResizable(false);
return super.show();
}
@Override
protected boolean verifyUserInput() {
try {
for (Property property : aggregatorPropertySet.getProperties()) {
property.validate(property.getValue());
}
} catch (ValidationException e) {
this.showErrorDialog(e.getMessage(), "Invalid Aggregator Properties");
return false;
}
return true;
}
@Override
protected void onOK() {
AggregatorConfig config = aggregatorDescriptor.createConfig();
PropertySet objectPropertySet = config.asPropertySet();
Property[] mapProperties = aggregatorPropertySet.getProperties();
for (Property mapProperty : mapProperties) {
objectPropertySet.setValue(mapProperty.getName(), mapProperty.getValue());
}
objectPropertySet.setValue("type", aggregatorDescriptor.getName());
aggregatorItem.aggregatorConfig = config;
aggregatorItem.aggregatorDescriptor = aggregatorDescriptor;
super.onOK();
}
private Component createUI() {
final JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
final TypedDescriptorsRegistry registry = TypedDescriptorsRegistry.getInstance();
List<AggregatorDescriptor> aggregatorDescriptors = registry.getDescriptors(AggregatorDescriptor.class);
List<String> aggregatorNames = aggregatorDescriptors.stream().map(TypedDescriptor::getName).collect(Collectors.toList());
Collections.sort(aggregatorNames);
aggregatorComboBox = new JComboBox<>(aggregatorNames.toArray(new String[aggregatorNames.size()]));
aggregatorComboBox.setSelectedItem(aggregatorConfig.getName());
aggregatorComboBox.addActionListener(e -> {
aggregatorDescriptor = getDescriptorFromComboBox();
aggregatorConfig = aggregatorDescriptor.createConfig();
aggregatorPropertySet = createPropertySet(aggregatorConfig);
JPanel aggrPropertyPanel = createPropertyPanel(aggregatorPropertySet);
mainPanel.remove(1);
mainPanel.add(aggrPropertyPanel, BorderLayout.CENTER);
getJDialog().getContentPane().revalidate();
getJDialog().pack();
});
JPanel aggrPropertyPanel = createPropertyPanel(aggregatorPropertySet);
mainPanel.add(aggregatorComboBox, BorderLayout.NORTH);
mainPanel.add(aggrPropertyPanel, BorderLayout.CENTER);
return mainPanel;
}
private PropertySet createPropertySet(AggregatorConfig config) {
return PropertyContainer.createMapBacked(new HashMap<>(), config.getClass(),
new ParameterDescriptorFactory());
}
private AggregatorDescriptor getDescriptorFromComboBox() {
final TypedDescriptorsRegistry registry = TypedDescriptorsRegistry.getInstance();
String aggrType = (String) aggregatorComboBox.getSelectedItem();
return registry.getDescriptor(AggregatorDescriptor.class, aggrType);
}
private JPanel createPropertyPanel(PropertySet propertySet) {
Property[] properties = propertySet.getProperties();
for (Property property : properties) {
String propertyName = property.getName();
if ("type".equals(propertyName)) {
property.getDescriptor().setAttribute("visible", false);
}
if (AggregatorTableController.isSourcePropertyName(propertyName)) {
property.getDescriptor().setValueSet(new ValueSet(sourceVarNames));
}
}
return new PropertyPane(propertySet).createPanel();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
final JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final JButton aggregatorComboBox1 = new JButton("Show Dialog...");
aggregatorComboBox1.addActionListener(e -> {
AggregatorItemDialog dialog1 = new AggregatorItemDialog(jFrame, new String[]{
"stein",
"papier",
"schere",
"echse",
"spock"
}, new AggregatorItem(), true);
dialog1.getJDialog().setLocation(550, 300);
dialog1.show();
});
jFrame.setContentPane(aggregatorComboBox1);
jFrame.setBounds(300, 300, 200, 80);
jFrame.setVisible(true);
});
}
}
| 7,986 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VariableTableController.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/main/java/org/esa/snap/binning/operator/ui/VariableTableController.java | package org.esa.snap.binning.operator.ui;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.swing.Grid;
import com.bc.ceres.swing.ListControlBar;
import org.esa.snap.binning.operator.VariableConfig;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.ui.AbstractDialog;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
/**
* Controls adding, removing and moving rows in the variable table.
*/
class VariableTableController extends ListControlBar.AbstractListController {
final Grid grid;
private final BinningFormModel binningFormModel;
private final List<VariableItem> variableItems;
VariableTableController(Grid grid, BinningFormModel binningFormModel) {
this.grid = grid;
this.binningFormModel = binningFormModel;
this.variableItems = new ArrayList<>();
addVariableConfigs(this.binningFormModel.getVariableConfigs());
}
@Override
public boolean addRow(int index) {
return editVariableItem(new VariableItem(), -1);
}
@Override
public boolean removeRows(int[] indices) {
grid.removeDataRows(indices);
for (int i = indices.length - 1; i >= 0; i--) {
variableItems.remove(indices[i]);
}
updateBinningFormModel();
return true;
}
@Override
public boolean moveRowUp(int index) {
grid.moveDataRowUp(index);
VariableItem vi1 = variableItems.get(index - 1);
VariableItem vi2 = variableItems.get(index);
variableItems.set(index - 1, vi2);
variableItems.set(index, vi1);
updateBinningFormModel();
return true;
}
@Override
public boolean moveRowDown(int index) {
grid.moveDataRowDown(index);
VariableItem vi1 = variableItems.get(index);
VariableItem vi2 = variableItems.get(index + 1);
variableItems.set(index, vi2);
variableItems.set(index + 1, vi1);
updateBinningFormModel();
return true;
}
@Override
public void updateState(ListControlBar listControlBar) {
}
void setVariableConfigs(VariableConfig[] variableConfigs) {
clearGrid();
variableItems.clear();
addVariableConfigs(variableConfigs);
updateBinningFormModel();
}
private void addDataRow(VariableItem vi) {
EmptyBorder emptyBorder = new EmptyBorder(2, 2, 2, 2);
JLabel nameLabel = new JLabel(vi.variableConfig.getName());
nameLabel.setBorder(emptyBorder);
JLabel exprLabel = new JLabel(vi.variableConfig.getExpr());
exprLabel.setBorder(emptyBorder);
JLabel validExprLabel = new JLabel(vi.variableConfig.getValidExpr());
validExprLabel.setBorder(emptyBorder);
final AbstractButton editButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("/org/esa/snap/resources/images/icons/Edit16.gif"),
false);
editButton.setRolloverEnabled(true);
editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int rowIndex = grid.findDataRowIndex(editButton);
editVariableItem(variableItems.get(rowIndex), rowIndex);
}
});
grid.addDataRow(
/*1*/ nameLabel,
/*2*/ exprLabel,
/*3*/ validExprLabel,
/*4*/ editButton);
variableItems.add(vi);
}
private boolean editVariableItem(VariableItem variableItem, int rowIndex) {
final Product contextProduct = binningFormModel.getContextProduct();
if (contextProduct == null) {
AbstractDialog.showInformationDialog(grid, "At least one source product must be set first", "Information");
return false;
}
boolean newVariable = rowIndex == -1;
if (newVariable) {
int newVarIndex = variableItems.size();
String varName;
do {
varName = "variable_" + newVarIndex++;
} while (contextProduct.containsRasterDataNode(varName));
variableItem.variableConfig.setName(varName);
}
String oldVarName = variableItem.variableConfig.getName();
final VariableItemDialog variableItemDialog = new VariableItemDialog(SwingUtilities.getWindowAncestor(grid), variableItem,
newVariable, contextProduct);
if (variableItemDialog.show() == ModalDialog.ID_OK) {
if (newVariable) {
addDataRow(variableItem);
} else {
updateDataRow(variableItem, rowIndex);
if (!oldVarName.equals(variableItem.variableConfig.getName())) {
updateVariableExpressions(oldVarName, variableItem.variableConfig.getName());
}
}
updateBinningFormModel();
return true;
}
return false;
}
private void updateVariableExpressions(String oldVarName, String newVarName) {
for (int i = 0; i < variableItems.size(); i++) {
VariableItem updatedItem = variableItems.get(i);
VariableConfig updatedVarConfig = updatedItem.variableConfig;
if (updatedVarConfig.getExpr().contains(oldVarName)) {
String updatedExpr = updatedVarConfig.getExpr().replace(oldVarName, newVarName);
updatedVarConfig.setExpr(updatedExpr);
updateDataRow(updatedItem, i);
}
}
}
private void updateBinningFormModel() {
VariableConfig[] variableConfigs = new VariableConfig[variableItems.size()];
for (int i = 0; i < variableItems.size(); i++) {
VariableItem variableItem = variableItems.get(i);
variableConfigs[i] = variableItem.variableConfig;
}
try {
binningFormModel.setVariableConfigs(variableConfigs);
} catch (ValidationException e) {
AbstractDialog.showErrorDialog(grid, e.getMessage(), "Aggregator Configuration");
}
}
private void clearGrid() {
int[] rowIndices = new int[grid.getDataRowCount()];
for (int i = 0; i < rowIndices.length; i++) {
rowIndices[i] = i;
}
removeRows(rowIndices);
}
private void updateDataRow(VariableItem variableItem, int rowIndex) {
JComponent[] components = grid.getDataRow(rowIndex);
((JLabel) components[0]).setText(variableItem.variableConfig.getName());
((JLabel) components[1]).setText(variableItem.variableConfig.getExpr());
((JLabel) components[2]).setText(variableItem.variableConfig.getValidExpr());
}
private void addVariableConfigs(VariableConfig[] variableConfigs) {
for (VariableConfig variableConfig : variableConfigs) {
addDataRow(new VariableItem(variableConfig));
}
}
}
| 7,370 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BinningFormModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/main/java/org/esa/snap/binning/operator/ui/BinningFormModel.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.binning.operator.ui;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.binding.ValueSet;
import com.bc.ceres.binding.accessors.DefaultPropertyAccessor;
import com.bc.ceres.swing.binding.BindingContext;
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.esa.snap.binning.AggregatorConfig;
import org.esa.snap.binning.operator.BinningOp;
import org.esa.snap.binning.operator.VariableConfig;
import org.esa.snap.core.dataio.ProductIOPlugInManager;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.FlagCoding;
import org.esa.snap.core.datamodel.Mask;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.datamodel.TiePointGrid;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory;
import org.esa.snap.core.util.StringUtils;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.HashMap;
/**
* The model responsible for managing the binning parameters.
*
* @author Thomas Storm
*/
class BinningFormModel {
static final String PROPERTY_KEY_WEST_BOUND = "westBound";
static final String PROPERTY_KEY_NORTH_BOUND = "northBound";
static final String PROPERTY_KEY_EAST_BOUND = "eastBound";
static final String PROPERTY_KEY_SOUTH_BOUND = "southBound";
static final String PROPERTY_KEY_WKT = "manualWkt";
static final String PROPERTY_KEY_AGGREGATOR_CONFIGS = "aggregatorConfigs";
static final String PROPERTY_KEY_VARIABLE_CONFIGS = "variableConfigs";
static final String PROPERTY_KEY_REGION = "region";
static final String PROPERTY_KEY_BOUNDS = "bounds";
static final String PROPERTY_KEY_COMPUTE_REGION = "compute";
static final String PROPERTY_KEY_GLOBAL = "global";
static final String PROPERTY_KEY_MASK_EXPR = "maskExpr";
static final String PROPERTY_KEY_TIME_FILTER_METHOD = "timeFilterMethod";
static final String PROPERTY_KEY_START_DATE_TIME = "startDateTime";
static final String PROPERTY_KEY_PERIOD_DURATION = "periodDuration";
static final String PROPERTY_KEY_MIN_DATA_HOUR = "minDataHour";
static final String PROPERTY_KEY_NUM_ROWS = "numRows";
static final String PROPERTY_KEY_SUPERSAMPLING = "superSampling";
static final String PROPERTY_KEY_MANUAL_WKT = "manualWktKey";
static final String PROPERTY_KEY_SOURCE_PRODUCTS = "sourceProducts";
static final String PROPERTY_KEY_SOURCE_PRODUCT_FORMAT = "sourceProductFormat";
static final String PROPERTY_KEY_SOURCE_PRODUCT_PATHS = "sourceProductPaths";
static final String PROPERTY_KEY_CONTEXT_SOURCE_PRODUCT = "contextSourceProduct";
static final String GLOBAL_WKT = "polygon((-180 -90, 180 -90, 180 90, -180 90, -180 -90))";
static final int DEFAULT_NUM_ROWS = 2160;
private PropertySet propertySet;
private BindingContext bindingContext;
private HashMap<String, Object> parameterMap;
public BinningFormModel() {
parameterMap = new HashMap<>();
propertySet = ParameterDescriptorFactory.createMapBackedOperatorPropertyContainer("Binning", parameterMap);
hideProperties();
// dynamically init the value set
String[] readerFormats = ProductIOPlugInManager.getInstance().getAllProductReaderFormatStrings();
Arrays.sort(readerFormats);
PropertyDescriptor descriptor = propertySet.getDescriptor(PROPERTY_KEY_SOURCE_PRODUCT_FORMAT);
descriptor.setValueSet(new ValueSet(readerFormats));
// Just for GUI
propertySet.addProperty(createTransientProperty(PROPERTY_KEY_GLOBAL, Boolean.class)); // temp
propertySet.addProperty(createTransientProperty(PROPERTY_KEY_COMPUTE_REGION, Boolean.class)); // temp
propertySet.addProperty(createTransientProperty(PROPERTY_KEY_MANUAL_WKT, Boolean.class)); // temp
propertySet.addProperty(createTransientProperty(PROPERTY_KEY_WKT, String.class)); // temp
propertySet.addProperty(createTransientProperty(PROPERTY_KEY_BOUNDS, Boolean.class)); // temp
propertySet.addProperty(createTransientProperty(PROPERTY_KEY_EAST_BOUND, Double.class)); // temp
propertySet.addProperty(createTransientProperty(PROPERTY_KEY_NORTH_BOUND, Double.class)); // temp
propertySet.addProperty(createTransientProperty(PROPERTY_KEY_WEST_BOUND, Double.class)); // temp
propertySet.addProperty(createTransientProperty(PROPERTY_KEY_SOUTH_BOUND, Double.class)); // temp
propertySet.addProperty(createTransientProperty(PROPERTY_KEY_SOURCE_PRODUCTS, Product[].class)); // temp
propertySet.addProperty(createTransientProperty(PROPERTY_KEY_CONTEXT_SOURCE_PRODUCT, Product.class)); // temp
propertySet.setDefaultValues();
propertySet.getProperty(PROPERTY_KEY_REGION).addPropertyChangeListener(evt -> {
Geometry newGeometry = (Geometry) evt.getNewValue();
propertySet.setValue(PROPERTY_KEY_MANUAL_WKT, true);
propertySet.setValue(PROPERTY_KEY_WKT, newGeometry.toText());
});
}
void hideProperties() {
// those properties are not shown in GUI and shall not go into parameter file
propertySet.getProperty("metadataPropertiesFile").getDescriptor().setTransient(true);
propertySet.getProperty("metadataTemplateDir").getDescriptor().setTransient(true);
propertySet.getProperty("outputType").getDescriptor().setTransient(true);
propertySet.getProperty("outputFormat").getDescriptor().setTransient(true);
propertySet.getProperty("outputBinnedData").getDescriptor().setTransient(true);
propertySet.getProperty("outputMappedProduct").getDescriptor().setTransient(true);
}
public PropertySet getPropertySet() {
return propertySet;
}
public HashMap<String, Object> getParameterMap() {
return parameterMap;
}
public Product[] getSourceProducts() {
final Product[] products = getPropertyValue(BinningFormModel.PROPERTY_KEY_SOURCE_PRODUCTS);
if (products == null) {
return new Product[0];
}
return products;
}
public String[] getSourceProductPaths() {
return getPropertyValue(BinningFormModel.PROPERTY_KEY_SOURCE_PRODUCT_PATHS);
}
public String getSourceProductFormat() {
return getPropertyValue(BinningFormModel.PROPERTY_KEY_SOURCE_PRODUCT_FORMAT);
}
public Product getContextProduct() {
return getPropertyValue(BinningFormModel.PROPERTY_KEY_CONTEXT_SOURCE_PRODUCT);
}
public void useAsContextProduct(Product contextProduct) {
if (contextProduct != null && contextProduct.getProductReader() != null) {
String format = contextProduct.getProductReader().getReaderPlugIn().getFormatNames()[0];
propertySet.setValue(BinningFormModel.PROPERTY_KEY_SOURCE_PRODUCT_FORMAT, format);
}
Product currentContextProduct = createContextProduct(contextProduct);
propertySet.setValue(BinningFormModel.PROPERTY_KEY_CONTEXT_SOURCE_PRODUCT, currentContextProduct);
}
private Product createContextProduct(Product srcProduct) {
if (srcProduct == null) {
return null;
}
Product contextProduct = new Product("contextProduct", srcProduct.getProductType(), 10, 10);
for (String flagCodingName : srcProduct.getFlagCodingGroup().getNodeNames()) {
FlagCoding srcFC = srcProduct.getFlagCodingGroup().get(flagCodingName);
String[] flagNames = srcFC.getFlagNames();
FlagCoding contextFC = new FlagCoding(flagCodingName);
for (String flagName : flagNames) {
contextFC.addFlag(flagName, srcFC.getFlagMask(flagName), srcFC.getFlag(flagName).getDescription());
}
contextProduct.getFlagCodingGroup().add(contextFC);
}
for (Band srcBand : srcProduct.getBands()) {
Band contextBand = contextProduct.addBand(srcBand.getName(), srcBand.getDataType());
if (srcBand.isFlagBand()) {
contextBand.setSampleCoding(contextProduct.getFlagCodingGroup().get(srcBand.getFlagCoding().getName()));
}
}
for (TiePointGrid grid : srcProduct.getTiePointGrids()) {
contextProduct.addTiePointGrid(new TiePointGrid(grid.getName(), 10, 10, 0, 0, 1, 1, new float[100]));
}
for (String vectorDataName : srcProduct.getVectorDataGroup().getNodeNames()) {
VectorDataNode vectorData = srcProduct.getVectorDataGroup().get(vectorDataName);
contextProduct.getVectorDataGroup().add(new VectorDataNode(vectorDataName, vectorData.getFeatureType()));
}
for (String maskName : srcProduct.getMaskGroup().getNodeNames()) {
Mask mask = srcProduct.getMaskGroup().get(maskName);
contextProduct.addMask(maskName, mask.getImageType());
}
VariableConfig[] variableConfigs = getVariableConfigs();
for (VariableConfig variableConfig : variableConfigs) {
contextProduct.addBand(new VariableConfigBand(variableConfig.getName()));
}
return contextProduct;
}
public AggregatorConfig[] getAggregatorConfigs() {
AggregatorConfig[] aggregatorConfigs = getPropertyValue(PROPERTY_KEY_AGGREGATOR_CONFIGS);
if (aggregatorConfigs == null) {
aggregatorConfigs = new AggregatorConfig[0];
}
return aggregatorConfigs;
}
public VariableConfig[] getVariableConfigs() {
VariableConfig[] variableConfigs = getPropertyValue(PROPERTY_KEY_VARIABLE_CONFIGS);
if (variableConfigs == null) {
variableConfigs = new VariableConfig[0];
}
return variableConfigs;
}
public void setVariableConfigs(VariableConfig[] variableConfigs) throws ValidationException {
if (variableConfigs == null) {
variableConfigs = new VariableConfig[0];
}
setProperty(PROPERTY_KEY_VARIABLE_CONFIGS, variableConfigs);
Product contextProduct = getContextProduct();
if (contextProduct != null) {
removeAllVariableConfigBands(contextProduct);
for (VariableConfig variableConfig : variableConfigs) {
contextProduct.addBand(new VariableConfigBand(variableConfig.getName()));
}
}
}
void removeAllVariableConfigBands(Product contextProduct) {
Band[] bands = contextProduct.getBands();
for (Band band : bands) {
if(band instanceof VariableConfigBand) {
contextProduct.removeBand(band);
}
}
}
public Geometry getRegion() {
if (Boolean.TRUE.equals(getPropertyValue(PROPERTY_KEY_GLOBAL))) {
return toGeometry(GLOBAL_WKT);
} else if (Boolean.TRUE.equals(getPropertyValue(PROPERTY_KEY_COMPUTE_REGION))) {
return null;
} else if (Boolean.TRUE.equals(getPropertyValue(PROPERTY_KEY_BOUNDS))) {
final double westValue = getPropertyValue(PROPERTY_KEY_WEST_BOUND);
final double eastValue = getPropertyValue(PROPERTY_KEY_EAST_BOUND);
final double northValue = getPropertyValue(PROPERTY_KEY_NORTH_BOUND);
final double southValue = getPropertyValue(PROPERTY_KEY_SOUTH_BOUND);
Coordinate[] coordinates = {
new Coordinate(westValue, southValue), new Coordinate(westValue, northValue),
new Coordinate(eastValue, northValue), new Coordinate(eastValue, southValue),
new Coordinate(westValue, southValue)
};
final GeometryFactory geometryFactory = new GeometryFactory();
return geometryFactory.createPolygon(geometryFactory.createLinearRing(coordinates), null);
} else if (Boolean.TRUE.equals(getPropertyValue(PROPERTY_KEY_MANUAL_WKT))) {
return toGeometry(getPropertyValue(PROPERTY_KEY_WKT));
}
throw new IllegalStateException("Should never come here");
}
Geometry toGeometry(String wkt) {
try {
return new WKTReader().read(wkt);
} catch (ParseException e) {
throw new IllegalStateException("WKT for region is not valid:\n" + wkt);
}
}
public String getMaskExpr() {
final String propertyValue = getPropertyValue(PROPERTY_KEY_MASK_EXPR);
if (StringUtils.isNullOrEmpty(propertyValue)) {
return "true";
}
return propertyValue;
}
public BinningOp.TimeFilterMethod getTimeFilterMethod() {
return propertySet.getProperty(PROPERTY_KEY_TIME_FILTER_METHOD).getValue();
}
public String getStartDateTime() {
BinningOp.TimeFilterMethod temporalFilter = getPropertyValue(PROPERTY_KEY_TIME_FILTER_METHOD);
switch (temporalFilter) {
case NONE: {
return null;
}
case TIME_RANGE:
case SPATIOTEMPORAL_DATA_DAY: {
return getPropertyValue(PROPERTY_KEY_START_DATE_TIME);
}
}
throw new IllegalStateException("Illegal temporal filter method: '" + temporalFilter + "'");
}
public Double getPeriodDuration() {
return getPropertyValue(PROPERTY_KEY_PERIOD_DURATION);
}
public Double getMinDataHour() {
return getPropertyValue(PROPERTY_KEY_MIN_DATA_HOUR);
}
public int getSuperSampling() {
if (getPropertyValue(PROPERTY_KEY_SUPERSAMPLING) == null) {
return 1;
}
return (Integer) getPropertyValue(PROPERTY_KEY_SUPERSAMPLING);
}
public int getNumRows() {
if (getPropertyValue(PROPERTY_KEY_NUM_ROWS) == null) {
return DEFAULT_NUM_ROWS;
}
return (Integer) getPropertyValue(PROPERTY_KEY_NUM_ROWS);
}
public void setProperty(String key, Object value) throws ValidationException {
if (propertySet.isPropertyDefined(key)) {
final Property property = propertySet.getProperty(key);
property.setValue(value);
} else {
throw new IllegalStateException("Unknown property: " + key);
}
}
public void addPropertyChangeListener(PropertyChangeListener propertyChangeListener) {
propertySet.addPropertyChangeListener(propertyChangeListener);
}
public BindingContext getBindingContext() {
if (bindingContext == null) {
bindingContext = new BindingContext(propertySet);
}
return bindingContext;
}
@SuppressWarnings("unchecked")
<T> T getPropertyValue(String key) {
final Property property = propertySet.getProperty(key);
if (property != null) {
return (T) property.getValue();
}
return null;
}
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);
}
private static class VariableConfigBand extends Band {
public VariableConfigBand(String varName) {
super(varName, ProductData.TYPE_FLOAT32, 10, 10);
}
}
}
| 16,807 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VariableItem.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/main/java/org/esa/snap/binning/operator/ui/VariableItem.java | package org.esa.snap.binning.operator.ui;
import org.esa.snap.binning.operator.VariableConfig;
class VariableItem {
VariableConfig variableConfig;
VariableItem() {
this.variableConfig = new VariableConfig();
}
VariableItem(VariableConfig variableConfig) {
this.variableConfig = variableConfig;
}
}
| 339 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BinningFilterPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/main/java/org/esa/snap/binning/operator/ui/BinningFilterPanel.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.binning.operator.ui;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.Enablement;
import com.bc.ceres.swing.binding.internal.AbstractButtonAdapter;
import com.jidesoft.swing.AutoResizingTextArea;
import com.jidesoft.swing.TitledSeparator;
import org.esa.snap.binning.operator.BinningOp;
import org.esa.snap.ui.RegionBoundsInputUI;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.Map;
import static org.esa.snap.binning.operator.BinningOp.TimeFilterMethod.*;
/**
* The panel in the binning operator UI which allows for setting the regional and temporal filters.
*
* @author Olaf Danne
* @author Thomas Storm
*/
class BinningFilterPanel extends JPanel {
private static final String TIME_FILTER_METHOD_NONE = "ignore pixel observation time, use all source pixels";
private static final String TIME_FILTER_METHOD_TIME_RANGE = "use all pixels that have been acquired in the given binning period";
private static final String TIME_FILTER_METHOD_SPATIOTEMPORAL_DATA_DAY = "<html>use a sensor-dependent, spatial \"data-day\" definition with the goal to minimise the<br>" +
"time between the first and last observation contributing to the same bin in the given binning period.</html>";
private final Map<BinningOp.TimeFilterMethod, String> timeFilterMethodDescriptions;
private final BindingContext bindingContext;
private BinningFormModel binningFormModel;
BinningFilterPanel(final BinningFormModel binningFormModel) {
timeFilterMethodDescriptions = new HashMap<>();
timeFilterMethodDescriptions.put(BinningOp.TimeFilterMethod.NONE, TIME_FILTER_METHOD_NONE);
timeFilterMethodDescriptions.put(BinningOp.TimeFilterMethod.TIME_RANGE, TIME_FILTER_METHOD_TIME_RANGE);
timeFilterMethodDescriptions.put(BinningOp.TimeFilterMethod.SPATIOTEMPORAL_DATA_DAY, TIME_FILTER_METHOD_SPATIOTEMPORAL_DATA_DAY);
this.binningFormModel = binningFormModel;
bindingContext = binningFormModel.getBindingContext();
init();
}
private void init() {
ButtonGroup buttonGroup = new ButtonGroup();
final JRadioButton computeOption = new JRadioButton("Compute the geographical region according to extents of input products");
final JRadioButton globalOption = new JRadioButton("Use the whole globe as region");
final JRadioButton regionOption = new JRadioButton("Specify region:");
final JRadioButton wktOption = new JRadioButton("Enter WKT:");
bindingContext.bind(BinningFormModel.PROPERTY_KEY_COMPUTE_REGION, new RadioButtonAdapter(computeOption));
bindingContext.bind(BinningFormModel.PROPERTY_KEY_GLOBAL, new RadioButtonAdapter(globalOption));
bindingContext.bind(BinningFormModel.PROPERTY_KEY_MANUAL_WKT, new RadioButtonAdapter(wktOption));
bindingContext.bind(BinningFormModel.PROPERTY_KEY_BOUNDS, new RadioButtonAdapter(regionOption));
buttonGroup.add(computeOption);
buttonGroup.add(globalOption);
buttonGroup.add(wktOption);
buttonGroup.add(regionOption);
computeOption.setSelected(true);
final TableLayout layout = new TableLayout(1);
layout.setTableAnchor(TableLayout.Anchor.NORTHEAST);
layout.setTableFill(TableLayout.Fill.HORIZONTAL);
layout.setTableWeightX(1.0);
layout.setTablePadding(4, 3);
setLayout(layout);
add(new TitledSeparator("Spatial Filter / Region", SwingConstants.CENTER));
add(computeOption);
add(globalOption);
add(wktOption);
add(createWktInputPanel());
add(regionOption);
add(createAndInitBoundsUI());
add(new TitledSeparator("Temporal Filter", SwingConstants.CENTER));
add(createTemporalFilterPanel());
add(layout.createVerticalSpacer());
}
private JComponent createWktInputPanel() {
final JTextArea textArea = new AutoResizingTextArea(3, 30);
//Overrides behavior when set enabled
textArea.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (textArea.isEnabled()) {
textArea.setBackground(Color.WHITE);
} else {
textArea.setBackground(new Color(240, 240, 240));
}
}
});
bindingContext.bind(BinningFormModel.PROPERTY_KEY_WKT, textArea);
bindingContext.bindEnabledState(BinningFormModel.PROPERTY_KEY_WKT, false, BinningFormModel.PROPERTY_KEY_MANUAL_WKT, false);
textArea.setEnabled(false);
return new JScrollPane(textArea);
}
private JPanel createAndInitBoundsUI() {
final RegionBoundsInputUI regionBoundsInputUI;
regionBoundsInputUI = new RegionBoundsInputUI(bindingContext);
bindingContext.addPropertyChangeListener(BinningFormModel.PROPERTY_KEY_BOUNDS, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
final boolean enabled = (Boolean) evt.getNewValue();
regionBoundsInputUI.setEnabled(enabled);
}
});
regionBoundsInputUI.setEnabled(false);
return regionBoundsInputUI.getUI();
}
private Component createTemporalFilterPanel() {
TableLayout layout = new TableLayout(3);
layout.setTableFill(TableLayout.Fill.BOTH);
layout.setTableAnchor(TableLayout.Anchor.NORTHWEST);
layout.setTableWeightX(0.0);
layout.setTableWeightY(0.0);
layout.setTablePadding(10, 5);
layout.setCellColspan(0, 1, 2);
layout.setCellColspan(3, 1, 2);
layout.setCellWeightX(2, 1, 1.0);
layout.setCellWeightX(2, 2, 0.0);
layout.setColumnWeightX(1, 1.0);
JPanel panel = new JPanel(layout);
JLabel temporalFilterLabel = new JLabel("Time filter method:");
JLabel startDateLabel = new JLabel("Start date:");
JLabel startDateFormatLabel = new JLabel("yyyy-MM-dd( HH:mm:ss)");
JLabel periodDurationLabel = new JLabel("Period duration:");
JLabel minDataHourLabel = new JLabel("Min data hour:");
JLabel periodDurationUnitLabel = new JLabel("days");
final JComboBox<BinningOp.TimeFilterMethod> temporalFilterComboBox = new JComboBox<>(new BinningOp.TimeFilterMethod[]{
NONE,
TIME_RANGE,
SPATIOTEMPORAL_DATA_DAY
});
temporalFilterComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
BinningOp.TimeFilterMethod method = (BinningOp.TimeFilterMethod) temporalFilterComboBox.getSelectedItem();
if (method != null) {
temporalFilterComboBox.setToolTipText(timeFilterMethodDescriptions.get(method));
}
}
});
JTextField startDateTextField = new JTextField();
JTextField periodDurationTextField = new JTextField();
JTextField minDataHourTextField = new JTextField();
startDateLabel.setEnabled(false);
periodDurationLabel.setEnabled(false);
temporalFilterLabel.setToolTipText("The method that is used to decide which source pixels are used with respect to their observation time.");
startDateLabel.setToolTipText("The UTC start date of the binning period. If only the date part is given, the time 00:00:00 is assumed.");
periodDurationLabel.setToolTipText("Duration of the binning period in days.");
minDataHourLabel.setToolTipText(
"A sensor-dependent constant given in hours of a day (0 to 24) at which a sensor has a minimum number of observations at the date line (the 180 degree meridian).");
BindingContext bindingContext = binningFormModel.getBindingContext();
bindingContext.bind(BinningFormModel.PROPERTY_KEY_TIME_FILTER_METHOD, temporalFilterComboBox);
bindingContext.bind(BinningFormModel.PROPERTY_KEY_START_DATE_TIME, startDateTextField);
bindingContext.bind(BinningFormModel.PROPERTY_KEY_PERIOD_DURATION, periodDurationTextField);
bindingContext.bind(BinningFormModel.PROPERTY_KEY_MIN_DATA_HOUR, minDataHourTextField);
bindingContext.getBinding(BinningFormModel.PROPERTY_KEY_START_DATE_TIME).addComponent(startDateLabel);
bindingContext.getBinding(BinningFormModel.PROPERTY_KEY_START_DATE_TIME).addComponent(startDateFormatLabel);
bindingContext.getBinding(BinningFormModel.PROPERTY_KEY_PERIOD_DURATION).addComponent(periodDurationLabel);
bindingContext.getBinding(BinningFormModel.PROPERTY_KEY_PERIOD_DURATION).addComponent(periodDurationUnitLabel);
bindingContext.getBinding(BinningFormModel.PROPERTY_KEY_MIN_DATA_HOUR).addComponent(minDataHourLabel);
temporalFilterComboBox.setSelectedIndex(0); // selected value must not be empty when setting enablement
bindingContext.bindEnabledState(BinningFormModel.PROPERTY_KEY_START_DATE_TIME, true, hasTimeInformation(TIME_RANGE, SPATIOTEMPORAL_DATA_DAY));
bindingContext.bindEnabledState(BinningFormModel.PROPERTY_KEY_PERIOD_DURATION, true, hasTimeInformation(TIME_RANGE, SPATIOTEMPORAL_DATA_DAY));
bindingContext.bindEnabledState(BinningFormModel.PROPERTY_KEY_MIN_DATA_HOUR, true, hasTimeInformation(SPATIOTEMPORAL_DATA_DAY));
temporalFilterComboBox.setSelectedIndex(0); // ensure that enablement is applied
panel.add(temporalFilterLabel);
panel.add(temporalFilterComboBox);
panel.add(startDateLabel);
panel.add(startDateTextField);
panel.add(startDateFormatLabel);
panel.add(periodDurationLabel);
panel.add(periodDurationTextField);
panel.add(periodDurationUnitLabel);
panel.add(minDataHourLabel);
panel.add(minDataHourTextField);
return panel;
}
private static Enablement.Condition hasTimeInformation(final BinningOp.TimeFilterMethod... conditions) {
return new Enablement.Condition() {
@Override
public boolean evaluate(BindingContext bindingContext) {
BinningOp.TimeFilterMethod chosenMethod = bindingContext.getPropertySet().getProperty(
BinningFormModel.PROPERTY_KEY_TIME_FILTER_METHOD).getValue();
for (BinningOp.TimeFilterMethod condition : conditions) {
if (condition == chosenMethod) {
return true;
}
}
return false;
}
@Override
public void install(BindingContext bindingContext, Enablement enablement) {
bindingContext.addPropertyChangeListener(BinningFormModel.PROPERTY_KEY_TIME_FILTER_METHOD, enablement);
}
@Override
public void uninstall(BindingContext bindingContext, Enablement enablement) {
bindingContext.removePropertyChangeListener(BinningFormModel.PROPERTY_KEY_TIME_FILTER_METHOD, enablement);
}
};
}
private static class RadioButtonAdapter extends AbstractButtonAdapter implements ItemListener {
RadioButtonAdapter(AbstractButton button) {
super(button);
}
@Override
public void bindComponents() {
getButton().addItemListener(this);
}
@Override
public void unbindComponents() {
getButton().removeItemListener(this);
}
@Override
public void itemStateChanged(ItemEvent e) {
getBinding().setPropertyValue(getButton().isSelected());
}
}
}
| 13,225 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BinningDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/main/java/org/esa/snap/binning/operator/ui/BinningDialog.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.binning.operator.ui;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import org.esa.snap.binning.AggregatorConfig;
import org.esa.snap.binning.AggregatorDescriptor;
import org.esa.snap.binning.TypedDescriptorsRegistry;
import org.esa.snap.binning.operator.BinningOp;
import org.esa.snap.binning.operator.VariableConfig;
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.ParameterUpdater;
import org.esa.snap.core.gpf.ui.SingleTargetProductDialog;
import org.esa.snap.core.gpf.ui.TargetProductSelectorModel;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.ui.AppContext;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* UI for binning operator.
*
* @author Olaf Danne
* @author Thomas Storm
*/
public class BinningDialog extends SingleTargetProductDialog {
private static final String OPERATOR_NAME = "Binning";
private final BinningForm form;
private final BinningFormModel formModel;
protected BinningDialog(AppContext appContext, String title, String helpID) {
super(appContext, title, ID_APPLY_CLOSE_HELP, helpID, new TargetProductSelectorModel(), true);
formModel = new BinningFormModel();
form = new BinningForm(appContext, formModel, getTargetProductSelector());
OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(OPERATOR_NAME);
ParameterUpdater parameterUpdater = new BinningParameterUpdater();
OperatorParameterSupport parameterSupport = new OperatorParameterSupport(operatorSpi.getOperatorDescriptor(),
formModel.getPropertySet(),
formModel.getParameterMap(),
parameterUpdater);
OperatorMenu operatorMenu = new OperatorMenu(this.getJDialog(),
operatorSpi.getOperatorDescriptor(),
parameterSupport,
appContext,
helpID);
getJDialog().setJMenuBar(operatorMenu.createDefaultMenu());
}
@Override
protected boolean verifyUserInput() {
AggregatorConfig[] aggregatorConfigs = formModel.getAggregatorConfigs();
if (!isAtLeastOneAggreatorConfigDefined(aggregatorConfigs)) {
return false;
}
if (!doUsedVariablesStillExist(aggregatorConfigs)) {
return false;
}
if (!areTargetNamesUnique(aggregatorConfigs)) {
return false;
}
if (!isTimeFilterWellConfigured()) {
return false;
}
return true;
}
@Override
protected Product createTargetProduct() throws Exception {
final TargetProductCreator targetProductCreator = new TargetProductCreator();
targetProductCreator.executeWithBlocking();
return targetProductCreator.get();
}
@Override
public int show() {
setContent(form);
return super.show();
}
@Override
public void hide() {
form.prepareClose();
super.hide();
}
private boolean doUsedVariablesStillExist(AggregatorConfig[] aggregatorConfigs) {
Product contextProduct = formModel.getContextProduct();
// assuming that the variables are defined in the context product
TypedDescriptorsRegistry registry = TypedDescriptorsRegistry.getInstance();
for (AggregatorConfig aggregatorConfig : aggregatorConfigs) {
String aggregatorConfigName = aggregatorConfig.getName();
AggregatorDescriptor descriptor = registry.getDescriptor(AggregatorDescriptor.class, aggregatorConfigName);
String[] sourceVarNames = descriptor.getSourceVarNames(aggregatorConfig);
for (String sourceVarName : sourceVarNames) {
if (Objects.isNull(contextProduct) || !contextProduct.containsBand(sourceVarName)) {
String msg = String.format(
"Source band name '%s' of aggregator '%s' is unknown.\nIt is neither one of the bands of the source products,\n" +
"nor is it defined by an intermediate source band.", sourceVarName, aggregatorConfigName
);
showErrorDialog(msg);
return false;
}
}
}
return true;
}
private boolean isTimeFilterWellConfigured() {
if (formModel.getTimeFilterMethod() == BinningOp.TimeFilterMethod.SPATIOTEMPORAL_DATA_DAY ||
formModel.getTimeFilterMethod() == BinningOp.TimeFilterMethod.TIME_RANGE) {
if (formModel.getStartDateTime() == null) {
showErrorDialog("Start date/time must be provided when time filter method 'spatiotemporal data day' or 'time range' is chosen.");
return false;
}
if (formModel.getPeriodDuration() == null) {
showErrorDialog("Period duration must be provided when time filter method 'spatiotemporal data day' or 'time range' is chosen.");
return false;
}
}
if (formModel.getTimeFilterMethod() == BinningOp.TimeFilterMethod.SPATIOTEMPORAL_DATA_DAY) {
if (formModel.getMinDataHour() == null) {
showErrorDialog("Min data hour must be provided when time filter method 'spatiotemporal data day' is chosen.");
return false;
}
}
return true;
}
private boolean isAtLeastOneAggreatorConfigDefined(AggregatorConfig[] aggregatorConfigs) {
if (aggregatorConfigs.length == 0) {
showErrorDialog("Please configure at least a single aggregator.");
return false;
}
return true;
}
private boolean areTargetNamesUnique(AggregatorConfig[] aggregatorConfigs) {
List<String> targetVarNameList = new ArrayList<>();
TypedDescriptorsRegistry registry = TypedDescriptorsRegistry.getInstance();
for (AggregatorConfig aggregatorConfig : aggregatorConfigs) {
AggregatorDescriptor descriptor = registry.getDescriptor(AggregatorDescriptor.class, aggregatorConfig.getName());
String[] targetNames = descriptor.getTargetVarNames(aggregatorConfig);
for (String targetName : targetNames) {
if (targetVarNameList.contains(targetName)) {
showErrorDialog(String.format("The target band with the name '%s' is defined twice.", targetName));
return false;
} else {
targetVarNameList.add(targetName);
}
}
}
return true;
}
private void updateParameterMap(Map<String, Object> parameters) {
parameters.put("variableConfigs", formModel.getVariableConfigs());
parameters.put("aggregatorConfigs", formModel.getAggregatorConfigs());
parameters.put("outputFile", getTargetProductSelector().getModel().getProductFile().getPath());
parameters.put("outputFormat", getTargetProductSelector().getModel().getFormatName());
parameters.put("maskExpr", formModel.getMaskExpr());
parameters.put("region", formModel.getRegion());
parameters.put("numRows", formModel.getNumRows());
parameters.put("superSampling", formModel.getSuperSampling());
parameters.put("sourceProductFormat", formModel.getSourceProductFormat());
parameters.put("sourceProductPaths", formModel.getSourceProductPaths());
BinningOp.TimeFilterMethod method = formModel.getTimeFilterMethod();
parameters.put("timeFilterMethod", method);
if (method == BinningOp.TimeFilterMethod.SPATIOTEMPORAL_DATA_DAY) {
parameters.put("minDataHour", formModel.getMinDataHour());
parameters.put("startDateTime", formModel.getStartDateTime());
parameters.put("periodDuration", formModel.getPeriodDuration());
} else if (method == BinningOp.TimeFilterMethod.TIME_RANGE) {
parameters.put("startDateTime", formModel.getStartDateTime());
parameters.put("periodDuration", formModel.getPeriodDuration());
}
}
private void updateFormModel(Map<String, Object> parameterMap) throws ValidationException {
final PropertySet propertySet = formModel.getBindingContext().getPropertySet();
final Set<Map.Entry<String, Object>> entries = parameterMap.entrySet();
for (Map.Entry<String, Object> entry : entries) {
Property property = propertySet.getProperty(entry.getKey());
if (property != null) {
property.setValue(entry.getValue());
}
}
if (parameterMap.containsKey("outputFile")) {
File outputFile = new File((String) parameterMap.get("outputFile"));
File outputDir = outputFile.getParentFile();
if (outputDir != null) {
getTargetProductSelector().getModel().setProductDir(outputDir);
}
getTargetProductSelector().getModel().setProductName(FileUtils.getFilenameWithoutExtension(outputFile));
}
if (parameterMap.containsKey("outputFormat")) {
String outputFormat = (String) parameterMap.get("outputFormat");
getTargetProductSelector().getModel().setFormatName(outputFormat);
}
BinningConfigurationPanel configurationPanel = form.getBinningConfigurationPanel();
VariableTableController variableTableController = configurationPanel.getVariableTableController();
VariableConfig[] variableConfigs = new VariableConfig[0];
if (parameterMap.containsKey("variableConfigs")) {
variableConfigs = (VariableConfig[]) parameterMap.get("variableConfigs");
}
variableTableController.setVariableConfigs(variableConfigs);
AggregatorTableController aggregatorTableController = configurationPanel.getAggregatorTableController();
AggregatorConfig[] aggregatorConfigs = new AggregatorConfig[0];
if (parameterMap.containsKey("aggregatorConfigs")) {
aggregatorConfigs = (AggregatorConfig[]) parameterMap.get("aggregatorConfigs");
}
aggregatorTableController.setAggregatorConfigs(aggregatorConfigs);
}
private class TargetProductCreator extends ProgressMonitorSwingWorker<Product, Void> {
protected TargetProductCreator() {
super(BinningDialog.this.getJDialog(), "Creating target product");
}
@Override
protected Product doInBackground(ProgressMonitor pm) {
pm.beginTask("Binning...", 100);
final Map<String, Object> parameters = new HashMap<>();
updateParameterMap(parameters);
final Product targetProduct = GPF.createProduct("Binning", parameters, formModel.getSourceProducts());
pm.done();
return targetProduct;
}
}
private class BinningParameterUpdater implements ParameterUpdater {
@Override
public void handleParameterSaveRequest(Map<String, Object> parameterMap) {
formModel.getBindingContext().adjustComponents();
updateParameterMap(parameterMap);
}
@Override
public void handleParameterLoadRequest(Map<String, Object> parameterMap) throws ValidationException {
updateFormModel(parameterMap);
formModel.getBindingContext().adjustComponents();
}
}
}
| 12,641 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BinningConfigurationPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/main/java/org/esa/snap/binning/operator/ui/BinningConfigurationPanel.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.binning.operator.ui;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.swing.Grid;
import com.bc.ceres.swing.ListControlBar;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import com.jidesoft.swing.JideSplitPane;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.product.ProductExpressionPane;
import org.esa.snap.ui.tool.ToolButtonFactory;
import javax.swing.AbstractButton;
import javax.swing.JButton;
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 javax.swing.border.TitledBorder;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
/**
* The panel in the binning operator UI which allows for specifying the configuration of binning variables.
*
* @author Norman
*/
class BinningConfigurationPanel extends JPanel {
private final AppContext appContext;
private final BinningFormModel binningFormModel;
private double currentGridResolution;
private AggregatorTableController aggregatorTableController;
private VariableTableController variableTableController;
BinningConfigurationPanel(AppContext appContext, BinningFormModel binningFormModel) {
this.appContext = appContext;
this.binningFormModel = binningFormModel;
setLayout(new BorderLayout());
add(createAggregatorsAndVariablesPanel(), BorderLayout.CENTER);
add(createParametersPanel(), BorderLayout.SOUTH);
}
VariableTableController getVariableTableController() {
return variableTableController;
}
AggregatorTableController getAggregatorTableController() {
return aggregatorTableController;
}
private JComponent createAggregatorsAndVariablesPanel() {
JideSplitPane splitPane = new JideSplitPane(JideSplitPane.VERTICAL_SPLIT);
splitPane.add(createAggregatorsPanel());
splitPane.add(createVariablesPanel());
splitPane.setShowGripper(true);
splitPane.setProportionalLayout(true);
splitPane.setProportions(new double[]{0.6});
return splitPane;
}
private JPanel createParametersPanel() {
BindingContext bindingContext = binningFormModel.getBindingContext();
JLabel validPixelExpressionLabel = new JLabel("Valid-pixel expression:");
final JButton validPixelExpressionButton = new JButton("...");
final Dimension preferredSize = validPixelExpressionButton.getPreferredSize();
preferredSize.setSize(25, preferredSize.getHeight());
validPixelExpressionButton.setPreferredSize(preferredSize);
validPixelExpressionButton.setEnabled(hasSourceProducts());
binningFormModel.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(BinningFormModel.PROPERTY_KEY_CONTEXT_SOURCE_PRODUCT)) {
validPixelExpressionButton.setEnabled(hasSourceProducts());
}
}
});
JLabel targetHeightLabel = new JLabel("#Rows (90N - 90S):");
final JTextField validPixelExpressionField = new JTextField();
bindingContext.bind(BinningFormModel.PROPERTY_KEY_MASK_EXPR, validPixelExpressionField);
validPixelExpressionButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
final String expression = editExpression(validPixelExpressionField.getText());
if (expression != null) {
try {
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_MASK_EXPR, expression);
} catch (ValidationException e) {
appContext.handleError("Invalid expression", e);
}
}
}
});
final JTextField numRowsTextField = new IntegerTextField(BinningFormModel.DEFAULT_NUM_ROWS);
JLabel resolutionLabel = new JLabel("Spatial resolution (km/px):");
final String defaultResolution = getString(computeResolution(BinningFormModel.DEFAULT_NUM_ROWS));
final JTextField resolutionTextField = new DoubleTextField(defaultResolution);
JButton resolutionButton = new JButton("default");
JLabel superSamplingLabel = new JLabel("Super-sampling:");
final JTextField superSamplingTextField = new IntegerTextField(1);
final ResolutionTextFieldListener listener = new ResolutionTextFieldListener(resolutionTextField, numRowsTextField);
bindingContext.bind(BinningFormModel.PROPERTY_KEY_NUM_ROWS, numRowsTextField);
bindingContext.bind(BinningFormModel.PROPERTY_KEY_SUPERSAMPLING, superSamplingTextField);
bindingContext.getBinding(BinningFormModel.PROPERTY_KEY_NUM_ROWS).setPropertyValue(BinningFormModel.DEFAULT_NUM_ROWS);
bindingContext.getBinding(BinningFormModel.PROPERTY_KEY_SUPERSAMPLING).setPropertyValue(1);
bindingContext.getPropertySet().getProperty(BinningFormModel.PROPERTY_KEY_NUM_ROWS).addPropertyChangeListener(
new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateResolutionLabel(numRowsTextField, resolutionTextField, listener);
}
}
);
resolutionTextField.addFocusListener(listener);
resolutionTextField.addActionListener(listener);
resolutionButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resolutionTextField.setText(defaultResolution);
listener.update();
}
});
validPixelExpressionLabel.setToolTipText("Only those pixels matching this expression are considered");
targetHeightLabel.setToolTipText("<html>The number of rows of the <b>maximum</b> target grid</html>");
resolutionLabel.setToolTipText("The spatial resolution, directly depending on #rows");
superSamplingLabel.setToolTipText("Every input pixel is subdivided into n x n sub-pixels in order to reduce or avoid the Moiré effect");
TableLayout layout = new TableLayout(3);
layout.setTableAnchor(TableLayout.Anchor.NORTHWEST);
layout.setTableWeightX(0.0);
layout.setCellColspan(1, 1, 2);
layout.setCellColspan(3, 1, 2);
layout.setTableFill(TableLayout.Fill.HORIZONTAL);
layout.setColumnWeightX(1, 1.0);
layout.setTablePadding(10, 5);
final JPanel parametersPanel = new JPanel(layout);
parametersPanel.add(validPixelExpressionLabel);
parametersPanel.add(validPixelExpressionField);
parametersPanel.add(validPixelExpressionButton);
parametersPanel.add(targetHeightLabel);
parametersPanel.add(numRowsTextField);
parametersPanel.add(resolutionLabel);
parametersPanel.add(resolutionTextField);
parametersPanel.add(resolutionButton);
parametersPanel.add(superSamplingLabel);
parametersPanel.add(superSamplingTextField);
return parametersPanel;
}
private static int computeNumRows(double resolution) {
final double RE = 6378.145;
int numRows = (int) ((RE * Math.PI) / resolution) + 1;
return numRows % 2 == 0 ? numRows : numRows + 1;
}
private static double computeResolution(int numRows) {
final double RE = 6378.145;
return (RE * Math.PI) / (numRows - 1);
}
private static void updateResolutionLabel(JTextField targetHeightTextField, JTextField resolutionField, ResolutionTextFieldListener listener) {
resolutionField.setText(getResolutionString(Integer.parseInt(targetHeightTextField.getText())));
listener.update();
}
static String getResolutionString(int numRows) {
double number = computeResolution(numRows);
return getString(number);
}
private static String getString(double number) {
final DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols();
formatSymbols.setDecimalSeparator('.');
final DecimalFormat decimalFormat = new DecimalFormat("#.##", formatSymbols);
return decimalFormat.format(number);
}
private boolean hasSourceProducts() {
return binningFormModel.getContextProduct() != null;
}
private String editExpression(String expression) {
final Product product = binningFormModel.getContextProduct();
if (product == null) {
return null;
}
final ProductExpressionPane expressionPane;
expressionPane = ProductExpressionPane.createBooleanExpressionPane(new Product[]{product}, product, appContext.getPreferences());
expressionPane.setCode(expression);
final int i = expressionPane.showModalDialog(appContext.getApplicationWindow(), "Expression Editor");
if (i == ModalDialog.ID_OK) {
return expressionPane.getCode();
}
return null;
}
private JPanel createAggregatorsPanel() {
final Grid grid = new Grid(6, false);
TableLayout gridLayout = grid.getLayout();
gridLayout.setTablePadding(4, 3);
gridLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST);
gridLayout.setColumnFill(2, TableLayout.Fill.HORIZONTAL);
gridLayout.setColumnFill(3, TableLayout.Fill.HORIZONTAL);
gridLayout.setColumnFill(4, TableLayout.Fill.HORIZONTAL);
gridLayout.setColumnWeightX(2, 1.0);
gridLayout.setColumnWeightX(3, 1.0);
gridLayout.setColumnWeightX(4, 1.0);
grid.setHeaderRow(
/*0*/ //selection column
/*1*/ new JLabel("<html><b>Aggregator</b>"),
/*2*/ new JLabel("<html><b>Source Bands</b>"),
/*3*/ new JLabel("<html><b>Parameters</b>"),
/*4*/ new JLabel("<html><b>Target Bands</b>"),
/*5*/ null // column for edit button
);
aggregatorTableController = new AggregatorTableController(grid, binningFormModel);
final ListControlBar gridControlBar = ListControlBar.create(ListControlBar.HORIZONTAL, grid, aggregatorTableController);
final AbstractButton sel = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ShowSelection16.png"), true);
sel.setToolTipText("Show/hide selection column");
sel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
grid.setShowSelectionColumn(sel.isSelected());
gridControlBar.updateState();
}
});
gridControlBar.add(sel, 0);
JPanel panel = new JPanel(new BorderLayout(4, 4));
panel.setBorder(new EmptyBorder(4, 4, 4, 4));
panel.add(gridControlBar, BorderLayout.NORTH);
panel.add(new JScrollPane(grid), BorderLayout.CENTER);
return panel;
}
private JPanel createVariablesPanel() {
final Grid grid = new Grid(5, false);
TableLayout gridLayout = grid.getLayout();
gridLayout.setTablePadding(4, 3);
gridLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST);
gridLayout.setColumnFill(2, TableLayout.Fill.HORIZONTAL);
gridLayout.setColumnWeightX(2, 1.0);
grid.setHeaderRow(
/*0*/ //selection column
/*1*/ new JLabel("<html><b>Name</b>"),
/*2*/ new JLabel("<html><b>Expression</b>"),
/*3*/ new JLabel("<html><b>Valid-Pixel Expression</b>"),
/*5*/ null // column for edit button
);
variableTableController = new VariableTableController(grid, binningFormModel);
final ListControlBar gridControlBar = ListControlBar.create(ListControlBar.HORIZONTAL, grid, variableTableController);
final AbstractButton sel = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ShowSelection16.png"), true);
sel.setToolTipText("Show/hide selection column");
sel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
grid.setShowSelectionColumn(sel.isSelected());
gridControlBar.updateState();
}
});
gridControlBar.add(sel, 0);
JPanel panel = new JPanel(new BorderLayout(4, 4));
panel.setBorder(new TitledBorder("Intermediate Source Bands (optional)"));
panel.add(gridControlBar, BorderLayout.NORTH);
panel.add(new JScrollPane(grid), BorderLayout.CENTER);
return panel;
}
private static class IntegerTextField extends JTextField {
private final static String disallowedChars = "`§~!@#$%^&*()_+=\\|\"':;?/>.<,- ";
public IntegerTextField(int defaultValue) {
super(defaultValue + "");
}
@Override
protected void processKeyEvent(KeyEvent e) {
if (!Character.isLetter(e.getKeyChar()) && disallowedChars.indexOf(e.getKeyChar()) == -1) {
super.processKeyEvent(e);
}
}
}
private class DoubleTextField extends JTextField {
private final static String disallowedChars = "`§~!@#$%^&*()_+=\\|\"':;?/><,- ";
public DoubleTextField(String defaultValue) {
super(defaultValue);
}
@Override
protected void processKeyEvent(KeyEvent e) {
if (!Character.isLetter(e.getKeyChar()) && disallowedChars.indexOf(e.getKeyChar()) == -1) {
super.processKeyEvent(e);
}
}
}
private class ResolutionTextFieldListener extends FocusAdapter implements ActionListener {
private final JTextField resolutionTextField;
private final JTextField numRowsTextField;
public ResolutionTextFieldListener(JTextField resolutionTextField, JTextField numRowsTextField) {
this.resolutionTextField = resolutionTextField;
this.numRowsTextField = numRowsTextField;
}
@Override
public void focusLost(FocusEvent e) {
update();
}
@Override
public void actionPerformed(ActionEvent e) {
update();
}
private void update() {
double resolution = Double.parseDouble(resolutionTextField.getText());
if (Math.abs(currentGridResolution - resolution) > 1E-6) {
binningFormModel.getBindingContext().getPropertySet().setValue(BinningFormModel.PROPERTY_KEY_NUM_ROWS, computeNumRows(resolution));
numRowsTextField.setText(String.valueOf(computeNumRows(resolution)));
currentGridResolution = resolution;
}
}
}
}
| 16,165 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AggregatorTableController.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/main/java/org/esa/snap/binning/operator/ui/AggregatorTableController.java | package org.esa.snap.binning.operator.ui;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.swing.Grid;
import com.bc.ceres.swing.ListControlBar;
import org.esa.snap.binning.AggregatorConfig;
import org.esa.snap.binning.operator.VariableConfig;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
/**
* @author Norman Fomferra
*/
class AggregatorTableController extends ListControlBar.AbstractListController {
private final Grid grid;
private final BinningFormModel binningFormModel;
private final List<AggregatorItem> aggregatorItems;
AggregatorTableController(Grid grid, BinningFormModel binningFormModel) {
this.grid = grid;
this.binningFormModel = binningFormModel;
this.aggregatorItems = new ArrayList<>();
addAggregatorConfigs(this.binningFormModel.getAggregatorConfigs());
}
@Override
public boolean addRow(int index) {
boolean ok = editAggregatorItem(new AggregatorItem(), -1);
if (ok) {
updateBinningFormModel();
}
return ok;
}
@Override
public boolean removeRows(int[] indices) {
grid.removeDataRows(indices);
for (int i = indices.length - 1; i >= 0; i--) {
aggregatorItems.remove(indices[i]);
}
updateBinningFormModel();
return true;
}
@Override
public boolean moveRowUp(int index) {
grid.moveDataRowUp(index);
AggregatorItem ac1 = aggregatorItems.get(index - 1);
AggregatorItem ac2 = aggregatorItems.get(index);
aggregatorItems.set(index - 1, ac2);
aggregatorItems.set(index, ac1);
updateBinningFormModel();
return true;
}
@Override
public boolean moveRowDown(int index) {
grid.moveDataRowDown(index);
AggregatorItem ac1 = aggregatorItems.get(index);
AggregatorItem ac2 = aggregatorItems.get(index + 1);
aggregatorItems.set(index, ac2);
aggregatorItems.set(index + 1, ac1);
updateBinningFormModel();
return true;
}
void setAggregatorConfigs(AggregatorConfig[] configs) {
clearGrid();
addAggregatorConfigs(configs);
updateBinningFormModel();
}
static boolean isSourcePropertyName(String propertyName) {
return propertyName.toLowerCase().contains("varname");
}
private void clearGrid() {
int[] rowIndices = new int[grid.getDataRowCount()];
for (int i = 0; i < rowIndices.length; i++) {
rowIndices[i] = i;
}
removeRows(rowIndices);
}
private void addAggregatorConfigs(AggregatorConfig[] aggregatorConfigs) {
for (AggregatorConfig aggregatorConfig : aggregatorConfigs) {
addDataRow(new AggregatorItem(aggregatorConfig));
}
}
private void updateBinningFormModel() {
AggregatorConfig[] aggregatorConfigs = new AggregatorConfig[aggregatorItems.size()];
for (int i = 0; i < aggregatorItems.size(); i++) {
AggregatorItem aggregatorItem = aggregatorItems.get(i);
aggregatorConfigs[i] = aggregatorItem.aggregatorConfig;
}
try {
binningFormModel.setProperty(BinningFormModel.PROPERTY_KEY_AGGREGATOR_CONFIGS, aggregatorConfigs);
} catch (ValidationException e) {
Dialogs.showError("Aggregator Configuration", e.getMessage());
}
}
private boolean editAggregatorItem(AggregatorItem aggregatorItem, int rowIndex) {
Product contextProduct = binningFormModel.getContextProduct();
if (contextProduct == null) {
Dialogs.showInformation("Please select source products before adding aggregators.");
return false;
}
String[] varNames = getVariableNames(binningFormModel.getVariableConfigs());
String[] bandNames = contextProduct.getBandNames();
String[] tiePointGridNames = contextProduct.getTiePointGridNames();
String[] maskNames = contextProduct.getMaskGroup().getNodeNames();
String[] sourceNames = StringUtils.addArrays(varNames, bandNames);
sourceNames = StringUtils.addArrays(sourceNames, tiePointGridNames);
sourceNames = StringUtils.addArrays(sourceNames, maskNames);
boolean isNewAggregatorItem = rowIndex < 0;
ModalDialog aggregatorDialog = new AggregatorItemDialog(SwingUtilities.getWindowAncestor(grid), sourceNames, aggregatorItem, isNewAggregatorItem);
int result = aggregatorDialog.show();
if (result == ModalDialog.ID_OK) {
if (isNewAggregatorItem) {
addDataRow(aggregatorItem);
} else {
updateDataRow(aggregatorItem, rowIndex);
}
return true;
}
return false;
}
private String[] getVariableNames(VariableConfig[] variableConfigs) {
String[] varNames = new String[variableConfigs.length];
for (int i = 0; i < variableConfigs.length; i++) {
varNames[i] = variableConfigs[i].getName();
}
return varNames;
}
private void addDataRow(AggregatorItem ac) {
EmptyBorder emptyBorder = new EmptyBorder(2, 2, 2, 2);
JLabel typeLabel = new JLabel(getTypeText(ac));
typeLabel.setBorder(emptyBorder);
JLabel sourceBandsLabel = new JLabel(getSourceBandsText(ac));
sourceBandsLabel.setBorder(emptyBorder);
JLabel parametersLabel = new JLabel(getParametersText(ac));
parametersLabel.setBorder(emptyBorder);
JLabel targetBandsLabel = new JLabel(getTargetBandsText(ac));
targetBandsLabel.setBorder(emptyBorder);
final AbstractButton editButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("/org/esa/snap/resources/images/icons/Edit16.gif"),
false);
editButton.setRolloverEnabled(true);
editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int rowIndex = grid.findDataRowIndex(editButton);
editAggregatorItem(aggregatorItems.get(rowIndex), rowIndex);
}
});
grid.addDataRow(
/*1*/ typeLabel,
/*2*/ sourceBandsLabel,
/*3*/ parametersLabel,
/*4*/ targetBandsLabel,
/*5*/ editButton);
aggregatorItems.add(ac);
}
private void updateDataRow(AggregatorItem ac, int rowIndex) {
JComponent[] components = grid.getDataRow(rowIndex);
((JLabel) components[0]).setText(getTypeText(ac));
((JLabel) components[1]).setText(getSourceBandsText(ac));
((JLabel) components[2]).setText(getParametersText(ac));
((JLabel) components[3]).setText(getTargetBandsText(ac));
updateBinningFormModel();
}
private String getTypeText(AggregatorItem ac) {
return "<html><b>" + (ac.aggregatorConfig.getName()) + "</b>";
}
private String getSourceBandsText(AggregatorItem ac) {
String[] sourceVarNames = ac.aggregatorDescriptor.getSourceVarNames(ac.aggregatorConfig);
return sourceVarNames.length != 0 ? "<html>" + StringUtils.join(sourceVarNames, "<br/>") : "";
}
private String getTargetBandsText(AggregatorItem ac) {
String[] targetVarNames = ac.aggregatorDescriptor.getTargetVarNames(ac.aggregatorConfig);
return targetVarNames.length != 0 ? "<html>" + StringUtils.join(targetVarNames, "<br/>") : "";
}
private String getParametersText(AggregatorItem ac) {
PropertySet container = ac.aggregatorConfig.asPropertySet();
StringBuilder sb = new StringBuilder();
for (Property property : container.getProperties()) {
String propertyName = property.getName();
if (!(isSourcePropertyName(propertyName) || propertyName.equals("type"))) {
if (sb.length() > 0) {
sb.append("<br/>");
}
sb.append(String.format("%s = %s", propertyName, property.getValueAsText()));
}
}
return "<html>" + sb.toString();
}
}
| 8,768 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VariableItemDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/main/java/org/esa/snap/binning/operator/ui/VariableItemDialog.java | package org.esa.snap.binning.operator.ui;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.binding.Validator;
import com.bc.ceres.swing.TableLayout;
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.TextComponentAdapter;
import com.bc.ceres.swing.binding.internal.TextFieldEditor;
import org.esa.snap.binning.operator.VariableConfig;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.dataop.barithm.BandArithmetic;
import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory;
import org.esa.snap.core.jexp.ParseException;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.ui.AbstractDialog;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.product.ProductExpressionPane;
import javax.swing.*;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class VariableItemDialog extends ModalDialog {
private static final String PROPERTY_VARIABLE_NAME = "name";
private static final String PROPERTY_EXPRESSION = "expr";
private static final String PROPERTY_VALID_EXPRESSION = "validExpr";
private final VariableItem variableItem;
private final boolean newVariable;
private final Product contextProduct;
private final BindingContext bindingContext;
VariableItemDialog(final Window parent, VariableItem variableItem, boolean createNewVariable, Product contextProduct) {
super(parent, "Intermediate Source Band", ID_OK_CANCEL, null);
this.variableItem = variableItem;
newVariable = createNewVariable;
this.contextProduct = contextProduct;
bindingContext = createBindingContext();
makeUI();
}
@Override
protected boolean verifyUserInput() {
String expression = variableItem.variableConfig.getExpr() != null ? variableItem.variableConfig.getExpr().trim() : "";
if (StringUtils.isNullOrEmpty(expression)) {
AbstractDialog.showInformationDialog(getParent(), "The source band could not be created. The expression is empty.", "Information");
return false;
}
String variableName = variableItem.variableConfig.getName() != null ? variableItem.variableConfig.getName().trim() : "";
if (StringUtils.isNullOrEmpty(variableName)) {
AbstractDialog.showInformationDialog(getParent(), "The source band could not be created. The name is empty.", "Information");
return false;
}
if (newVariable && contextProduct.containsBand(variableName)) {
String message = String.format("A source band or band with the name '%s' is already defined", variableName);
AbstractDialog.showInformationDialog(getParent(), message, "Information");
return false;
}
try {
BandArithmetic.getValidMaskExpression(expression, contextProduct, null);
} catch (ParseException e) {
String errorMessage = "The source band could not be created.\nThe expression could not be parsed:\n" + e.getMessage(); /*I18N*/
AbstractDialog.showErrorDialog(getParent(), errorMessage, "Error");
return false;
}
String validExpression = variableItem.variableConfig.getValidExpr() != null ? variableItem.variableConfig.getValidExpr().trim() : "";
if (!validExpression.isEmpty()) {
try {
BandArithmetic.parseExpression(validExpression, new Product[]{contextProduct}, 0);
} catch (ParseException e) {
String errorMessage = "The valid pixel expression could not be parsed:\n" + e.getMessage(); /*I18N*/
JOptionPane.showMessageDialog(getParent(), errorMessage);
return false;
}
}
return true;
}
@Override
protected void onOK() {
VariableConfig vc = variableItem.variableConfig;
vc.setName(vc.getName().trim());
vc.setExpr(vc.getExpr().trim());
vc.setValidExpr(vc.getValidExpr() != null ? vc.getValidExpr().trim() : "");
super.onOK();
}
VariableItem getVariableItem() {
return variableItem;
}
private BindingContext createBindingContext() {
final PropertyContainer container = PropertyContainer.createObjectBacked(variableItem.variableConfig, new ParameterDescriptorFactory());
final BindingContext context = new BindingContext(container);
PropertyDescriptor descriptor = container.getDescriptor(PROPERTY_VARIABLE_NAME);
descriptor.setDescription("The name for the source band.");
descriptor.setValidator(new VariableNameValidator());
container.setDefaultValues();
return context;
}
private void makeUI() {
JComponent[] variableComponents = createComponents(PROPERTY_VARIABLE_NAME, TextFieldEditor.class);
final TableLayout layout = new TableLayout(3);
layout.setTableFill(TableLayout.Fill.HORIZONTAL);
layout.setTablePadding(4, 3);
layout.setTableAnchor(TableLayout.Anchor.WEST);
layout.setTableWeightX(0.0);
layout.setCellWeightX(0, 1, 1.0);
layout.setCellWeightX(1, 1, 1.0);
layout.setCellWeightX(3, 2, 1.0);
layout.setCellWeightX(4, 1, 1.0);
layout.setCellWeightX(6, 2, 1.0);
layout.setCellColspan(0, 1, 2);
layout.setCellColspan(1, 1, 2);
layout.setCellColspan(2, 0, 3);
layout.setCellColspan(3, 0, 2);
layout.setCellColspan(4, 1, 2);
layout.setCellColspan(5, 0, 3);
layout.setCellColspan(6, 0, 2);
final JPanel panel = new JPanel(layout);
// row 0
panel.add(variableComponents[1]);
// panel.add(layout.createHorizontalSpacer());
panel.add(variableComponents[0]);
JLabel expressionLabel = new JLabel("Variable expression:");
JTextArea expressionArea = new JTextArea();
expressionArea.setRows(3);
expressionArea.setColumns(80);
expressionArea.setLineWrap(true);
expressionArea.setWrapStyleWord(true);
bindingContext.bind(PROPERTY_EXPRESSION, new TextComponentAdapter(expressionArea));
// row 1
panel.add(expressionLabel);
panel.add(layout.createHorizontalSpacer());
// row 2
panel.add(expressionArea);
JButton editExpressionButton = new JButton("Edit...");
editExpressionButton.setName("editExpressionButton");
editExpressionButton.addActionListener(createEditExpressionButtonListener());
// row 3
panel.add(layout.createHorizontalSpacer());
panel.add(editExpressionButton);
JLabel validExpressionLabel = new JLabel("Valid-pixel expression:");
JTextArea validExpressionArea = new JTextArea();
validExpressionArea.setRows(3);
validExpressionArea.setColumns(80);
validExpressionArea.setLineWrap(true);
validExpressionArea.setWrapStyleWord(true);
bindingContext.bind(PROPERTY_VALID_EXPRESSION, new TextComponentAdapter(validExpressionArea));
// row 4
panel.add(validExpressionLabel);
panel.add(layout.createHorizontalSpacer());
// row 5
panel.add(validExpressionArea);
JButton editValidExpressionButton = new JButton("Edit...");
editValidExpressionButton.setName("editValidExpressionButton");
editValidExpressionButton.addActionListener(createEditValidExpressionButtonListener());
// row 6
panel.add(layout.createHorizontalSpacer());
panel.add(editValidExpressionButton);
setContent(panel);
}
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 ActionListener createEditExpressionButtonListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProductExpressionPane expressionPane =
ProductExpressionPane.createGeneralExpressionPane(new Product[]{contextProduct},
contextProduct,
null);
expressionPane.setCode(variableItem.variableConfig.getExpr());
int status = expressionPane.showModalDialog(getJDialog(), "Expression Editor");
if (status == ModalDialog.ID_OK) {
bindingContext.getBinding(PROPERTY_EXPRESSION).setPropertyValue(expressionPane.getCode());
}
expressionPane.dispose();
}
};
}
private ActionListener createEditValidExpressionButtonListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProductExpressionPane expressionPane =
ProductExpressionPane.createBooleanExpressionPane(new Product[]{contextProduct},
contextProduct,
null);
expressionPane.setCode(variableItem.variableConfig.getValidExpr());
int status = expressionPane.showModalDialog(getJDialog(), "Valid Expression Editor");
if (status == ModalDialog.ID_OK) {
bindingContext.getBinding(PROPERTY_VALID_EXPRESSION).setPropertyValue(expressionPane.getCode());
}
expressionPane.dispose();
}
};
}
private class VariableNameValidator implements Validator {
@Override
public void validateValue(Property property, Object value) throws ValidationException {
final String name = (String) value;
if (contextProduct.containsRasterDataNode(name)) {
throw new ValidationException("The source band name must be unique.");
}
}
}
}
| 10,615 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BinningForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/main/java/org/esa/snap/binning/operator/ui/BinningForm.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.binning.operator.ui;
import org.esa.snap.core.gpf.ui.TargetProductSelector;
import org.esa.snap.ui.AppContext;
import javax.swing.JTabbedPane;
/**
* The form for the {@link BinningDialog}.
*
* @author Olaf Danne
* @author Thomas Storm
*/
class BinningForm extends JTabbedPane {
private final BinningIOPanel ioPanel;
private BinningConfigurationPanel configurationPanel;
BinningForm(AppContext appContext, BinningFormModel binningFormModel, TargetProductSelector targetProductSelector) {
ioPanel = new BinningIOPanel(appContext, binningFormModel, targetProductSelector);
addTab("I/O Parameters", ioPanel);
addTab("Filter", new BinningFilterPanel(binningFormModel));
configurationPanel = new BinningConfigurationPanel(appContext, binningFormModel);
addTab("Configuration", configurationPanel);
}
void prepareClose() {
ioPanel.prepareClose();
}
public BinningConfigurationPanel getBinningConfigurationPanel() {
return configurationPanel;
}
}
| 1,782 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BinningOperatorAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/main/java/org/esa/snap/binning/operator/ui/BinningOperatorAction.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.binning.operator.ui;
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;
/**
* Action for starting the GPF binning operator user interface.
*
* @author Tonio Fincke
* @author Thomas Storm
* @author Marco Peters
*/
@ActionID(category = "Processors", id = "org.esa.snap.binning.operator.ui.BinningOperatorAction")
@ActionRegistration(displayName = "#CTL_BinningOperatorAction_Text", lazy = false)
@ActionReference(path = "Menu/Raster/Geometric", position = 40)
@NbBundle.Messages({
"CTL_BinningOperatorAction_Text=Level-3 Binning",
"CTL_BinningOperatorAction_Description=Spatial and temporal aggregation of input products."
})
public class BinningOperatorAction extends AbstractSnapAction {
private static final String HELP_ID = "binning_overview";
private static final String OPERATOR_NAME = "Binning";
private ModelessDialog dialog;
public BinningOperatorAction() {
putValue(NAME, Bundle.CTL_BinningOperatorAction_Text());
putValue(SHORT_DESCRIPTION, Bundle.CTL_BinningOperatorAction_Description());
setHelpId(HELP_ID);
}
@Override
public void actionPerformed(ActionEvent e) {
if (dialog == null) {
dialog = new BinningDialog(getAppContext(), OPERATOR_NAME, HELP_ID);
}
dialog.show();
}
}
| 2,278 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AggregatorItem.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-binning-ui/src/main/java/org/esa/snap/binning/operator/ui/AggregatorItem.java | package org.esa.snap.binning.operator.ui;
import org.esa.snap.binning.AggregatorConfig;
import org.esa.snap.binning.AggregatorDescriptor;
import org.esa.snap.binning.TypedDescriptorsRegistry;
import org.esa.snap.binning.aggregators.AggregatorAverage;
/**
* @author Norman Fomferra
*/
class AggregatorItem {
AggregatorDescriptor aggregatorDescriptor;
AggregatorConfig aggregatorConfig;
AggregatorItem() {
this.aggregatorDescriptor = new AggregatorAverage.Descriptor();
this.aggregatorConfig = aggregatorDescriptor.createConfig();
}
AggregatorItem(AggregatorConfig aggregatorConfig) {
this.aggregatorConfig = aggregatorConfig;
this.aggregatorDescriptor = TypedDescriptorsRegistry.getInstance().getDescriptor(AggregatorDescriptor.class, aggregatorConfig.getName());
}
}
| 828 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SpringUtilities.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/utils/SpringUtilities.java | /*
* Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle or the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.esa.snap.utils;
import javax.swing.*;
import java.awt.*;
/**
* A 1.4 file that provides utility methods for
* creating form- or grid-style layouts with SpringLayout.
* These utilities are used by several programs, such as
* SpringBox and SpringCompactGrid.
*/
public class SpringUtilities {
public static final int DEFAULT_PADDING = 2;
/**
* A debugging utility that prints to stdout the component's
* minimum, preferred, and maximum sizes.
*/
public static void printSizes(Component c) {
System.out.println("minimumSize = " + c.getMinimumSize());
System.out.println("preferredSize = " + c.getPreferredSize());
System.out.println("maximumSize = " + c.getMaximumSize());
}
/**
* Aligns the first <code>rows</code> * <code>cols</code>
* components of <code>operatorDescriptor</code> in
* a grid. Each component is as big as the maximum
* preferred width and height of the components.
* The operatorDescriptor is made just big enough to fit them all.
*
* @param rows number of rows
* @param cols number of columns
* @param initialX x location to start the grid at
* @param initialY y location to start the grid at
* @param xPad x padding between cells
* @param yPad y padding between cells
*/
public static void makeGrid(Container parent,
int rows, int cols,
int initialX, int initialY,
int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout)parent.getLayout();
} catch (ClassCastException exc) {
System.err.println("The first argument to makeGrid must use SpringLayout.");
return;
}
Spring xPadSpring = Spring.constant(xPad);
Spring yPadSpring = Spring.constant(yPad);
Spring initialXSpring = Spring.constant(initialX);
Spring initialYSpring = Spring.constant(initialY);
int max = rows * cols;
//Calculate Springs that are the max of the width/height so that all
//cells have the same size.
Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)).
getWidth();
Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)).
getHeight();
for (int i = 1; i < max; i++) {
SpringLayout.Constraints cons = layout.getConstraints(
parent.getComponent(i));
maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth());
maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight());
}
//Apply the new width/height Spring. This forces all the
//components to have the same size.
for (int i = 0; i < max; i++) {
SpringLayout.Constraints cons = layout.getConstraints(
parent.getComponent(i));
cons.setWidth(maxWidthSpring);
cons.setHeight(maxHeightSpring);
}
//Then adjust the x/y constraints of all the cells so that they
//are aligned in a grid.
SpringLayout.Constraints lastCons = null;
SpringLayout.Constraints lastRowCons = null;
for (int i = 0; i < max; i++) {
SpringLayout.Constraints cons = layout.getConstraints(
parent.getComponent(i));
if (i % cols == 0) { //start of new row
lastRowCons = lastCons;
cons.setX(initialXSpring);
} else { //x position depends on previous component
cons.setX(Spring.sum(lastCons != null ? lastCons.getConstraint(SpringLayout.EAST) : null,
xPadSpring));
}
if (i / cols == 0) { //first row
cons.setY(initialYSpring);
} else { //y position depends on previous row
cons.setY(Spring.sum(lastRowCons != null ? lastRowCons.getConstraint(SpringLayout.SOUTH) : null,
yPadSpring));
}
lastCons = cons;
}
//Set the operatorDescriptor's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH,
Spring.sum(
Spring.constant(yPad),
lastCons != null ? lastCons.getConstraint(SpringLayout.SOUTH) : null));
pCons.setConstraint(SpringLayout.EAST,
Spring.sum(
Spring.constant(xPad),
lastCons != null ? lastCons.getConstraint(SpringLayout.EAST) : null));
}
/* Used by makeCompactGrid. */
private static SpringLayout.Constraints getConstraintsForCell(
int row, int col,
Container parent,
int cols) {
SpringLayout layout = (SpringLayout) parent.getLayout();
Component c = parent.getComponent(row * cols + col);
return layout.getConstraints(c);
}
/**
* Aligns the first <code>rows</code> * <code>cols</code>
* components of <code>operatorDescriptor</code> in
* a grid. Each component in a column is as wide as the maximum
* preferred width of the components in that column;
* height is similarly determined for each row.
* The operatorDescriptor is made just big enough to fit them all.
*
* @param rows number of rows
* @param cols number of columns
* @param initialX x location to start the grid at
* @param initialY y location to start the grid at
* @param xPad x padding between cells
* @param yPad y padding between cells
*/
public static void makeCompactGrid(Container parent,
int rows, int cols,
int initialX, int initialY,
int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout)parent.getLayout();
} catch (ClassCastException exc) {
System.err.println("The first argument to makeCompactGrid must use SpringLayout.");
return;
}
//Align all cells in each column and make them the same width.
Spring x = Spring.constant(initialX);
for (int c = 0; c < cols; c++) {
Spring width = Spring.constant(0);
for (int r = 0; r < rows; r++) {
width = Spring.max(width,
getConstraintsForCell(r, c, parent, cols).
getWidth());
}
for (int r = 0; r < rows; r++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setX(x);
constraints.setWidth(width);
}
x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
}
//Align all cells in each row and make them the same height.
Spring y = Spring.constant(initialY);
for (int r = 0; r < rows; r++) {
Spring height = Spring.constant(0);
for (int c = 0; c < cols; c++) {
height = Spring.max(height,
getConstraintsForCell(r, c, parent, cols).
getHeight());
}
for (int c = 0; c < cols; c++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setY(y);
constraints.setHeight(height);
}
y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
}
//Set the operatorDescriptor's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH, y);
pCons.setConstraint(SpringLayout.EAST, x);
}
}
| 9,590 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
UIUtils.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/utils/UIUtils.java | /*
*
* * Copyright (C) 2016 CS ROMANIA
* *
* * 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.utils;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.validators.NotEmptyValidator;
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.TextFieldEditor;
import org.esa.snap.core.util.StringUtils;
import org.jdesktop.swingx.prompt.PromptSupport;
import javax.swing.*;
import javax.swing.text.JTextComponent;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Created by kraftek on 12/5/2016.
*/
public class UIUtils {
private static final String FILE_FIELD_PROMPT = "browse for %s";
private static final String TEXT_FIELD_PROMPT = "enter %s here";
private static final String CAMEL_CASE_SPLIT = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])";
private static class UndoAction extends AbstractAction {
private UndoManager undoManager;
UndoAction(UndoManager manager) {
this.undoManager = manager;
}
@Override
public void actionPerformed(ActionEvent e) {
try {
if (undoManager != null && undoManager.canUndo()) {
undoManager.undo();
}
} catch (CannotUndoException ignored) {}
}
};
private static class RedoAction extends AbstractAction {
private UndoManager undoManager;
RedoAction(UndoManager manager) {
this.undoManager = manager;
}
@Override
public void actionPerformed(ActionEvent e) {
try {
if (undoManager != null && undoManager.canRedo()) {
undoManager.redo();
}
} catch (CannotUndoException ignored) {}
}
};
public static JTextField addTextField(JPanel parent, TextFieldEditor textEditor, String labelText,
PropertyContainer propertyContainer, BindingContext bindingContext,
String propertyName, boolean isRequired) {
parent.add(new JLabel(labelText));
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor(propertyName);
if (isRequired) {
propertyDescriptor.setValidator(new NotEmptyValidator());
}
JComponent editorComponent = textEditor.createEditorComponent(propertyDescriptor, bindingContext);
UIUtils.addPromptSupport(editorComponent, "enter " + labelText.toLowerCase().replace(":", "") + " here");
UIUtils.enableUndoRedo(editorComponent);
parent.add(editorComponent);
return (JTextField) editorComponent;
}
public static List<JRadioButton> addChoiceField(JPanel parent, String label, Map<String, String> valuesAndLabels,
PropertyContainer propertyContainer, String propertyName, Class enumClass) {
parent.add(new JLabel(label));
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor(propertyName);
ButtonGroup rbGroup = new ButtonGroup();
java.util.List<JRadioButton> components = new ArrayList<>(valuesAndLabels.size());
for (Map.Entry<String, String> choice : valuesAndLabels.entrySet()) {
JRadioButton button = new JRadioButton(choice.getValue());
button.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
propertyDescriptor.setDefaultValue(Enum.valueOf(enumClass, choice.getKey()));
}
});
rbGroup.add(button);
parent.add(button);
components.add(button);
}
return components;
}
public static JComboBox addComboField(JPanel parent, String labelText, PropertyContainer propertyContainer, BindingContext bindingContext,
String propertyName, GridBagConstraints constraints) {
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor(propertyName);
PropertyEditor editor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
JComponent editorComponent = editor.createEditorComponent(propertyDescriptor, bindingContext);
if (editorComponent instanceof JComboBox) {
JComboBox comboBox = (JComboBox)editorComponent;
comboBox.setEditable(false);
comboBox.setEnabled(true);
parent.add(new JLabel(labelText));
parent.add(editorComponent);
return comboBox;
}
return null;
}
public static void addPromptSupport(JComponent component, String text) {
if (JTextComponent.class.isAssignableFrom(component.getClass())) {
JTextComponent castedComponent = (JTextComponent) component;
PromptSupport.setPrompt(text, castedComponent);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.HIDE_PROMPT, castedComponent);
}
}
public static void addPromptSupport(JComponent component, Property property) {
addPromptSupport(component, property, null);
}
public static void addPromptSupport(JComponent component, Property property, String promptText) {
if (JTextComponent.class.isAssignableFrom(component.getClass())) {
JTextComponent castedComponent = (JTextComponent) component;
String text;
if (File.class.isAssignableFrom(property.getType())) {
text = promptText != null ? promptText :
String.format(FILE_FIELD_PROMPT, separateWords(property.getName()));
} else {
if (promptText == null) {
text = property.getDescriptor().getDescription();
if (StringUtils.isNullOrEmpty(text)) {
text = String.format(TEXT_FIELD_PROMPT, separateWords(property.getName()));
}
} else {
text = promptText;
}
}
PromptSupport.setPrompt(text, castedComponent);
PromptSupport.setFocusBehavior(PromptSupport.FocusBehavior.HIDE_PROMPT, castedComponent);
}
}
public static void enableUndoRedo(JComponent component) {
if (component != null) {
if (JTextComponent.class.isAssignableFrom(component.getClass())) {
UndoManager undoManager = new UndoManager();
((JTextComponent) component).getDocument().addUndoableEditListener(e -> undoManager.addEdit(e.getEdit()));
InputMap inputMap = component.getInputMap(JComponent.WHEN_FOCUSED);
ActionMap actionMap = component.getActionMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "Undo");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "Redo");
actionMap.put("Undo", new UndoAction(undoManager));
actionMap.put("Redo", new RedoAction(undoManager));
} else if (JPanel.class.equals(component.getClass())) {
Arrays.stream(component.getComponents())
.filter(c -> JTextComponent.class.isAssignableFrom(c.getClass()))
.map(c -> (JTextComponent) c)
.forEach(UIUtils::enableUndoRedo);
}
}
}
private static String separateWords(String text) {
return separateWords(text, true);
}
private static String separateWords(String text, boolean lowerCase) {
String[] words = text.split(CAMEL_CASE_SPLIT);
if (lowerCase) {
for (int i = 0; i < words.length; i++) {
words[i] = words[i].toLowerCase();
}
}
return String.join(" ", words);
}
}
| 9,053 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AdapterWatcher.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/utils/AdapterWatcher.java | /*
*
* * Copyright (C) 2016 CS ROMANIA
* *
* * 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.utils;
import org.esa.snap.core.gpf.OperatorException;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterIO;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterRegistry;
import org.esa.snap.modules.ModulePackager;
import org.openide.modules.Places;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* This singleton class watches for changes (additions/deletions) in the tool adapters folder.
*
* @author Cosmin Cara
*/
public enum AdapterWatcher {
INSTANCE;
private final Logger logger = Logger.getLogger(AdapterWatcher.class.getName());
private WatchService watcher;
private final WatchEvent.Kind[] eventTypes = new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE };
private Thread thread;
private volatile boolean isRunning;
private volatile boolean isSuspended;
private Map<Path, String> jarAliases;
private Map<Path, WatchKey> monitoredPaths;
AdapterWatcher() {
try {
watcher = FileSystems.getDefault().newWatchService();
monitoredPaths = new HashMap<>();
jarAliases = new HashMap<>();
Path adaptersFolder = ToolAdapterIO.getAdaptersPath();
File userDirectory = Places.getUserDirectory();
Path nbUserModulesPath = Paths.get(userDirectory != null ? userDirectory.getAbsolutePath() : "", "modules");
if (!Files.exists(nbUserModulesPath)) {
Files.createDirectory(nbUserModulesPath);
}
readMap();
monitorPath(adaptersFolder);
monitorPath(nbUserModulesPath);
File[] jars = nbUserModulesPath.toFile().listFiles(pathname -> pathname.getName().toLowerCase().endsWith("jar"));
if (jars != null) {
Arrays.stream(jars)
.forEach(f -> {
try {
processJarFile(f.toPath());
} catch (Exception ex) {
logger.warning(ex.getMessage());
}
});
}
handleUninstalledModules();
thread = new Thread(() -> {
while (isRunning) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
return;
}
key.pollEvents().forEach(event -> {
WatchEvent.Kind<?> kind = event.kind();
@SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();
boolean isJar = fileName.toString().endsWith(".jar");
if (!isSuspended) {
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
if (!isJar) {
folderAdded(adaptersFolder.resolve(fileName));
} else {
jarAdded(nbUserModulesPath.resolve(fileName));
}
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
if (!isJar) {
folderDeleted(adaptersFolder.resolve(fileName));
} else {
jarDeleted(nbUserModulesPath.resolve(fileName));
}
}
}
});
boolean valid = key.reset();
if (!valid) {
break;
}
}
});
} catch (IOException ignored) {
}
}
/**
* Enables this watch service to monitor the registered paths
*/
public void startMonitor() {
isRunning = true;
isSuspended = false;
thread.start();
}
/**
* Stops this watch service to monitor the registered paths
*/
public void stopMonitor() {
isRunning = false;
}
/**
* Pauses monitoring on the registered paths
*/
public void suspend() {
isSuspended = true;
}
/**
* Resumes monitoring on the registered paths
*/
public void resume() {
isSuspended = false;
}
/**
* Registers the watch service for the given path to monitor changes.
*
* @param path The path to monitor
*/
public void monitorPath(Path path) throws IOException {
if (path != null && Files.isDirectory(path)) {
WatchKey key = path.register(watcher, eventTypes);
monitoredPaths.put(path, key);
logger.fine(String.format("Registered %s for watching", path.toString()));
}
}
/**
* Unregisters the watch service from the given path.
*
* @param path The path to unregister for
*/
public void unmonitorPath(Path path) {
if (path != null && Files.isDirectory(path)) {
WatchKey key = monitoredPaths.remove(path);
if (key != null) {
key.cancel();
logger.fine(String.format("Unregistered %s for watching", path.toString()));
}
}
}
private void handleUninstalledModules() {
Path[] paths = new Path[jarAliases.size()];
jarAliases.keySet().toArray(paths);
for (Path path : paths) {
if (!Files.exists(path)) {
jarDeleted(path);
}
}
}
private void folderAdded(Path folder) {
try {
Thread.sleep(500);
ToolAdapterIO.registerAdapter(folder);
}catch (InterruptedException | OperatorException ex){
logger.warning("Could not load adapter for folder added in repository: " + folder.toString() + " (error:" + ex.getMessage());
}
}
private void folderDeleted(Path folder) {
if (folder != null) {
String alias = folder.toFile().getName();
ToolAdapterOperatorDescriptor operatorDescriptor = ToolAdapterRegistry.INSTANCE.findByAlias(alias);
if (operatorDescriptor != null) {
ToolAdapterIO.removeOperator(operatorDescriptor);
}
}
}
private void jarAdded(Path jarFile) {
Path unpackLocation = processJarFile(jarFile);
if (unpackLocation != null) {
suspend();
folderAdded(unpackLocation);
saveMap();
resume();
} else {
logger.warning(String.format("Jar %s has not been unpacked.", jarFile.toString()));
}
}
private void jarDeleted(Path jarFile) {
String alias = jarAliases.get(jarFile);
if (alias == null) {
String fileName = jarFile.getFileName().toString().replace(".jar", "");
int idx = fileName.lastIndexOf(".");
if (idx > 0) {
alias = fileName.substring(idx + 1);
} else {
alias = fileName;
}
}
ToolAdapterOperatorDescriptor operatorDescriptor = ToolAdapterRegistry.INSTANCE.findByAlias(alias);
if (operatorDescriptor != null) {
suspend();
ToolAdapterIO.removeOperator(operatorDescriptor);
jarAliases.remove(jarFile);
saveMap();
resume();
} else {
logger.warning(String.format("Cannot find adapter for %s", jarFile.toString()));
}
}
private Path processJarFile(Path jarFile) {
Path destination = null;
String aliasOrName = null;
try {
aliasOrName = ModulePackager.getAdapterAlias(jarFile.toFile());
} catch (IOException ignored) {
}
if (aliasOrName != null) {
jarAliases.put(jarFile, aliasOrName);
destination = ToolAdapterIO.getAdaptersPath().resolve(aliasOrName);
try {
if (!Files.exists(destination)) {
ModulePackager.unpackAdapterJar(jarFile.toFile(), destination.toFile());
} else {
Path versionFile = destination.resolve("version.txt");
if (Files.exists(versionFile)) {
String versionText = new String(Files.readAllBytes(versionFile));
String jarVersion = ModulePackager.getAdapterVersion(jarFile.toFile());
if (jarVersion != null && !versionText.equals(jarVersion)) {
ModulePackager.unpackAdapterJar(jarFile.toFile(), destination.toFile());
logger.fine(String.format("The adapter with the name %s and version %s was replaced by version %s", aliasOrName, versionText, jarVersion));
} else {
logger.fine(String.format("An adapter with the name %s and version %s already exists", aliasOrName, versionText));
}
} else {
ModulePackager.unpackAdapterJar(jarFile.toFile(), destination.toFile());
}
}
} catch (Exception e) {
logger.severe(e.getMessage());
}
}
return destination;
}
private void saveMap() {
Path path = ToolAdapterIO.getAdaptersPath().resolve("installed.dat");
StringBuilder builder = new StringBuilder();
for (Map.Entry<Path, String> entry : jarAliases.entrySet()) {
builder.append(entry.getKey().toString())
.append(",")
.append(entry.getValue())
.append("\n");
}
try {
Files.write(path, builder.toString().getBytes());
} catch (IOException e) {
logger.severe(e.getMessage());
}
}
private void readMap() {
Path path = ToolAdapterIO.getAdaptersPath().resolve("installed.dat");
jarAliases.clear();
try {
if (Files.exists(path)) {
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
String[] tokens = line.split(",");
jarAliases.put(Paths.get(tokens[0]), tokens[1]);
}
}
} catch (IOException e) {
logger.severe(e.getMessage());
}
}
}
| 11,630 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RequiredFieldValidator.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/validators/RequiredFieldValidator.java | package org.esa.snap.ui.tooladapter.validators;
/**
* Simple class for validating that a text component has no null or empty input.
*
* @author Cosmin Cara
*/
public class RequiredFieldValidator extends TextFieldValidator {
public RequiredFieldValidator(String message) {
super(message);
}
@Override
protected boolean verifyValue(String text) {
return text != null && text.length() > 0;
}
}
| 434 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TextFieldValidator.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/validators/TextFieldValidator.java | package org.esa.snap.ui.tooladapter.validators;
import org.esa.snap.rcp.util.Dialogs;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.text.JTextComponent;
/**
* Base validator for text-input components
*
* @author Cosmin Cara
*/
public abstract class TextFieldValidator extends InputVerifier {
private String errorMessage;
public TextFieldValidator(String message) {
errorMessage = message;
}
@Override
public boolean verify(JComponent input) {
if (input instanceof JTextComponent) {
boolean isValid = false;
String text = ((JTextComponent) input).getText();
isValid = verifyValue(text);
if (!isValid) {
Dialogs.showError(errorMessage);
}
return isValid;
} else {
return true;
}
}
protected abstract boolean verifyValue(String text);
}
| 944 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RegexFieldValidator.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/validators/RegexFieldValidator.java | package org.esa.snap.ui.tooladapter.validators;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.binding.Validator;
import java.text.MessageFormat;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* Simple validator that checks a regex is compilable.
*
* @author Cosmin Cara
*/
public class RegexFieldValidator implements Validator {
@Override
public void validateValue(Property property, Object value) throws ValidationException {
if (value != null && !value.toString().trim().isEmpty()) {
try {
Pattern.compile(value.toString());
} catch (PatternSyntaxException e) {
throw new ValidationException(MessageFormat.format("The regular expression for ''{0}'' is not valid [{1}]",
property.getDescriptor().getDisplayName(), e.getMessage()));
}
}
}
}
| 965 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TypedValueValidator.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/validators/TypedValueValidator.java | package org.esa.snap.ui.tooladapter.validators;
/**
* Created by kraftek on 5/5/2015.
*/
public class TypedValueValidator extends TextFieldValidator {
private Class type;
public TypedValueValidator(String message, Class clazz) {
super(message);
this.type = clazz;
}
@Override
protected boolean verifyValue(String text) {
boolean isValid = false;
if (text != null) {
try {
Object cast = this.type.cast(text);
isValid = true;
} catch (Exception ignored) {
}
}
return isValid;
}
}
| 624 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DecoratedNotEmptyValidator.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/validators/DecoratedNotEmptyValidator.java | /*
*
* * Copyright (C) 2016 CS ROMANIA
* *
* * 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.ui.tooladapter.validators;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.binding.Validator;
import com.bc.ceres.binding.validators.NotEmptyValidator;
import org.esa.snap.tango.TangoIcons;
import javax.swing.JLabel;
/**
* @author kraftek
* @date 3/15/2017
*/
public class DecoratedNotEmptyValidator implements Validator {
private String[] excludedChars;
private JLabel label;
private NotEmptyValidator validator;
public DecoratedNotEmptyValidator(JLabel componentLabel, String[] excludedChars) {
this.validator = new NotEmptyValidator();
this.label = componentLabel;
this.excludedChars = excludedChars;
this.label.setText("<html><font color=\"#"
+ Integer.toHexString(this.label.getForeground().getRGB()).substring(2, 8)
+ "\">"
+ this.label.getText()
+ "</font><font color=\"RED\">*</font></html>");
}
@Override
public void validateValue(Property property, Object value) throws ValidationException {
try {
if (value != null) {
String stringValue = value.toString();
if (this.excludedChars != null) {
for (String exclChar : this.excludedChars) {
if (stringValue.contains(exclChar)) {
throw new ValidationException(String.format("Character '%s' not allowed", exclChar));
}
}
}
}
this.validator.validateValue(property, value);
this.label.setIcon(null);
this.label.setToolTipText(null);
} catch (ValidationException vex) {
this.label.setIcon(TangoIcons.status_dialog_error(TangoIcons.Res.R16));
throw vex;
}
}
}
| 2,657 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ToolAdapterOptionsController.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/preferences/ToolAdapterOptionsController.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.preferences;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.PropertyEditorRegistry;
import org.esa.snap.rcp.preferences.DefaultConfigController;
import org.esa.snap.rcp.preferences.Preference;
import org.esa.snap.rcp.util.Dialogs;
import org.netbeans.spi.options.OptionsPanelController;
import org.openide.util.HelpCtx;
import org.openide.util.NbPreferences;
import javax.swing.JComponent;
import javax.swing.JPanel;
import java.awt.Insets;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
/**
* Options controller for Standalone Tool Adapter.
*
* @author Cosmin Cara
*/
@OptionsPanelController.SubRegistration(location = "GeneralPreferences",
displayName = "#Options_DisplayName_STAOptions",
keywords = "#Options_Keywords_STAOptions",
keywordsCategory = "Tool Adapter",
id = "STA",
position = 7)
@org.openide.util.NbBundle.Messages({
"Options_DisplayName_STAOptions=Tool Adapter",
"Options_Keywords_STAOptions=adapter, tool"
})
public class ToolAdapterOptionsController extends DefaultConfigController {
public static final String PREFERENCE_KEY_VALIDATE_ON_SAVE = "sta.validate.save";
public static final String PREFERENCE_KEY_SHOW_EMPTY_PRODUCT_WARNING = "sta.warn.no.product";
public static final String PREFERENCE_KEY_AUTOCOMPLETE = "sta.autocomplete";
public static final String PREFERENCE_KEY_SHOW_EXECUTION_OUTPUT = "sta.display.output";
public static final boolean DEFAULT_VALUE_VALIDATE_PATHS = false;
public static final boolean DEFAULT_VALUE_SHOW_EMPTY_PRODUCT_WARINING = true;
public static final boolean DEFAULT_VALUE_SHOW_EXECUTION_OUTPUT = true;
public static final boolean DEFAULT_VALUE_AUTOCOMPLETE = false;
private static final String DECISION_SUFFIX = ".decision";
private BindingContext context;
private Preferences preferences;
@Override
protected PropertySet createPropertySet() {
return createPropertySet(new STAOptionsBean());
}
@Override
protected JPanel createPanel(BindingContext context) {
this.context = context;
preferences = NbPreferences.forModule(Dialogs.class);
TableLayout tableLayout = new TableLayout(1);
tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST);
tableLayout.setTablePadding(4, 10);
tableLayout.setTableFill(TableLayout.Fill.BOTH);
tableLayout.setTableWeightX(1.0);
tableLayout.setRowWeightY(4, 1.0);
JPanel pageUI = new JPanel(tableLayout);
PropertyEditorRegistry registry = PropertyEditorRegistry.getInstance();
Property pathValidationControl = context.getPropertySet().getProperty(PREFERENCE_KEY_VALIDATE_ON_SAVE);
setPropertyValue(pathValidationControl, DEFAULT_VALUE_VALIDATE_PATHS);
Property noProductWarningControl = context.getPropertySet().getProperty(PREFERENCE_KEY_SHOW_EMPTY_PRODUCT_WARNING);
setPropertyValue(noProductWarningControl, DEFAULT_VALUE_SHOW_EMPTY_PRODUCT_WARINING);
Property displayOutputControl = context.getPropertySet().getProperty(PREFERENCE_KEY_SHOW_EXECUTION_OUTPUT);
setPropertyValue(displayOutputControl, DEFAULT_VALUE_SHOW_EXECUTION_OUTPUT);
Property autocompleteControl = context.getPropertySet().getProperty(PREFERENCE_KEY_AUTOCOMPLETE);
setPropertyValue(autocompleteControl, DEFAULT_VALUE_AUTOCOMPLETE);
JComponent[] pathValidationComponents = registry.findPropertyEditor(pathValidationControl.getDescriptor()).createComponents(pathValidationControl.getDescriptor(), context);
JComponent[] noProductWarningComponents = registry.findPropertyEditor(noProductWarningControl.getDescriptor()).createComponents(noProductWarningControl.getDescriptor(), context);
JComponent[] displayOutputComponents = registry.findPropertyEditor(displayOutputControl.getDescriptor()).createComponents(displayOutputControl.getDescriptor(), context);
JComponent[] autocompleteComponents = registry.findPropertyEditor(autocompleteControl.getDescriptor()).createComponents(autocompleteControl.getDescriptor(), context);
tableLayout.setRowPadding(0, new Insets(10, 80, 10, 4));
pageUI.add(pathValidationComponents[0]);
pageUI.add(noProductWarningComponents[0]);
pageUI.add(displayOutputComponents[0]);
pageUI.add(autocompleteComponents[0]);
pageUI.add(tableLayout.createVerticalSpacer());
return pageUI;
}
@Override
public void update() {
Property property = context.getPropertySet().getProperty(PREFERENCE_KEY_VALIDATE_ON_SAVE);
if (property != null) {
preferences.put(PREFERENCE_KEY_VALIDATE_ON_SAVE, property.getValueAsText());
}
property = context.getPropertySet().getProperty(PREFERENCE_KEY_SHOW_EXECUTION_OUTPUT);
if (property != null) {
preferences.put(PREFERENCE_KEY_SHOW_EXECUTION_OUTPUT, property.getValueAsText());
}
property = context.getPropertySet().getProperty(PREFERENCE_KEY_AUTOCOMPLETE);
if (property != null) {
preferences.put(PREFERENCE_KEY_AUTOCOMPLETE, property.getValueAsText());
}
// decision preferences
property = context.getPropertySet().getProperty(PREFERENCE_KEY_SHOW_EMPTY_PRODUCT_WARNING);
if (property != null) {
if (Boolean.parseBoolean(property.getValueAsText())) {
preferences.remove(PREFERENCE_KEY_SHOW_EMPTY_PRODUCT_WARNING + DECISION_SUFFIX);
} else {
preferences.put(PREFERENCE_KEY_SHOW_EMPTY_PRODUCT_WARNING + DECISION_SUFFIX, "no");
}
}
try {
preferences.flush();
} catch (BackingStoreException ignored) {
}
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx("sta_editor");
}
private boolean getPropertyValue(String key, boolean defaultValue) {
if (preferences == null) {
preferences = NbPreferences.forModule(Dialogs.class);
}
return preferences.getBoolean(key, defaultValue);
}
private void setPropertyValue(Property property, boolean defaultValue) {
try {
property.setValue(getPropertyValue(property.getName(), defaultValue));
} catch (ValidationException e) {
e.printStackTrace();
}
}
static class STAOptionsBean {
@Preference(label = "Validate tool paths and variables on save", key = PREFERENCE_KEY_VALIDATE_ON_SAVE)
boolean validatePaths = DEFAULT_VALUE_VALIDATE_PATHS;
@Preference(label = "Display warning when source products are missing", key = PREFERENCE_KEY_SHOW_EMPTY_PRODUCT_WARNING)
boolean warnNoProduct = DEFAULT_VALUE_SHOW_EMPTY_PRODUCT_WARINING;
@Preference(label = "Display execution output", key = PREFERENCE_KEY_SHOW_EXECUTION_OUTPUT)
boolean displayOutput = DEFAULT_VALUE_SHOW_EXECUTION_OUTPUT;
@Preference(label = "Use autocomplete of parameters for template editing [experimental]", key = PREFERENCE_KEY_AUTOCOMPLETE)
boolean autocomplete = DEFAULT_VALUE_AUTOCOMPLETE;
}
}
| 8,143 | 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-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/docs/package-info.java | @HelpSetRegistration(helpSet = "help.hs", position = 2480)
package org.esa.snap.ui.tooladapter.docs;
import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration; | 163 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
EscapeAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/actions/EscapeAction.java | package org.esa.snap.ui.tooladapter.actions;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Convenience Action to dispose of a Swing Window by using the Escape key.
* Before disposing of the window the Action will first attempt to hide
* any popups. In this case the user will need to invoke the Escape key a
* second time before the Window is disposed.
*/
public class EscapeAction extends AbstractAction {
private static final String KEY_STROKE_AND_KEY = "ESCAPE";
private static final KeyStroke ESCAPE_KEY_STROKE = KeyStroke.getKeyStroke( KEY_STROKE_AND_KEY );
private static EscapeAction instance = new EscapeAction();
/**
* Registers an EscapeAction on the specified JDialog
*
* @param dialog the JDialog the EscapeAction is registered with
*/
public static void register(JDialog dialog) {
register(dialog.getRootPane());
}
/**
* Registers an EscapeAction on the specified JRootPane
*
* @param rootPane the JRootPane the EscapeAction is registered with
*/
public static void register(JRootPane rootPane) {
rootPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ESCAPE_KEY_STROKE, KEY_STROKE_AND_KEY);
rootPane.getActionMap().put(KEY_STROKE_AND_KEY, instance);
}
private EscapeAction()
{
super("Escape");
}
/**
* Implement the Escape Action. First attempt to hide a popup menu.
* If no popups are found then dispose the window.
*/
@Override
public void actionPerformed(ActionEvent e) {
// When a popup is visible the root pane of the Window will
// (generally) have focus
Component component = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
JComponent rootPane = (JComponent)component;
// In some cases a component added to a popup menu may have focus, but
// we need the root pane to check for popup menu key bindings
if (!(rootPane instanceof JRootPane)) {
rootPane = (JComponent)SwingUtilities.getAncestorOfClass(JRootPane.class, component);
}
// Hide the popup menu when an ESCAPE key binding is found, otherwise dispose the Window
ActionListener escapeAction = getEscapeAction(rootPane);
if (escapeAction != null) {
escapeAction.actionPerformed(null);
} else {
Window window = SwingUtilities.windowForComponent(component);
if (window != null) {
window.dispose();
}
}
}
private ActionListener getEscapeAction(JComponent rootPane) {
// Search the operatorDescriptor InputMap to see if a binding for the ESCAPE key
// exists. This binding is added when a popup menu is made visible
// (and removed when the popup menu is hidden).
InputMap im = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
if (im == null || (im = im.getParent()) == null) {
return null;
}
Object[] keys = im.keys();
if (keys == null) {
return null;
}
for (Object keyStroke : keys) {
if (keyStroke.equals(ESCAPE_KEY_STROKE)) {
Object key = im.get(ESCAPE_KEY_STROKE);
return rootPane.getActionMap().get(key);
}
}
return null;
}
} | 3,474 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ToolAdapterActionRegistrar.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/actions/ToolAdapterActionRegistrar.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.actions;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.gpf.OperatorSpi;
import org.esa.snap.core.gpf.OperatorSpiRegistry;
import org.esa.snap.core.gpf.descriptor.OperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterIO;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterListener;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterOpSpi;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterRegistry;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.utils.AdapterWatcher;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.modules.OnStart;
import org.openide.modules.OnStop;
import org.openide.modules.Places;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
/**
* Helper class for creating menu entries for tool adapter operators.
* The inner runnable class should be invoked when the IDE starts, and will
* register the available adapters as menu actions.
*
* @author Cosmin Cara
*/
public class ToolAdapterActionRegistrar {
private static final String DEFAULT_MENU_PATH = "Menu/Tools/External Tools";
private static FileObject defaultMenu;
private static final Map<String, ToolAdapterOperatorDescriptor> actionMap = new HashMap<>();
private static final ToolAdapterListener listener = new ToolAdapterListener() {
@Override
public void adapterAdded(ToolAdapterOperatorDescriptor operatorDescriptor) {
registerOperatorMenu(operatorDescriptor);
}
@Override
public void adapterRemoved(ToolAdapterOperatorDescriptor operatorDescriptor) {
removeOperatorMenu(operatorDescriptor);
}
};
/**
* Returns the map of menu items (actions) and operator descriptors.
*
* @return
*/
public static Map<String, ToolAdapterOperatorDescriptor> getActionMap() {
return actionMap;
}
public static String getDefaultMenuLocation() {
return DEFAULT_MENU_PATH;
}
/**
* Creates a menu entry in the default menu location (Tools > External Tools) for the given adapter operator.
*
* @param operator The operator descriptor
*/
public static void registerOperatorMenu(ToolAdapterOperatorDescriptor operator) {
String menuGroup = operator.getMenuLocation();
if (menuGroup == null) {
operator.setMenuLocation(DEFAULT_MENU_PATH);
}
registerOperatorMenu(operator, true);
}
/**
* Creates a menu entry in the given menu location for the given adapter operator.
*
* @param operator The operator descriptor
* @param hasChanged Flag that indicates if the descriptor has changed (true) or is new (false)
*/
public static void registerOperatorMenu(ToolAdapterOperatorDescriptor operator, boolean hasChanged) {
String menuLocation = operator.getMenuLocation();
try {
getDefaultLocation();
} catch (IOException e) {
e.printStackTrace();
}
if (menuLocation == null) {
menuLocation = getDefaultMenuLocation();
operator.setMenuLocation(menuLocation);
}
FileObject menuFolder = FileUtil.getConfigFile(menuLocation);
try {
if (menuFolder == null) {
menuFolder = FileUtil.getConfigFile("Menu");
StringTokenizer tokenizer = new StringTokenizer(menuLocation, "/");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if ("Menu".equals(token)) {
continue;
}
FileObject subMenu = menuFolder.getFileObject(token);
if (subMenu == null) {
menuFolder = menuFolder.createFolder(token);
} else {
menuFolder = subMenu;
}
}
menuFolder.setAttribute("position", 2000);
}
String menuKey = operator.getAlias();
FileObject newItem = menuFolder.getFileObject(menuKey, "instance");
if (newItem == null) {
newItem = menuFolder.createData(menuKey, "instance");
}
ExecuteToolAdapterAction action = new ExecuteToolAdapterAction(menuKey);
newItem.setAttribute("instanceCreate", action);
newItem.setAttribute("instanceClass", action.getClass().getName());
if (actionMap.containsKey(menuKey)) {
actionMap.remove(menuKey);
}
actionMap.put(menuKey, operator);
} catch (IOException e) {
Dialogs.showError("Error:" + e.getMessage());
}
}
public static void removeOperatorMenu(ToolAdapterOperatorDescriptor operator) {
//if (!operator.isFromPackage()) {
FileObject menuFolder = FileUtil.getConfigFile(operator.getMenuLocation());
try {
if (menuFolder != null) {
String operatorAlias = operator.getAlias();
FileObject newItem = menuFolder.getFileObject(operatorAlias, "instance");
if (newItem != null) {
newItem.delete();
}
if (actionMap.containsKey(operatorAlias)) {
actionMap.remove(operatorAlias);
}
FileObject[] children = menuFolder.getChildren();
if (children == null || children.length == 0) {
menuFolder.delete();
}
}
FileObject defaultLocation = getDefaultLocation();
FileObject[] children = defaultLocation.getChildren();
if (children == null || children.length == 0) {
defaultLocation.delete();
}
} catch (IOException e) {
Dialogs.showError("Error:" + e.getMessage());
}
//}
}
private static FileObject getDefaultLocation() throws IOException {
if (defaultMenu == null) {
defaultMenu = FileUtil.getConfigFile(DEFAULT_MENU_PATH);
if (defaultMenu == null) {
defaultMenu = FileUtil.getConfigFile("Menu").getFileObject("Tools");
defaultMenu = defaultMenu.createFolder(DEFAULT_MENU_PATH.replace("Menu/Tools/", ""));
}
FileObject[] objects = defaultMenu.getParent().getChildren();
int position = 9999;
Object value = objects[objects.length - 1].getAttribute("position");
if (value != null) {
position = ((Integer) value) + 1;
}
defaultMenu.setAttribute("position", position);
}
return defaultMenu;
}
/**
* Startup class that performs menu initialization to be invoked by NetBeans.
*/
@OnStart
public static class StartOp implements Runnable {
@Override
public void run() {
OperatorSpiRegistry spiRegistry = GPF.getDefaultInstance().getOperatorSpiRegistry();
Path jarPaths = Paths.get(Places.getUserDirectory().getAbsolutePath(), "modules");
Map<String, File> jarAdapters = Files.exists(jarPaths) ? getJarAdapters(jarPaths.toFile()) : null;
if (spiRegistry != null) {
Collection<OperatorSpi> operatorSpis = spiRegistry.getOperatorSpis();
if (operatorSpis != null) {
if (operatorSpis.size() == 0) {
operatorSpis.addAll(ToolAdapterIO.searchAndRegisterAdapters());
}
/*final List<OperatorSpi> orphaned = operatorSpis.stream()
.filter(spi -> spi instanceof ToolAdapterOpSpi &&
((ToolAdapterOperatorDescriptor) spi.getOperatorDescriptor()).isFromPackage() &&
jarAdapters != null && !jarAdapters.containsKey(spi.getOperatorDescriptor().getAlias()))
.collect(Collectors.toList());
orphaned.forEach(spi -> {
ToolAdapterOperatorDescriptor operatorDescriptor = (ToolAdapterOperatorDescriptor) spi.getOperatorDescriptor();
operatorSpis.remove(spi);
//ToolAdapterActionRegistrar.removeOperatorMenu(operatorDescriptor);
ToolAdapterIO.removeOperator(operatorDescriptor);
});*/
operatorSpis.stream().filter(spi -> spi instanceof ToolAdapterOpSpi).forEach(spi -> {
OperatorDescriptor descriptor = spi.getOperatorDescriptor();
if (descriptor instanceof ToolAdapterOperatorDescriptor) {
registerOperatorMenu((ToolAdapterOperatorDescriptor) descriptor, false);
}
});
}
ToolAdapterRegistry.INSTANCE.addListener(listener);
AdapterWatcher.INSTANCE.startMonitor();
}
}
private Map<String, File> getJarAdapters(File fromPath) {
Map<String, File> output = new HashMap<>();
if (fromPath != null && fromPath.exists()) {
String descriptionKeyName = "OpenIDE-Module-Short-Description";
Attributes.Name typeKey = new Attributes.Name("OpenIDE-Module-Type");
File[] files = fromPath.listFiles((dir, name) -> name.endsWith("jar"));
if (files != null) {
try {
for (File file : files) {
JarFile jarFile = new JarFile(file);
Manifest manifest = jarFile.getManifest();
if (manifest != null) {
Attributes manifestEntries = manifest.getMainAttributes();
if (manifestEntries.containsKey(typeKey) &&
"STA".equals(manifestEntries.getValue(typeKey.toString()))) {
output.put(manifestEntries.getValue(descriptionKeyName), file);
}
}
}
} catch (Exception ignored) {
}
}
}
return output;
}
}
@OnStop
public static class StopOp implements Runnable {
@Override
public void run() {
AdapterWatcher.INSTANCE.stopMonitor();
}
}
}
| 11,782 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ManageToolAdaptersAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/actions/ManageToolAdaptersAction.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.actions;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.ui.tooladapter.dialogs.ToolAdaptersManagementDialog;
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;
/**
* Action for launching the form that manages the existing
* tool adapters.
*
* @author Lucian Barbulescu
*/
@ActionID(category = "Tools", id = "ToolAdapterAction")
@ActionRegistration(displayName = "#CTL_ToolAdapterOperatorAction_Text", lazy = false)
@ActionReference(path = "Menu/Tools", position = 610, separatorBefore = 600)
@NbBundle.Messages({
"CTL_ToolAdapterOperatorAction_Text=Manage External Tools",
"CTL_ToolAdapterOperatorAction_Description=Define adapters for external processes.",
"CTL_ExternalOperatorsEditorDialog_Title=External Tools"
})
public class ManageToolAdaptersAction extends AbstractSnapAction {
public ManageToolAdaptersAction() {
putValue(NAME, Bundle.CTL_ToolAdapterOperatorAction_Text());
putValue(SHORT_DESCRIPTION, Bundle.CTL_ToolAdapterOperatorAction_Description());
}
/**
* Open the external tools selection window
*
* @param event the command event
*/
@Override
public void actionPerformed(ActionEvent event) {
ToolAdaptersManagementDialog.showDialog(getAppContext(), event.getActionCommand());
}
}
| 2,216 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExecuteToolAdapterAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/actions/ExecuteToolAdapterAction.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.actions;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.ui.tooladapter.dialogs.ToolAdapterExecutionDialog;
import java.awt.event.ActionEvent;
/**
* Action to be performed when a toll adapter menu entry is invoked.
*
* @author Cosmin Cara
*/
public class ExecuteToolAdapterAction extends AbstractSnapAction {
public ExecuteToolAdapterAction() {
super();
}
public ExecuteToolAdapterAction(String label) {
putValue(NAME, label);
}
@Override
public void actionPerformed(ActionEvent e) {
ToolAdapterOperatorDescriptor operatorDescriptor = ToolAdapterActionRegistrar.getActionMap().get(getValue(NAME));
if (operatorDescriptor != null) {
final ToolAdapterExecutionDialog operatorDialog = new ToolAdapterExecutionDialog(operatorDescriptor, getAppContext(), operatorDescriptor.getLabel());
operatorDialog.show();
}
}
}
| 1,765 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RequiredTextComponentAdapter.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/RequiredTextComponentAdapter.java | package org.esa.snap.ui.tooladapter.dialogs;
import com.bc.ceres.swing.binding.internal.TextComponentAdapter;
import org.esa.snap.rcp.util.Dialogs;
import javax.swing.*;
import javax.swing.text.JTextComponent;
/**
* Created by jcoravu on 9/23/2016.
*/
public class RequiredTextComponentAdapter extends TextComponentAdapter {
private final String messageToDisplay;
public RequiredTextComponentAdapter(JTextComponent textComponent, String messageToDisplay) {
super(textComponent);
this.messageToDisplay = messageToDisplay;
}
@Override
public InputVerifier createInputVerifier() {
return new RequiredTextVerifier();
}
private class RequiredTextVerifier extends InputVerifier {
private RequiredTextVerifier() {
}
@Override
public boolean verify(JComponent input) {
String text = ((JTextComponent) input).getText();
if (text != null && text.length() > 0) {
actionPerformed(null);
return getBinding().getProblem() == null;
}
Dialogs.showError(messageToDisplay);
return false;
}
}
}
| 1,175 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ToolAdaptersManagementDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/ToolAdaptersManagementDialog.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.dialogs;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.operators.tooladapter.*;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.tango.TangoIcons;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.ModelessDialog;
import org.esa.snap.ui.tooladapter.actions.EscapeAction;
import org.esa.snap.ui.tooladapter.actions.ToolAdapterActionRegistrar;
import org.esa.snap.ui.tooladapter.model.OperationType;
import org.esa.snap.ui.tooladapter.model.OperatorsTableModel;
import org.esa.snap.utils.AdapterWatcher;
import org.openide.util.NbBundle;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import static org.esa.snap.utils.SpringUtilities.DEFAULT_PADDING;
import static org.esa.snap.utils.SpringUtilities.makeCompactGrid;
/**
* Dialog that allows the management (create, edit, remove and execute) of external
* tool adapters
*
* @author Ramona Manda
* @author Cosmin Cara
*/
@NbBundle.Messages({
"Dialog_Title=External Tools",
"ToolTipNewOperator_Text=Define new operator",
"ToolTipCopyOperator_Text=Duplicate the selected operator",
"ToolTipEditOperator_Text=Edit the selected operator",
"ToolTipExport_Text=Create an installable module",
"ToolTipExecuteOperator_Text=Execute the selected operator",
"ToolTipDeleteOperator_Text=Delete the selected operator",
"PathLabel_Text=Adapters location",
"MessageNoSelection_Text=Please select an adapter first",
"MessageConfirmRemoval_TitleText=Confirm removal",
"MessageConfirmRemoval_Text=Are you sure you want to remove the selected adapter?\nThe operation will delete also the associated folder and files",
"MessageConfirmRemovalDontAsk_Text=Don't ask me in the future",
"MessagePackageModules_Text=The adapter %s was installed as a NetBeans module and cannot be removed from here.%nPlease uninstall the module."
})
public class ToolAdaptersManagementDialog extends ModelessDialog {
final int CHECK_COLUMN_WIDTH = 20;
final int LABEL_COLUMN_WIDTH = 250;
final int COLUMN_WIDTH = 270;
final int PATH_ROW_HEIGHT = 20;
final int BUTTON_HEIGHT = 32;
final Dimension buttonDimension = new Dimension((CHECK_COLUMN_WIDTH + LABEL_COLUMN_WIDTH + COLUMN_WIDTH) / 5, BUTTON_HEIGHT);
private AppContext appContext;
private JTable operatorsTable = null;
private Logger logger = Logger.getLogger(ToolAdaptersManagementDialog.class.getName());
private static ToolAdaptersManagementDialog instance;
public static void showDialog(AppContext appContext, String helpID) {
if (instance == null) {
instance = new ToolAdaptersManagementDialog(appContext, Bundle.Dialog_Title(), helpID);
}
instance.show();
}
private ToolAdaptersManagementDialog(AppContext appContext, String title, String helpID) {
super(appContext.getApplicationWindow(), title, 0, helpID);
this.appContext = appContext;
JPanel contentPanel = createContentPanel();
setContent(contentPanel);
super.getJDialog().setMinimumSize(contentPanel.getPreferredSize());
EscapeAction.register(super.getJDialog());
ToolAdapterRegistry.INSTANCE.addListener(new ToolAdapterListener() {
@Override
public void adapterAdded(ToolAdapterOperatorDescriptor operatorDescriptor) {
refreshContent();
}
@Override
public void adapterRemoved(ToolAdapterOperatorDescriptor operatorDescriptor) {
refreshContent();
}
@Override
public void adapterUpdated(ToolAdapterOperatorDescriptor operatorDescriptor) {
((OperatorsTableModel) operatorsTable.getModel()).fireTableDataChanged();
}
});
}
private JPanel createContentPanel() {
JPanel panel = new JPanel(new BorderLayout(DEFAULT_PADDING, DEFAULT_PADDING));
int panelHeight = 0;
JTable propertiesPanel = createPropertiesPanel();
panelHeight += propertiesPanel.getPreferredSize().getHeight();
panel.add(propertiesPanel, BorderLayout.PAGE_START);
panelHeight += 10;
SpringLayout springLayout = new SpringLayout();
JPanel adaptersAndButtonsPanel = new JPanel(springLayout);
JScrollPane scrollPane = new JScrollPane(createAdaptersPanel());
panelHeight += scrollPane.getPreferredSize().getHeight();
adaptersAndButtonsPanel.add(scrollPane);
panelHeight += 10;
JPanel buttonsPanel = createButtonsPanel();
panelHeight += buttonsPanel.getPreferredSize().getHeight();
adaptersAndButtonsPanel.add(buttonsPanel);
springLayout.putConstraint(SpringLayout.NORTH, adaptersAndButtonsPanel, DEFAULT_PADDING, SpringLayout.NORTH, scrollPane);
springLayout.putConstraint(SpringLayout.WEST, adaptersAndButtonsPanel, DEFAULT_PADDING, SpringLayout.WEST, scrollPane);
springLayout.putConstraint(SpringLayout.EAST, adaptersAndButtonsPanel, DEFAULT_PADDING, SpringLayout.EAST, scrollPane);
springLayout.putConstraint(SpringLayout.SOUTH, scrollPane, DEFAULT_PADDING, SpringLayout.NORTH, buttonsPanel);
springLayout.putConstraint(SpringLayout.EAST, adaptersAndButtonsPanel, DEFAULT_PADDING, SpringLayout.EAST, buttonsPanel);
springLayout.putConstraint(SpringLayout.WEST, adaptersAndButtonsPanel, DEFAULT_PADDING, SpringLayout.WEST, buttonsPanel);
springLayout.putConstraint(SpringLayout.SOUTH, adaptersAndButtonsPanel, DEFAULT_PADDING, SpringLayout.SOUTH, buttonsPanel);
makeCompactGrid(adaptersAndButtonsPanel, 2, 1, 0, 0, DEFAULT_PADDING, DEFAULT_PADDING);
panel.add(adaptersAndButtonsPanel, BorderLayout.CENTER);
JPanel sideButtonsPanel = createSideButtonsPanel();
panel.add(sideButtonsPanel, BorderLayout.LINE_END);
panel.setPreferredSize(new Dimension(CHECK_COLUMN_WIDTH + LABEL_COLUMN_WIDTH + COLUMN_WIDTH - 32, panelHeight + DEFAULT_PADDING));
return panel;
}
private JPanel createSideButtonsPanel() {
JPanel panel = new JPanel(new SpringLayout());
/**
* New adapter button
*/
panel.add(createButton(null, //"New",
TangoIcons.actions_list_add(TangoIcons.Res.R22),
Bundle.ToolTipNewOperator_Text(),
e -> {
ToolAdapterOperatorDescriptor newOperatorSpi = new ToolAdapterOperatorDescriptor(ToolAdapterConstants.OPERATOR_NAMESPACE + "NewOperator", ToolAdapterOp.class, "NewOperator", null, null, null, null, null, null);
AbstractAdapterEditor dialog = AbstractAdapterEditor.createEditorDialog(appContext, getJDialog(), newOperatorSpi, OperationType.NEW);
dialog.show();
refreshContent();
}));
/**
* Duplicate adapter button
*/
panel.add(createButton(null, //"Copy",
TangoIcons.actions_edit_copy(TangoIcons.Res.R22),
Bundle.ToolTipCopyOperator_Text(),
e -> {
ToolAdapterOperatorDescriptor operatorDesc = requestSelection();
if (operatorDesc != null) {
String opName = operatorDesc.getName();
int newNameIndex = 0;
while (GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(opName) != null) {
newNameIndex++;
opName = operatorDesc.getName() + ToolAdapterConstants.OPERATOR_GENERATED_NAME_SEPARATOR + newNameIndex;
}
AbstractAdapterEditor dialog = AbstractAdapterEditor.createEditorDialog(appContext, getJDialog(), operatorDesc, newNameIndex, OperationType.COPY);
dialog.show();
refreshContent();
}
}));
/**
* Edit adapter button
*/
panel.add(createButton(null, //"Edit",
TangoIcons.apps_accessories_text_editor(TangoIcons.Res.R22),
Bundle.ToolTipEditOperator_Text(),
e -> {
ToolAdapterOperatorDescriptor operatorDesc = requestSelection();
if (operatorDesc != null) {
AbstractAdapterEditor dialog = AbstractAdapterEditor.createEditorDialog(appContext, getJDialog(), operatorDesc, OperationType.EDIT);
dialog.show();
refreshContent();
}
}));
/**
* Delete adapter button
*/
panel.add(createButton(null, //"Delete",
TangoIcons.actions_list_remove(TangoIcons.Res.R22),
Bundle.ToolTipDeleteOperator_Text(),
e -> {
ToolAdapterOperatorDescriptor operatorDescriptor = requestSelection();
if (operatorDescriptor != null) {
if (Dialogs.Answer.YES == Dialogs.requestDecision(Bundle.MessageConfirmRemoval_TitleText(),
Bundle.MessageConfirmRemoval_Text(), true,
Bundle.MessageConfirmRemovalDontAsk_Text())) {
if (operatorDescriptor.isFromPackage()) {
Dialogs.showWarning(String.format(Bundle.MessagePackageModules_Text(), operatorDescriptor.getName()));
} else {
ToolAdapterIO.removeOperator(operatorDescriptor);
}
refreshContent();
}
}
}));
makeCompactGrid(panel, 4, 1, 0, 0, DEFAULT_PADDING, DEFAULT_PADDING);
return panel;
}
private JPanel createButtonsPanel() {
FlowLayout layout = new FlowLayout(FlowLayout.TRAILING);
JPanel panel = new JPanel();
/**
* Execute adapter button
*/
AbstractButton runButton = createButton("Run",
TangoIcons.actions_media_playback_start(TangoIcons.Res.R22),
Bundle.ToolTipExecuteOperator_Text(),
e -> {
ToolAdapterOperatorDescriptor operatorDesc = requestSelection();
if (operatorDesc != null) {
//close();
final ToolAdapterExecutionDialog operatorDialog = new ToolAdapterExecutionDialog(
operatorDesc,
appContext,
operatorDesc.getLabel());
operatorDialog.getJDialog().setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
operatorDialog.show();
}
});
panel.add(runButton);
/**
* Create suite button
*/
AbstractButton packButton = createButton("Pack",
TangoIcons.apps_system_installer(TangoIcons.Res.R22),
Bundle.ToolTipExport_Text(),
e -> {
ModuleSuiteDialog dialog = new ModuleSuiteDialog(appContext, "Create Adapter Suite", null, getSelection());
dialog.show();
refreshContent();
});
panel.add(packButton);
AbstractButton closeButton = createButton("Close",
TangoIcons.actions_system_log_out(TangoIcons.Res.R22),
null,
e -> {
ToolAdaptersManagementDialog.this.onClose();
});
panel.add(closeButton);
return panel;
}
private AbstractButton createButton(String text, ImageIcon icon, String toolTip, ActionListener actionListener) {
AbstractButton button = StringUtils.isNullOrEmpty(text) ? new JButton(icon) : new JButton(text, icon);
Dimension dimension = StringUtils.isNullOrEmpty(text) ?
new Dimension(24, 24) :
buttonDimension;
button.setMinimumSize(dimension);
button.setMaximumSize(dimension);
button.setPreferredSize(dimension);
if (toolTip != null) {
button.setToolTipText(toolTip);
}
if (actionListener != null) {
button.addActionListener(actionListener);
}
return button;
}
private JTable createPropertiesPanel() {
DefaultTableModel model = new DefaultTableModel(1, 2) {
@Override
public boolean isCellEditable(int row, int column) {
return column == 1;
}
};
model.setValueAt(Bundle.PathLabel_Text(), 0, 0);
model.setValueAt(ToolAdapterIO.getAdaptersPath(), 0, 1);
model.addTableModelListener(l -> {
String newPath = model.getValueAt(0, 1).toString();
Path path = Paths.get(newPath);
Path oldPath = ToolAdapterIO.getAdaptersPath();
try {
if (Files.isSameFile(oldPath, path)) {
return;
}
} catch (IOException ignored) {
}
if (!Files.exists(path) &&
Dialogs.Answer.YES == Dialogs.requestDecision("Path does not exist", "The path you have entered does not exist.\nDo you want to create it?", true, "Don't ask me in the future")) {
try {
Files.createDirectories(Files.isDirectory(path) ? path : path.getParent());
} catch (IOException ex) {
Dialogs.showError("Path could not be created!");
}
}
if (Files.exists(path)) {
ToolAdapterOperatorDescriptor[] operatorDescriptors = ToolAdapterActionRegistrar.getActionMap().values()
.toArray(new ToolAdapterOperatorDescriptor[ToolAdapterActionRegistrar.getActionMap().values().size()]);
for (ToolAdapterOperatorDescriptor descriptor : operatorDescriptors) {
ToolAdapterIO.removeOperator(descriptor, false);
}
AdapterWatcher.INSTANCE.unmonitorPath(oldPath);
ToolAdapterIO.setAdaptersPath(path);
if (!newPath.equals(oldPath.toAbsolutePath().toString())) {
ToolAdapterIO.searchAndRegisterAdapters();
refreshContent();
}
try {
AdapterWatcher.INSTANCE.monitorPath(path);
} catch (IOException e) {
logger.warning(String.format("Could not watch for the new adapter path %s [%s]", path.toString(), e.getMessage()));
}
}
});
JTable table = new JTable(model);
TableColumn labelColumn = table.getColumnModel().getColumn(0);
labelColumn.setPreferredWidth((CHECK_COLUMN_WIDTH + LABEL_COLUMN_WIDTH)/2);
TableColumn pathColumn = table.getColumnModel().getColumn(1);
pathColumn.setPreferredWidth(COLUMN_WIDTH);
pathColumn.setCellEditor(new FileChooserCellEditor());
table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
table.setRowHeight(PATH_ROW_HEIGHT);
table.setBorder(BorderFactory.createLineBorder(Color.black));
table.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
Object source = e.getSource();
if (!table.equals(source)) {
table.editingCanceled(new ChangeEvent(source));
table.clearSelection();
}
}
});
return table;
}
private JTable createAdaptersPanel() {
java.util.List<ToolAdapterOperatorDescriptor> toolboxSpis = new ArrayList<>();
toolboxSpis.addAll(ToolAdapterRegistry.INSTANCE.getOperatorMap().values()
.stream()
.map(e -> (ToolAdapterOperatorDescriptor) e.getOperatorDescriptor())
.collect(Collectors.toList()));
toolboxSpis.sort(Comparator.comparing(ToolAdapterOperatorDescriptor::getAlias));
OperatorsTableModel model = new OperatorsTableModel(toolboxSpis);
operatorsTable = new JTable(model) {
@Override
public String getToolTipText(MouseEvent event) {
final Point point = event.getPoint();
int col = columnAtPoint(point);
String tip = null;
if (col == 0) {
int row = rowAtPoint(point);
tip = "<html><p style=\"color:";
if (TangoIcons.emblems_emblem_important(TangoIcons.Res.R16).equals(getValueAt(row, col))) {
tip += "red;\">Tool executable not found!<br/>Verify that the adapter bundle is installed or the tool location is correct.";
} else {
tip += "green;\">Tool seems properly configured.";
}
tip += "</p></html>";
}
return tip;
}
};
operatorsTable.setRowHeight(PATH_ROW_HEIGHT);
TableColumnModel columnModel = operatorsTable.getColumnModel();
columnModel.getColumn(0).setPreferredWidth(3 * CHECK_COLUMN_WIDTH);
columnModel.getColumn(0).setMaxWidth(3 * CHECK_COLUMN_WIDTH);
columnModel.getColumn(0).setResizable(false);
columnModel.getColumn(1).setPreferredWidth(LABEL_COLUMN_WIDTH);
columnModel.getColumn(1).setMaxWidth(300);
columnModel.getColumn(2).setResizable(true);
columnModel.getColumn(2).setPreferredWidth(LABEL_COLUMN_WIDTH);
operatorsTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
operatorsTable.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() >= 2) {
int selectedRow = operatorsTable.getSelectedRow();
operatorsTable.repaint();
ToolAdapterOperatorDescriptor operatorDesc = ((OperatorsTableModel) operatorsTable.getModel()).getObjectAt(selectedRow);
operatorsTable.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
AbstractAdapterEditor dialog = AbstractAdapterEditor.createEditorDialog(appContext, getJDialog(), operatorDesc, OperationType.EDIT);
operatorsTable.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
dialog.show();
refreshContent();
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
return operatorsTable;
}
private Set<ToolAdapterOperatorDescriptor> getSelection() {
Set<ToolAdapterOperatorDescriptor> selection = new HashSet<>();
int[] selectedRows = operatorsTable.getSelectedRows();
for (int idx : selectedRows) {
selection.add(((OperatorsTableModel) operatorsTable.getModel()).getObjectAt(idx));
}
return selection;
}
private ToolAdapterOperatorDescriptor requestSelection() {
ToolAdapterOperatorDescriptor selected = null;
int selectedRow = operatorsTable.getSelectedRow();
if (selectedRow >= 0) {
selected = ((OperatorsTableModel) operatorsTable.getModel()).getObjectAt(selectedRow);
} else {
Dialogs.showWarning(Bundle.MessageNoSelection_Text());
}
return selected;
}
private void refreshContent() {
setContent(createContentPanel());
getContent().repaint();
}
public class FileChooserCellEditor extends DefaultCellEditor implements TableCellEditor {
/** Number of clicks to start editing */
private static final int CLICK_COUNT_TO_START = 2;
/** Editor component */
private JButton button;
/** File chooser */
private JFileChooser fileChooser;
/** Selected file */
private String file = "";
/**
* Constructor.
*/
public FileChooserCellEditor() {
super(new JTextField());
setClickCountToStart(CLICK_COUNT_TO_START);
// Using a JButton as the editor component
button = new JButton();
button.setBackground(Color.white);
button.setFont(button.getFont().deriveFont(Font.PLAIN));
button.setBorder(null);
// Dialog which will do the actual editing
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
@Override
public Object getCellEditorValue() {
return file;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
file = value.toString();
SwingUtilities.invokeLater(() -> {
fileChooser.setSelectedFile(new File(file));
if (fileChooser.showOpenDialog(button) == JFileChooser.APPROVE_OPTION) {
file = fileChooser.getSelectedFile().getAbsolutePath();
}
fireEditingStopped();
});
button.setText(file);
return button;
}
}
}
| 23,294 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ConsolePane.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/ConsolePane.java | package org.esa.snap.ui.tooladapter.dialogs;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import java.awt.*;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
/**
* Console-like panel for displaying tool output.
*
* @author Cosmin Cara
*/
public class ConsolePane extends JScrollPane {
private JTextPane textArea;
private final StringBuilder buffer;
private final StyleContext styleContext;
public ConsolePane() {
super();
styleContext = StyleContext.getDefaultStyleContext();
buffer = new StringBuilder();
textArea = new JTextPane();
textArea.setBackground(Color.BLACK);
textArea.setFont(new Font("Lucida Console", Font.PLAIN, 10));
textArea.setForeground(Color.WHITE);
setViewportView(textArea);
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setWheelScrollingEnabled(true);
getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
BoundedRangeModel brm = getVerticalScrollBar().getModel();
boolean wasAtBottom = true;
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
if (!brm.getValueIsAdjusting()) {
if (wasAtBottom)
brm.setValue(brm.getMaximum());
} else
wasAtBottom = ((brm.getValue() + brm.getExtent()) == brm.getMaximum());
}
});
addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
if (buffer.length() > 0) {
appendInfo(buffer.toString());
}
buffer.setLength(0);
}
});
}
/**
* Appends text to this console.
*
* @param text The text to appendInfo
*/
public void appendInfo(String text) {
AttributeSet aset = styleContext.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.WHITE);
aset = styleContext.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_LEFT);
append(text, aset);
}
public void appendError(String text) {
AttributeSet aset = styleContext.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.RED);
aset = styleContext.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_LEFT);
append(text, aset);
}
/**
* Clears the contents of this console
*/
public void clear() {
textArea.setText("");
}
private void append(String text, AttributeSet attributes) {
if (this.isVisible()) {
int len = textArea.getDocument().getLength();
textArea.setCaretPosition(len);
textArea.setCharacterAttributes(attributes, false);
textArea.replaceSelection("\n" + text);
textArea.repaint();
} else {
buffer.append(text);
}
}
}
| 3,348 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ToolAdapterExecutionDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/ToolAdapterExecutionDialog.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.dialogs;
import com.bc.ceres.binding.Property;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.gpf.Operator;
import org.esa.snap.core.gpf.descriptor.ParameterDescriptor;
import org.esa.snap.core.gpf.descriptor.SystemVariable;
import org.esa.snap.core.gpf.descriptor.TemplateParameterDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolParameterDescriptor;
import org.esa.snap.core.gpf.descriptor.template.FileTemplate;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterConstants;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterOp;
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.rcp.actions.file.SaveProductAsAction;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AbstractDialog;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.tooladapter.actions.EscapeAction;
import org.esa.snap.ui.tooladapter.dialogs.progress.ConsoleConsumer;
import org.esa.snap.ui.tooladapter.dialogs.progress.ProgressHandler;
import org.esa.snap.ui.tooladapter.model.OperationType;
import org.esa.snap.ui.tooladapter.preferences.ToolAdapterOptionsController;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.netbeans.api.progress.ProgressUtils;
import org.openide.util.Cancellable;
import org.openide.util.NbBundle;
import java.awt.Dimension;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Form dialog for running a tool adapter operator.
*
* @author Lucian Barbulescu.
* @author Cosmin Cara
*/
@NbBundle.Messages({
"NoSourceProductWarning_Text=No input product was selected.\nAre you sure you want to continue?",
"RequiredTargetProductMissingWarning_Text=A target product is required in adapter's template, but none was provided",
"NoOutput_Text=The operator did not produce any output",
"BeginOfErrorMessages_Text=The operator completed with the following errors:\n",
"OutputTitle_Text=Process output",
"ExecutionFailed_Text=Execution Failed",
"ExecutionFailed_Message=The execution completed with errors: \n%s\n\nDo you want to try to open the resulting product?"
})
public class ToolAdapterExecutionDialog extends SingleTargetProductDialog {
private static final String SOURCE_PRODUCT_FIELD = "sourceProduct";
/**
* Operator identifier.
*/
private ToolAdapterOperatorDescriptor operatorDescriptor;
/**
* Parameters related info.
*/
private OperatorParameterSupport parameterSupport;
/**
* The form used to get the user's input
*/
private ToolExecutionForm form;
private Product result;
private OperatorTask operatorTask;
private Logger logger;
private List<String> warnings;
private static final String helpID = "sta_execution";
private List<ToolParameterDescriptor> artificiallyAddedParams;
/**
* Constructor.
*
* @param descriptor The operator descriptor
* @param appContext The application context
* @param title The dialog title
*/
public ToolAdapterExecutionDialog(ToolAdapterOperatorDescriptor descriptor, AppContext appContext, String title) {
super(appContext, title, descriptor.getHelpID() != null ? descriptor.getHelpID() : helpID);
logger = Logger.getLogger(ToolAdapterExecutionDialog.class.getName());
initialize(descriptor);
warnings = new ArrayList<>();
}
private void initialize(ToolAdapterOperatorDescriptor descriptor) {
//this.operatorDescriptor = new ToolAdapterOperatorDescriptor(descriptor);
this.operatorDescriptor = descriptor;
//add paraeters of template parameters
artificiallyAddedParams = new ArrayList<>();
Arrays.stream(this.operatorDescriptor.getToolParameterDescriptors().toArray()).filter(p -> ((ToolParameterDescriptor)p).isTemplateParameter()).
forEach(p -> artificiallyAddedParams.addAll(((TemplateParameterDescriptor)p).getParameterDescriptors()));
this.operatorDescriptor.getToolParameterDescriptors().addAll(artificiallyAddedParams);
this.parameterSupport = new OperatorParameterSupport(this.operatorDescriptor);
Arrays.stream(this.operatorDescriptor.getToolParameterDescriptors().toArray()).
filter(p -> ToolAdapterConstants.FOLDER_PARAM_MASK.equals(((ToolParameterDescriptor)p).getParameterType())).
forEach(p -> parameterSupport.getPropertySet().getProperty(((ToolParameterDescriptor)p).getName()).getDescriptor().setAttribute("directory", true));
form = new ToolExecutionForm(appContext, this.operatorDescriptor, parameterSupport.getPropertySet(),
getTargetProductSelector());
OperatorMenu operatorMenu = new OperatorMenu(this.getJDialog(),
this.operatorDescriptor,
parameterSupport,
appContext,
descriptor.getHelpID() != null ? descriptor.getHelpID() : helpID);
getJDialog().setJMenuBar(operatorMenu.createDefaultMenu());
EscapeAction.register(getJDialog());
this.getJDialog().addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e) {form.refreshDimension();}
});
this.getJDialog().addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {form.refreshDimension();}
});
this.getJDialog().setMinimumSize(new Dimension(250, 250));
}
/* Begin @Override methods section */
@Override
protected void onApply() {
final Product[] sourceProducts = form.getSourceProducts();
List<ParameterDescriptor> descriptors = Arrays.stream(operatorDescriptor.getParameterDescriptors())
.filter(p -> ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE.equals(p.getName()))
.collect(Collectors.toList());
String templateContents;
try {
//templateContents = ToolAdapterIO.readOperatorTemplate(operatorDescriptor.getName());
FileTemplate template = operatorDescriptor.getTemplate();
templateContents = template.getContents();
} catch (Exception ex) {
showErrorDialog(String.format("Cannot read operator template [%s]", ex.getMessage()));
return;
}
if (Arrays.stream(sourceProducts).anyMatch(Objects::isNull)) {
Dialogs.Answer decision = Dialogs.requestDecision("No Product Selected", Bundle.NoSourceProductWarning_Text(), false,
ToolAdapterOptionsController.PREFERENCE_KEY_SHOW_EMPTY_PRODUCT_WARNING);
if (decision.equals(Dialogs.Answer.NO)) {
return;
}
}
if (descriptors.size() == 1 && form.getPropertyValue(ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE) == null &&
templateContents.contains("$" + ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE)) {
Dialogs.showWarning(Bundle.RequiredTargetProductMissingWarning_Text());
} else {
if (!canApply()) {
displayWarnings();
AbstractAdapterEditor dialog = AbstractAdapterEditor.createEditorDialog(appContext, getJDialog(), operatorDescriptor, OperationType.FORCED_EDIT);
final int code = dialog.show();
if (code == AbstractDialog.ID_OK) {
onOperatorDescriptorChanged(dialog.getUpdatedOperatorDescriptor());
}
dialog.close();
} else {
if (validateUserInput()) {
Map<String, Product> sourceProductMap = new HashMap<>();
if (sourceProducts.length > 0) {
sourceProductMap.put(SOURCE_PRODUCT_FIELD, sourceProducts[0]);
}
Operator op = GPF.getDefaultInstance().createOperator(operatorDescriptor.getAlias(), parameterSupport.getParameterMap(), sourceProductMap, null);
for (Property property : parameterSupport.getPropertySet().getProperties()) {
op.setParameter(property.getName(), property.getValue());
}
op.setSourceProducts(sourceProducts);
operatorTask = new OperatorTask(op, ToolAdapterExecutionDialog.this::operatorCompleted);
ProgressHandle progressHandle = ProgressHandleFactory.createHandle(this.getTitle());
String progressPattern = operatorDescriptor.getProgressPattern();
ConsoleConsumer consumer;
ProgressHandler progressWrapper = new ProgressHandler(progressHandle, progressPattern == null || progressPattern.isEmpty());
consumer = new ConsoleConsumer(operatorDescriptor.getProgressPattern(),
operatorDescriptor.getErrorPattern(),
operatorDescriptor.getStepPattern(),
progressWrapper,
form.console);
form.console.clear();
progressWrapper.setConsumer(consumer);
((ToolAdapterOp) op).setProgressMonitor(progressWrapper);
((ToolAdapterOp) op).setConsumer(consumer);
ProgressUtils.runOffEventThreadWithProgressDialog(operatorTask, this.getTitle(), progressHandle, true, 1, 1);
} else {
if (warnings.size() > 0) {
displayWarnings();
}
}
}
}
}
@Override
public int show() {
form.prepareShow();
setContent(form);
return super.show();
}
@Override
public void hide() {
form.prepareHide();
super.hide();
this.operatorDescriptor.getToolParameterDescriptors().removeAll(artificiallyAddedParams);
}
@Override
protected Product createTargetProduct() throws Exception {
return result;
}
@Override
protected boolean canApply() {
warnings.clear();
try {
Path toolLocation = operatorDescriptor.resolveVariables(operatorDescriptor.getMainToolFileLocation()).toPath();
if (!(Files.exists(toolLocation) && Files.isExecutable(toolLocation))) {
warnings.add(logAndReturn(String.format("Path does not exist: '%s'", toolLocation)));
}
Path workLocation = operatorDescriptor.resolveVariables(operatorDescriptor.getWorkingDir()).toPath();
if (!(Files.exists(workLocation))) {
warnings.add(logAndReturn("Working path does not exist: '%s'", workLocation));
}
ParameterDescriptor[] parameterDescriptors = operatorDescriptor.getParameterDescriptors();
if (parameterDescriptors != null && parameterDescriptors.length > 0) {
for (ParameterDescriptor parameterDescriptor : parameterDescriptors) {
Class<?> dataType = parameterDescriptor.getDataType();
String paramName = parameterDescriptor.getName();
if (parameterSupport.getParameterMap().containsKey(paramName)) {
Object value = parameterSupport.getParameterMap().get(paramName);
String currentValue = value != null ? value.toString() : null;
try {
if (File.class.isAssignableFrom(dataType) &&
(parameterDescriptor.isNotNull() || parameterDescriptor.isNotEmpty()) &&
(currentValue == null || currentValue.isEmpty() || !Files.exists(Paths.get(currentValue)))) {
warnings.add(logAndReturn("Path does not exist: '%s'", currentValue == null ? "null" : currentValue));
}
} catch (Exception ex) {
warnings.add(logAndReturn("Cannot access path %s [%s]", currentValue, ex.getMessage()));
}
}
}
}
for (SystemVariable variable : operatorDescriptor.getVariables()) {
String value = variable.getValue();
if (value == null || value.isEmpty()) {
warnings.add(logAndReturn("Variable %s is not set", variable.getKey()));
}
}
} catch (Exception e) {
warnings.add(logAndReturn(e.getMessage()));
}
return warnings.size() == 0;
}
@Override
protected void onCancel() {
if (operatorTask != null) {
operatorTask.cancel();
}
super.onCancel();
}
@Override
protected void onClose() {
super.onClose();
}
/* End @Override methods section */
private void onOperatorDescriptorChanged(ToolAdapterOperatorDescriptor newOperatorDescriptor) {
initialize(newOperatorDescriptor);
show();
}
/**
* Performs any validation on the user input.
*
* @return <code>true</code> if the input is valid, <code>false</code> otherwise
*/
private boolean validateUserInput() {
boolean isValid = true;
if(!operatorDescriptor.isHandlingOutputName()) {
File productDir = null;//targetProductSelector.getModel().getProductDir();
Object value = form.getPropertyValue(ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE);
if (value != null && value instanceof File) {
value = operatorDescriptor.resolveVariables((File)value);
productDir = ((File) value).getParentFile();
appContext.getPreferences().setPropertyString(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, ((File) value).getAbsolutePath());
}
isValid = (productDir != null) && productDir.exists();
if (!isValid) {
warnings.add("Target product folder is not accessible or does not exist");
}
}
List<ToolParameterDescriptor> mandatoryParams = operatorDescriptor.getToolParameterDescriptors()
.stream()
.filter(d -> d.isNotEmpty() || d.isNotNull())
.collect(Collectors.toList());
Map<String, Object> parameterMap = parameterSupport.getParameterMap();
for (ToolParameterDescriptor mandatoryParam : mandatoryParams) {
String name = mandatoryParam.getName();
if (!parameterMap.containsKey(name) ||
parameterMap.get(name) == null ||
parameterMap.get(name).toString().isEmpty()) {
isValid = false;
warnings.add(String.format("No value was assigned for the mandatory parameter [%s]", name));
}
}
if (operatorDescriptor.getSourceProductCount() > 0) {
Product[] sourceProducts = form.getSourceProducts();
boolean isProdValid = (sourceProducts != null) && sourceProducts.length > 0 && Arrays.stream(sourceProducts).filter(sp -> sp == null).count() == 0;
if (!isProdValid) {
warnings.add("No source product was selected");
}
isValid &= isProdValid;
}
return isValid;
}
private String logAndReturn(String templateMessage, Object...params) {
String message = String.format(templateMessage, params);
logger.warning(message);
return message;
}
private void displayWarnings() {
StringBuilder warnMessage = new StringBuilder();
warnMessage.append("Before executing the tool, please correct the errors below:")
.append("\n").append("\n");
for (String msg : warnings) {
warnMessage.append("\t").append(msg).append("\n");
}
Dialogs.showWarning(warnMessage.toString());
}
/**
* This is actually the callback method to be passed to the runnable
* wrapping the operator execution.
*
* @param result The output product
*/
private void operatorCompleted(Product result) {
this.result = result;
super.onApply();
//displayErrors();
}
private void tearDown(Throwable throwable, Product result) {
//boolean hasBeenCancelled = operatorTask != null && !operatorTask.hasCompleted;
if (operatorTask != null) {
operatorTask.cancel();
}
if (throwable != null) {
if (result != null) {
final Dialogs.Answer answer = Dialogs.requestDecision(Bundle.ExecutionFailed_Text(),
String.format(Bundle.ExecutionFailed_Message(), throwable.getMessage()),
false, null);
if (answer == Dialogs.Answer.YES) {
operatorCompleted(result);
}
} /*else
displayErrors();*/
//SnapDialogs.showError(Bundle.ExecutionFailed_Text(), throwable.getMessage());
}
//displayErrors();
displayErrorMessage();
}
private void displayErrorMessage() {
if (operatorTask != null) {
List<String> errors = operatorTask.getErrors();
if (errors != null && errors.size() > 0){
Dialogs.showWarning("\nIt seems there was en error on execution or the defined tool output error pattern was found.\nPlease consult the SNAP log file");
}
}
}
/**
* Runnable for executing the operator. It requires a callback
* method that is to be called when the operator has finished its
* execution.
*/
private class OperatorTask implements Runnable, Cancellable {
private Operator operator;
private Consumer<Product> callbackMethod;
private boolean hasCompleted;
/**
* Constructs a runnable for the given operator that will
* call back the given method when the execution has finished.
*
* @param op The operator to be executed
* @param callback The callback method to be invoked at completion
*/
OperatorTask(Operator op, Consumer<Product> callback) {
operator = op;
callbackMethod = callback;
}
@Override
public boolean cancel() {
if (!hasCompleted) {
if (operator instanceof ToolAdapterOp) {
((ToolAdapterOp) operator).stop();
//onCancel();
}
hasCompleted = true;
}
return true;
}
@Override
public void run() {
try {
callbackMethod.accept(operator.getTargetProduct());
} catch (Throwable t) {
if (operator instanceof ToolAdapterOp) {
tearDown(t, ((ToolAdapterOp) operator).getResult());
} else {
tearDown(t, null);
}
} finally {
hasCompleted = true;
}
}
List<String> getErrors() {
List<String> errors = null;
if (operator != null && operator instanceof ToolAdapterOp) {
errors = ((ToolAdapterOp) operator).getErrors();
}
return errors;
}
public List<String> getOutput() {
List<String> allMessages = null;
if (operator != null && operator instanceof ToolAdapterOp) {
allMessages = ((ToolAdapterOp) operator).getExecutionOutput();
}
return allMessages;
}
}
}
| 21,187 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ToolParameterEditorDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/ToolParameterEditorDialog.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.dialogs;
import com.bc.ceres.binding.*;
import com.bc.ceres.binding.converters.ArrayConverter;
import com.bc.ceres.binding.converters.FloatConverter;
import com.bc.ceres.binding.converters.IntegerConverter;
import com.bc.ceres.binding.converters.NumberConverter;
import com.bc.ceres.swing.binding.Binding;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.ComponentAdapter;
import com.bc.ceres.swing.binding.internal.*;
import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolParameterDescriptor;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterConstants;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.tooladapter.actions.EscapeAction;
import org.esa.snap.ui.tooladapter.model.OperatorParametersTable;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.logging.Logger;
/**
* Form for displaying and editing details of a tool adapter parameter.
*
* @author Ramona Manda
*/
public class ToolParameterEditorDialog extends ModalDialog {
private static final Logger logger = Logger.getLogger(ToolAdapterEditorDialog.class.getName());
public static final String helpID = "sta_editor";
private static final Map<String, Class<?>> typesMap = new LinkedHashMap<String, Class<?>>();
static {
typesMap.put("String", String.class);
typesMap.put("File", File.class);
typesMap.put("Folder", File.class);
typesMap.put("Integer", Integer.class);
typesMap.put("Decimal", Float.class);
typesMap.put("List", String[].class);
typesMap.put("Boolean", Boolean.class);
}
private ToolParameterDescriptor parameter;
private ToolParameterDescriptor oldParameter;
private PropertyContainer container;
private BindingContext valuesContext;
private BindingContext paramContext;
private JComponent defaultValueComponent;
private JPanel mainPanel;
private JTextField valueSetTextComponent;
private final ToolAdapterOperatorDescriptor operator;
public ToolParameterEditorDialog(AppContext appContext, ToolAdapterOperatorDescriptor operator, ToolParameterDescriptor inputParameter) {
super(appContext.getApplicationWindow(), inputParameter.getName(), ID_OK_CANCEL, helpID);
this.operator = operator;
this.oldParameter = inputParameter;
this.parameter = new ToolParameterDescriptor(inputParameter);
this.parameter.setDeprecated(inputParameter.isDeprecated()); // copy the value
this.container = PropertyContainer.createObjectBacked(this.parameter);
this.valuesContext = new BindingContext(this.container);
addComponents();
EscapeAction.register(getJDialog());
}
@Override
protected void onOK() {
if (!OperatorParametersTable.checkUniqueParameterName(this.operator, parameter.getName(), this.oldParameter)) {
return;
}
super.onOK();
oldParameter.setName(parameter.getName());
oldParameter.setAlias(parameter.getAlias());
oldParameter.setDataType(parameter.getDataType());
Object defaultValue = getProperty().getValue();
String defaultValueAsString = processDefaultValue(defaultValue);
oldParameter.setDefaultValue(defaultValueAsString);
oldParameter.setDescription(parameter.getDescription());
oldParameter.setLabel(parameter.getLabel());
oldParameter.setUnit(parameter.getUnit());
oldParameter.setInterval(parameter.getInterval());
oldParameter.setValueSet(parameter.getValueSet());
oldParameter.setCondition(parameter.getCondition());
oldParameter.setPattern(parameter.getPattern());
oldParameter.setFormat(parameter.getFormat());
oldParameter.setNotNull(parameter.isNotNull());
oldParameter.setNotEmpty(parameter.isNotEmpty());
oldParameter.setRasterDataNodeClass(parameter.getRasterDataNodeClass());
oldParameter.setValidatorClass(parameter.getValidatorClass());
oldParameter.setConverterClass(parameter.getConverterClass());
oldParameter.setDomConverterClass(parameter.getDomConverterClass());
oldParameter.setItemAlias(parameter.getItemAlias());
oldParameter.setDeprecated(parameter.isDeprecated());
oldParameter.setParameterType(parameter.getParameterType());
}
private void addComponents() {
GridBagLayout layout = new GridBagLayout();
layout.columnWidths = new int[]{100, 390};
this.mainPanel = new JPanel(layout);
addTextPropertyEditor(mainPanel, "Name: ", "name", 0, "The 'Name' field is required.");
addTextPropertyEditor(mainPanel, "Alias: ", "alias", 1, "The 'Alias' field is required.");
String itemNameToSelect = null;
if (this.parameter.getDataType() == File.class) {
itemNameToSelect = "File";
if (this.parameter.getDefaultValue() != null) {
File f = new File(this.parameter.getDefaultValue());
if (f.isDirectory()) {
itemNameToSelect = "Folder";
}
}
} else {
Iterator<Map.Entry<String, Class<?>>> it = typesMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Class<?>> entry = it.next();
if (entry.getValue() == this.parameter.getDataType()) {
itemNameToSelect = entry.getKey();
break;
}
}
}
//dataType
JComboBox comboEditor = new JComboBox(typesMap.keySet().toArray());
comboEditor.setSelectedItem(itemNameToSelect);
comboEditor.addActionListener(ev -> {
JComboBox cb = (JComboBox) ev.getSource();
String selectedTypeName = (String) cb.getSelectedItem();
Class<?> selectedTypeClass = typesMap.get(selectedTypeName);
if (!parameter.getDataType().equals(selectedTypeClass)) {
Class<?> previousTypeClass = parameter.getDataType();
parameter.setDataType(selectedTypeClass);
try {
valuesContext.getPropertySet().getProperty("defaultValue").setValue(null); // reset the default value
} catch (ValidationException e) {
logger.warning(e.getMessage());
}
Object defaultValue = getProperty().getValue();
String defaultValueAsString = processDefaultValue(defaultValue);
boolean canResetValueSet = true;
if (selectedTypeClass == String.class || selectedTypeClass == String[].class) {
canResetValueSet = false;
if (previousTypeClass == Float.class) {
defaultValueAsString = null; // reset the default value
}
} else if (selectedTypeClass == Integer.class) {
if (previousTypeClass == Float.class || previousTypeClass == String.class || previousTypeClass == String[].class) {
if (canConvertArrayToNumber(new IntegerConverter(), parameter.getValueSet())) {
canResetValueSet = false;
if (previousTypeClass == Float.class) {
defaultValueAsString = null; // reset the default value
}
}
}
} else if (selectedTypeClass == Float.class) {
if (previousTypeClass == Integer.class || previousTypeClass == String.class || previousTypeClass == String[].class) {
if (canConvertArrayToNumber(new FloatConverter(), parameter.getValueSet())) {
canResetValueSet = false;
}
}
}
if (canResetValueSet) {
try {
valuesContext.getPropertySet().getProperty("valueSet").setValue(null); // reset the value set
} catch (ValidationException e) {
logger.warning(e.getMessage());
}
}
newDataTypeSelected(selectedTypeName, selectedTypeClass, defaultValueAsString);
}
});
this.mainPanel.add(new JLabel("Data type"), getConstraints(2, 0, 1));
this.mainPanel.add(comboEditor, getConstraints(2, 1, 1));
addTextPropertyEditor(mainPanel, "Description: ", "description", 4, null);
addTextPropertyEditor(mainPanel, "Label: ", "label", 5, null);
addTextPropertyEditor(mainPanel, "Unit: ", "unit", 6, null);
addTextPropertyEditor(mainPanel, "Interval: ", "interval", 7, null);
this.valueSetTextComponent = new JTextField();
ValidateTextComponentAdapter adapter = new ValidateTextComponentAdapter(this.valueSetTextComponent) {
@Override
protected boolean validateText(String valueSetToValidate) {
return validateValueSetText(valueSetToValidate);
}
};
addTextPropertyEditor(mainPanel, adapter, "Value set: ", "valueSet", 8);
addTextPropertyEditor(mainPanel, "Condition: ", "condition", 9, null);
addTextPropertyEditor(mainPanel, "Pattern: ", "pattern", 10, null);
addTextPropertyEditor(mainPanel, "Format: ", "format", 11, null);
addBoolPropertyEditor(mainPanel, "Not null", "notNull", 12);
addBoolPropertyEditor(mainPanel, "Not empty", "notEmpty", 13);
addTextPropertyEditor(mainPanel, "ItemAlias: ", "itemAlias", 14, null);
addBoolPropertyEditor(mainPanel, "Deprecated", "deprecated", 15);
//defaultValue
JLabel label = new JLabel("Default value");
label.setPreferredSize(new Dimension(150, 35));
this.mainPanel.add(label, getConstraints(3, 0, 1));
newDataTypeSelected(itemNameToSelect, this.parameter.getDataType(), this.parameter.getDefaultValue());
setContent(this.mainPanel);
}
private boolean validateDefaultValueText(String textToValidate) {
if (!StringUtils.isNullOrEmpty(textToValidate)) {
if (this.parameter.getDataType() == Integer.class) {
try {
Integer.parseInt(textToValidate);
} catch (NumberFormatException ex) {
Dialogs.showError("Failed to convert '" + textToValidate + "' to integer number.");
return false;
}
} else if (this.parameter.getDataType() == Float.class) {
try {
Float.parseFloat(textToValidate);
} catch (NumberFormatException ex) {
Dialogs.showError("Failed to convert '" + textToValidate + "' to decimal number.");
return false;
}
}
}
return true;
}
private boolean validateValueSetText(String valueSetToValidate) {
String[] valueSet = null;
if (!StringUtils.isNullOrEmpty(valueSetToValidate)) {
valueSet = valueSetToValidate.split(ArrayConverter.SEPARATOR);
}
if (this.parameter.getDataType() == Integer.class) {
String wrongValue = null;
Integer[] numbers = null;
if (valueSet != null && valueSet.length > 0) {
numbers = new Integer[valueSet.length];
IntegerConverter integerConverter = new IntegerConverter();
for (int i = 0; i < valueSet.length && wrongValue == null; i++) {
try {
numbers[i] = integerConverter.parse(valueSet[i]);
if (numbers[i] == null) {
wrongValue = ""; // an empty value
}
} catch (ConversionException ex) {
wrongValue = valueSet[i];
}
}
}
if (wrongValue == null) {
populateDefaultValueComponent(numbers, null);
} else {
Dialogs.showError("Failed to convert '" + wrongValue + "' to integer number.");
return false;
}
} else if (this.parameter.getDataType() == Float.class) {
String wrongValue = null;
Float[] numbers = null;
if (valueSet != null && valueSet.length > 0) {
numbers = new Float[valueSet.length];
FloatConverter floatConverter = new FloatConverter();
for (int i = 0; i < valueSet.length && wrongValue == null; i++) {
try {
numbers[i] = floatConverter.parse(valueSet[i]);
if (numbers[i] == null) {
wrongValue = ""; // an empty value
}
} catch (ConversionException ex) {
wrongValue = valueSet[i];
}
}
}
if (wrongValue == null) {
populateDefaultValueComponent(numbers, null);
} else {
Dialogs.showError("Failed to convert '" + wrongValue + "' to decimal number.");
return false;
}
} else if (this.parameter.getDataType() == String.class) {
populateDefaultValueComponent(valueSet, null);
} else if (this.parameter.getDataType() == String[].class) {
populateListComponent(valueSet);
} else {
throw new IllegalArgumentException("Unknown parameter data type '" + this.parameter.getDataType().getName() + "'.");
}
return true;
}
private void populateDefaultValueComponent(Object[] valueSet, Object valueToSelect) {
if (valueSet == null || valueSet.length == 0) {
removeDefaultValueComponent();
createDefaultValueTextComponent();
addDefaultValueComponent();
} else {
if (!(defaultValueComponent instanceof JComboBox)) {
removeDefaultValueComponent();
createDefaultValueComboBoxComponent();
addDefaultValueComponent();
}
populateDefaultValueComboBoxComponent(valueSet, valueToSelect);
}
}
private void createDefaultValueTextComponent() {
this.defaultValueComponent = new JTextField();
ValidateTextComponentAdapter adapter = new ValidateTextComponentAdapter((JTextField)this.defaultValueComponent) {
@Override
protected boolean validateText(String textToValidate) {
return validateDefaultValueText(textToValidate);
}
};
PropertyDescriptor descriptor = getProperty().getDescriptor();
this.paramContext.bind(descriptor.getName(), adapter);
}
private void createDefaultValueComboBoxComponent() {
PropertyDescriptor descriptor = getProperty().getDescriptor();
SingleSelectionEditor singleSelectionEditor = new SingleSelectionEditor();
this.defaultValueComponent = singleSelectionEditor.createEditorComponent(descriptor, this.paramContext);
}
private void createDefaultValueComponent(Object[] valueSet, Object valueToSelect) {
if (valueSet == null || valueSet.length == 0) {
createDefaultValueTextComponent();
} else {
createDefaultValueComboBoxComponent();
}
}
private void addDefaultValueComponent() {
this.mainPanel.add(this.defaultValueComponent, getConstraints(3, 1, 1));
this.mainPanel.revalidate();
}
private void removeDefaultValueComponent() {
if (this.defaultValueComponent != null) {
Property property = getProperty();
Binding binding = this.paramContext.getBinding(property.getName());
binding.getComponentAdapter().unbindComponents();
this.mainPanel.remove(this.defaultValueComponent);
}
}
private void populateDefaultValueComboBoxComponent(Object[] valueSet, Object valueToSelect) {
JComboBox comboBox = (JComboBox)defaultValueComponent;
DefaultComboBoxModel model = new DefaultComboBoxModel();
if (valueSet != null && valueSet.length > 0) {
Object itemToSelect = null;
for (int i=0; i<valueSet.length; i++) {
model.addElement(valueSet[i]);
if (valueToSelect != null && valueToSelect.equals(valueSet[i])) {
itemToSelect = valueSet[i];
}
}
model.setSelectedItem(itemToSelect);
}
comboBox.setModel(model);
}
private void populateListComponent(String[] valueSet) {
JScrollPane scrollPane = (JScrollPane)this.defaultValueComponent;
JList list = (JList)scrollPane.getViewport().getView();
DefaultListModel model = new DefaultListModel();
if (valueSet != null) {
for (int i=0; i<valueSet.length; i++) {
model.addElement(valueSet[i]);
}
}
list.setModel(model);
}
private Property getProperty() {
Property[] properties = this.paramContext.getPropertySet().getProperties();
return properties[0];
}
private void newDataTypeSelected(String typeName, Class<?> typeClass, String defaultValue) {
removeDefaultValueComponent();
// recreate context of the default value
try {
if (this.paramContext != null) {
// remove the old properties
PropertySet propertySet = this.paramContext.getPropertySet();
Property property = getProperty();
propertySet.removeProperty(property);
}
PropertyDescriptor propertyDescriptor = ParameterDescriptorFactory.convert(this.parameter, new ParameterDescriptorFactory().getSourceProductMap());
DefaultPropertySetDescriptor propertySetDescriptor = new DefaultPropertySetDescriptor();
propertySetDescriptor.addPropertyDescriptor(propertyDescriptor);
PropertyContainer paramContainer = PropertyContainer.createMapBacked(new HashMap<>(), propertySetDescriptor);
this.paramContext = new BindingContext(paramContainer);
} catch (ConversionException e) {
logger.warning(e.getMessage());
}
boolean enabled = false;
String parameterType = ToolAdapterConstants.REGULAR_PARAM_MASK;
if (typeClass == Boolean.class) {
changeBooleanDataType(defaultValue);
} else if (typeClass == String.class) {
enabled = true;
changeStringDataType(defaultValue);
} else if (typeClass == String[].class) {
enabled = true;
changeListDataType(defaultValue);
} else if (typeName.equals("File")) {
changeFileDataType(defaultValue);
} else if (typeName.equals("Folder")) {
parameterType = ToolAdapterConstants.FOLDER_PARAM_MASK;
changeFolderDataType(defaultValue);
} else if (typeClass == Integer.class) {
enabled = true;
changeIntegerDataType(defaultValue);
} else if (typeClass == Float.class) {
enabled = true;
changeFloatDataType(defaultValue);
} else {
throw new IllegalArgumentException("Unknown type name '"+ typeName+"' and type class '" + typeClass.getName() + "'.");
}
this.parameter.setParameterType(parameterType);
this.valueSetTextComponent.setEnabled(enabled);
addDefaultValueComponent();
}
private void changeBooleanDataType(String defaultValue) {
Property property = getProperty();
ValueSet valueSet = new ValueSet(new Object[]{true, false});
property.getDescriptor().setValueSet(valueSet);
boolean isSelected = Boolean.parseBoolean(defaultValue);
try {
property.setValue(isSelected);
} catch (ValidationException e) {
logger.warning(e.getMessage());
}
CheckBoxEditor checkBoxEditor = new CheckBoxEditor();
defaultValueComponent = checkBoxEditor.createEditorComponent(property.getDescriptor(), this.paramContext);
defaultValueComponent.setBorder(new EmptyBorder(1, 0, 1, 0));
}
private void changeListDataType(String defaultValue) {
String[] valueSet = null;
if (!StringUtils.isNullOrEmpty(defaultValue)) {
valueSet = defaultValue.split(ArrayConverter.SEPARATOR);
}
try {
getProperty().setValue(valueSet);
} catch (ValidationException e) {
logger.warning(e.getMessage());
}
MultiSelectionEditor multiSelectionEditor = new MultiSelectionEditor();
this.defaultValueComponent = multiSelectionEditor.createEditorComponent(getProperty().getDescriptor(), this.paramContext);
JScrollPane scrollPane = (JScrollPane)this.defaultValueComponent;
JList list = (JList)scrollPane.getViewport().getView();
list.setVisibleRowCount(2);
if (valueSet != null && valueSet.length > 0) {
java.util.List<Integer> selectedIndices = new ArrayList<Integer>();
for (int i=0; i<list.getModel().getSize(); i++) {
Object item = list.getModel().getElementAt(i);
for (int k=0; k<valueSet.length; k++) {
if (item.equals(valueSet[k])) {
selectedIndices.add(i);
break;
}
}
}
int[] indices = new int[selectedIndices.size()];
for (int i=0; i<selectedIndices.size(); i++) {
indices[i] = selectedIndices.get(i).intValue();
}
list.setSelectedIndices(indices);
}
}
private void changeStringDataType(String defaultValue) {
try {
getProperty().setValue(defaultValue);
} catch (ValidationException e) {
logger.warning(e.getMessage());
}
String[] valueSet = this.valuesContext.getPropertySet().getProperty("valueSet").getValue();
createDefaultValueComponent(valueSet, defaultValue);
}
private void changeFolderDataType(String defaultValue) {
File file = null;
if (!StringUtils.isNullOrEmpty(defaultValue)) {
file = new File(defaultValue);
}
Property property = getProperty();
try {
property.setValue(file);
} catch (ValidationException e) {
logger.warning(e.getMessage());
}
DirectoryEditor folderEditor = new DirectoryEditor();
this.defaultValueComponent = folderEditor.createEditorComponent(property.getDescriptor(), this.paramContext);
}
private void changeFileDataType(String defaultValue) {
File file = null;
if (!StringUtils.isNullOrEmpty(defaultValue)) {
file = new File(defaultValue);
}
Property property = getProperty();
try {
property.setValue(file);
} catch (ValidationException e) {
logger.warning(e.getMessage());
}
FileEditor fileEditor = new FileEditor();
this.defaultValueComponent = fileEditor.createEditorComponent(property.getDescriptor(), this.paramContext);
}
private void changeIntegerDataType(String defaultValue) {
changeNumberDataType(new IntegerConverter(), defaultValue);
}
private void changeFloatDataType(String defaultValue) {
changeNumberDataType(new FloatConverter(), defaultValue);
}
private <NumberType extends Number> void changeNumberDataType(NumberConverter<NumberType> converter, String defaultValue) {
String[] valueSet = this.valuesContext.getPropertySet().getProperty("valueSet").getValue();
Number[] numbers = null;
if (valueSet != null && valueSet.length > 0) {
numbers = new Number[valueSet.length];
for (int i=0; i<valueSet.length; i++) {
try {
numbers[i] = converter.parse(valueSet[i]);
} catch (ConversionException ex) {
// ignore exception
}
}
}
Number defaultNumber = null;
if (!StringUtils.isNullOrEmpty(defaultValue)) {
try {
defaultNumber = converter.parse(defaultValue);
} catch (ConversionException e) {
logger.warning(e.getMessage());
}
}
try {
getProperty().setValue(defaultNumber);
} catch (ValidationException e) {
logger.warning(e.getMessage());
}
createDefaultValueComponent(numbers, defaultNumber);
}
private JComponent addTextPropertyEditor(JPanel parent, String label, String propertyName, int line, String requiredMessage) {
PropertyDescriptor propertyDescriptor = this.container.getDescriptor(propertyName);
JTextField editorComponent = new JTextField();
ComponentAdapter adapter = null;
if (StringUtils.isNullOrEmpty(requiredMessage)) {
adapter = new TextComponentAdapter(editorComponent);
} else {
adapter = new RequiredTextComponentAdapter(editorComponent, requiredMessage);
}
this.valuesContext.bind(propertyDescriptor.getName(), adapter);
parent.add(new JLabel(label), getConstraints(line, 0, 1));
parent.add(editorComponent, getConstraints(line, 1, 1));
return editorComponent;
}
private JComponent addTextPropertyEditor(JPanel parent, ComponentAdapter adapter, String label, String propertyName, int line) {
JComponent editorComponent = adapter.getComponents()[0];
PropertyDescriptor propertyDescriptor = this.container.getDescriptor(propertyName);
this.valuesContext.bind(propertyDescriptor.getName(), adapter);
parent.add(new JLabel(label), getConstraints(line, 0, 1));
parent.add(editorComponent, getConstraints(line, 1, 1));
return editorComponent;
}
private JComponent addBoolPropertyEditor(JPanel parent, String label, String propertyName, int line) {
PropertyDescriptor propertyDescriptor = this.container.getDescriptor(propertyName);
CheckBoxEditor boolEditor = new CheckBoxEditor();
JCheckBox checkBoxComponent = (JCheckBox)boolEditor.createEditorComponent(propertyDescriptor, valuesContext);
checkBoxComponent.setBorder(new EmptyBorder(1, 0, 1, 0));
parent.add(new JLabel(label), getConstraints(line, 0, 1));
parent.add(checkBoxComponent, getConstraints(line, 1, 1));
return checkBoxComponent;
}
private static GridBagConstraints getConstraints(int row, int col, int noCells) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = col;
c.gridy = row;
if(noCells != -1){
c.gridwidth = noCells;
}
c.insets = new Insets(2, 10, 2, 10);
return c;
}
public static String processDefaultValue(Object defaultValue) {
String defaultValueAsString = null;
if (defaultValue != null) {
if (defaultValue.getClass().isArray()) {
Object[] array = (Object[])defaultValue;
defaultValueAsString = "";
for (int i=0; i<array.length; i++) {
if (i > 0) {
defaultValueAsString += ",";
}
defaultValueAsString += array[i].toString();
}
} else {
defaultValueAsString = defaultValue.toString();
}
}
return defaultValueAsString;
}
private static <NumberType extends Number> boolean canConvertArrayToNumber(NumberConverter<NumberType> converter, String[] valueSet) {
if (valueSet != null && valueSet.length > 0) {
for (int i=0; i<valueSet.length; i++) {
try {
NumberType number = converter.parse(valueSet[i]);
if (number == null) {
return false;
}
} catch (ConversionException e) {
return false;
}
}
return true;
}
return false;
}
}
| 29,664 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ForwardFocusAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/ForwardFocusAction.java | package org.esa.snap.ui.tooladapter.dialogs;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* @author Jean Coravu
*/
public class ForwardFocusAction extends AbstractAction {
private final JComponent componentToReceiveFocus;
public ForwardFocusAction(String actionName, JComponent componentToReceiveFocus) {
super();
this.componentToReceiveFocus = componentToReceiveFocus;
putValue("actionName", actionName);
}
@Override
public void actionPerformed(ActionEvent event) {
this.componentToReceiveFocus.requestFocusInWindow();
}
public String getName() {
return (String)getValue("actionName");
}
} | 687 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ToolAdapterEditorDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/ToolAdapterEditorDialog.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.dialogs;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.binding.validators.NotEmptyValidator;
import com.bc.ceres.swing.binding.PropertyEditor;
import com.bc.ceres.swing.binding.PropertyEditorRegistry;
import com.bc.ceres.swing.binding.internal.TextFieldEditor;
import org.esa.snap.core.gpf.descriptor.*;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterConstants;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.esa.snap.ui.tooladapter.model.OperationType;
import org.esa.snap.ui.tooladapter.validators.RegexFieldValidator;
import org.esa.snap.utils.SpringUtilities;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.SpringLayout;
import javax.swing.border.TitledBorder;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.text.MessageFormat;
import static org.esa.snap.utils.SpringUtilities.DEFAULT_PADDING;
/**
* A dialog window used to edit an operator, or to create a new operator.
* It shows details of an operator such as: descriptor details (name, alias, label, version, copyright,
* authors, description), system variables, preprocessing tool, product writer, tool location,
* operator working directory, command line template content, tool output patterns and parameters.
*
* @author Cosmin Cara
*/
public class ToolAdapterEditorDialog extends AbstractAdapterEditor {
public ToolAdapterEditorDialog(AppContext appContext, JDialog parent, ToolAdapterOperatorDescriptor operatorDescriptor, OperationType operation) {
super(appContext, parent, operatorDescriptor, operation);
}
public ToolAdapterEditorDialog(AppContext appContext, JDialog parent, ToolAdapterOperatorDescriptor operatorDescriptor, int newNameIndex, OperationType operation) {
super(appContext, parent, operatorDescriptor, newNameIndex, operation);
}
@Override
protected JSplitPane createMainPanel() {
JSplitPane mainPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
mainPanel.setOneTouchExpandable(false);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double widthRatio = 0.5;
formWidth = Math.max((int) (Math.min(screenSize.width, MAX_4K_WIDTH) * widthRatio), MIN_WIDTH);
double heightRatio = 0.6;
int formHeight = Math.max((int) (Math.min(screenSize.height, MAX_4K_HEIGHT) * heightRatio), MIN_HEIGHT);
getJDialog().setMinimumSize(new Dimension(formWidth + 16, formHeight + 72));
// top panel first
JSplitPane topPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
topPanel.setOneTouchExpandable(false);
JPanel descriptorPanel = createDescriptorAndVariablesAndPreprocessingPanel();
Dimension topPanelDimension = new Dimension((int)((formWidth - 3 * DEFAULT_PADDING) * 0.5), (int)((formHeight - 3 * DEFAULT_PADDING) * 0.75));
descriptorPanel.setMinimumSize(topPanelDimension);
descriptorPanel.setPreferredSize(topPanelDimension);
topPanel.setLeftComponent(descriptorPanel);
JPanel configurationPanel = createToolInfoPanel();
configurationPanel.setMinimumSize(topPanelDimension);
configurationPanel.setPreferredSize(topPanelDimension);
topPanel.setRightComponent(configurationPanel);
topPanel.setDividerLocation(0.5);
// bottom panel last
JPanel bottomPannel = createParametersPanel();
Dimension bottomPanelDimension = new Dimension(formWidth - 2 * DEFAULT_PADDING, (int)((formHeight - 3 * DEFAULT_PADDING) * 0.25));
bottomPannel.setMinimumSize(bottomPanelDimension);
bottomPannel.setPreferredSize(bottomPanelDimension);
mainPanel.setTopComponent(topPanel);
mainPanel.setBottomComponent(bottomPannel);
mainPanel.setDividerLocation(0.75);
mainPanel.setPreferredSize(new Dimension(formWidth, formHeight));
mainPanel.revalidate();
return mainPanel;
}
@Override
protected JPanel createDescriptorPanel() {
final JPanel descriptorPanel = new JPanel(new SpringLayout());
TextFieldEditor textEditor = new TextFieldEditor();
addValidatedTextField(descriptorPanel, textEditor, Bundle.CTL_Label_Alias_Text(), ToolAdapterConstants.ALIAS, "[^\\\\\\?%\\*:\\|\"<>\\./]*");
addTextField(descriptorPanel, textEditor, Bundle.CTL_Label_UniqueName_Text(), ToolAdapterConstants.NAME, true, null);
addTextField(descriptorPanel, textEditor, Bundle.CTL_Label_Label_Text(), ToolAdapterConstants.LABEL, true, null);
addTextField(descriptorPanel, textEditor, Bundle.CTL_Label_Version_Text(), ToolAdapterConstants.VERSION, true, null);
addTextField(descriptorPanel, textEditor, Bundle.CTL_Label_Copyright_Text(), ToolAdapterConstants.COPYRIGHT, false, null);
addTextField(descriptorPanel, textEditor, Bundle.CTL_Label_Authors_Text(), ToolAdapterConstants.AUTHORS, false, null);
addTextField(descriptorPanel, textEditor, Bundle.CTL_Label_Description_Text(), ToolAdapterConstants.DESCRIPTION, false, null);
java.util.List<String> menus = getAvailableMenuOptions(null);
addComboField(descriptorPanel, Bundle.CTL_Label_MenuLocation_Text(), ToolAdapterConstants.MENU_LOCATION, menus);
TitledBorder title = BorderFactory.createTitledBorder(Bundle.CTL_Panel_OperatorDescriptor_Text());
descriptorPanel.setBorder(title);
SpringUtilities.makeCompactGrid(descriptorPanel, 8, 2, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
return descriptorPanel;
}
@Override
protected JPanel createVariablesPanel() {
JPanel variablesBorderPanel = new JPanel();
BoxLayout layout = new BoxLayout(variablesBorderPanel, BoxLayout.PAGE_AXIS);
variablesBorderPanel.setLayout(layout);
variablesBorderPanel.setBorder(BorderFactory.createTitledBorder(Bundle.CTL_Panel_SysVar_Border_TitleText()));
AbstractButton addVariableButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon(Bundle.Icon_Add()), false);
addVariableButton.setText(Bundle.CTL_Button_Add_Variable_Text());
addVariableButton.setAlignmentX(Component.LEFT_ALIGNMENT);
addVariableButton.setMaximumSize(new Dimension(150, controlHeight));
AbstractButton addDependentVariableButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon(Bundle.Icon_Add()), false);
addDependentVariableButton.setText(Bundle.CTL_Button_Add_PDVariable_Text());
addDependentVariableButton.setAlignmentX(Component.LEFT_ALIGNMENT);
addDependentVariableButton.setMaximumSize(new Dimension(250, controlHeight));
JPanel buttonsPannel = new JPanel(new SpringLayout());
buttonsPannel.add(addVariableButton);
buttonsPannel.add(addDependentVariableButton);
SpringUtilities.makeCompactGrid(buttonsPannel, 1, 2, 0, 0, 0, 0);
buttonsPannel.setAlignmentX(Component.LEFT_ALIGNMENT);
variablesBorderPanel.add(buttonsPannel);
varTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
varTable.setRowHeight(20);
JScrollPane scrollPane = new JScrollPane(varTable);
scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
variablesBorderPanel.add(scrollPane);
variablesBorderPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
Dimension variablesPanelDimension = new Dimension((formWidth - 3 * DEFAULT_PADDING) / 2 - 2 * DEFAULT_PADDING, 130);
variablesBorderPanel.setMinimumSize(variablesPanelDimension);
variablesBorderPanel.setMaximumSize(variablesPanelDimension);
variablesBorderPanel.setPreferredSize(variablesPanelDimension);
addVariableButton.addActionListener(e -> {
newOperatorDescriptor.getVariables().add(new SystemVariable("key", ""));
varTable.revalidate();
});
addDependentVariableButton.addActionListener(e -> {
newOperatorDescriptor.getVariables().add(new SystemDependentVariable("key", ""));
varTable.revalidate();
});
return variablesBorderPanel;
}
@Override
protected JPanel createPreProcessingPanel() {
final JPanel preProcessingPanel = new JPanel(new SpringLayout());
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor("preprocessorExternalTool");
PropertyEditor editor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
JComponent editorComponent = editor.createEditorComponent(propertyDescriptor, bindingContext);
editorComponent.setMaximumSize(new Dimension(editorComponent.getMaximumSize().width, controlHeight));
editorComponent.setPreferredSize(new Dimension(editorComponent.getPreferredSize().width, controlHeight));
preProcessingPanel.add(createCheckboxComponent("preprocessTool", editorComponent, newOperatorDescriptor.getPreprocessTool()));
preProcessingPanel.add(new JLabel(Bundle.CTL_Label_PreprocessingTool_Text()));
preProcessingPanel.add(editorComponent);
propertyDescriptor = propertyContainer.getDescriptor("processingWriter");
editor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
editorComponent = editor.createEditorComponent(propertyDescriptor, bindingContext);
editorComponent.setMaximumSize(new Dimension(editorComponent.getMaximumSize().width, controlHeight));
editorComponent.setPreferredSize(new Dimension(editorComponent.getPreferredSize().width, controlHeight));
JComponent writeComponent = createCheckboxComponent("writeForProcessing", editorComponent, newOperatorDescriptor.shouldWriteBeforeProcessing());
preProcessingPanel.add(writeComponent);
preProcessingPanel.add(new JLabel(Bundle.CTL_Label_WriteBefore_Text()));
preProcessingPanel.add(editorComponent);
TitledBorder title = BorderFactory.createTitledBorder(Bundle.CTL_Panel_PreProcessing_Border_TitleText());
preProcessingPanel.setBorder(title);
SpringUtilities.makeCompactGrid(preProcessingPanel, 2, 3, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
return preProcessingPanel;
}
@Override
protected JPanel createToolInfoPanel() {
JPanel container = new JPanel(new SpringLayout());
JPanel configPanel = new JPanel(new SpringLayout());
configPanel.setBorder(BorderFactory.createTitledBorder(Bundle.CTL_Panel_ConfigParams_Text()));
JPanel panelToolFiles = new JPanel(new SpringLayout());
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor(ToolAdapterConstants.MAIN_TOOL_FILE_LOCATION);
propertyDescriptor.setValidator(new NotEmptyValidator());
PropertyEditor editor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
JComponent editorComponent = editor.createEditorComponent(propertyDescriptor, bindingContext);
editorComponent.setMaximumSize(new Dimension(editorComponent.getMaximumSize().width, controlHeight));
editorComponent.setPreferredSize(new Dimension(editorComponent.getPreferredSize().width, controlHeight));
panelToolFiles.add(new JLabel(Bundle.CTL_Label_ToolLocation_Text()));
panelToolFiles.add(editorComponent);
propertyDescriptor = propertyContainer.getDescriptor(ToolAdapterConstants.WORKING_DIR);
propertyDescriptor.setAttribute("directory", true);
propertyDescriptor.setValidator((property, value) -> {
if (value == null || value.toString().trim().isEmpty()) {
throw new ValidationException(MessageFormat.format("Value for ''{0}'' must not be empty.",
property.getDescriptor().getDisplayName()));
}
});
editor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
editorComponent = editor.createEditorComponent(propertyDescriptor, bindingContext);
editorComponent.setMaximumSize(new Dimension(editorComponent.getMaximumSize().width, controlHeight));
editorComponent.setPreferredSize(new Dimension(editorComponent.getPreferredSize().width, controlHeight));
panelToolFiles.add(new JLabel(Bundle.CTL_Label_WorkDir_Text()));
panelToolFiles.add(editorComponent);
SpringUtilities.makeCompactGrid(panelToolFiles, 2, 2, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
configPanel.add(panelToolFiles);
JPanel checkPanel = new JPanel(new SpringLayout());
propertyDescriptor = propertyContainer.getDescriptor(ToolAdapterConstants.HANDLE_OUTPUT);
editor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
editorComponent = editor.createEditorComponent(propertyDescriptor, bindingContext);
editorComponent.setMaximumSize(new Dimension(editorComponent.getMaximumSize().width, controlHeight));
editorComponent.setPreferredSize(new Dimension(editorComponent.getPreferredSize().width, controlHeight));
checkPanel.add(editorComponent);
checkPanel.add(new JLabel("Tool produces the name of the output product"));
SpringUtilities.makeCompactGrid(checkPanel, 1, 2, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
configPanel.add(checkPanel);
JLabel label = new JLabel(Bundle.CTL_Label_CmdLineTemplate_Text());
configPanel.add(label);
JScrollPane scrollPane = new JScrollPane(createTemplateEditorField());
configPanel.add(scrollPane);
SpringUtilities.makeCompactGrid(configPanel, 4, 1, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
container.add(configPanel);
container.add(createPatternsPanel());
SpringUtilities.makeCompactGrid(container, 2, 1, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
return container;
}
@Override
protected JPanel createPatternsPanel() {
JPanel patternsPanel = new JPanel(new SpringLayout());
patternsPanel.setBorder(BorderFactory.createTitledBorder(Bundle.CTL_Panel_OutputPattern_Border_TitleText()));
TextFieldEditor textEditor = new TextFieldEditor();
addTextField(patternsPanel, textEditor, Bundle.CTL_Label_ProgressPattern(), ToolAdapterConstants.PROGRESS_PATTERN, false, null);
propertyContainer.getDescriptor(ToolAdapterConstants.PROGRESS_PATTERN).setValidator(new RegexFieldValidator());
addTextField(patternsPanel, textEditor, Bundle.CTL_Label_ErrorPattern(), ToolAdapterConstants.ERROR_PATTERN, false, null);
propertyContainer.getDescriptor(ToolAdapterConstants.ERROR_PATTERN).setValidator(new RegexFieldValidator());
SpringUtilities.makeCompactGrid(patternsPanel, 2, 2, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
return patternsPanel;
}
@Override
protected JPanel createParametersPanel() {
JPanel paramsPanel = new JPanel();
BoxLayout layout = new BoxLayout(paramsPanel, BoxLayout.PAGE_AXIS);
paramsPanel.setLayout(layout);
AbstractButton addParamBut = ToolButtonFactory.createButton(UIUtils.loadImageIcon(Bundle.Icon_Add()), false);
addParamBut.setAlignmentX(Component.LEFT_ALIGNMENT);
addParamBut.setAlignmentY(Component.TOP_ALIGNMENT);
paramsPanel.add(addParamBut);
int tableWidth = (formWidth - 2 * DEFAULT_PADDING);
int widths[] = {27, 120, (int)(tableWidth * 0.25), (int)(tableWidth * 0.1), 100, (int)(tableWidth * 0.32), 30};
for(int i=0; i < widths.length; i++) {
paramsTable.getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
}
JScrollPane tableScrollPane = new JScrollPane(paramsTable);
tableScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
paramsPanel.add(tableScrollPane);
addParamBut.addActionListener(e -> paramsTable.addParameterToTable(new ToolParameterDescriptor("parameterName", String.class), 0));
TitledBorder title = BorderFactory.createTitledBorder(Bundle.CTL_Panel_OpParams_Border_TitleText());
paramsPanel.setBorder(title);
return paramsPanel;
}
@Override
protected JPanel createBundlePanel() {
return null;
}
private JPanel createDescriptorAndVariablesAndPreprocessingPanel() {
JPanel descriptorAndVariablesPanel = new JPanel(new SpringLayout());
descriptorAndVariablesPanel.add(createDescriptorPanel());
descriptorAndVariablesPanel.add(createVariablesPanel());
descriptorAndVariablesPanel.add(createPreProcessingPanel());
SpringUtilities.makeCompactGrid(descriptorAndVariablesPanel, 3, 1, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
return descriptorAndVariablesPanel;
}
}
| 18,075 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ToolExecutionForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/ToolExecutionForm.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.dialogs;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.swing.binding.PropertyPane;
import com.bc.ceres.swing.selection.AbstractSelectionChangeListener;
import com.bc.ceres.swing.selection.SelectionChangeEvent;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.gpf.descriptor.TemplateParameterDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolParameterDescriptor;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterConstants;
import org.esa.snap.core.gpf.ui.DefaultIOParametersPanel;
import org.esa.snap.core.gpf.ui.SourceProductSelector;
import org.esa.snap.core.gpf.ui.TargetProductSelector;
import org.esa.snap.core.gpf.ui.TargetProductSelectorModel;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.tooladapter.preferences.ToolAdapterOptionsController;
import org.esa.snap.utils.SpringUtilities;
import org.openide.util.NbPreferences;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.border.EmptyBorder;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Form for displaying execution parameters.
* This form is part of <code>ToolAdapterExecutionDialog</code>.
*
* @author Ramona Manda
*/
class ToolExecutionForm extends JTabbedPane {
private AppContext appContext;
private ToolAdapterOperatorDescriptor operatorDescriptor;
private PropertySet propertySet;
private TargetProductSelector targetProductSelector;
private DefaultIOParametersPanel ioParamPanel;
private String fileExtension;
private JCheckBox checkDisplayOutput;
ConsolePane console;
private final String TIF_EXTENSION = ".tif";
JSplitPane bottomPane;
public ToolExecutionForm(AppContext appContext, ToolAdapterOperatorDescriptor descriptor, PropertySet propertySet,
TargetProductSelector targetProductSelector) {
this.appContext = appContext;
this.operatorDescriptor = descriptor;
this.propertySet = propertySet;
this.targetProductSelector = targetProductSelector;
//before executing, the sourceProduct and sourceProductFile must be removed from the list, since they cannot be edited
Property sourceProperty = this.propertySet.getProperty(ToolAdapterConstants.TOOL_SOURCE_PRODUCT_FILE);
if(sourceProperty != null) {
this.propertySet.removeProperty(sourceProperty);
}
sourceProperty = this.propertySet.getProperty(ToolAdapterConstants.TOOL_SOURCE_PRODUCT_ID);
if(sourceProperty != null) {
this.propertySet.removeProperty(sourceProperty);
}
// if the tool is handling by itself the output product name, then remove targetProductFile from the list,
// since it may bring only confusion in this case
if (operatorDescriptor.isHandlingOutputName()) {
sourceProperty = this.propertySet.getProperty(ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE);
if (sourceProperty != null) {
this.propertySet.removeProperty(sourceProperty);
}
}
//initialise the target product's directory to the working directory
final TargetProductSelectorModel targetProductSelectorModel = targetProductSelector.getModel();
targetProductSelectorModel.setProductDir(operatorDescriptor.resolveVariables(operatorDescriptor.getWorkingDir()));
if(!operatorDescriptor.isHandlingOutputName() || operatorDescriptor.getSourceProductCount() > 0) {
ioParamPanel = createIOParamTab();
addTab("I/O Parameters", ioParamPanel);
}
JPanel processingParamPanel = new JPanel(new SpringLayout());
checkDisplayOutput = new JCheckBox("Display execution output");
checkDisplayOutput.setSelected(Boolean.parseBoolean(NbPreferences.forModule(Dialogs.class).get(ToolAdapterOptionsController.PREFERENCE_KEY_SHOW_EXECUTION_OUTPUT, "false")));
processingParamPanel.add(checkDisplayOutput);
bottomPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
bottomPane.setTopComponent(createProcessingParamTab());
console = new ConsolePane();
if (checkDisplayOutput.isSelected()) {
bottomPane.setBottomComponent(console);
bottomPane.setDividerLocation(0.6);
}
processingParamPanel.add(bottomPane);
checkDisplayOutput.addActionListener((ActionEvent e) -> {
if (!checkDisplayOutput.isSelected()) {
bottomPane.remove(console);
} else {
bottomPane.setBottomComponent(console);
}
refreshDimension();
});
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
setPreferredSize(new Dimension((int)(screen.getWidth() / 3), (int)(screen.getHeight() / 2.5)));
setMinimumSize(new Dimension(200, 200));
SpringUtilities.makeCompactGrid(processingParamPanel, 2, 1, 2, 2, 2, 2);
addTab("Processing Parameters", processingParamPanel);
updateTargetProductFields();
}
/**
* Reset the split procentage to 60%.
*/
public void refreshDimension(){
bottomPane.setDividerLocation(0.6);
bottomPane.revalidate();
bottomPane.repaint();
}
/**
* Method called before actually showing the form, in which additional
* initialisation may occur.
*/
public void prepareShow() {
if (ioParamPanel != null) {
ioParamPanel.initSourceProductSelectors();
}
}
/**
* Method called before hiding the form, in which additional
* cleanup may be performed.
*/
public void prepareHide() {
if (ioParamPanel != null) {
ioParamPanel.releaseSourceProductSelectors();
}
}
/**
* Fetches the list of products selected in UI
*
* @return The list of selected products to be used as input source
*/
public Product[] getSourceProducts() {
List<Product> sourceProducts = new ArrayList<>();
if (ioParamPanel != null){
ArrayList<SourceProductSelector> sourceProductSelectorList = ioParamPanel.getSourceProductSelectorList();
sourceProducts.addAll(sourceProductSelectorList.stream().map(SourceProductSelector::getSelectedProduct).collect(Collectors.toList()));
}
return sourceProducts.toArray(new Product[sourceProducts.size()]);
}
public Object getPropertyValue(String propertyName) {
Object result = null;
if (propertySet.isPropertyDefined(propertyName)) {
result = propertySet.getProperty(propertyName).getValue();
}
return result;
}
/**
* Gets the target (destination) product file
*
* @return The target product file
*/
public File getTargetProductFile() {
return targetProductSelector.getModel().getProductFile();
}
public boolean shouldDisplayOutput() {
return checkDisplayOutput.isSelected();
}
private DefaultIOParametersPanel createIOParamTab() {
final DefaultIOParametersPanel ioPanel = new DefaultIOParametersPanel(appContext, operatorDescriptor,
targetProductSelector, !operatorDescriptor.isHandlingOutputName());
final ArrayList<SourceProductSelector> sourceProductSelectorList = ioPanel.getSourceProductSelectorList();
if (!sourceProductSelectorList.isEmpty()) {
final SourceProductSelector sourceProductSelector = sourceProductSelectorList.get(0);
sourceProductSelector.addSelectionChangeListener(new SourceProductChangeListener());
}
return ioPanel;
}
private JScrollPane createProcessingParamTab() {
Arrays.stream(operatorDescriptor.getToolParameterDescriptors().toArray()).filter(p -> !((ToolParameterDescriptor)p).isTemplateParameter()).forEach(p ->
{
ToolParameterDescriptor param = (ToolParameterDescriptor)p;
String label = param.getAlias();
String propName = param.getName();
if (label != null && !label.isEmpty() && propertySet.isPropertyDefined(propName)) {
Property property = propertySet.getProperty(propName);
property.getDescriptor().setDisplayName(label);
}
});
Arrays.stream(operatorDescriptor.getToolParameterDescriptors().toArray())
.filter(p -> ((ToolParameterDescriptor)p).isTemplateParameter())
.forEach(tp -> {
TemplateParameterDescriptor tParam = (TemplateParameterDescriptor) tp;
propertySet.getProperty(tParam.getName()).getDescriptor().setAttribute("visible", false);
Arrays.stream(tParam.getParameterDescriptors().toArray())
.forEach(p -> {
ToolParameterDescriptor param = (ToolParameterDescriptor) p;
String label = param.getAlias();
String propName = param.getName();
if (label != null && !label.isEmpty() && propertySet.isPropertyDefined(propName)) {
Property property = propertySet.getProperty(propName);
property.getDescriptor().setDisplayName(label);
}
});
});
PropertyPane parametersPane = new PropertyPane(propertySet);
final JPanel parametersPanel = parametersPane.createPanel();
parametersPanel.addPropertyChangeListener(evt -> {
if (!(evt.getNewValue() instanceof JTextField)) return;
JTextField field = (JTextField) evt.getNewValue();
String text = field.getText();
if (text != null && text.isEmpty()) {
field.setCaretPosition(text.length());
}
});
parametersPanel.setBorder(new EmptyBorder(4, 4, 4, 4));
//parametersPanel.setPreferredSize(ioParamPanel.getPreferredSize());
return new JScrollPane(parametersPanel);
}
private void updateTargetProductFields() {
TargetProductSelectorModel model = targetProductSelector.getModel();
Property property = propertySet.getProperty(ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE);
model.setSaveToFileSelected(false);
if (!operatorDescriptor.isHandlingOutputName()) {
Object value = property.getValue();
if (value != null) {
File file = operatorDescriptor.resolveVariables(new File(property.getValueAsText()));
if (!file.isAbsolute()) {
file = new File(operatorDescriptor.getWorkingDir(), file.getAbsolutePath());
}
String productName = FileUtils.getFilenameWithoutExtension(file);
if (fileExtension == null) {
fileExtension = FileUtils.getExtension(file);
}
model.setProductName(productName);
}
} else {
try {
model.setProductName("Output Product");
if (property != null) {
property.setValue(null);
}
targetProductSelector.setEnabled(false);
targetProductSelector.getSaveToFileCheckBox().setEnabled(false);
} catch (ValidationException e) {
Logger.getLogger(ToolExecutionForm.class.getName()).severe(e.getMessage());
}
}
targetProductSelector.getProductDirTextField().setEnabled(false);
}
private class SourceProductChangeListener extends AbstractSelectionChangeListener {
private static final String TARGET_PRODUCT_NAME_SUFFIX = "_processed";
@Override
public void selectionChanged(SelectionChangeEvent event) {
if (!operatorDescriptor.isHandlingOutputName()) {
Property targetProperty = propertySet.getProperty(ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE);
Object value = targetProperty.getValue();
String productName = "";
final Product selectedProduct = (Product) event.getSelection().getSelectedValue();
if (selectedProduct != null) {
productName = FileUtils.getFilenameWithoutExtension(selectedProduct.getName());
}
final TargetProductSelectorModel targetProductSelectorModel = targetProductSelector.getModel();
productName += TARGET_PRODUCT_NAME_SUFFIX;
targetProductSelectorModel.setProductName(productName);
String workingDir = operatorDescriptor.getWorkingDir();
if (value != null) {
File oldValue = operatorDescriptor.resolveVariables(value instanceof File ? (File) value : new File((String) value));
if (fileExtension == null)
fileExtension = TIF_EXTENSION;
File current;
File parent;
if (oldValue != null && (parent = oldValue.getParentFile()) != null) {
current = new File(parent.getAbsolutePath(), productName + fileExtension);
} else {
current = new File(workingDir, productName + fileExtension);
}
propertySet.setValue(ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE, current);
} else {
try {
targetProperty.setValue(new File(workingDir, productName + TIF_EXTENSION));
} catch (ValidationException ignored) {
}
}
}
}
}
}
| 15,145 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ToolAdapterTabbedEditorDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/ToolAdapterTabbedEditorDialog.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.dialogs;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.binding.validators.NotEmptyValidator;
import com.bc.ceres.swing.binding.PropertyEditor;
import com.bc.ceres.swing.binding.PropertyEditorRegistry;
import com.bc.ceres.swing.binding.internal.TextFieldEditor;
import org.esa.snap.core.gpf.descriptor.SystemDependentVariable;
import org.esa.snap.core.gpf.descriptor.SystemVariable;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.dependency.BundleInstaller;
import org.esa.snap.core.gpf.descriptor.dependency.BundleLocation;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterConstants;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.esa.snap.ui.tooladapter.dialogs.components.AnchorLabel;
import org.esa.snap.ui.tooladapter.dialogs.progress.ProgressHandler;
import org.esa.snap.ui.tooladapter.model.OperationType;
import org.esa.snap.ui.tooladapter.validators.RegexFieldValidator;
import org.esa.snap.utils.SpringUtilities;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
import javax.swing.table.TableColumn;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import static org.esa.snap.utils.SpringUtilities.DEFAULT_PADDING;
/**
* A tabbed dialog window used to edit an operator, or to create a new operator.
* It shows details of an operator such as: descriptor details (name, alias, label, version, copyright,
* authors, description), system variables, preprocessing tool, product writer, tool location,
* operator working directory, command line template content, tool output patterns and parameters.
*
* @author Ramona Manda
* @author Cosmin Cara
*/
public class ToolAdapterTabbedEditorDialog extends AbstractAdapterEditor {
private static final String ALIAS_PATTERN = "[^\\\\\\?%\\*:\\|\"<>\\./]*";
private JTabbedPane tabbedPane;
private int currentIndex;
ToolAdapterTabbedEditorDialog(AppContext appContext, JDialog parent, ToolAdapterOperatorDescriptor operatorDescriptor, OperationType operation) {
super(appContext, parent, operatorDescriptor, operation);
}
ToolAdapterTabbedEditorDialog(AppContext appContext, JDialog parent, ToolAdapterOperatorDescriptor operatorDescriptor, int newNameIndex, OperationType operation) {
super(appContext, parent, operatorDescriptor, newNameIndex, operation);
}
@Override
protected JTabbedPane createMainPanel() {
this.tabbedPane = new JTabbedPane(JTabbedPane.LEFT);
this.tabbedPane.setBorder(BorderFactory.createEmptyBorder());
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double widthRatio = 0.5;
formWidth = Math.max((int) (screenSize.width * widthRatio), MIN_TABBED_WIDTH);
double heightRatio = 0.5;
int formHeight = Math.max((int) (screenSize.height * heightRatio), MIN_TABBED_HEIGHT);
tabbedPane.setPreferredSize(new Dimension(formWidth, formHeight));
getJDialog().setMinimumSize(new Dimension(formWidth + 16, formHeight + 72));
addTab(tabbedPane, Bundle.CTL_Panel_OperatorDescriptor_Text(), createDescriptorTab());
currentIndex++;
addTab(tabbedPane, Bundle.CTL_Panel_ConfigParams_Text(), createToolInfoPanel());
currentIndex++;
addTab(tabbedPane, Bundle.CTL_Panel_PreProcessing_Border_TitleText(), createPreProcessingTab());
currentIndex++;
addTab(tabbedPane, Bundle.CTL_Panel_OpParams_Border_TitleText(), createParametersTab(formWidth));
currentIndex++;
addTab(tabbedPane, Bundle.CTL_Panel_SysVar_Border_TitleText(), createVariablesPanel());
currentIndex++;
addTab(tabbedPane, Bundle.CTL_Panel_Bundle_TitleText(), createBundlePanel());
currentIndex++;
tabbedPane.setUI(new BasicTabbedPaneUI());
formWidth = tabbedPane.getTabComponentAt(0).getWidth();
return tabbedPane;
}
@Override
protected JPanel createDescriptorPanel() {
JPanel descriptorPanel = new JPanel(new SpringLayout());
TextFieldEditor textEditor = new TextFieldEditor();
addValidatedTextField(descriptorPanel, textEditor, Bundle.CTL_Label_Alias_Text(),
ToolAdapterConstants.ALIAS, ALIAS_PATTERN);
JComponent component = addTextField(descriptorPanel, textEditor, Bundle.CTL_Label_UniqueName_Text(),
ToolAdapterConstants.NAME, true, new String[] { " " });
anchorLabels.put(ToolAdapterConstants.NAME, new AnchorLabel("Name is not unique",
tabbedPane, currentIndex, component));
addTextField(descriptorPanel, textEditor, Bundle.CTL_Label_Label_Text(),
ToolAdapterConstants.LABEL, true, null);
addTextField(descriptorPanel, textEditor, Bundle.CTL_Label_Version_Text(),
ToolAdapterConstants.VERSION, true, new String[] { " ", "-", "+" });
addTextField(descriptorPanel, textEditor, Bundle.CTL_Label_Copyright_Text(),
ToolAdapterConstants.COPYRIGHT, false, null);
addTextField(descriptorPanel, textEditor, Bundle.CTL_Label_Authors_Text(),
ToolAdapterConstants.AUTHORS, false, null);
addTextField(descriptorPanel, textEditor, Bundle.CTL_Label_Description_Text(),
ToolAdapterConstants.DESCRIPTION, false, null);
propertyContainer
.addPropertyChangeListener(ToolAdapterConstants.ALIAS,
evt -> propertyContainer.setValue(ToolAdapterConstants.NAME,
ToolAdapterConstants.OPERATOR_NAMESPACE +
evt.getNewValue().toString()));
List<String> menus = getAvailableMenuOptions(null);
addComboField(descriptorPanel, Bundle.CTL_Label_MenuLocation_Text(), ToolAdapterConstants.MENU_LOCATION, menus);
addComboField(descriptorPanel, Bundle.CTL_Label_TemplateType_Text(), ToolAdapterConstants.TEMPLATE_TYPE, true, false);
SpringUtilities.makeCompactGrid(descriptorPanel, 9, 2, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
return descriptorPanel;
}
@Override
protected JPanel createVariablesPanel() {
JPanel variablesBorderPanel = new JPanel();
BoxLayout layout = new BoxLayout(variablesBorderPanel, BoxLayout.PAGE_AXIS);
variablesBorderPanel.setLayout(layout);
AbstractButton addVariableButton =
ToolButtonFactory.createButton(UIUtils.loadImageIcon(Bundle.Icon_Add()), false);
addVariableButton.setText(Bundle.CTL_Button_Add_Variable_Text());
addVariableButton.setMaximumSize(new Dimension(150, controlHeight));
addVariableButton.setAlignmentX(Component.LEFT_ALIGNMENT);
AbstractButton addDependentVariableButton =
ToolButtonFactory.createButton(UIUtils.loadImageIcon(Bundle.Icon_Add()), false);
addDependentVariableButton.setText(Bundle.CTL_Button_Add_PDVariable_Text());
addDependentVariableButton.setMaximumSize(new Dimension(250, controlHeight));
addDependentVariableButton.setAlignmentX(Component.LEFT_ALIGNMENT);
JPanel buttonsPannel = new JPanel(new SpringLayout());
buttonsPannel.add(addVariableButton);
buttonsPannel.add(addDependentVariableButton);
SpringUtilities.makeCompactGrid(buttonsPannel, 1, 2, 0, 0, 0, 0);
buttonsPannel.setAlignmentX(Component.LEFT_ALIGNMENT);
variablesBorderPanel.add(buttonsPannel);
varTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
varTable.setRowHeight(controlHeight);
int widths[] = {controlHeight, 3 * controlHeight, 10 * controlHeight};
for (int i = 0; i < widths.length; i++) {
TableColumn column = varTable.getColumnModel().getColumn(i);
column.setPreferredWidth(widths[i]);
column.setWidth(widths[i]);
}
JScrollPane scrollPane = new JScrollPane(varTable);
scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
variablesBorderPanel.add(scrollPane);
variablesBorderPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
Dimension variablesPanelDimension =
new Dimension((formWidth - 3 * DEFAULT_PADDING) / 2 - 2 * DEFAULT_PADDING, 130);
variablesBorderPanel.setMinimumSize(variablesPanelDimension);
variablesBorderPanel.setMaximumSize(variablesPanelDimension);
variablesBorderPanel.setPreferredSize(variablesPanelDimension);
addVariableButton.addActionListener(e -> {
newOperatorDescriptor.getVariables().add(new SystemVariable("key", ""));
varTable.revalidate();
});
addDependentVariableButton.addActionListener(e -> {
newOperatorDescriptor.getVariables().add(new SystemDependentVariable("key", ""));
varTable.revalidate();
});
return variablesBorderPanel;
}
@Override
protected JPanel createPreProcessingPanel() {
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor("preprocessorExternalTool");
PropertyEditor editor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
JComponent firstEditorComponent = editor.createEditorComponent(propertyDescriptor, bindingContext);
firstEditorComponent.setMaximumSize(new Dimension(firstEditorComponent.getMaximumSize().width,
controlHeight));
firstEditorComponent.setPreferredSize(new Dimension(firstEditorComponent.getPreferredSize().width,
controlHeight));
propertyDescriptor = propertyContainer.getDescriptor("processingWriter");
editor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
JComponent secondEditorComponent = editor.createEditorComponent(propertyDescriptor, bindingContext);
secondEditorComponent.setMaximumSize(new Dimension(secondEditorComponent.getMaximumSize().width,
controlHeight));
secondEditorComponent.setPreferredSize(new Dimension(secondEditorComponent.getPreferredSize().width,
controlHeight));
JCheckBox checkBoxComponent =
(JCheckBox)createCheckboxComponent("preprocessTool", firstEditorComponent,
newOperatorDescriptor.getPreprocessTool());
checkBoxComponent.setText(Bundle.CTL_Label_PreprocessingTool_Text());
JCheckBox writeComponent =
(JCheckBox)createCheckboxComponent("writeForProcessing", secondEditorComponent,
newOperatorDescriptor.shouldWriteBeforeProcessing());
writeComponent.setText(Bundle.CTL_Label_WriteBefore_Text());
JPanel preProcessingPanel = new JPanel(new SpringLayout());
preProcessingPanel.add(checkBoxComponent);
preProcessingPanel.add(firstEditorComponent);
preProcessingPanel.add(writeComponent);
preProcessingPanel.add(secondEditorComponent);
SpringUtilities.makeCompactGrid(preProcessingPanel, 2, 2,
DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
forwardFocusWhenTabKeyReleased(checkBoxComponent, firstEditorComponent);
forwardFocusWhenTabKeyReleased(firstEditorComponent, writeComponent);
forwardFocusWhenTabKeyReleased(writeComponent, secondEditorComponent);
forwardFocusWhenTabKeyReleased(secondEditorComponent, this.tabbedPane);
return preProcessingPanel;
}
@Override
protected JPanel createToolInfoPanel() {
final JPanel configPanel = new JPanel(new SpringLayout());
JPanel panelToolFiles = new JPanel(new SpringLayout());
PropertyEditorRegistry editorRegistry = PropertyEditorRegistry.getInstance();
PropertyDescriptor propertyDescriptor =
propertyContainer.getDescriptor(ToolAdapterConstants.MAIN_TOOL_FILE_LOCATION);
propertyDescriptor.setValidator(new NotEmptyValidator());
PropertyEditor editor = editorRegistry.findPropertyEditor(propertyDescriptor);
JComponent editorComponent = editor.createEditorComponent(propertyDescriptor, bindingContext);
editorComponent.setMaximumSize(new Dimension(editorComponent.getMaximumSize().width, controlHeight));
editorComponent.setPreferredSize(new Dimension(editorComponent.getPreferredSize().width, controlHeight));
org.esa.snap.utils.UIUtils.enableUndoRedo(editorComponent);
JLabel jLabel = new JLabel(Bundle.CTL_Label_ToolLocation_Text());
panelToolFiles.add(jLabel);
jLabel.setLabelFor(editorComponent);
panelToolFiles.add(editorComponent);
anchorLabels.put(ToolAdapterConstants.MAIN_TOOL_FILE_LOCATION,
new AnchorLabel(Bundle.MSG_Inexistent_Tool_Path_Text(),
this.tabbedPane, this.currentIndex, editorComponent));
propertyDescriptor = propertyContainer.getDescriptor(ToolAdapterConstants.WORKING_DIR);
propertyDescriptor.setAttribute("directory", true);
propertyDescriptor.setValidator((property, value) -> {
if (value == null || value.toString().trim().isEmpty()) {
throw new ValidationException(MessageFormat.format("Value for ''{0}'' must not be empty.",
property.getDescriptor().getDisplayName()));
}
});
editor = editorRegistry.findPropertyEditor(propertyDescriptor);
editorComponent = editor.createEditorComponent(propertyDescriptor, bindingContext);
editorComponent.setMaximumSize(new Dimension(editorComponent.getMaximumSize().width, controlHeight));
editorComponent.setPreferredSize(new Dimension(editorComponent.getPreferredSize().width, controlHeight));
org.esa.snap.utils.UIUtils.enableUndoRedo(editorComponent);
jLabel = new JLabel(Bundle.CTL_Label_WorkDir_Text());
panelToolFiles.add(jLabel);
jLabel.setLabelFor(editorComponent);
anchorLabels.put(ToolAdapterConstants.WORKING_DIR,
new AnchorLabel(Bundle.MSG_Inexistent_WorkDir_Text(),
this.tabbedPane, this.currentIndex, editorComponent));
panelToolFiles.add(editorComponent);
SpringUtilities.makeCompactGrid(panelToolFiles, 2, 2,
DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
configPanel.add(panelToolFiles);
JPanel checkPanel = new JPanel(new SpringLayout());
propertyDescriptor = propertyContainer.getDescriptor(ToolAdapterConstants.HANDLE_OUTPUT);
editor = editorRegistry.findPropertyEditor(propertyDescriptor);
editorComponent = editor.createEditorComponent(propertyDescriptor, bindingContext);
editorComponent.setMaximumSize(new Dimension(editorComponent.getMaximumSize().width, controlHeight));
editorComponent.setPreferredSize(new Dimension(editorComponent.getPreferredSize().width, controlHeight));
checkPanel.add(editorComponent);
checkPanel.add(new JLabel("Tool produces the name of the output product"));
SpringUtilities.makeCompactGrid(checkPanel, 1, 2,
DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
configPanel.add(checkPanel);
JLabel label = new JLabel(Bundle.CTL_Label_CmdLineTemplate_Text());
configPanel.add(label);
JScrollPane scrollPane = new JScrollPane(createTemplateEditorField());
configPanel.add(scrollPane);
configPanel.add(createPatternsPanel());
SpringUtilities.makeCompactGrid(configPanel, 5, 1,
DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
return configPanel;
}
@Override
protected JPanel createPatternsPanel() {
JPanel patternsPanel = new JPanel(new SpringLayout());
TitledBorder titledBorder = BorderFactory.createTitledBorder(Bundle.CTL_Panel_OutputPattern_Border_TitleText());
titledBorder.setTitleJustification(TitledBorder.CENTER);
patternsPanel.setBorder(titledBorder);
TextFieldEditor textEditor = new TextFieldEditor();
addTextField(patternsPanel, textEditor, Bundle.CTL_Label_ProgressPattern(),
ToolAdapterConstants.PROGRESS_PATTERN, false, null);
propertyContainer.getDescriptor(ToolAdapterConstants.PROGRESS_PATTERN)
.setValidator(new RegexFieldValidator());
addTextField(patternsPanel, textEditor, Bundle.CTL_Label_StepPattern(),
ToolAdapterConstants.STEP_PATTERN, false, null);
propertyContainer.getDescriptor(ToolAdapterConstants.STEP_PATTERN)
.setValidator(new RegexFieldValidator());
addTextField(patternsPanel, textEditor, Bundle.CTL_Label_ErrorPattern(),
ToolAdapterConstants.ERROR_PATTERN, false, null);
propertyContainer.getDescriptor(ToolAdapterConstants.ERROR_PATTERN)
.setValidator(new RegexFieldValidator());
SpringUtilities.makeCompactGrid(patternsPanel, 3, 2,
DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
return patternsPanel;
}
@Override
protected JPanel createParametersPanel() {
JPanel paramsPanel = new JPanel();
BoxLayout layout = new BoxLayout(paramsPanel, BoxLayout.PAGE_AXIS);
paramsPanel.setLayout(layout);
AbstractButton addParamBut = ToolButtonFactory.createButton(UIUtils.loadImageIcon(Bundle.Icon_Add()), false);
addParamBut.setText("New Parameter");
addParamBut.setMaximumSize(new Dimension(150, controlHeight));
addParamBut.setAlignmentX(Component.LEFT_ALIGNMENT);
addParamBut.setAlignmentY(Component.TOP_ALIGNMENT);
paramsPanel.add(addParamBut);
JScrollPane tableScrollPane = new JScrollPane(paramsTable);
tableScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
paramsPanel.add(tableScrollPane);
addParamBut.addActionListener(e -> paramsTable.addParameterToTable());
return paramsPanel;
}
@Override
protected JPanel createBundlePanel() {
JPanel bundlePanel = new JPanel(new SpringLayout());
int rows = 0;
bundleForm = new BundleForm(this.context,
newOperatorDescriptor.getWindowsBundle(),
newOperatorDescriptor.getLinuxBundle(),
newOperatorDescriptor.getMacosxBundle(),
newOperatorDescriptor.getVariables());
bundlePanel.add(bundleForm);
rows++;
org.esa.snap.core.gpf.descriptor.dependency.Bundle currentBundle = newOperatorDescriptor.getBundle();
JButton button = renderInstallButton(currentBundle, bundlePanel);
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setMaximumSize(new Dimension(buttonPanel.getWidth(), controlHeight));
buttonPanel.add(button, BorderLayout.EAST);
bundlePanel.add(buttonPanel);
bundleForm.setPropertyChangeListener(evt -> {
org.esa.snap.core.gpf.descriptor.dependency.Bundle bundle =
(org.esa.snap.core.gpf.descriptor.dependency.Bundle) evt.getSource();
button.setText((bundle.getLocation() == BundleLocation.REMOTE ?
"Download and " :
"") + "Install Now");
button.setToolTipText(bundle.getLocation() == BundleLocation.REMOTE ?
bundle.getDownloadURL() :
bundle.getSource() != null ?
bundle.getSource().toString() : "");
button.setMaximumSize(button.getPreferredSize());
button.setVisible(canInstall(bundle));
});
rows++;
SpringUtilities.makeCompactGrid(bundlePanel, rows, 1,
DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
return bundlePanel;
}
private JButton renderInstallButton(org.esa.snap.core.gpf.descriptor.dependency.Bundle currentBundle,
JPanel bundlePanel) {
JButton installButton = new JButton() {
@Override
public void setText(String text) {
super.setText(text);
adjustDimension(this);
}
};
installButton.setText((currentBundle.getLocation() == BundleLocation.REMOTE ?
"Download and " :
"") + "Install Now");
installButton.setToolTipText(currentBundle.getLocation() == BundleLocation.REMOTE ?
currentBundle.getDownloadURL() :
currentBundle.getSource() != null ?
currentBundle.getSource().toString() : "");
installButton.setMaximumSize(installButton.getPreferredSize());
installButton.addActionListener((ActionEvent e) -> {
newOperatorDescriptor.setBundles(bundleForm.applyChanges());
org.esa.snap.core.gpf.descriptor.dependency.Bundle modifiedBundle = newOperatorDescriptor.getBundle();
try (BundleInstaller installer = new BundleInstaller(newOperatorDescriptor)) {
ProgressHandle progressHandle = ProgressHandleFactory.createSystemHandle("Installing bundle");
installer.setProgressMonitor(new ProgressHandler(progressHandle, false));
installer.setCallback(() -> {
if (modifiedBundle.isInstalled()) {
Path path = newOperatorDescriptor.resolveVariables(modifiedBundle.getTargetLocation())
.toPath()
.resolve(FileUtils.getFilenameWithoutExtension(modifiedBundle.getEntryPoint()));
SwingUtilities.invokeLater(() -> {
progressHandle.finish();
Dialogs.showInformation(String.format("Bundle was installed in location:\n%s", path));
installButton.setVisible(false);
bundlePanel.revalidate();
});
String updateVariable = modifiedBundle.getUpdateVariable();
if (updateVariable != null) {
Optional<SystemVariable> variable = newOperatorDescriptor.getVariables()
.stream()
.filter(v -> v.getKey().equals(updateVariable))
.findFirst();
variable.ifPresent(systemVariable -> {
systemVariable.setShared(true);
systemVariable.setValue(path.toString());
});
varTable.revalidate();
}
} else {
SwingUtilities.invokeLater(() -> {
progressHandle.finish();
Dialogs.showInformation("Bundle installation failed. \n" +
"Please see the application log for details.");
bundlePanel.revalidate();
});
}
return null;
});
installButton.setVisible(false);
installer.install(true);
} catch (Exception ex) {
logger.warning(ex.getMessage());
}
});
this.downloadAction = () -> {
tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
installButton.requestFocusInWindow();
installButton.doClick();
return null;
};
installButton.setVisible(canInstall(currentBundle));
return installButton;
}
private boolean canInstall(org.esa.snap.core.gpf.descriptor.dependency.Bundle bundle) {
return (bundle != null &&
!bundle.isInstalled() &&
BundleInstaller.isBundleFileAvailable(bundle) &&
((BundleLocation.LOCAL.equals(bundle.getLocation()) && bundle.getSource() != null) ||
(BundleLocation.REMOTE.equals(bundle.getLocation()) && bundle.getDownloadURL() != null)));
}
private JPanel createPreProcessingTab() {
JPanel preprocessAndPatternsPanel = new JPanel(new SpringLayout());
preprocessAndPatternsPanel.add(createPreProcessingPanel());
SpringUtilities.makeCompactGrid(preprocessAndPatternsPanel, 1, 1,
DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
preprocessAndPatternsPanel.setMaximumSize(preprocessAndPatternsPanel.getSize());
return preprocessAndPatternsPanel;
}
private JPanel createDescriptorTab() {
JPanel jPanel = new JPanel(new SpringLayout());
jPanel.add(createDescriptorPanel());
SpringUtilities.makeCompactGrid(jPanel, 1, 1,
DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
jPanel.setMaximumSize(jPanel.getSize());
return jPanel;
}
private JPanel createParametersTab(int width) {
JPanel paramsPanel = createParametersPanel();
int tableWidth = width - 2 * DEFAULT_PADDING;
int widths[] = {controlHeight, 5 * controlHeight, 5 * controlHeight,
3 * controlHeight, 3 * controlHeight, (int)(tableWidth * 0.3), 30};
for(int i=0; i < widths.length; i++) {
paramsTable.getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
}
paramsTable.setRowHeight(controlHeight);
return paramsPanel;
}
private void addTab(JTabbedPane tabControl, String title, JPanel content) {
JLabel tabText = new JLabel(title, JLabel.LEFT);
tabText.setPreferredSize(new Dimension(6 * controlHeight, controlHeight));
TitledBorder titledBorder = BorderFactory.createTitledBorder(title);
titledBorder.setTitleJustification(TitledBorder.CENTER);
content.setBorder(titledBorder);
tabControl.addTab(null, content);
tabControl.setTabComponentAt(tabControl.getTabCount() - 1, tabText);
}
private static void forwardFocusWhenTabKeyReleased(JComponent aSenderComponent, JComponent aReceiverComponent) {
ForwardFocusAction forwardFocusAction = new ForwardFocusAction("TabKeyAction", aReceiverComponent);
aSenderComponent.setFocusTraversalKeys(0, new HashSet());
int modifiers = 0; // '0' => no modifiers
int keyCode = KeyEvent.VK_TAB;
KeyStroke tabKeyReleased = KeyStroke.getKeyStroke(keyCode, modifiers, true);
aSenderComponent.getInputMap(1).put(tabKeyReleased, forwardFocusAction.getName());
aSenderComponent.getActionMap().put(forwardFocusAction.getName(), forwardFocusAction);
}
}
| 29,658 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BundleForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/BundleForm.java | /*
*
* * Copyright (C) 2016 CS ROMANIA
* *
* * 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.ui.tooladapter.dialogs;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.ValueSet;
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.gpf.descriptor.OSFamily;
import org.esa.snap.core.gpf.descriptor.SystemVariable;
import org.esa.snap.core.gpf.descriptor.TemplateParameterDescriptor;
import org.esa.snap.core.gpf.descriptor.dependency.Bundle;
import org.esa.snap.core.gpf.descriptor.dependency.BundleLocation;
import org.esa.snap.core.gpf.descriptor.dependency.BundleType;
import org.esa.snap.ui.AbstractDialog;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.GridBagUtils;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ItemEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.esa.snap.utils.SpringUtilities.DEFAULT_PADDING;
/**
* Form for editing the bundle properties for an adapter
*
* @author Cosmin Cara
*/
public class BundleForm extends JPanel {
private Map<OSFamily, Bundle> original;
private Map<OSFamily, Bundle> modified;
private final Map<OSFamily, PropertyContainer> propertyContainers;
private final Map<OSFamily, BindingContext> bindingContexts;
private final Map<OSFamily, List<JComponent>> controls;
private List<SystemVariable> variables;
private PropertyChangeListener listener;
private AppContext appContext;
private JTabbedPane bundleTabPane;
private JComponent variablesCombo;
public BundleForm(AppContext appContext, Bundle windowsBundle, Bundle linuxBundle, Bundle macosxBundle, List<SystemVariable> variables) {
this.original = new HashMap<OSFamily, Bundle>() {{
put(OSFamily.windows, windowsBundle);
put(OSFamily.linux, linuxBundle);
put(OSFamily.macosx, macosxBundle); }};
this.appContext = appContext;
try {
this.modified = copy(this.original);
} catch (Exception e) {
e.printStackTrace();
}
this.variables = variables;
propertyContainers = new HashMap<>();
bindingContexts = new HashMap<>();
this.bundleTabPane = new JTabbedPane(JTabbedPane.TOP);
this.bundleTabPane.setBorder(BorderFactory.createEmptyBorder());
this.controls = new HashMap<>();
Bundle bundle = modified.get(OSFamily.windows);
PropertyContainer propertyContainer = PropertyContainer.createObjectBacked(bundle);
propertyContainers.put(OSFamily.windows, propertyContainer);
bindingContexts.put(OSFamily.windows, new BindingContext(propertyContainer));
controls.put(OSFamily.windows, new ArrayList<>());
bundle = modified.get(OSFamily.linux);
propertyContainer = PropertyContainer.createObjectBacked(bundle);
propertyContainers.put(OSFamily.linux, propertyContainer);
bindingContexts.put(OSFamily.linux, new BindingContext(propertyContainer));
controls.put(OSFamily.linux, new ArrayList<>());
bundle = modified.get(OSFamily.macosx);
propertyContainer = PropertyContainer.createObjectBacked(bundle);
propertyContainers.put(OSFamily.macosx, propertyContainer);
bindingContexts.put(OSFamily.macosx, new BindingContext(propertyContainer));
controls.put(OSFamily.macosx, new ArrayList<>());
buildUI();
addChangeListeners();
toggleControls(OSFamily.windows);
toggleControls(OSFamily.linux);
toggleControls(OSFamily.macosx);
}
/**
* Updates the source bundle object and returns the modified bundle object.
*/
public Map<OSFamily, Bundle> applyChanges() {
try {
this.original = copy(this.modified);
} catch (Exception e) {
e.printStackTrace();
}
return this.original;
}
public void setPropertyChangeListener(PropertyChangeListener listener) {
this.listener = listener;
}
private void buildUI() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.insets = new Insets(DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
gbc.weighty = 0.01;
addTab("Windows Bundle", createTab(OSFamily.windows));
addTab("Linux Bundle", createTab(OSFamily.linux));
addTab("MacOSX Bundle", createTab(OSFamily.macosx));
GridBagUtils.addToPanel(this, this.bundleTabPane, gbc, "gridx=0, gridy=0, gridwidth=11, weightx=1");
GridBagUtils.addToPanel(this, new JLabel("Reflect in Variable:"), gbc, "gridx=0, gridy=1, gridwidth=1, weightx=0");
variablesCombo = getEditorComponent(OSFamily.all, "updateVariable", this.variables.stream().map(SystemVariable::getKey).toArray());
GridBagUtils.addToPanel(this, variablesCombo, gbc, "gridx=1, gridy=1, gridwidth=10, weightx=0");
GridBagUtils.addToPanel(this, new JLabel(" "), gbc, "gridx=0, gridy=2, gridwidth=11, weighty=1");
int selected = 0;
switch (Bundle.getCurrentOS()) {
case windows:
selected = 0;
break;
case linux:
selected = 1;
break;
case macosx:
selected = 2;
break;
}
this.bundleTabPane.setSelectedIndex(selected);
this.bundleTabPane.setUI(new BasicTabbedPaneUI());
}
public void setVariables(List<SystemVariable> variables) {
this.variables = variables;
PropertyContainer propertyContainer = propertyContainers.get(OSFamily.windows);
BindingContext bindingContext = bindingContexts.get(OSFamily.windows);
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor("updateVariable");
propertyDescriptor.setValueSet(new ValueSet(this.variables.stream().map(SystemVariable::getKey).toArray()));
PropertyEditor propertyEditor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
variablesCombo = propertyEditor.createEditorComponent(propertyDescriptor, bindingContext);
repaint();
}
private JPanel createTab(OSFamily osFamily) {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
c.insets = new Insets(DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
c.weighty = 0.01;
List<JComponent> controlGroup = controls.get(osFamily);
final Bundle bundle = modified.get(osFamily);
GridBagUtils.addToPanel(panel, new JLabel("Type:"), c, "gridx=0, gridy=0, gridwidth=1, weightx=0");
JComponent type = getEditorComponent(osFamily, "bundleType");
GridBagUtils.addToPanel(panel, type, c, "gridx=1, gridy=0, gridwidth=10, weightx=1");
GridBagUtils.addToPanel(panel, new JLabel("Location:"), c, "gridx=0, gridy=1, gridwidth=1, weightx=0");
ButtonGroup rbGroup = new ButtonGroup();
JRadioButton rbLocal = new JRadioButton(BundleLocation.LOCAL.toString());
rbGroup.add(rbLocal);
JRadioButton rbRemote = new JRadioButton(BundleLocation.REMOTE.toString());
rbGroup.add(rbRemote);
if (BundleLocation.LOCAL.equals(bundle.getLocation())) {
rbLocal.setSelected(true);
} else if (BundleLocation.REMOTE.equals(bundle.getLocation())) {
rbRemote.setSelected(true);
}
rbLocal.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
//this is first because, for some reason, otherwise is not triggering the editing event
propertyContainers.get(osFamily).setValue("downloadURL", "");
bundle.setLocation(BundleLocation.LOCAL);
propertyContainers.get(osFamily).setValue("bundleLocation", BundleLocation.LOCAL);
toggleControls(osFamily);
firePropertyChange(new PropertyChangeEvent(bundle, "bundleLocation", null, BundleLocation.LOCAL));
}
});
rbRemote.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
//this is first because, for some reason, otherwise is not triggering the editing event
propertyContainers.get(osFamily).setValue("source", null);
bundle.setLocation(BundleLocation.REMOTE);
propertyContainers.get(osFamily).setValue("bundleLocation", BundleLocation.REMOTE);
toggleControls(osFamily);
firePropertyChange(new PropertyChangeEvent(bundle, "bundleLocation", null, BundleLocation.REMOTE));
}
});
GridBagUtils.addToPanel(panel, rbLocal, c, "gridx=1, gridy=1, gridwidth=4, weightx=1");
GridBagUtils.addToPanel(panel, rbRemote, c, "gridx=5, gridy=1, gridwidth=5, weightx=1");
controlGroup.add(rbLocal);
controlGroup.add(rbRemote);
GridBagUtils.addToPanel(panel, new JLabel("Source File:"), c, "gridx=0, gridy=2, gridwidth=1, weightx=0");
JComponent component = getEditorComponent(osFamily, "source");
GridBagUtils.addToPanel(panel, component, c, "gridx=1, gridy=2, gridwidth=10, weightx=1");
controlGroup.add(component);
GridBagUtils.addToPanel(panel, new JLabel("URL:"), c, "gridx=0, gridy=3, gridwidth=1, weightx=0");
final JComponent downloadURL = getEditorComponent(osFamily, "downloadURL", "url");
((JTextField) downloadURL).getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
}
@Override
public void removeUpdate(DocumentEvent e) {
}
@Override
public void changedUpdate(DocumentEvent e) {
try {
String url = ((JTextField) downloadURL).getText();
URL checkedURL = new URL(url);
bundle.setDownloadURL(checkedURL.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
component.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
try {
String url = ((JTextField) downloadURL).getText();
URL checkedURL = new URL(url);
bundle.setDownloadURL(checkedURL.toString());
super.focusLost(e);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
GridBagUtils.addToPanel(panel, downloadURL, c, "gridx=1, gridy=3, gridwidth=10, weightx=1");
controlGroup.add(downloadURL);
GridBagUtils.addToPanel(panel, new JLabel("Arguments:"), c, "gridx=0, gridy=4, gridwidth=1, weightx=0");
final JTextField argumentsParam = new JTextField(bundle.getCommandLine());
GridBagUtils.addToPanel(panel, argumentsParam, c, "gridx=1, gridy=4, gridwidth=9, weightx=0");
controlGroup.add(argumentsParam);
argumentsParam.setEditable(false);
JButton argumentDetailsButton = new JButton("...");
argumentDetailsButton.setMaximumSize(new Dimension(32, argumentDetailsButton.getHeight()));
argumentDetailsButton.addActionListener(e -> {
TemplateParameterEditorDialog parameterEditorDialog =
new TemplateParameterEditorDialog(appContext,
bundle.getArgumentsParameter(),
bundle.getParent());
int returnCode = parameterEditorDialog.show();
if (returnCode == AbstractDialog.ID_OK) {
argumentsParam.setText(bundle.getCommandLine());
}
});
GridBagUtils.addToPanel(panel, argumentDetailsButton, c, "gridx=10, gridy=4, gridwidth=1, weightx=0");
controlGroup.add(argumentDetailsButton);
GridBagUtils.addToPanel(panel, new JLabel("Target Folder:"), c, "gridx=0, gridy=5, gridwidth=1, weightx=0");
component = getEditorComponent(osFamily, "targetLocation", true);
GridBagUtils.addToPanel(panel, component, c, "gridx=1, gridy=5, gridwidth=10, weightx=1");
controlGroup.add(component);
toggleControls(osFamily);
return panel;
}
private void addTab(String text, JPanel contents) {
JLabel tabText = new JLabel(text, JLabel.LEFT);
Border titledBorder = BorderFactory.createEmptyBorder();
contents.setBorder(titledBorder);
this.bundleTabPane.addTab(null, contents);
this.bundleTabPane.setTabComponentAt(this.bundleTabPane.getTabCount() - 1, tabText);
}
private void addChangeListeners() {
propertyContainers.entrySet().forEach(entry -> {
OSFamily osFamily = entry.getKey();
Bundle bundle = modified.get(osFamily);
PropertyContainer propertyContainer = entry.getValue();
Property property = propertyContainer.getProperty("bundleType");
property.addPropertyChangeListener(evt -> {
bundle.setBundleType((BundleType) evt.getNewValue());
toggleControls(osFamily);
});
property = propertyContainer.getProperty("updateVariable");
property.addPropertyChangeListener(evt -> {
Object value = evt.getNewValue();
if (value != null) {
modified.values().forEach(b -> b.setUpdateVariable(value.toString()));
}
});
property = propertyContainer.getProperty("bundleLocation");
property.addPropertyChangeListener(evt -> {
bundle.setLocation(Enum.valueOf(BundleLocation.class, (String) evt.getNewValue()));
toggleControls(osFamily);
});
property = propertyContainer.getProperty("source");
property.addPropertyChangeListener(evt -> {
bundle.setSource((File) evt.getNewValue());
firePropertyChange(new PropertyChangeEvent(bundle, "source",
evt.getOldValue(), evt.getNewValue()));
});
property = propertyContainer.getProperty("downloadURL");
property.addPropertyChangeListener(evt -> {
try {
String url = String.valueOf(evt.getNewValue());
if(url != null && url.length() > 0) {
URL checkedURL = new URL(url);
bundle.setDownloadURL(checkedURL.toString());
}else {
bundle.setDownloadURL(null);
}
firePropertyChange(new PropertyChangeEvent(bundle, "source",
evt.getOldValue(), evt.getNewValue()));
} catch (Exception ex) {
ex.printStackTrace();
}
});
property = propertyContainer.getProperty("targetLocation");
property.addPropertyChangeListener(evt -> {
bundle.setTargetLocation(String.valueOf(evt.getNewValue()));
firePropertyChange(new PropertyChangeEvent(bundle, "source",
evt.getOldValue(), evt.getNewValue()));
});
property = propertyContainer.getProperty("templateparameter");
property.addPropertyChangeListener(evt -> bundle.setArgumentsParameter((TemplateParameterDescriptor) evt.getNewValue()));
});
}
private void firePropertyChange(PropertyChangeEvent event) {
if (this.listener != null) {
this.listener.propertyChange(event);
}
}
private void toggleControls(OSFamily osFamily) {
Bundle bundle = modified.get(osFamily);
boolean canSelect = bundle.getBundleType() != BundleType.NONE;
BundleLocation location = bundle.getLocation();
boolean remoteCondition = canSelect && location == BundleLocation.REMOTE;
boolean localCondition = canSelect && location == BundleLocation.LOCAL;
for (JComponent component : controls.get(osFamily)) {
if ("url".equals(component.getName())) {
component.setEnabled(remoteCondition);
} else {
component.setEnabled(canSelect);
}
}
BindingContext bindingContext = bindingContexts.get(osFamily);
JComponent[] components = bindingContext.getBinding("source").getComponents();
for (JComponent component : components) {
component.setEnabled(localCondition);
}
for (Component jcomponent : components[0].getParent().getComponents()) {
jcomponent.setEnabled(localCondition);
}
components = bindingContext.getBinding("targetLocation").getComponents();
for (JComponent component : components) {
component.setEnabled(canSelect);
}
repaint();
}
private JComponent getEditorComponent(OSFamily osFamily, String propertyName) {
return getEditorComponent(osFamily, propertyName, null, false);
}
private JComponent getEditorComponent(OSFamily osFamily, String propertyName, boolean isFolder) {
return getEditorComponent(osFamily, propertyName, null, isFolder);
}
private JComponent getEditorComponent(OSFamily osFamily, String propertyName, String controlName) {
return getEditorComponent(osFamily, propertyName, controlName, false);
}
private JComponent getEditorComponent(OSFamily osFamily, String propertyName, Object[] items) {
if (osFamily == OSFamily.all) {
osFamily = OSFamily.windows;
}
PropertyContainer propertyContainer = propertyContainers.get(osFamily);
BindingContext bindingContext = bindingContexts.get(osFamily);
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor(propertyName);
if (items != null) {
propertyDescriptor.setValueSet(new ValueSet(items));
}
PropertyEditor propertyEditor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
return propertyEditor.createEditorComponent(propertyDescriptor, bindingContext);
}
private JComponent getEditorComponent(OSFamily osFamily, String propertyName,String controlName, boolean isFolder) {
if (osFamily == OSFamily.all) {
osFamily = OSFamily.windows;
}
PropertyContainer propertyContainer = propertyContainers.get(osFamily);
BindingContext bindingContext = bindingContexts.get(osFamily);
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor(propertyName);
if (isFolder) {
propertyDescriptor.setAttribute("directory", true);
}
PropertyEditor propertyEditor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
JComponent editorComponent = propertyEditor.createEditorComponent(propertyDescriptor, bindingContext);
if (controlName != null) {
editorComponent.setName(controlName);
}
return editorComponent;
}
private Map<OSFamily, Bundle> copy(Map<OSFamily, Bundle> sources) throws Exception {
if (sources == null) {
throw new IllegalArgumentException("source cannot be null");
}
Map<OSFamily, Bundle> bundles = new HashMap<>();
for (Map.Entry<OSFamily, Bundle> entry : sources.entrySet()) {
Bundle source = entry.getValue();
Bundle target = new Bundle(source);
bundles.put(entry.getKey(), target);
}
return bundles;
}
}
| 21,768 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractAdapterEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/AbstractAdapterEditor.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.dialogs;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.ValueSet;
import com.bc.ceres.binding.converters.ArrayConverter;
import com.bc.ceres.binding.validators.PatternValidator;
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.TextFieldEditor;
import org.esa.snap.core.dataio.ProductIOPlugInManager;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.gpf.OperatorException;
import org.esa.snap.core.gpf.OperatorSpi;
import org.esa.snap.core.gpf.descriptor.AnnotationOperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.ParameterDescriptor;
import org.esa.snap.core.gpf.descriptor.SystemVariable;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolParameterDescriptor;
import org.esa.snap.core.gpf.descriptor.dependency.BundleInstaller;
import org.esa.snap.core.gpf.descriptor.dependency.BundleLocation;
import org.esa.snap.core.gpf.descriptor.template.FileTemplate;
import org.esa.snap.core.gpf.descriptor.template.TemplateEngine;
import org.esa.snap.core.gpf.descriptor.template.TemplateException;
import org.esa.snap.core.gpf.descriptor.template.TemplateType;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterConstants;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterIO;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterOpSpi;
import org.esa.snap.modules.ModulePackager;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.tooladapter.actions.EscapeAction;
import org.esa.snap.ui.tooladapter.actions.ToolAdapterActionRegistrar;
import org.esa.snap.ui.tooladapter.dialogs.components.AnchorLabel;
import org.esa.snap.ui.tooladapter.model.AutoCompleteTextArea;
import org.esa.snap.ui.tooladapter.model.OperationType;
import org.esa.snap.ui.tooladapter.model.OperatorParametersTable;
import org.esa.snap.ui.tooladapter.model.VariablesTable;
import org.esa.snap.ui.tooladapter.preferences.ToolAdapterOptionsController;
import org.esa.snap.ui.tooladapter.validators.DecoratedNotEmptyValidator;
import org.esa.snap.ui.tooladapter.validators.RequiredFieldValidator;
import org.esa.snap.utils.AdapterWatcher;
import org.esa.snap.utils.UIUtils;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
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.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.awt.event.ItemEvent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.esa.snap.utils.SpringUtilities.DEFAULT_PADDING;
import static org.esa.snap.utils.SpringUtilities.makeCompactGrid;
/**
* A dialog window used to edit an operator, or to create a new operator.
* It shows details of an operator such as: descriptor details (name, alias, label, version, copyright,
* authors, description), system variables, preprocessing tool, product writer, tool location,
* operator working directory, command line template content, tool output patterns and parameters.
*
* @author Cosmin Cara
*/
@NbBundle.Messages({
"CTL_Label_Alias_Text=Alias:",
"CTL_Label_UniqueName_Text=Unique Name:",
"CTL_Label_Label_Text=Label:",
"CTL_Label_Version_Text=Version:",
"CTL_Label_Copyright_Text=Copyright:",
"CTL_Label_Authors_Text=Authors:",
"CTL_Label_Description_Text=Description:",
"CTL_Label_MenuLocation_Text=Menu Location:",
"CTL_Label_TemplateType_Text=Template Type:",
"CTL_Panel_OperatorDescriptor_Text=Operator Descriptor",
"CTL_Label_PreprocessingTool_Text=Preprocessing Tool: ",
"CTL_Label_WriteBefore_Text=Before Processing Convert To: ",
"CTL_Panel_PreProcessing_Border_TitleText=Preprocessing",
"CTL_Panel_ConfigParams_Text=Configuration Parameters",
"CTL_Label_ToolLocation_Text=Tool Executable: ",
"CTL_Label_WorkDir_Text=Working Directory: ",
"CTL_Label_CmdLineTemplate_Text=Command Line Template:",
"CTL_Panel_OutputPattern_Border_TitleText=Tool Output Patterns",
"CTL_Label_ProgressPattern=Numeric Progress Pattern: ",
"CTL_Label_ErrorPattern=Error Pattern: ",
"CTL_Label_StepPattern=Intermediate Operation Pattern: ",
"CTL_Panel_SysVar_Border_TitleText=System Variables",
"CTL_Label_RadioButton_ExistingMenus=Existing Menus",
"CTL_Label_RadioButton_NewMenu=Create Menu",
"Icon_Add=/org/esa/snap/resources/images/icons/Add16.png",
"CTL_Panel_OpParams_Border_TitleText=Operator Parameters",
"CTL_Button_Export_Text=Export as Module",
"CTL_Button_Add_Variable_Text=Add Variable",
"CTL_Button_Add_PDVariable_Text=Add Platform-Dependent Variable",
"CTL_Panel_Bundle_TitleText=Bundled Binaries",
"MSG_Export_Complete_Text=The adapter was exported as a NetBeans module in %s",
"MSG_Inexistent_Tool_Path_Text=The tool executable does not exist.\n" +
"Please specify the location of an existing executable.",
"MSG_Inexistent_WorkDir_Text=The working directory does not exist.\n" +
"Please specify a valid location.",
"MSG_Existing_UniqueName_Text=An operator with the same unique name is already registered.\n" +
"Please specify an unique name for the operator.",
"MSG_Inexistem_Parameter_Value_Text=The file or folder for parameter %s does not exist.\n" +
"Please specify a valid location or change the %s property of the parameter.",
"MSG_Wrong_Value_Text=One or more form parameters have invalid values.\n" +
"Please correct them before saving the adapter.",
"MSG_Wrong_Usage_Array_Text=You have used array notation for source products, but only one product will be used.\n" +
"Please correct the problem before saving the adapter.",
"MSG_Empty_Variable_Text=The variable %s has no value set",
"MSG_Empty_MenuLocation_Text=Value of 'Menu location' cannot be empty",
"MSG_Empty_Variable_Key_Text=Empty variable key/name is not allowed",
"MSG_Empty_Bundle_Key_Text=The Bundle local file does not exist."
})
public abstract class AbstractAdapterEditor extends ModalDialog {
private static final String MESSAGE_REQUIRED = "This field is required";
static final int MIN_WIDTH = 720;
static final int MIN_HEIGHT = 580;
static final int MIN_TABBED_WIDTH = 640;
static final int MIN_TABBED_HEIGHT = 512;
static int MAX_4K_WIDTH = 4096;
static int MAX_4K_HEIGHT = 2160;
private ToolAdapterOperatorDescriptor oldOperatorDescriptor;
ToolAdapterOperatorDescriptor newOperatorDescriptor;
private int newNameIndex = -1;
PropertyContainer propertyContainer;
BindingContext bindingContext;
private JTextArea templateContent;
OperatorParametersTable paramsTable;
protected AppContext context;
protected Logger logger;
private JTextField customMenuLocation;
private JRadioButton rbMenuNew;
private static final String helpID = "sta_editor";
int formWidth;
int controlHeight = 24;
private OperationType currentOperation;
VariablesTable varTable;
BundleForm bundleForm;
Map<String, AnchorLabel> anchorLabels = new HashMap<>();
private JPanel errorPanel;
Callable<Void> downloadAction;
static AbstractAdapterEditor createEditorDialog(AppContext appContext, JDialog parent, ToolAdapterOperatorDescriptor operatorDescriptor, OperationType operation) {
return new ToolAdapterTabbedEditorDialog(appContext, parent, operatorDescriptor, operation);
}
static AbstractAdapterEditor createEditorDialog(AppContext appContext, JDialog parent, ToolAdapterOperatorDescriptor operatorDescriptor, int newNameIndex, OperationType operation) {
return new ToolAdapterTabbedEditorDialog(appContext, parent, operatorDescriptor, newNameIndex, operation);
}
private AbstractAdapterEditor(AppContext appContext, JDialog parent, String title) {
super(parent.getOwner(), title, ID_OK_CANCEL_HELP, new Object[] { new JButton(Bundle.CTL_Button_Export_Text()) }, helpID);
this.context = appContext;
this.logger = Logger.getLogger(ToolAdapterEditorDialog.class.getName());
this.registerButton(ID_OTHER, new JButton(Bundle.CTL_Button_Export_Text()));
controlHeight = (getJDialog().getFont().getSize() + 1) * 2;
errorPanel = new JPanel();
errorPanel.setLayout(new BoxLayout(errorPanel, BoxLayout.Y_AXIS));
getButtonPanel().add(errorPanel, 0);
}
private AbstractAdapterEditor(AppContext appContext, JDialog parent, ToolAdapterOperatorDescriptor operatorDescriptor) {
this(appContext, parent, operatorDescriptor.getAlias());
this.oldOperatorDescriptor = operatorDescriptor;
this.newOperatorDescriptor = new ToolAdapterOperatorDescriptor(this.oldOperatorDescriptor);
//see if all necessary parameters are present:
if (newOperatorDescriptor.getToolParameterDescriptors().stream().filter(p -> p.getName().equals(ToolAdapterConstants.TOOL_SOURCE_PRODUCT_ID)).count() == 0){
ToolParameterDescriptor parameterDescriptor = new ToolParameterDescriptor(ToolAdapterConstants.TOOL_SOURCE_PRODUCT_ID, Product[].class);
parameterDescriptor.setDescription("Input product");
newOperatorDescriptor.getToolParameterDescriptors().add(parameterDescriptor);
}
if (newOperatorDescriptor.getToolParameterDescriptors().stream().filter(p -> p.getName().equals(ToolAdapterConstants.TOOL_SOURCE_PRODUCT_FILE)).count() == 0){
ToolParameterDescriptor parameterDescriptor = new ToolParameterDescriptor(ToolAdapterConstants.TOOL_SOURCE_PRODUCT_FILE, File[].class);
parameterDescriptor.setDescription("Input file");
newOperatorDescriptor.getToolParameterDescriptors().add(parameterDescriptor);
}
if (newOperatorDescriptor.getToolParameterDescriptors().stream().filter(p -> p.getName().equals(ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE)).count() == 0){
ToolParameterDescriptor parameterDescriptor = new ToolParameterDescriptor(ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE, File.class);
parameterDescriptor.setDescription("Output file");
parameterDescriptor.setNotNull(false);
newOperatorDescriptor.getToolParameterDescriptors().add(parameterDescriptor);
} else {
Optional<ToolParameterDescriptor> result = newOperatorDescriptor.getToolParameterDescriptors()
.stream()
.filter(p -> p.getName().equals(ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE)).findFirst();
result.ifPresent(toolParameterDescriptor -> toolParameterDescriptor.setDescription("Output file"));
}
propertyContainer = PropertyContainer.createObjectBacked(newOperatorDescriptor);
ProductIOPlugInManager registry = ProductIOPlugInManager.getInstance();
String[] writers = registry.getAllProductWriterFormatStrings();
Arrays.sort(writers);
propertyContainer.getDescriptor(ToolAdapterConstants.PROCESSING_WRITER).setValueSet(new ValueSet(writers));
Set<OperatorSpi> spis = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpis();
java.util.List<String> toolboxSpis = new ArrayList<>();
spis.stream().filter(p -> (p instanceof ToolAdapterOpSpi)
&& (p.getOperatorDescriptor().getClass() != AnnotationOperatorDescriptor.class)
&& !p.getOperatorAlias().equals(oldOperatorDescriptor.getAlias()))
.forEach(operator -> toolboxSpis.add(operator.getOperatorDescriptor().getAlias()));
toolboxSpis.sort(Comparator.naturalOrder());
propertyContainer.getDescriptor(ToolAdapterConstants.PREPROCESSOR_EXTERNAL_TOOL).setValueSet(new ValueSet(toolboxSpis.toArray(new String[toolboxSpis.size()])));
bindingContext = new BindingContext(propertyContainer);
paramsTable = new OperatorParametersTable(newOperatorDescriptor, appContext);
varTable = new VariablesTable(newOperatorDescriptor.getVariables(), appContext);
//in case the name of the variable is edited (or even new variable is added),
//the combobox of the bundle must be updated
varTable.getCellEditor(0,2).addCellEditorListener(new CellEditorListener() {
@Override
public void editingStopped(ChangeEvent e) {
bundleForm.setVariables(newOperatorDescriptor.getVariables());
}
@Override
public void editingCanceled(ChangeEvent e) {}
});
}
/**
* Constructs a new window for editing the operator
* @param appContext the application context
* @param operatorDescriptor the descriptor of the operator to be edited
* @param operation is the type of desired operation: NEW/COPY if the operator was not previously registered (so it is a new operator) and EDIT if the operator was registered and the editing operation is requested
*/
AbstractAdapterEditor(AppContext appContext, JDialog parent, ToolAdapterOperatorDescriptor operatorDescriptor, OperationType operation) {
this(appContext, parent, operatorDescriptor);
this.currentOperation = operation;
this.newNameIndex = -1;
setContent(createMainPanel());
EscapeAction.register(this.getJDialog());
}
/**
* Constructs a new window for editing the operator
* @param appContext the application context
* @param operatorDescriptor the descriptor of the operator to be edited
* @param newNameIndex an integer value representing the suffix for the new operator name; if this value is less than 1, the editing operation of the current operator is executed; if the value is equal to or greater than 1, the operator is duplicated and the index value is used to compute the name of the new operator
* @param operation is the type of desired operation: NEW/COPY if the operator was not previously registered (so it is a new operator) and EDIT if the operator was registered and the editing operation is requested
*/
AbstractAdapterEditor(AppContext appContext, JDialog parent, ToolAdapterOperatorDescriptor operatorDescriptor, int newNameIndex, OperationType operation) {
this(appContext, parent, operatorDescriptor);
this.newNameIndex = newNameIndex;
this.currentOperation = operation;
if(this.newNameIndex >= 1) {
this.newOperatorDescriptor.setName(this.oldOperatorDescriptor.getName() + ToolAdapterConstants.OPERATOR_GENERATED_NAME_SEPARATOR + this.newNameIndex);
this.newOperatorDescriptor.setAlias(this.oldOperatorDescriptor.getAlias() + ToolAdapterConstants.OPERATOR_GENERATED_NAME_SEPARATOR + this.newNameIndex);
}
setContent(createMainPanel());
EscapeAction.register(this.getJDialog());
}
ToolAdapterOperatorDescriptor getUpdatedOperatorDescriptor() { return this.newOperatorDescriptor; }
protected abstract JComponent createMainPanel();
protected abstract JPanel createDescriptorPanel();
protected abstract JPanel createVariablesPanel();
protected abstract JPanel createPreProcessingPanel();
protected abstract JPanel createToolInfoPanel();
protected abstract JPanel createPatternsPanel();
protected abstract JPanel createParametersPanel();
protected abstract JPanel createBundlePanel();
private boolean shouldValidate() {
String value = NbPreferences.forModule(Dialogs.class).get(ToolAdapterOptionsController.PREFERENCE_KEY_VALIDATE_ON_SAVE, null);
return value != null && Boolean.parseBoolean(value);
}
@Override
protected boolean verifyUserInput() {
/* Make sure we have stopped table cell editing for both: VariablesTable and OperatorParametersTable */
varTable.stopVariablesTableEditing();
paramsTable.stopVariablesTableEditing();
/* Verify the existence of the tool executable */
if (shouldValidate()) {
String fileLocation = newOperatorDescriptor.getMainToolFileLocation();
File file = null;
if (fileLocation != null) {
file = new File(fileLocation);
// should not come here unless, somehow, the property value was not set by binding
Object value = bindingContext.getBinding(ToolAdapterConstants.MAIN_TOOL_FILE_LOCATION).getPropertyValue();
if (value != null) {
file = value instanceof File ? (File) value : new File(value.toString());
}
}
boolean problemFound = file == null;
if (!problemFound) {
Path toolLocation = newOperatorDescriptor.resolveVariables(newOperatorDescriptor.getMainToolFileLocation()).toPath();
if (!(Files.exists(toolLocation) && Files.isExecutable(toolLocation))) {
problemFound = true;
}
}
AnchorLabel anchorLabel = anchorLabels.get(ToolAdapterConstants.MAIN_TOOL_FILE_LOCATION);
if (problemFound) {
if (Arrays.stream(errorPanel.getComponents()).noneMatch(anchorLabel::equals)) {
errorPanel.add(anchorLabel);
anchorLabel.markError();
errorPanel.revalidate();
}
} else {
if (Arrays.stream(errorPanel.getComponents()).anyMatch(anchorLabel::equals)) {
errorPanel.remove(anchorLabel);
anchorLabel.clearError();
errorPanel.revalidate();
}
}
/* Verify the existence of the working directory */
File workingDir = newOperatorDescriptor.resolveVariables(newOperatorDescriptor.getWorkingDir());
anchorLabel = anchorLabels.get(ToolAdapterConstants.WORKING_DIR);
if (!(workingDir != null && workingDir.exists() && workingDir.isDirectory())) {
if (Arrays.stream(errorPanel.getComponents()).noneMatch(anchorLabel::equals)) {
errorPanel.add(anchorLabel);
anchorLabel.markError();
errorPanel.revalidate();
}
problemFound = true;
} else {
if (Arrays.stream(errorPanel.getComponents()).anyMatch(anchorLabel::equals)) {
errorPanel.remove(anchorLabel);
anchorLabel.clearError();
errorPanel.revalidate();
}
}
if (problemFound) {
return false;
}
/* Verify that there is no System Variable without value */
List<SystemVariable> variables = newOperatorDescriptor.getVariables();
if (variables != null) {
for (SystemVariable variable : variables) {
String key = variable.getKey();
if (key == null || key.isEmpty()) {
Dialogs.showWarning(Bundle.MSG_Empty_Variable_Key_Text());
return false;
}
String value = variable.getValue();
if (value == null || value.isEmpty()) {
Dialogs.showWarning(String.format(Bundle.MSG_Empty_Variable_Text(), key));
return false;
}
}
}
/* Verify the existence of files for File parameter values that are marked as Not Null or Not Empty */
ParameterDescriptor[] parameterDescriptors = newOperatorDescriptor.getParameterDescriptors();
if (parameterDescriptors != null && parameterDescriptors.length > 0) {
for (ParameterDescriptor parameterDescriptor : parameterDescriptors) {
Class<?> dataType = parameterDescriptor.getDataType();
String defaultValue = parameterDescriptor.getDefaultValue();
if (File.class.isAssignableFrom(dataType) &&
(parameterDescriptor.isNotNull() || parameterDescriptor.isNotEmpty()) &&
(defaultValue == null || defaultValue.isEmpty() || !Files.exists(Paths.get(defaultValue)))) {
Dialogs.showWarning(String.format(Bundle.MSG_Inexistem_Parameter_Value_Text(),
parameterDescriptor.getName(), parameterDescriptor.isNotNull() ? ToolAdapterConstants.NOT_NULL : ToolAdapterConstants.NOT_EMPTY));
return false;
}
}
}
}
//verify the adapter unique name really is unique
if (currentOperation.equals(OperationType.COPY) || currentOperation.equals(OperationType.NEW) ||
(currentOperation.equals(OperationType.COPY) && !newOperatorDescriptor.getName().equals(oldOperatorDescriptor.getName()))) {
AnchorLabel anchorLabel = anchorLabels.get(ToolAdapterConstants.NAME);
JPanel buttonPanel = getButtonPanel();
if (GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(newOperatorDescriptor.getName()) != null) {
//Dialogs.showWarning(String.format(Bundle.MSG_Existing_UniqueName_Text()));
if (Arrays.stream(buttonPanel.getComponents()).noneMatch(anchorLabel::equals)) {
buttonPanel.add(anchorLabel, 0);
buttonPanel.revalidate();
}
return false;
} else {
if (Arrays.stream(buttonPanel.getComponents()).anyMatch(anchorLabel::equals)) {
buttonPanel.remove(anchorLabel);
buttonPanel.revalidate();
}
}
}
/* In case of local bundle, verify the existence of the bundle file */
if(newOperatorDescriptor.getBundle().getLocation().equals(BundleLocation.LOCAL)) {
File bundleFile = newOperatorDescriptor.resolveVariables(newOperatorDescriptor.getBundle().getSource());
if (!(bundleFile != null && bundleFile.exists() && !bundleFile.isDirectory())) {
Dialogs.showWarning(Bundle.MSG_Empty_Bundle_Key_Text());
return false;
}
}
return true;
}
@Override
protected void onOK() {
//the bundle must be set before validating the adapter
newOperatorDescriptor.setBundles(bundleForm.applyChanges());
if (!verifyUserInput()) {
Dialogs.showWarning(Bundle.MSG_Wrong_Value_Text());
this.getJDialog().requestFocus();
} else {
String templateContent = this.templateContent.getText();
if (!resolveTemplateProductCount(templateContent)) {
Dialogs.showWarning(Bundle.MSG_Wrong_Usage_Array_Text());
this.getJDialog().requestFocus();
} else {
Path backupCopy = null;
Exception thrown = null;
try {
backupCopy = ToolAdapterIO.backupOperator(oldOperatorDescriptor);
if (newOperatorDescriptor.getSourceProductCount() == 0) {
Dialogs.showInformation("The template is not using the parameter $sourceProduct.\nNo source product selection will be available at execution time.", "empty.source.info");
}
if (!newOperatorDescriptor.isFromPackage()) {
newOperatorDescriptor.setSource(ToolAdapterOperatorDescriptor.SOURCE_USER);
}
FileTemplate template = new FileTemplate(TemplateEngine.createInstance(newOperatorDescriptor, TemplateType.VELOCITY),
newOperatorDescriptor.getAlias() + ToolAdapterConstants.TOOL_VELO_TEMPLATE_SUFIX);
template.setContents(templateContent, true);
newOperatorDescriptor.setTemplate(template);
java.util.List<ToolParameterDescriptor> toolParameterDescriptors = newOperatorDescriptor.getToolParameterDescriptors();
toolParameterDescriptors.stream().filter(param -> paramsTable.getBindingContext().getBinding(param.getName()) != null)
.filter(param -> paramsTable.getBindingContext().getBinding(param.getName()).getPropertyValue() != null)
.forEach(param -> {
Object propertyValue = paramsTable.getBindingContext().getBinding(param.getName()).getPropertyValue();
if (param.isParameter()) {
String defaultValueString;
if (propertyValue.getClass().isArray()) {
defaultValueString = String.join(ArrayConverter.SEPARATOR,
Arrays.stream((Object[]) propertyValue)
.map(Object::toString)
.collect(Collectors.toList()));
} else {
defaultValueString = propertyValue.toString();
}
param.setDefaultValue(defaultValueString);
}
});
java.util.List<ToolParameterDescriptor> remParameters = toolParameterDescriptors.stream().filter(param ->
(ToolAdapterConstants.TOOL_SOURCE_PRODUCT_ID.equals(param.getName()) || ToolAdapterConstants.TOOL_SOURCE_PRODUCT_FILE.equals(param.getName()))).
collect(Collectors.toList());
newOperatorDescriptor.removeParamDescriptors(remParameters);
if (rbMenuNew.isSelected()) {
String customMenuLocationText = customMenuLocation.getText();
if (customMenuLocationText != null && !customMenuLocationText.isEmpty()) {
newOperatorDescriptor.setMenuLocation(customMenuLocationText);
}
}
String menuLocation = newOperatorDescriptor.getMenuLocation();
if (menuLocation != null && !menuLocation.startsWith("Menu/")) {
newOperatorDescriptor.setMenuLocation("Menu/" + menuLocation);
}
//the bundle must be set before validating the adapter
//newOperatorDescriptor.setBundles(bundleForm.applyChanges());
AdapterWatcher.INSTANCE.suspend();
if (currentOperation != OperationType.NEW) {
ToolAdapterActionRegistrar.removeOperatorMenu(oldOperatorDescriptor);
}
ToolAdapterIO.saveAndRegisterOperator(newOperatorDescriptor);
oldOperatorDescriptor = newOperatorDescriptor;
AdapterWatcher.INSTANCE.resume();
ToolAdapterIO.deleteFolder(backupCopy);
super.setButtonID(ID_OK);
super.hide();
} catch (TemplateException tex) {
logger.warning(tex.getMessage());
Dialogs.showError("The adapter template contains errors [" + tex.toString() + "]!");
thrown = tex;
} catch (Exception e) {
logger.warning(e.getMessage());
Dialogs.showError("There was an error on saving the operator; check the disk space and permissions and try again! " + e.toString());
thrown = e;
} finally {
if (thrown != null) {
if (backupCopy != null) {
try {
ToolAdapterIO.restoreOperator(oldOperatorDescriptor, backupCopy);
} catch (IOException e) {
logger.severe(e.getMessage());
Dialogs.showError("The operator could not be restored [" + e.getMessage() + "]");
}
}
}
}
}
}
}
@Override
public int show() {
getJDialog().revalidate();
if (this.currentOperation == OperationType.FORCED_EDIT) {
if (BundleInstaller.isBundleFileAvailable(this.oldOperatorDescriptor.getBundle())) {
SwingUtilities.invokeLater(() -> {
Dialogs.Answer answer = Dialogs.requestDecision("Bundle Available", "A bundle has been configured for this adapter.\n" +
"Do you want to proceed with bundle download/installation?", false, null);
if (answer == Dialogs.Answer.YES) {
if (downloadAction != null) {
try {
downloadAction.call();
} catch (Exception e) {
logger.warning(e.getMessage());
}
}
} else {
onOK();
}
});
} else {
SwingUtilities.invokeLater(this::onOK);
}
}
return super.show();
}
@Override
protected void onOther() {
try {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fileChooser.showOpenDialog(getButton(ID_OTHER)) == JFileChooser.APPROVE_OPTION) {
File targetFolder = fileChooser.getSelectedFile();
newOperatorDescriptor.setSource(ToolAdapterOperatorDescriptor.SOURCE_PACKAGE);
onOK();
ModulePackager.packModule(newOperatorDescriptor, new File(targetFolder, newOperatorDescriptor.getAlias() + ".nbm"));
Dialogs.showInformation(String.format(Bundle.MSG_Export_Complete_Text(), targetFolder.getAbsolutePath()), null);
}
} catch (IOException e) {
logger.warning(e.getMessage());
Dialogs.showError(e.getMessage());
}
}
JComponent createCheckboxComponent(String memberName, JComponent toogleComponentEnabled, Boolean value) {
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor(memberName);
PropertyEditor editor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
JComponent editorComponent = editor.createEditorComponent(propertyDescriptor, bindingContext);
if (editorComponent instanceof JCheckBox && toogleComponentEnabled != null) {
((JCheckBox) editorComponent).setSelected(value);
toogleComponentEnabled.setEnabled(value);
((JCheckBox) editorComponent).addActionListener(e -> toogleComponentEnabled.setEnabled(((JCheckBox) editorComponent).isSelected()));
}
return editorComponent;
}
JComponent addValidatedTextField(JPanel parent, TextFieldEditor textEditor, String labelText, String propertyName, String validatorRegex) {
if(validatorRegex == null || validatorRegex.isEmpty()){
return addTextField(parent, textEditor, labelText, propertyName, false, null);
} else {
JLabel jLabel = new JLabel(labelText);
parent.add(jLabel);
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor(propertyName);
propertyDescriptor.setValidator(new PatternValidator(Pattern.compile(validatorRegex)));
JComponent editorComponent = textEditor.createEditorComponent(propertyDescriptor, bindingContext);
UIUtils.addPromptSupport(editorComponent, "enter " + labelText.toLowerCase().replace(":", "") + " here");
editorComponent.setPreferredSize(new Dimension(editorComponent.getPreferredSize().width, controlHeight));
editorComponent.setMaximumSize(new Dimension(editorComponent.getMaximumSize().width, controlHeight));
jLabel.setLabelFor(editorComponent);
parent.add(editorComponent);
return editorComponent;
}
}
JComponent addTextField(JPanel parent, TextFieldEditor textEditor, String labelText,
String propertyName, boolean isRequired, String[] excludedChars) {
JLabel jLabel = new JLabel(labelText);
Dimension size = jLabel.getPreferredSize();
parent.add(jLabel);
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor(propertyName);
if (isRequired) {
propertyDescriptor.setValidator(new DecoratedNotEmptyValidator(jLabel, excludedChars));
jLabel.setMaximumSize(new Dimension(size.width + 20, size.height));
}
JComponent editorComponent = textEditor.createEditorComponent(propertyDescriptor, bindingContext);
UIUtils.addPromptSupport(editorComponent, "enter " + labelText.toLowerCase().replace(":", "") + " here");
UIUtils.enableUndoRedo(editorComponent);
editorComponent.setPreferredSize(new Dimension(editorComponent.getPreferredSize().width, controlHeight));
editorComponent.setMaximumSize(new Dimension(editorComponent.getMaximumSize().width, controlHeight));
jLabel.setLabelFor(editorComponent);
parent.add(editorComponent);
return editorComponent;
}
JComponent addComboField(JPanel parent, String labelText, String propertyName, boolean isRequired, boolean isEditable) {
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor(propertyName);
propertyDescriptor.setNotEmpty(isRequired);
PropertyEditor editor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
JComponent editorComponent = editor.createEditorComponent(propertyDescriptor, bindingContext);
editorComponent.setMaximumSize(new Dimension(editorComponent.getMaximumSize().width, controlHeight));
editorComponent.setPreferredSize(new Dimension(editorComponent.getPreferredSize().width, controlHeight));
if (editorComponent instanceof JComboBox) {
JComboBox comboBox = (JComboBox)editorComponent;
comboBox.setEditable(isEditable);
comboBox.setEnabled(isEditable);
}
JLabel jLabel = new JLabel(labelText);
parent.add(jLabel);
jLabel.setLabelFor(editorComponent);
parent.add(editorComponent);
return editorComponent;
}
void addComboField(JPanel parent, String labelText, String propertyName, List<String> values) {
JLabel jLabel = new JLabel(labelText);
parent.add(jLabel);
PropertyDescriptor propertyDescriptor = propertyContainer.getDescriptor(propertyName);
propertyDescriptor.setNotEmpty(true);
values.sort(Comparator.naturalOrder());
propertyDescriptor.setValueSet(new ValueSet(values.toArray()));
PropertyEditor editor = PropertyEditorRegistry.getInstance().findPropertyEditor(propertyDescriptor);
JComponent editorComp = editor.createEditorComponent(propertyDescriptor, bindingContext);
if (editorComp instanceof JComboBox) {
JComboBox comboBox = (JComboBox)editorComp;
comboBox.setEditable(true);
}
editorComp.setMaximumSize(new Dimension(editorComp.getMaximumSize().width, controlHeight));
customMenuLocation = new JTextField();
customMenuLocation.setInputVerifier(new RequiredFieldValidator(Bundle.MSG_Empty_MenuLocation_Text()));
customMenuLocation.setEnabled(false);
JPanel subPanel = new JPanel(new SpringLayout());
subPanel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
JRadioButton rbExistingMenu = new JRadioButton(Bundle.CTL_Label_RadioButton_ExistingMenus(), true);
rbMenuNew = new JRadioButton(Bundle.CTL_Label_RadioButton_NewMenu());
ButtonGroup rbGroup = new ButtonGroup();
rbGroup.add(rbExistingMenu);
rbGroup.add(rbMenuNew);
// this radio button should be able to capture focus even when the validator of the rbMenuNew says otherwise
rbExistingMenu.setVerifyInputWhenFocusTarget(false);
rbExistingMenu.addItemListener(e -> {
editorComp.setEnabled(e.getStateChange() == ItemEvent.SELECTED);
customMenuLocation.setEnabled(e.getStateChange() == ItemEvent.DESELECTED);
});
subPanel.add(rbExistingMenu);
subPanel.add(rbMenuNew);
jLabel.setLabelFor(editorComp);
subPanel.add(editorComp);
subPanel.add(customMenuLocation);
Dimension dimension = new Dimension(parent.getWidth() / 2, controlHeight);
editorComp.setPreferredSize(dimension);
customMenuLocation.setPreferredSize(dimension);
subPanel.setPreferredSize(new Dimension(subPanel.getWidth(), (int)(2.5 * controlHeight)));
subPanel.setMaximumSize(new Dimension(subPanel.getWidth(), (int) (2.5 * controlHeight)));
makeCompactGrid(subPanel, 2, 2, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING, DEFAULT_PADDING);
parent.add(subPanel);
}
List<String> getAvailableMenuOptions(FileObject current) {
List<String> resultList = new ArrayList<>();
if (current == null) {
current = FileUtil.getConfigRoot().getFileObject("Menu");
}
FileObject[] children = current.getChildren();
for (FileObject child : children) {
String entry = child.getPath();
if (!(entry.endsWith(".instance") ||
entry.endsWith(".shadow") ||
entry.endsWith(".xml"))) {
resultList.add(entry);
resultList.addAll(getAvailableMenuOptions(child));
}
}
return resultList;
}
private boolean resolveTemplateProductCount(String templateContent) {
boolean success = true;
if (templateContent.contains(ToolAdapterConstants.TOOL_SOURCE_PRODUCT_ID) ||
templateContent.contains(ToolAdapterConstants.TOOL_SOURCE_PRODUCT_FILE)) {
int idx = templateContent.lastIndexOf(ToolAdapterConstants.TOOL_SOURCE_PRODUCT_ID + "[");
if (idx > 0) {
String value = templateContent.substring(idx + (ToolAdapterConstants.TOOL_SOURCE_PRODUCT_ID + "[").length(), templateContent.indexOf("]", idx));
int maxNum = Integer.valueOf(value) + 1;
if (maxNum > 1) {
newOperatorDescriptor.setSourceProductCount(maxNum);
} else {
success = false;
}
} else {
idx = templateContent.lastIndexOf(ToolAdapterConstants.TOOL_SOURCE_PRODUCT_FILE + "[");
if (idx > 0) {
String value = templateContent.substring(idx + (ToolAdapterConstants.TOOL_SOURCE_PRODUCT_FILE + "[").length(), templateContent.indexOf("]", idx));
int maxNum = Integer.valueOf(value) + 1;
if (maxNum > 1) {
newOperatorDescriptor.setSourceProductCount(maxNum);
} else {
success = false;
}
} else {
newOperatorDescriptor.setSourceProductCount(1);
}
}
} else {
newOperatorDescriptor.setSourceProductCount(0);
}
return success;
}
JTextArea createTemplateEditorField() {
boolean useAutocomplete = Boolean.parseBoolean(NbPreferences.forModule(Dialogs.class).get(ToolAdapterOptionsController.PREFERENCE_KEY_AUTOCOMPLETE, "false"));
if (useAutocomplete) {
templateContent = new AutoCompleteTextArea("", 15, 9);
} else {
templateContent = new JTextArea("", 15, 9);
}
UIUtils.enableUndoRedo(templateContent);
try {
FileTemplate template;
if ( (currentOperation == OperationType.NEW) || (currentOperation == OperationType.COPY) ) {
template = oldOperatorDescriptor.getTemplate();
if (template != null) {
//templateContent.setText(ToolAdapterIO.readOperatorTemplate(oldOperatorDescriptor.getName()));
templateContent.setText(template.getContents());
}
} else {
template = newOperatorDescriptor.getTemplate();
if (template != null) {
//templateContent.setText(ToolAdapterIO.readOperatorTemplate(newOperatorDescriptor.getName()));
templateContent.setText(template.getContents());
}
}
} catch (IOException | OperatorException e) {
logger.warning(e.getMessage());
}
templateContent.setInputVerifier(new RequiredFieldValidator(MESSAGE_REQUIRED));
if (useAutocomplete && templateContent instanceof AutoCompleteTextArea) {
((AutoCompleteTextArea) templateContent).setAutoCompleteEntries(getAutocompleteEntries());
((AutoCompleteTextArea) templateContent).setTriggerChar('$');
}
return templateContent;
}
void adjustDimension(JButton component) {
FontMetrics metrics = component.getFontMetrics(component.getFont());
int width = metrics.stringWidth(component.getText());
component.setPreferredSize(new Dimension(width + 32, controlHeight));
component.setBounds(new Rectangle(component.getLocation(), component.getPreferredSize()));
}
private List<String> getAutocompleteEntries() {
List<String> entries = new ArrayList<>();
entries.addAll(newOperatorDescriptor.getVariables().stream().map(SystemVariable::getKey).collect(Collectors.toList()));
for (ParameterDescriptor parameterDescriptor : newOperatorDescriptor.getParameterDescriptors()) {
entries.add(parameterDescriptor.getName());
}
entries.sort(Comparator.naturalOrder());
return entries;
}
}
| 44,831 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TemplateParameterEditorDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/TemplateParameterEditorDialog.java | package org.esa.snap.ui.tooladapter.dialogs;
import com.bc.ceres.binding.ConversionException;
import com.bc.ceres.binding.DefaultPropertySetDescriptor;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.internal.FileEditor;
import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory;
import org.esa.snap.core.gpf.descriptor.ParameterDescriptor;
import org.esa.snap.core.gpf.descriptor.SystemVariable;
import org.esa.snap.core.gpf.descriptor.TemplateParameterDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolParameterDescriptor;
import org.esa.snap.core.gpf.descriptor.template.Template;
import org.esa.snap.core.gpf.descriptor.template.TemplateException;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterOp;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.esa.snap.ui.tooladapter.actions.EscapeAction;
import org.esa.snap.ui.tooladapter.model.AutoCompleteTextArea;
import org.esa.snap.ui.tooladapter.model.OperatorParametersTable;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Form for displaying and editing details of a tool adapter parameter of File Template type.
*
* @author Ramona Manda
*/
public class TemplateParameterEditorDialog extends ModalDialog {
private static final Logger logger = Logger.getLogger(TemplateParameterEditorDialog.class.getName());
private static String EMPTY_FILE_CONTENT = "[no content]";
private TemplateParameterDescriptor parameter;
private TemplateParameterDescriptor modifiedParameter;
private ToolAdapterOperatorDescriptor fakeOperatorDescriptor;
private ToolAdapterOperatorDescriptor parentDescriptor;
private AppContext appContext;
private JTextField outFileName;
private AutoCompleteTextArea fileContentArea;
private OperatorParametersTable paramsTable;
private BindingContext paramContext;
public TemplateParameterEditorDialog(AppContext appContext, TemplateParameterDescriptor parameter, ToolAdapterOperatorDescriptor parent) {
super(appContext.getApplicationWindow(), parameter.getName(), ID_OK_CANCEL, "");
this.appContext = appContext;
EscapeAction.register(getJDialog());
this.fileContentArea = new AutoCompleteTextArea("", 10, 10);
this.parameter = parameter;
this.modifiedParameter = new TemplateParameterDescriptor(this.parameter);
try {
this.modifiedParameter.setTemplateEngine(parent.getTemplateEngine());
} catch (TemplateException e) {
logger.warning(e.getMessage());
}
this.parentDescriptor = parent;
try {
PropertyDescriptor propertyDescriptor = ParameterDescriptorFactory.convert(this.modifiedParameter, new ParameterDescriptorFactory().getSourceProductMap());
DefaultPropertySetDescriptor propertySetDescriptor = new DefaultPropertySetDescriptor();
propertySetDescriptor.addPropertyDescriptor(propertyDescriptor);
PropertyContainer paramContainer = PropertyContainer.createMapBacked(new HashMap<>(), propertySetDescriptor);
this.paramContext = new BindingContext(paramContainer);
} catch (ConversionException e) {
logger.warning(e.getMessage());
}
/*try {
parameter.setTemplateEngine(parentDescriptor.getTemplateEngine());
} catch (TemplateException e) {
e.printStackTrace();
logger.warning(e.getMessage());
}*/
this.fakeOperatorDescriptor = new ToolAdapterOperatorDescriptor("OperatorForParameters", ToolAdapterOp.class);
for (ToolParameterDescriptor param : parameter.getParameterDescriptors()) {
this.fakeOperatorDescriptor.getToolParameterDescriptors().add(new ToolParameterDescriptor(param));
}
PropertyChangeListener pcListener = evt -> updateFileAreaContent();
this.paramContext.addPropertyChangeListener(pcListener);
addComponents();
}
private JPanel createParametersPanel() {
JPanel paramsPanel = new JPanel();
BoxLayout layout = new BoxLayout(paramsPanel, BoxLayout.PAGE_AXIS);
paramsPanel.setLayout(layout);
AbstractButton addParamBut = ToolButtonFactory.createButton(UIUtils.loadImageIcon("/org/esa/snap/resources/images/icons/Add16.png"), false);
addParamBut.setAlignmentX(Component.LEFT_ALIGNMENT);
paramsPanel.add(addParamBut);
this.paramsTable = new OperatorParametersTable(this.fakeOperatorDescriptor, appContext);
JScrollPane tableScrollPane = new JScrollPane(paramsTable);
tableScrollPane.setPreferredSize(new Dimension(500, 130));
tableScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
paramsPanel.add(tableScrollPane);
addParamBut.addActionListener((ActionEvent e) -> paramsTable.addParameterToTable());
TitledBorder title = BorderFactory.createTitledBorder("Template Parameters");
paramsPanel.setBorder(title);
return paramsPanel;
}
private Property getProperty() {
Property[] properties = this.paramContext.getPropertySet().getProperties();
return properties[0];
}
private void addComponents() {
Property property = getProperty();
try {
Template template = this.modifiedParameter.getTemplate();
property.setValue(template.getPath());
} catch (ValidationException e) {
logger.warning(e.getMessage());
}
FileEditor fileEditor = new FileEditor();
JComponent filePathComponent = fileEditor.createEditorComponent(property.getDescriptor(), this.paramContext);
filePathComponent.setPreferredSize(new Dimension(770, 25));
JPanel topPanel = new JPanel(new BorderLayout());
JPanel filePanel = new JPanel();
final JLabel label = new JLabel("File:");
filePanel.add(label);
filePanel.add(filePathComponent);
topPanel.add(filePanel, BorderLayout.NORTH);
JPanel outFilePanel = new JPanel();
final JLabel jLabel = new JLabel("Output File:");
outFilePanel.add(jLabel);
File outputFile = this.modifiedParameter.getOutputFile();
outFileName = new JTextField(outputFile != null ? outputFile.toString() : "");
outFileName.setPreferredSize(
new Dimension(filePathComponent.getPreferredSize().width + label.getPreferredSize().width - jLabel.getPreferredSize().width, 25));
org.esa.snap.utils.UIUtils.addPromptSupport(outFileName, "Enter the name of transformed file here");
outFilePanel.add(outFileName);
topPanel.add(outFilePanel, BorderLayout.WEST);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setPreferredSize(new Dimension(800, 550));
mainPanel.add(topPanel, BorderLayout.PAGE_START);
//to create UI component for outputFile
fileContentArea.setAutoCompleteEntries(getAutocompleteEntries());
fileContentArea.setTriggerChar('$');
mainPanel.add(new JScrollPane(fileContentArea), BorderLayout.CENTER);
updateFileAreaContent();
mainPanel.add(createParametersPanel(), BorderLayout.PAGE_END);
setContent(mainPanel);
}
private void updateFileAreaContent() {
String result = null;
try {
File file = getProperty().getValue();
Template template = this.modifiedParameter.getTemplate();
if (file != null) {
template.setName(file.getName());
}
if (!template.isInMemory()) {
if (file != null && !file.isAbsolute()) {
file = template.getPath();
}
if (file != null && file.exists()) {
result = new String(Files.readAllBytes(file.toPath()));
}
} else {
result = template.getContents();
}
} catch (Exception e) {
logger.warning(e.getMessage());
showWarningDialog("There was an error loading the template file: " + e.getMessage());
}
if (result != null){
this.fileContentArea.setText(result);
this.fileContentArea.setCaretPosition(0);
} else {
this.fileContentArea.setText(EMPTY_FILE_CONTENT);
}
}
@Override
protected void onOK() {
super.onOK();
Template template = this.modifiedParameter.getTemplate();
this.modifiedParameter.setDefaultValue(template.getName());
if (!StringUtils.isNullOrEmpty(outFileName.getText())) {
this.modifiedParameter.setOutputFile(new File(outFileName.getText()));
}
//save parameters
this.modifiedParameter.getParameterDescriptors().clear();
for (ToolParameterDescriptor subparameter : fakeOperatorDescriptor.getToolParameterDescriptors()) {
if (paramsTable.getBindingContext().getBinding(subparameter.getName()) != null) {
Object propertyValue = paramsTable.getBindingContext().getBinding(subparameter.getName()).getPropertyValue();
if (propertyValue != null) {
subparameter.setDefaultValue(propertyValue.toString());
}
}
this.modifiedParameter.addParameterDescriptor(subparameter);
}
try {
String content = fileContentArea.getText();
if (!content.equals(EMPTY_FILE_CONTENT)) {
template.setContents(content, true);
template.save();
}
} catch (IOException | TemplateException e) {
logger.warning(e.getMessage());
}
this.parameter.copyFrom(this.modifiedParameter);
}
private java.util.List<String> getAutocompleteEntries() {
java.util.List<String> entries = new ArrayList<>();
entries.addAll(parentDescriptor.getVariables().stream().map(SystemVariable::getKey).collect(Collectors.toList()));
for (ParameterDescriptor parameterDescriptor : fakeOperatorDescriptor.getParameterDescriptors()) {
entries.add(parameterDescriptor.getName());
}
entries.sort(Comparator.<String>naturalOrder());
return entries;
}
}
| 11,302 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ValidateTextComponentAdapter.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/ValidateTextComponentAdapter.java | package org.esa.snap.ui.tooladapter.dialogs;
import com.bc.ceres.swing.binding.internal.TextComponentAdapter;
import javax.swing.*;
import javax.swing.text.JTextComponent;
/**
* Created by jcoravu on 9/28/2016.
*/
public abstract class ValidateTextComponentAdapter extends TextComponentAdapter {
public ValidateTextComponentAdapter(JTextComponent textComponent) {
super(textComponent);
}
protected abstract boolean validateText(String text);
@Override
public InputVerifier createInputVerifier() {
return new ValidateTextVerifier();
}
private class ValidateTextVerifier extends InputVerifier {
private ValidateTextVerifier() {
}
@Override
public boolean verify(JComponent input) {
String text = ((JTextComponent) input).getText();
if (!validateText(text)) {
return false;
}
actionPerformed(null);
return getBinding().getProblem() == null;
}
}
}
| 1,019 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SystemDependentVariableEditorDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/SystemDependentVariableEditorDialog.java | package org.esa.snap.ui.tooladapter.dialogs;
import org.esa.snap.core.gpf.descriptor.SystemDependentVariable;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.tooladapter.actions.EscapeAction;
import org.esa.snap.ui.tooladapter.model.VariableChangedListener;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.lang.reflect.Method;
import java.util.*;
import java.util.logging.Logger;
/**
* A simple editor window for system-dependent variables
*
* @author Cosmin Cara
*/
public class SystemDependentVariableEditorDialog extends ModalDialog {
private SystemDependentVariable oldVariable;
private SystemDependentVariable newVariable;
private java.util.List<VariableChangedListener> listeners;
private Logger logger;
public SystemDependentVariableEditorDialog(Window parent, SystemDependentVariable variable, String helpID) {
super(parent, String.format("Edit %s", variable.getKey()), ID_OK_CANCEL, helpID);
listeners = new ArrayList<>();
oldVariable = variable;
newVariable = (SystemDependentVariable)oldVariable.createCopy();
newVariable.setTransient(true);
logger = Logger.getLogger(ToolAdapterEditorDialog.class.getName());
setContent(createPanel());
EscapeAction.register(getJDialog());
}
@Override
protected void onOK() {
super.onOK();
oldVariable.setWindows(newVariable.getWindows());
oldVariable.setLinux(newVariable.getLinux());
oldVariable.setMacosx(newVariable.getMacosx());
for (VariableChangedListener l : listeners) {
l.variableChanged(null);
}
}
private JPanel createPanel() {
GridBagLayout layout = new GridBagLayout();
layout.columnWidths = new int[]{100, 390};
JPanel mainPanel = new JPanel(layout);
addTextEditor(mainPanel, "Windows value:", newVariable.getWindows(), "windows", 0);
addTextEditor(mainPanel, "Linux value:", newVariable.getLinux(), "linux", 1);
addTextEditor(mainPanel, "MacOSX value:", newVariable.getMacosx(), "macosx", 2);
return mainPanel;
}
private void addTextEditor(JPanel parent, String label, String value, String fieldName, int line){
parent.add(new JLabel(label), getConstraints(line, 0, 1));
JTextField textField = new JTextField(value);
textField.getDocument().addDocumentListener(new TextChangeListener(textField, newVariable, fieldName));
parent.add(textField, getConstraints(line, 1, 1));
}
private GridBagConstraints getConstraints(int row, int col, int noCells) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = col;
c.gridy = row;
if(noCells != -1){
c.gridwidth = noCells;
}
c.insets = new Insets(2, 10, 2, 10);
return c;
}
private class TextChangeListener implements DocumentListener {
private JTextField parent;
private SystemDependentVariable instance;
private Method fieldSetter;
TextChangeListener(JTextField parentControl, SystemDependentVariable instance, String fieldName) {
this.parent = parentControl;
this.instance = instance;
try {
this.fieldSetter = instance.getClass().getDeclaredMethod("set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), String.class);
} catch (NoSuchMethodException e) {
logger.severe(e.getMessage());
}
}
@Override
public void insertUpdate(DocumentEvent e) {
updateProperty();
}
@Override
public void removeUpdate(DocumentEvent e) {
updateProperty();
}
@Override
public void changedUpdate(DocumentEvent e) {
updateProperty();
}
private void updateProperty() {
EventQueue.invokeLater(() -> {
try {
fieldSetter.invoke(instance, parent.getText());
} catch (Exception e1) {
logger.severe(e1.getMessage());
}
});
}
}
public void addListener(VariableChangedListener l){
this.listeners.add(l);
}
public void removeListener(VariableChangedListener l){
this.listeners.remove(l);
}
}
| 4,507 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ModuleSuiteDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/ModuleSuiteDialog.java | /*
*
* * Copyright (C) 2016 CS ROMANIA
* *
* * 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.ui.tooladapter.dialogs;
import org.esa.snap.core.gpf.descriptor.OSFamily;
import org.esa.snap.core.gpf.descriptor.SystemVariable;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.dependency.BundleType;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterOp;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterRegistry;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.modules.ModulePackager;
import org.esa.snap.modules.ModuleSuiteDescriptor;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.tooladapter.actions.EscapeAction;
import org.esa.snap.ui.tooladapter.dialogs.components.EntityForm;
import org.esa.snap.ui.tooladapter.model.ProgressWorker;
import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Dialog for creating a module suite nbm package
*
* @author Cosmin Cara
*/
public class ModuleSuiteDialog extends ModalDialog {
private static final int YEAR;
private JTable operatorsTable;
private ModuleSuiteDescriptor descriptor;
private Map<OSFamily, org.esa.snap.core.gpf.descriptor.dependency.Bundle> bundles;
private EntityForm<ModuleSuiteDescriptor> descriptorForm;
private BundleForm bundleForm;
private Set<ToolAdapterOperatorDescriptor> initialSelection;
private Map<String, SystemVariable> commonVariables;
static {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
YEAR = calendar.get(Calendar.YEAR);
}
ModuleSuiteDialog(AppContext appContext, String title, String helpID, Set<ToolAdapterOperatorDescriptor> selection) {
super(appContext.getApplicationWindow(), title, ID_OK | ID_CANCEL, helpID);
this.descriptor = new ModuleSuiteDescriptor();
this.descriptor.setAuthors(System.getProperty("user.name"));
this.descriptor.setName("NewBundle");
this.descriptor.setVersion("1");
this.descriptor.setCopyright("(C)" + String.valueOf(YEAR) + " " + this.descriptor.getAuthors());
this.bundles = new HashMap<>();
this.bundles.put(OSFamily.windows,
new org.esa.snap.core.gpf.descriptor.dependency.Bundle(
new ToolAdapterOperatorDescriptor("bundle", ToolAdapterOp.class),
BundleType.ZIP,
SystemUtils.getAuxDataPath().toString()) {{
setOS(OSFamily.windows);
}});
this.bundles.put(OSFamily.linux,
new org.esa.snap.core.gpf.descriptor.dependency.Bundle(
new ToolAdapterOperatorDescriptor("bundle", ToolAdapterOp.class),
BundleType.ZIP,
SystemUtils.getAuxDataPath().toString()) {{
setOS(OSFamily.linux);
}});
this.bundles.put(OSFamily.macosx,
new org.esa.snap.core.gpf.descriptor.dependency.Bundle(
new ToolAdapterOperatorDescriptor("bundle", ToolAdapterOp.class),
BundleType.ZIP,
SystemUtils.getAuxDataPath().toString()) {{
setOS(OSFamily.macosx);
}});
this.initialSelection = new HashSet<>();
this.commonVariables = new HashMap<>();
if (selection != null) {
this.initialSelection.addAll(selection);
this.initialSelection.forEach(d -> {
for (SystemVariable variable : d.getVariables()) {
this.commonVariables.put(variable.getKey(), variable);
}
});
}
JPanel contentPanel = createContentPanel();
setContent(contentPanel);
super.getJDialog().setMinimumSize(contentPanel.getPreferredSize());
EscapeAction.register(super.getJDialog());
}
private JPanel createContentPanel() {
GridBagLayout layout = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
JPanel panel = new JPanel(layout);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JLabel("Suite description:"), constraints);
constraints.gridx = 1;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JLabel("Adapters to include:"), constraints);
JPanel descriptorPanel = createDescriptorPanel();
descriptorPanel.setPreferredSize(new Dimension(350, 250));
constraints.gridx = 0;
constraints.gridy = 1;
constraints.weightx = 1;
constraints.weighty = 1;
constraints.fill = GridBagConstraints.BOTH;
panel.add(descriptorPanel, constraints);
JTable adaptersTable = createAdaptersTable();
JScrollPane scrollPane = new JScrollPane(adaptersTable);
constraints.gridx = 1;
constraints.gridy = 1;
constraints.weighty = 1;
constraints.fill = GridBagConstraints.BOTH;
panel.add(scrollPane, constraints);
JPanel bundlePanel = createBundlePanel();
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 2;
constraints.weightx = 1;
constraints.weighty = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
panel.add(bundlePanel, constraints);
panel.setPreferredSize(new Dimension(680, 350));
return panel;
}
private JTable createAdaptersTable() {
java.util.List<ToolAdapterOperatorDescriptor> toolboxSpis = new ArrayList<>();
toolboxSpis.addAll(ToolAdapterRegistry.INSTANCE.getOperatorMap().values()
.stream()
.map(e -> (ToolAdapterOperatorDescriptor) e.getOperatorDescriptor())
.collect(Collectors.toList()));
toolboxSpis.sort(Comparator.comparing(ToolAdapterOperatorDescriptor::getAlias));
AdapterListModel model = new AdapterListModel(toolboxSpis);
operatorsTable = new JTable(model);
operatorsTable.getSelectionModel().addListSelectionListener(e -> onSelectionChanged());
TableColumn checkColumn = operatorsTable.getColumnModel().getColumn(0);
int checkColumnWidth = 24;
checkColumn.setMaxWidth(checkColumnWidth);
checkColumn.setPreferredWidth(checkColumnWidth);
checkColumn.setResizable(false);
TableColumn aliasColumn = operatorsTable.getColumnModel().getColumn(1);
aliasColumn.setPreferredWidth(10 * checkColumnWidth);
return operatorsTable;
}
private JPanel createDescriptorPanel() {
this.descriptorForm = new EntityForm<>(this.descriptor);
JPanel panel = descriptorForm.getPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
return panel;
}
private JPanel createBundlePanel() {
this.bundleForm = new BundleForm(SnapApp.getDefault().getAppContext(),
this.bundles.get(OSFamily.windows),
this.bundles.get(OSFamily.linux),
this.bundles.get(OSFamily.macosx),
new ArrayList<>(this.commonVariables.values()));
this.bundleForm.setBorder(BorderFactory.createLineBorder(Color.GRAY));
return this.bundleForm;
}
private void onSelectionChanged() {
ToolAdapterOperatorDescriptor[] selection = ((AdapterListModel) this.operatorsTable.getModel()).getSelectedItems();
this.commonVariables.clear();
for (ToolAdapterOperatorDescriptor descriptor : selection) {
List<SystemVariable> variables = descriptor.getVariables();
for (SystemVariable variable : variables) {
this.commonVariables.put(variable.getKey(), variable);
}
}
this.bundleForm.setVariables(new ArrayList<>(this.commonVariables.values()));
}
@Override
protected void onOK() {
ToolAdapterOperatorDescriptor[] selection = ((AdapterListModel) this.operatorsTable.getModel()).getSelectedItems();
if (selection.length > 0) {
this.descriptor = this.descriptorForm.applyChanges();
final Map<OSFamily, org.esa.snap.core.gpf.descriptor.dependency.Bundle> bundles = this.bundleForm.applyChanges();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fileChooser.showOpenDialog(getButton(ID_OTHER)) == JFileChooser.APPROVE_OPTION) {
File targetFolder = fileChooser.getSelectedFile();
final String nbmName = this.descriptor.getName() + ".nbm";
ProgressWorker worker = new ProgressWorker("Export Module Suite", "Creating NetBeans module suite " + nbmName,
() -> {
try {
ModulePackager.packModules(this.descriptor, new File(targetFolder, nbmName), bundles, selection);
Dialogs.showInformation(String.format(Bundle.MSG_Export_Complete_Text(), targetFolder.getAbsolutePath()), null);
} catch (IOException e) {
SystemUtils.LOG.warning(e.getMessage());
Dialogs.showError(e.getMessage());
}
});
worker.executeWithBlocking();
super.onOK();
}
} else {
Dialogs.showWarning("Please select at least one adapter");
}
}
private class AdapterListModel extends AbstractTableModel {
private Object[][] checkedList;
private String[] columnNames;
AdapterListModel(List<ToolAdapterOperatorDescriptor> descriptors) {
super();
this.checkedList = new Object[descriptors.size()][2];
for (int i = 0; i < descriptors.size(); i++) {
ToolAdapterOperatorDescriptor descriptor = descriptors.get(i);
this.checkedList[i][0] = ModuleSuiteDialog.this.initialSelection.contains(descriptor);
this.checkedList[i][1] = descriptor;
}
this.columnNames = new String[] { "", "Adapter Alias" };
}
@Override
public String getColumnName(int column) {
return this.columnNames[column];
}
@Override
public int getRowCount() {
return this.checkedList != null ? this.checkedList.length : 0;
}
@Override
public int getColumnCount() {
return columnNames != null ? columnNames.length : 0;
}
@Override
public Object getValueAt(int row, int column) {
switch (column) {
case 0:
return this.checkedList[row][0];
case 1:
return ((ToolAdapterOperatorDescriptor) this.checkedList[row][1]).getAlias();
default:
return null;
}
}
ToolAdapterOperatorDescriptor[] getSelectedItems() {
List<ToolAdapterOperatorDescriptor> selection = new ArrayList<>();
for (Object[] aCheckedList : this.checkedList) {
if (aCheckedList[0] == Boolean.TRUE) {
selection.add((ToolAdapterOperatorDescriptor) aCheckedList[1]);
}
}
return selection.toArray(new ToolAdapterOperatorDescriptor[selection.size()]);
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex != 0)
return;
this.checkedList[rowIndex][0] = aValue;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return Boolean.class;
case 1:
return String.class;
default:
return null;
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex != 1;
}
}
}
| 13,891 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProgressHandler.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/progress/ProgressHandler.java | /*
*
* * Copyright (C) 2016 CS ROMANIA
* *
* * 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.ui.tooladapter.dialogs.progress;
import com.bc.ceres.core.ProgressMonitor;
import org.netbeans.api.progress.ProgressHandle;
/**
* @author kraftek
* @date 3/14/2017
*/
public class ProgressHandler implements ProgressMonitor {
private ProgressHandle progressHandle;
private boolean isIndeterminate;
private ConsoleConsumer console;
public ProgressHandler(ProgressHandle handle, boolean indeterminate) {
this.progressHandle = handle;
this.isIndeterminate = indeterminate;
this.progressHandle.setInitialDelay(10);
}
public void setConsumer(ConsoleConsumer consumer) {
console = consumer;
}
@Override
public void beginTask(String taskName, int totalWork) {
this.progressHandle.setDisplayName(taskName);
this.progressHandle.start(totalWork, -1);
if (this.isIndeterminate) {
this.progressHandle.switchToIndeterminate();
}
if (this.console != null) {
this.console.setVisible(true);
}
}
@Override
public void done() {
this.progressHandle.finish();
}
@Override
public void internalWorked(double work) {
this.progressHandle.progress((int) work);
}
@Override
public boolean isCanceled() {
return false;
}
@Override
public void setCanceled(boolean canceled) {
this.progressHandle.suspend("Cancelled");
}
@Override
public void setTaskName(String taskName) {
this.progressHandle.setDisplayName(taskName);
}
@Override
public void setSubTaskName(String subTaskName) {
this.progressHandle.progress(subTaskName);
}
@Override
public void worked(int work) {
internalWorked(work);
}
}
| 2,513 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ConsoleConsumer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/progress/ConsoleConsumer.java | /*
*
* * Copyright (C) 2016 CS ROMANIA
* *
* * 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.ui.tooladapter.dialogs.progress;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.snap.core.gpf.operators.tooladapter.DefaultOutputConsumer;
import org.esa.snap.ui.tooladapter.dialogs.ConsolePane;
import javax.swing.*;
/**
* @author kraftek
* @date 3/14/2017
*/
public class ConsoleConsumer extends DefaultOutputConsumer {
private ConsolePane consolePane;
public ConsoleConsumer(String progressPattern, String errorPattern, String stepPattern, ProgressMonitor pm, ConsolePane consolePane) {
super(progressPattern, errorPattern, stepPattern, pm);
this.consolePane = consolePane;
}
@Override
public void consumeOutput(String line) {
super.consumeOutput(line);
if (consolePane != null) {
if (SwingUtilities.isEventDispatchThread()) {
consume(line);
} else {
SwingUtilities.invokeLater(() -> consume(line));
}
}
}
void setVisible(boolean value) {
if (this.consolePane != null) {
this.consolePane.setVisible(value);
}
}
private void consume(String line) {
if (this.error == null || !this.error.matcher(line).matches()) {
consolePane.appendInfo(line);
} else {
consolePane.appendError(line);
}
}
}
| 2,083 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
EntityForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/components/EntityForm.java | /*
*
* * Copyright (C) 2016 CS ROMANIA
* *
* * 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.ui.tooladapter.dialogs.components;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.core.Assert;
import com.bc.ceres.swing.binding.Binding;
import com.bc.ceres.swing.binding.PropertyPane;
import org.esa.snap.core.gpf.descriptor.annotations.Folder;
import org.esa.snap.core.gpf.descriptor.annotations.ReadOnly;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.utils.UIUtils;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
/**
* Generic form for simplified binding of an object instance.
* Allows for property dependencies (i.e. if one property changes, a dependent one will change based on a function of the first one).
* Allows for additional actions to be performed.
*
* @author Cosmin Cara
*/
public class EntityForm<T> {
private Class<T> entityType;
private Map<String, FieldChangeTrigger[]> fieldMap;
private Map<String, Annotation[]> annotatedFields;
private T original;
private T modified;
private JPanel panel;
private Map<String, Function<T, Void>> actions;
public EntityForm(T object) {
this(object, null, null);
}
public EntityForm(T object, Map<String, FieldChangeTrigger[]> dependentFieldsActions, Map<String, Function<T, Void>> additionalActions) {
Assert.notNull(object);
this.original = object;
this.entityType = (Class<T>) this.original.getClass();
Field[] fields = this.entityType.getDeclaredFields();
this.fieldMap = new HashMap<>();
this.annotatedFields = new HashMap<>();
for (Field field : fields) {
String fieldName = field.getName();
FieldChangeTrigger[] dependencies = dependentFieldsActions != null ?
dependentFieldsActions.get(fieldName) : null;
this.fieldMap.put(fieldName, dependencies);
Annotation[] annotations = field.getAnnotations();
if (annotations != null) {
this.annotatedFields.put(fieldName, annotations);
}
}
try {
this.modified = duplicate(this.original, this.modified, false);
} catch (Exception ex) {
ex.printStackTrace();
}
actions = new HashMap<>();
if (additionalActions != null) {
actions.putAll(additionalActions);
}
buildUI();
}
public JPanel getPanel() {
return this.panel;
}
public T applyChanges() {
try {
this.original = duplicate(this.modified, this.original, true);
} catch (Exception ex) {
ex.printStackTrace();
}
return this.original;
}
private T duplicate(T source, T target, boolean useSetters) throws Exception {
if (target == null) {
Constructor<T> constructor = this.entityType.getConstructor();
target = constructor.newInstance();
}
for (String fieldName : this.fieldMap.keySet()) {
Object sourceValue = getValue(source, fieldName);
if (useSetters) {
try {
invokeMethod(target, "set" + StringUtils.firstLetterUp(fieldName), sourceValue);
} catch (Exception ignored) {
// if no setter, then set the field directly
setValue(target, fieldName, sourceValue);
}
} else {
setValue(target, fieldName, sourceValue);
}
}
return target;
}
private void buildUI() {
PropertyContainer propertyContainer = PropertyContainer.createObjectBacked(this.modified);
for (String field : this.fieldMap.keySet()) {
if (this.annotatedFields.containsKey(field)) {
Annotation[] annotations = this.annotatedFields.get(field);
Optional<Annotation> annotation = Arrays.stream(annotations)
.filter(a -> a.annotationType().equals(Folder.class))
.findFirst();
if (annotation.isPresent()) {
try {
if (File.class.isAssignableFrom(this.entityType.getDeclaredField(field).getType())) {
propertyContainer.getDescriptor(field).setAttribute("directory", true);
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
}
PropertyPane parametersPane = new PropertyPane(propertyContainer);
this.panel = parametersPane.createPanel();
for (Property property : propertyContainer.getProperties()) {
Arrays.stream(parametersPane.getBindingContext().getBinding(property.getName()).getComponents())
.forEach(c -> UIUtils.addPromptSupport(c, property));
if (this.annotatedFields.containsKey(property.getName())) {
Optional<Annotation> annotation = Arrays.stream(this.annotatedFields.get(property.getName()))
.filter(a -> a.annotationType().equals(ReadOnly.class))
.findFirst();
annotation.ifPresent(annotation1 -> Arrays.stream(parametersPane.getBindingContext().getBinding(property.getName()).getComponents())
.forEach(c -> c.setEnabled(false)));
}
}
propertyContainer.addPropertyChangeListener(evt -> {
String propertyName = evt.getPropertyName();
Object newValue = evt.getNewValue();
try {
invokeMethod(modified, "set" + StringUtils.firstLetterUp(propertyName), newValue);
} catch (Exception e) {
try {
setValue(modified, propertyName, newValue);
} catch (Exception e1) {
e1.printStackTrace();
}
}
FieldChangeTrigger[] dependencies = fieldMap.get(propertyName);
if (dependencies != null && dependencies.length > 0) {
for (FieldChangeTrigger dependency : dependencies) {
try {
if (dependency.canApply(newValue)) {
Object newTargetValue = dependency.apply(newValue);
Binding binding = parametersPane.getBindingContext().getBinding(dependency.getTargetFieldName());
binding.setPropertyValue(newTargetValue);
binding.adjustComponents();
}
} catch(Exception e){
e.printStackTrace();
}
}
}
});
this.panel.addPropertyChangeListener(evt -> {
if (!(evt.getNewValue() instanceof JTextField)) return;
JTextField field = (JTextField) evt.getNewValue();
String text = field.getText();
if (text != null && text.isEmpty()) {
field.setCaretPosition(text.length());
}
});
if (this.actions.size() > 0) {
JPanel actionsPanel = new JPanel(new BorderLayout());
for (Map.Entry<String, Function<T, Void>> action : this.actions.entrySet()) {
AbstractButton button = new JButton(action.getKey());
button.addActionListener(e -> {
parametersPane.getBindingContext().adjustComponents();
action.getValue().apply(EntityForm.this.modified);
});
actionsPanel.add(button, BorderLayout.EAST);
}
this.panel.add(actionsPanel);
}
this.panel.setBorder(new EmptyBorder(4, 4, 4, 4));
}
private static Object invokeMethod(Object instance, String methodName, Object... args)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (args == null)
args = new Object[] {};
Class[] classTypes = getClassArray(args);
Method[] methods = instance.getClass().getMethods();
for (Method method : methods) {
Class[] paramTypes = method.getParameterTypes();
if (method.getName().equals(methodName) && compare(paramTypes, args)) {
return method.invoke(instance, args);
}
}
StringBuilder sb = new StringBuilder();
sb.append("No method named ").append(methodName).append(" found in ")
.append(instance.getClass().getName()).append(" with parameters (");
for (int x = 0; x < classTypes.length; x++) {
sb.append(classTypes[x].getName());
if (x < classTypes.length - 1) {
sb.append(", ");
}
}
sb.append(")");
throw new NoSuchMethodException(sb.toString());
}
private static Class[] getClassArray(Object[] args) {
Class[] classTypes = null;
if (args != null) {
classTypes = new Class[args.length];
for (int i = 0; i < args.length; i++) {
if (args[i] != null)
classTypes[i] = args[i].getClass();
}
}
return classTypes;
}
private static boolean compare(Class[] c, Object[] args) {
if (c.length != args.length) {
return false;
}
for (int i = 0; i < c.length; i++) {
if (!c[i].isInstance(args[i])) {
return false;
}
}
return true;
}
private static Object getValue(Object instance, String fieldName)
throws IllegalAccessException, NoSuchFieldException {
Field field = getField(instance.getClass(), fieldName);
field.setAccessible(true);
return field.get(instance);
}
private static void setValue(Object instance, String fieldName, Object value)
throws IllegalAccessException, NoSuchFieldException {
Field field = getField(instance.getClass(), fieldName);
field.setAccessible(true);
field.set(instance, value);
}
private static Field getField(Class thisClass, String fieldName) throws NoSuchFieldException {
if (thisClass == null)
throw new NoSuchFieldException("Invalid field : " + fieldName);
try {
return thisClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
return getField(thisClass.getSuperclass(), fieldName);
}
}
}
| 11,863 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AnchorLabel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/components/AnchorLabel.java | /*
*
* * Copyright (C) 2016 CS ROMANIA
* *
* * 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.ui.tooladapter.dialogs.components;
import org.esa.snap.tango.TangoIcons;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.Optional;
/**
* Simple hyperlink-like label that navigates to the given tab index and component.
*
* @author Cosmin Cara
*/
public class AnchorLabel extends JLabel {
private JTabbedPane parentTabControl;
private int tabIndex;
private JComponent component;
public AnchorLabel(String text, JTabbedPane parent, int index, JComponent anchoredComponent) {
super(text);
this.parentTabControl = parent;
this.tabIndex = index;
this.component = anchoredComponent;
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
enableEvents(MouseEvent.MOUSE_EVENT_MASK);
}
@Override
public void setText(String text) {
super.setText("<html><font color=\"#FF0000\">" + text + "</font></html>");
}
public void markError() {
JLabel label = findLabelFor(component);
if (label != null) {
label.setIcon(TangoIcons.status_dialog_error(TangoIcons.Res.R16));
}
}
public void clearError() {
JLabel label = findLabelFor(component);
if (label != null) {
label.setIcon(null);
}
}
@Override
protected void processMouseEvent(MouseEvent e) {
super.processMouseEvent(e);
if (e.getID() == MouseEvent.MOUSE_CLICKED) {
parentTabControl.setSelectedIndex(tabIndex);
if (component instanceof JPanel &&
component.getComponents() != null && component.getComponents().length > 0) {
Component comp = component.getComponent(0);
comp.requestFocusInWindow();
} else {
component.requestFocusInWindow();
}
if (component instanceof JTextField)
SwingUtilities.invokeLater(() -> {
((JTextField) component).setCaretPosition(((JTextField) component).getDocument().getLength());
});
}
}
private JLabel findLabelFor(JComponent component) {
Optional<Component> label = Arrays.stream(component.getParent().getComponents())
.filter(c -> c instanceof JLabel && component.equals(((JLabel) c).getLabelFor()))
.findFirst();
return label.map(component1 -> (JLabel) component1).orElse(null);
}
}
| 3,427 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FieldChangeTrigger.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/dialogs/components/FieldChangeTrigger.java | /*
*
* * Copyright (C) 2016 CS ROMANIA
* *
* * 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.ui.tooladapter.dialogs.components;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* Models a relation between two entity fields such that, if one field changes, the other may change based on the new
* value of the first field.
*
* @param <S> The source field type
* @param <T> The target field type
*
* @author Cosmin Cara
*/
public class FieldChangeTrigger<S, T> implements Function<S, T> {
private String targetFieldName;
private Predicate<S> condition;
private Function<S, T> action;
/**
* Creates a field change trigger with just an action.
*
* @param fieldName The target field name
* @param action The action that will set the target
* @param <K> The source field type
* @param <V> The target field type
*/
public static <K,V> FieldChangeTrigger<K, V> create(String fieldName, Function<K, V> action) {
return create(fieldName, action, null);
}
/**
* Creates a field change trigger with an action that will execute based on a condition.
*
* @param fieldName The target field name
* @param action The action that may set the target
* @param condition The condition to check before performing the action
* @param <K> The source field type
* @param <V> The target field type
*/
public static <K,V> FieldChangeTrigger<K, V> create(String fieldName, Function<K, V> action, Predicate<K> condition) {
return new FieldChangeTrigger<K, V>(fieldName, action, condition);
}
private FieldChangeTrigger(String fieldName, Function<S, T> action, Predicate<S> condition) {
this.targetFieldName = fieldName;
this.action = action;
this.condition = condition;
}
/**
* Returns the target field name
*/
public String getTargetFieldName() {
return targetFieldName;
}
public boolean canApply(S input) {
return condition == null || condition.test(input);
}
public T apply(S input) {
return canApply(input) ?
action != null ? action.apply(input) : null : null;
}
}
| 2,966 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FilePanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/FilePanel.java | package org.esa.snap.ui.tooladapter.model;
import org.esa.snap.core.util.StringUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.File;
/**
* Created by jcoravu on 10/6/2016.
*/
public class FilePanel extends JPanel {
private final JTextField textField;
private final JButton browseButton;
public FilePanel() {
super(new BorderLayout());
this.textField = new JTextField();
this.textField.setBorder(new EmptyBorder(0, 0, 0, 0));
this.browseButton = new JButton("...");
browseButton.setFocusable(false);
Dimension size = new Dimension(26, 16);
browseButton.setPreferredSize(size);
browseButton.setMinimumSize(size);
addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent event) {
textField.requestFocusInWindow();
}
});
add(this.textField, BorderLayout.CENTER);
add(browseButton, BorderLayout.EAST);
}
public void addBrowseButtonActionListener(ActionListener actionListener) {
this.browseButton.addActionListener(actionListener);
}
public String getText() {
return this.textField.getText();
}
public void setText(String text) {
this.textField.setText(text);
}
public void addTextComponentFocusListener(FocusListener focusListener) {
this.textField.addFocusListener(focusListener);
}
public File showFileChooserDialog(int selectionMode, FileFilter filter) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(selectionMode);
String filePath = textField.getText();
if (!StringUtils.isNullOrEmpty(filePath)) {
File currentFile = new File(filePath);
fileChooser.setSelectedFile(currentFile);
}
if (filter != null) {
fileChooser.setFileFilter(filter);
}
int resultState = fileChooser.showDialog(FilePanel.this, "Select");
if (resultState == JFileChooser.APPROVE_OPTION && fileChooser.getSelectedFile() != null) {
textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
return fileChooser.getSelectedFile();
}
return null;
}
}
| 2,526 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PropertyUIDescriptor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/PropertyUIDescriptor.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.model;
import com.bc.ceres.swing.binding.BindingContext;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolParameterDescriptor;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.util.HashMap;
/**
* @author Ramona Manda
*/
public class PropertyUIDescriptor {
private AbstractButton delButton;
private AbstractButton editButton;
private HashMap<String, PropertyMemberUIWrapper> UIcomponentsMap;
public static PropertyUIDescriptor buildUIMinimalDescriptor(ToolParameterDescriptor parameter, String property, ToolAdapterOperatorDescriptor operator, BindingContext context, ActionListener deleteActionListener, ActionListener editActionListener, PropertyMemberUIWrapper.CallBackAfterEdit callback) {
PropertyUIDescriptor descriptor = new PropertyUIDescriptor();
AbstractButton delButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("/org/esa/snap/resources/images/icons/DeleteShapeTool16.gif"),
false);
delButton.addActionListener(deleteActionListener);
descriptor.setDelButton(delButton);
AbstractButton editButton = new JButton("...");
editButton.addActionListener(editActionListener);
descriptor.setEditButton(editButton);
HashMap<String, PropertyMemberUIWrapper> UIcomponentsMap = new HashMap<>();
UIcomponentsMap.put(property, PropertyMemberUIWrapperFactory.buildPropertyWrapper(property, parameter, operator, context, callback));
descriptor.setUIcomponentsMap(UIcomponentsMap);
return descriptor;
}
public static PropertyUIDescriptor buildUIDescriptor(ToolParameterDescriptor prop, String[] columnsMembers, ToolAdapterOperatorDescriptor opDescriptor, BindingContext context, ActionListener deleteActionListener, ActionListener editActionListener, PropertyMemberUIWrapper.CallBackAfterEdit callback) {
PropertyUIDescriptor descriptor = new PropertyUIDescriptor();
AbstractButton delButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("/org/esa/snap/resources/images/icons/DeleteShapeTool16.gif"),
false);
delButton.addActionListener(deleteActionListener);
descriptor.setDelButton(delButton);
AbstractButton editButton = new JButton("...");
editButton.addActionListener(editActionListener);
descriptor.setEditButton(editButton);
HashMap<String, PropertyMemberUIWrapper> UIcomponentsMap = new HashMap<>();
for (String col : columnsMembers) {
if (!col.equals("del")) {
UIcomponentsMap.put(col, PropertyMemberUIWrapperFactory.buildPropertyWrapper(col, prop, opDescriptor, context, callback));
}
}
descriptor.setUIcomponentsMap(UIcomponentsMap);
return descriptor;
}
public void fillDescriptor(String[] columnsMembers) {
for (String col : columnsMembers) {
if (!col.equals("del")) {
//UIcomponentsMap.put(col, PropertyMemberUIWrapperFactory.buildPropertyWrapper(col, prop, context, callback));
}
}
}
public void setAttributeEditCallback(String attributeName, PropertyMemberUIWrapper.CallBackAfterEdit callback) {
UIcomponentsMap.get(attributeName).setCallback(callback);
}
public void setEditCallback(PropertyMemberUIWrapper.CallBackAfterEdit callback) {
while (UIcomponentsMap.keySet().iterator().hasNext()) {
UIcomponentsMap.get(UIcomponentsMap.keySet().iterator().next()).setCallback(callback);
}
}
public AbstractButton getDelButton() {
return delButton;
}
public AbstractButton getEditButton() {
return editButton;
}
public HashMap<String, PropertyMemberUIWrapper> getUIcomponentsMap() {
return UIcomponentsMap;
}
public void setDelButton(AbstractButton delButton) {
this.delButton = delButton;
}
public void setEditButton(AbstractButton editButton) {
this.editButton = editButton;
}
public void setUIcomponentsMap(HashMap<String, PropertyMemberUIWrapper> UIcomponentsMap) {
this.UIcomponentsMap = UIcomponentsMap;
}
}
| 5,082 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VariablesTable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/VariablesTable.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.model;
import org.esa.snap.core.gpf.descriptor.SystemDependentVariable;
import org.esa.snap.core.gpf.descriptor.SystemVariable;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.esa.snap.ui.tooladapter.dialogs.SystemDependentVariableEditorDialog;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
/**
* @author Ramona Manda
*/
public class VariablesTable extends JTable {
private static String[] columnNames = {"", "Shared", "Key", "Value"};
private static int[] widths = {24, 40, 100, 250};
private List<SystemVariable> variables;
private MultiRenderer tableRenderer;
private AppContext appContext;
public VariablesTable(List<SystemVariable> variables, AppContext context) {
this.variables = variables;
this.appContext = context;
tableRenderer = new MultiRenderer();
setModel(new VariablesTableModel());
setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
for(int i=0; i < widths.length; i++) {
TableColumn column = getColumnModel().getColumn(i);
column.setPreferredWidth(widths[i]);
}
}
public void stopVariablesTableEditing(){
int row = getEditingRow();
int column = getEditingColumn();
if(row >= 0 && column >= 0){
/* For System Dependent Variables, the value is edited by using a dedicated form and not the Table Editor */
if(!(variables.get(row) instanceof SystemDependentVariable) || column != 3){
getCellEditor(getEditingRow(), getEditingColumn()).stopCellEditing();
}
}
}
@Override
public TableCellRenderer getCellRenderer(int row, int column) {
if (column == 0) {
return tableRenderer;
}
return super.getCellRenderer(row, column);
}
@Override
public TableCellEditor getCellEditor(int row, int column) {
switch (column) {
case 0:
case 2:
case 3:
return tableRenderer;
case 1:
return getDefaultEditor(Boolean.class);
default:
return getDefaultEditor(String.class);
}
}
class VariablesTableModel extends AbstractTableModel {
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnIndex != 1 ? String.class : Boolean.class;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return variables.size();
}
@Override
public Object getValueAt(int row, int column) {
switch (column) {
case 0:
return false;
case 1:
return variables.get(row).isShared();
case 2:
return variables.get(row).getKey();
case 3:
return variables.get(row).getValue();
}
return null;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (aValue != null) {
switch (columnIndex) {
case 0:
variables.remove(variables.get(rowIndex));
fireTableDataChanged();
break;
case 1:
variables.get(rowIndex).setShared(Boolean.valueOf(aValue.toString()));
break;
case 2:
variables.get(rowIndex).setKey(aValue.toString());
break;
case 3:
variables.get(rowIndex).setValue(aValue.toString());
break;
}
}
}
}
class MultiRenderer extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {
private TableCellRenderer defaultRenderer = new DefaultTableCellRenderer();
private AbstractButton delButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("/org/esa/snap/resources/images/icons/DeleteShapeTool16.gif"),
false);
private TableCellEditor lastEditor;
public MultiRenderer() {
delButton.addActionListener(e -> fireEditingStopped());
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
switch (column) {
case 0:
return delButton;
default:
return defaultRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
switch (column) {
case 0:
lastEditor = null;
return delButton;
case 1:
lastEditor = getDefaultEditor(Boolean.class);
return lastEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
case 3:
SystemVariable variable = variables.get(row);
if (variable instanceof SystemDependentVariable) {
lastEditor = new SystemDependentVariableCellEditor(appContext.getApplicationWindow(), (SystemDependentVariable)variable, null);
return lastEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
} else {
lastEditor = getDefaultEditor(String.class);
return lastEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
}
default:
lastEditor = getDefaultEditor(String.class);
return lastEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}
@Override
public Object getCellEditorValue() {
//return lastEditor != null ? lastEditor.getCellEditorValue() : delButton; //delButton;
return lastEditor != null ?
((DefaultCellEditor)lastEditor).getComponent() instanceof JTextField ?
((JTextField)((DefaultCellEditor)lastEditor).getComponent()).getText() :
lastEditor.getCellEditorValue() :
delButton;
}
}
class SystemDependentVariableCellEditor extends DefaultCellEditor implements TableCellEditor, VariableChangedListener {
private static final int CLICK_COUNT_TO_START = 2;
private JButton button;
private SystemDependentVariableEditorDialog dialog;
private SystemDependentVariable variable;
/**
* Constructor.
*/
public SystemDependentVariableCellEditor(Window window, SystemDependentVariable variable, String helpID) {
super(new JTextField());
setClickCountToStart(CLICK_COUNT_TO_START);
// Using a JButton as the editor component
button = new JButton();
button.setBackground(Color.white);
button.setFont(button.getFont().deriveFont(Font.PLAIN));
button.setBorder(null);
button.setHorizontalAlignment(SwingConstants.LEFT);
button.setText(variable.getValue());
this.variable = variable;
// Dialog which will do the actual editing
dialog = new SystemDependentVariableEditorDialog(window, this.variable, helpID);
dialog.addListener(this);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == CLICK_COUNT_TO_START) {
dialog.show();
fireEditingStopped();
}
}
});
}
@Override
public Object getCellEditorValue() {
return variable.getValue();
}
@Override
public Component getComponent() {
/* The button is used for editing System Dependent Variables;
therefore the table cell editor is calling this method to get the current value for the stop editing event */
return button;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
/*SwingUtilities.invokeLater(() -> {
dialog.show();
fireEditingStopped();
});*/
return button;
}
@Override
public void variableChanged(VariableChangedEvent ev) {
String currentOSValue = variable.getCurrentOSValue();
button.setText(currentOSValue);
}
}
}
| 10,293 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OperationType.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/OperationType.java | package org.esa.snap.ui.tooladapter.model;
/**
* Created by dmihailescu on 17/03/2016.
*/
public enum OperationType {
NEW,
COPY,
EDIT,
FORCED_EDIT
}
| 169 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProgressWorker.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/ProgressWorker.java | /*
*
* * Copyright (C) 2016 CS ROMANIA
* *
* * 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.ui.tooladapter.model;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import org.esa.snap.rcp.SnapApp;
import javax.swing.*;
import java.awt.*;
/**
* Simple graphical progress worker for a runnable task.
*
* @author Cosmin Cara
*/
public class ProgressWorker extends ProgressMonitorSwingWorker {
private final static SnapApp snapApp = SnapApp.getDefault();
private String message;
private Runnable task;
public ProgressWorker(String title, String message, Runnable task) {
super(snapApp.getMainFrame(), title);
this.message = message;
this.task = task;
}
@Override
protected Object doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception {
try {
pm.beginTask(message, 1);
SwingUtilities.invokeLater(() -> {
snapApp.setStatusBarMessage(message);
snapApp.getMainFrame().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
});
if (task != null) {
task.run();
}
} catch (Throwable e) {
snapApp.handleError("The operation failed.", e); //handleUnknownException(e);
} finally {
SwingUtilities.invokeLater(() -> snapApp.getMainFrame().setCursor(Cursor.getDefaultCursor()));
snapApp.setStatusBarMessage("");
pm.done();
}
return null;
}
} | 2,176 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VariableChangedListener.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/VariableChangedListener.java | package org.esa.snap.ui.tooladapter.model;
/**
* Created by dmihailescu on 06/04/2016.
*/
public interface VariableChangedListener{
void variableChanged(VariableChangedEvent ev);
}
class VariableChangedEvent{}
| 218 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PropertyMemberUIWrapper.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/PropertyMemberUIWrapper.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.model;
import com.bc.ceres.swing.binding.BindingContext;
import org.esa.snap.core.gpf.descriptor.PropertyAttributeException;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolParameterDescriptor;
import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.logging.Logger;
/**
* @author Ramona Manda
*/
public abstract class PropertyMemberUIWrapper implements FocusListener {
protected String attributeName;
protected JComponent UIComponent;
protected int width = 0;
protected ToolParameterDescriptor paramDescriptor;
protected ToolAdapterOperatorDescriptor opDescriptor;
private CallBackAfterEdit callback;
private BindingContext context;
private Logger logger;
public PropertyMemberUIWrapper(String attributeName, ToolParameterDescriptor paramDescriptor, ToolAdapterOperatorDescriptor opDescriptor, BindingContext context) {
this.attributeName = attributeName;
this.paramDescriptor = paramDescriptor;
this.opDescriptor = opDescriptor;
this.context = context;
this.logger = Logger.getLogger(PropertyMemberUIWrapper.class.getName());
}
public PropertyMemberUIWrapper(String attributeName, ToolParameterDescriptor paramDescriptor, ToolAdapterOperatorDescriptor opDescriptor, BindingContext context, int width, CallBackAfterEdit callback) {
this(attributeName, paramDescriptor, opDescriptor, context);
this.width = width;
this.callback = callback;
try {
getUIComponent();
}catch (Exception ex){
logger.warning(ex.getMessage());
}
}
public BindingContext getContext(){
return this.context;
}
public ToolParameterDescriptor getParamDescriptor(){
return this.paramDescriptor;
}
public String getErrorValueMessage(Object value) {
return null;
}
protected abstract void setMemberValue(Object value) throws PropertyAttributeException;
public abstract Object getMemberValue() throws PropertyAttributeException;
public JComponent getUIComponent() throws Exception {
if (UIComponent == null) {
buildAndLinkUIComponent();
}
return UIComponent;
}
public JComponent reloadUIComponent(Class<?> newParamType) throws Exception{
buildAndLinkUIComponent();
return UIComponent;
}
public void buildAndLinkUIComponent() throws Exception {
UIComponent = buildUIComponent();
if (width != -1) {
UIComponent.setPreferredSize(new Dimension(width, 20));
}
UIComponent.addFocusListener(this);
//Object value = context.getBinding(attributeName).getPropertyValue();
/*if(value != null) {
if (UIComponent instanceof JTextField) {
((JTextField) UIComponent).setText(value.toString());
}
if (UIComponent instanceof JFileChooser) {
((JFileChooser) UIComponent).setSelectedFile(new File(value.toString()));
}
if (UIComponent instanceof JComboBox) {
((JComboBox) UIComponent).setSelectedItem(value);
}
}*/
}
protected abstract JComponent buildUIComponent() throws Exception;
public void setMemberValueWithCheck(Object value) throws PropertyAttributeException {
String msg = getErrorValueMessage(value);
if (msg != null) {
throw new PropertyAttributeException(msg);
}
setMemberValue(value);
}
public boolean memberUIComponentNeedsRevalidation() {
return false;
}
public boolean propertyUIComponentsNeedsRevalidation() {
return false;
}
public boolean contextUIComponentsNeedsRevalidation() {
return false;
}
@Override
public void focusGained(FocusEvent e) {
//do nothing
}
@Override
public void focusLost(FocusEvent e) {
//save the value
if (!e.isTemporary()) {
try {
if (getValueFromUIComponent().equals(getMemberValue())) {
return;
}
setMemberValueWithCheck(getValueFromUIComponent());
if (callback != null) {
callback.doCallBack(null, paramDescriptor, null, attributeName);
}
} catch (PropertyAttributeException ex) {
if (callback != null) {
callback.doCallBack(ex, paramDescriptor, null, attributeName);
}
UIComponent.requestFocusInWindow();
}
}
}
public void setCallback(CallBackAfterEdit callback) {
this.callback = callback;
}
protected abstract Object getValueFromUIComponent() throws PropertyAttributeException;
public interface CallBackAfterEdit {
public void doCallBack(PropertyAttributeException exception, ToolParameterDescriptor oldProperty, ToolParameterDescriptor newProperty, String attributeName);
}
}
| 5,898 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CustomParameterClass.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/CustomParameterClass.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.model;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterConstants;
import java.io.File;
/**
* Enum-like class holding the possible types of operator parameters
*
* @author Ramona Manda
* @author Cosmin Cara
*/
public class CustomParameterClass {
private Class<?> aClass;
private String typeMask;
/**
* Represents a template file that is supposed to be executed before the actual tool execution
*/
public static final CustomParameterClass BeforeTemplateFileClass = new CustomParameterClass(File.class, ToolAdapterConstants.TEMPLATE_BEFORE_MASK);
/**
* Represents a template file that is supposed to be executed after the actual tool execution
*/
public static final CustomParameterClass AfterTemplateFileClass = new CustomParameterClass(File.class, ToolAdapterConstants.TEMPLATE_AFTER_MASK);
/**
* Represents a the template file of the actual tool execution
*/
public static final CustomParameterClass TemplateFileClass = new CustomParameterClass(File.class, ToolAdapterConstants.TEMPLATE_PARAM_MASK);
/**
* Represents a file parameter
*/
public static final CustomParameterClass RegularFileClass = new CustomParameterClass(File.class, ToolAdapterConstants.REGULAR_PARAM_MASK);
/**
* Represents a folder parameter
*/
public static final CustomParameterClass FolderClass = new CustomParameterClass(File.class, ToolAdapterConstants.FOLDER_PARAM_MASK);
/**
* Represents a file list parameter
*/
public static final CustomParameterClass FileListClass = new CustomParameterClass(File[].class, ToolAdapterConstants.REGULAR_PARAM_MASK);
/**
* Represents a string/text parameter
*/
public static final CustomParameterClass StringClass = new CustomParameterClass(String.class, ToolAdapterConstants.REGULAR_PARAM_MASK);
/**
* Represents an integer parameter
*/
public static final CustomParameterClass IntegerClass = new CustomParameterClass(Integer.class, ToolAdapterConstants.REGULAR_PARAM_MASK);
/**
* Represents a string list parameter
*/
public static final CustomParameterClass ListClass = new CustomParameterClass(String[].class, ToolAdapterConstants.REGULAR_PARAM_MASK);
/**
* Represents a boolean parameter
*/
public static final CustomParameterClass BooleanClass = new CustomParameterClass(Boolean.class, ToolAdapterConstants.REGULAR_PARAM_MASK);
/**
* Represents a float parameter
*/
public static final CustomParameterClass FloatClass = new CustomParameterClass(Float.class, ToolAdapterConstants.REGULAR_PARAM_MASK);
private CustomParameterClass(Class<?> aClass, String typeMask) {
this.aClass = aClass;
this.typeMask = typeMask;
}
/**
* @return The Java class of the parameter
*/
public Class<?> getParameterClass() {
return aClass;
}
/**
* Checks if the parameter is a template parameter
*/
public boolean isTemplateParameter() {
return typeMask.equals(ToolAdapterConstants.TEMPLATE_PARAM_MASK);
}
/**
* Checks if the parameter is a template-before parameter
*/
public boolean isTemplateBefore() {
return typeMask.equals(ToolAdapterConstants.TEMPLATE_BEFORE_MASK);
}
/**
* Checks if the parameter is a template-after parameter
*/
public boolean isTemplateAfter() {
return typeMask.equals(ToolAdapterConstants.TEMPLATE_AFTER_MASK);
}
/**
* Checks if the parameter is a regular parameter
*/
public boolean isParameter() {
return typeMask.equals(ToolAdapterConstants.REGULAR_PARAM_MASK) || typeMask.equals(ToolAdapterConstants.FOLDER_PARAM_MASK);
}
/**
* Returns the type mask of the parameter
*/
public String getTypeMask() { return this.typeMask; }
/**
* Returns the CustomParameterClass instance matching the given type mask
*/
public static CustomParameterClass getObject(Class<?> aClass, String typeMask) {
CustomParameterClass result = matchClass(TemplateFileClass, aClass, typeMask);
if (result == null) {
result = matchClass(BeforeTemplateFileClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(AfterTemplateFileClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(RegularFileClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(FolderClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(StringClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(IntegerClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(ListClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(BooleanClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(FloatClass, aClass, typeMask);
}
if (result == null) {
result = matchClass(FileListClass, aClass, typeMask);
}
return result;
}
private static CustomParameterClass matchClass(CustomParameterClass paramClass, Class<?> aClass, String typeMask){
return (paramClass.getParameterClass().equals(aClass) && paramClass.typeMask.equals(typeMask)) ?
paramClass : null;
}
}
| 6,267 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OperatorParametersTable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/OperatorParametersTable.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.model;
import com.bc.ceres.binding.*;
import com.bc.ceres.binding.converters.ArrayConverter;
import com.bc.ceres.binding.converters.FloatConverter;
import com.bc.ceres.binding.converters.IntegerConverter;
import com.bc.ceres.swing.binding.BindingContext;
import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.bidimap.DualHashBidiMap;
import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory;
import org.esa.snap.core.gpf.descriptor.PropertyAttributeException;
import org.esa.snap.core.gpf.descriptor.TemplateParameterDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolParameterDescriptor;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterConstants;
import org.esa.snap.core.gpf.ui.OperatorParameterSupport;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AbstractDialog;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.esa.snap.ui.tooladapter.dialogs.TemplateParameterEditorDialog;
import org.esa.snap.ui.tooladapter.dialogs.ToolParameterEditorDialog;
import org.openide.util.NbBundle;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* Table holding the operator parameter descriptors
*
* @author Ramona Manda
* @author Cosmin Cara
*/
@NbBundle.Messages({
"Column_Name_Text=Name",
"Column_Description_Text=Description",
"Column_Label_Text=Label",
"Column_DataType_Text=Data type",
"Column_DefaultValue_Text=Default value",
"Type_TemplateFileClass_Text=Template Parameter",
"Type_BeforeTemplateFileClass_Text=Template Before",
"Type_AfterTemplateFileClass_Text=Template After",
"Type_RegularFileClass_Text=File",
"Type_FolderClass_Text=Folder",
"Type_FileListClass_Text=File List",
"Type_StringClass_Text=String",
"Type_IntegerClass_Text=Integer",
"Type_ListClass_Text=List",
"Type_BooleanClass_Text=Boolean",
"Type_FloatClass_Text=Decimal",
"Type_ProductList_Text=Product List"
})
public class OperatorParametersTable extends JTable {
private static final Logger logger = Logger.getLogger(OperatorParametersTable.class.getName());
private static String[] columnNames = {"", "Name", "Description", "Label", "Data type", "Default value", ""};
private static String[] columnsMembers = {"del", "name", "description", "label", "dataType", "defaultValue", "edit"};
private static int[] widths = {27, 100, 200, 80, 100, 249, 30};
private static final BidiMap typesMap = new DualHashBidiMap();
static {
typesMap.put(Bundle.Type_TemplateFileClass_Text(), CustomParameterClass.TemplateFileClass);
typesMap.put(Bundle.Type_BeforeTemplateFileClass_Text(), CustomParameterClass.BeforeTemplateFileClass);
typesMap.put(Bundle.Type_AfterTemplateFileClass_Text(), CustomParameterClass.AfterTemplateFileClass);
typesMap.put(Bundle.Type_RegularFileClass_Text(), CustomParameterClass.RegularFileClass);
typesMap.put(Bundle.Type_FolderClass_Text(), CustomParameterClass.FolderClass);
typesMap.put(Bundle.Type_FileListClass_Text(), CustomParameterClass.FileListClass);
typesMap.put(Bundle.Type_StringClass_Text(), CustomParameterClass.StringClass);
typesMap.put(Bundle.Type_IntegerClass_Text(), CustomParameterClass.IntegerClass);
typesMap.put(Bundle.Type_ListClass_Text(), CustomParameterClass.ListClass);
typesMap.put(Bundle.Type_BooleanClass_Text(), CustomParameterClass.BooleanClass);
typesMap.put(Bundle.Type_FloatClass_Text(), CustomParameterClass.FloatClass);
}
private ToolAdapterOperatorDescriptor operator = null;
private Map<ToolParameterDescriptor, PropertyMemberUIWrapper> propertiesValueUIDescriptorMap;
private MultiRenderer tableRenderer;
private BindingContext context;
private final TableCellRenderer dataTypesComboCellRenderer;
private final AppContext appContext;
private final DefaultTableCellRenderer labelTypeCellRenderer;
private JComboBox cellDefaultValueComboBox;
private JCheckBox cellDefaultValueCheckBox;
private JScrollPane cellDefaultValueList;
private FilePanel cellDefaultValueFile;
private JComboBox cellDataTypesComboBox;
private JTextField cellTextComponent;
private JComponent currentDisplayedCellComponent;
private int cellComponentColumnIndex;
private int cellComponentRowIndex;
public OperatorParametersTable(ToolAdapterOperatorDescriptor operator, AppContext appContext) {
this.operator = operator;
this.appContext = appContext;
propertiesValueUIDescriptorMap = new HashMap<>();
dataTypesComboCellRenderer = new DefaultTableCellRenderer();
labelTypeCellRenderer = new DefaultTableCellRenderer();
labelTypeCellRenderer.setText(Bundle.Type_ProductList_Text());
List<ToolParameterDescriptor> data = operator.getToolParameterDescriptors();
PropertySet propertySet = new OperatorParameterSupport(operator).getPropertySet();
//if there is an exception in the line above, can be because the default value does not match the type
//TODO determine if (and which) param has a wrong type
context = new BindingContext(propertySet);
for (ToolParameterDescriptor paramDescriptor : data) {
if (paramDescriptor.getName().equals(ToolAdapterConstants.TOOL_SOURCE_PRODUCT_ID)) {
propertiesValueUIDescriptorMap.put(paramDescriptor, PropertyMemberUIWrapperFactory.buildEmptyPropertyWrapper());
} else {
propertiesValueUIDescriptorMap.put(paramDescriptor, PropertyMemberUIWrapperFactory.buildPropertyWrapper("defaultValue", paramDescriptor, operator, context, null));
}
}
tableRenderer = new MultiRenderer();
setModel(new OperatorParametersTableNewTableModel());
setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for (int i = 0; i < widths.length; i++) {
getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
}
this.putClientProperty("JComboBox.isTableCellEditor", Boolean.FALSE);
this.setRowHeight(20);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
int clickedColumn = columnAtPoint(event.getPoint());
int clickedRow = rowAtPoint(event.getPoint());
if (clickedColumn >= 0 && clickedRow >= 0 && isTableCellEditable(clickedRow, clickedColumn)) {
mouseClickOnCell(clickedColumn, clickedRow);
}
}
});
FocusListener focusListener = new FocusAdapter() {
@Override
public void focusLost(FocusEvent focusEvent) {
hideCurrentDisplayedCellComponent(focusEvent);
}
};
createCellDefaultValueList(focusListener);
createCellDefaultValueFileChooser(focusListener);
createCellDefaultValueCheckBox(focusListener);
createCellDefaultValueComboBox(focusListener);
createCellTextComponent(focusListener);
createCellDataTypesComponent();
resetCellComponentPosition();
}
private void createCellDefaultValueFileChooser(FocusListener focusListener) {
this.cellDefaultValueFile = new FilePanel();
this.cellDefaultValueFile.setBackground(Color.white);
this.cellDefaultValueFile.setOpaque(true);
this.cellDefaultValueFile.setVisible(false);
this.cellDefaultValueFile.addTextComponentFocusListener(focusListener);
this.cellDefaultValueFile.addBrowseButtonActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
ToolParameterDescriptor descriptor = operator.getToolParameterDescriptors().get(cellComponentRowIndex);
String parameterType = descriptor.getParameterType();
int selectionMode = JFileChooser.FILES_ONLY;
FileFilter filter = null;
switch (parameterType) {
case ToolAdapterConstants.FOLDER_PARAM_MASK:
selectionMode = JFileChooser.DIRECTORIES_ONLY;
break;
case ToolAdapterConstants.TEMPLATE_BEFORE_MASK:
case ToolAdapterConstants.TEMPLATE_AFTER_MASK:
filter = new FileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory() || file.getName().toLowerCase().endsWith(".vm");
}
@Override
public String getDescription() {
return "*.vm files";
}
};
break;
case ToolAdapterConstants.TEMPLATE_PARAM_MASK:
filter = new FileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory() ||
file.getName().toLowerCase().endsWith(".vm") ||
file.getName().toLowerCase().endsWith(".xml");
}
@Override
public String getDescription() {
return "*.vm files; *.xml files";
}
};
break;
}
File selectedFile = cellDefaultValueFile.showFileChooserDialog(selectionMode, filter);
if (selectedFile != null) {
descriptor.setDefaultValue(selectedFile.getAbsolutePath());
fireTableRowsChanged();
}
}
});
}
private void createCellDefaultValueList(FocusListener focusListener) {
JList list = new JList();
list.addFocusListener(focusListener);
this.cellDefaultValueList = new JScrollPane(list);
this.cellDefaultValueList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
this.cellDefaultValueList.setBorder(new EmptyBorder(0, 0, 0, 0));
this.cellDefaultValueList.setOpaque(true);
this.cellDefaultValueList.setVisible(false);
this.cellDefaultValueList.setBackground(Color.white);
this.cellDefaultValueList.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent event) {
cellDefaultValueList.getViewport().getView().requestFocusInWindow();
}
});
}
private void createCellDefaultValueCheckBox(FocusListener focusListener) {
this.cellDefaultValueCheckBox = new JCheckBox();
this.cellDefaultValueCheckBox.setBackground(Color.white);
this.cellDefaultValueCheckBox.setOpaque(true);
this.cellDefaultValueCheckBox.setVisible(false);
this.cellDefaultValueCheckBox.addFocusListener(focusListener);
}
private void createCellDefaultValueComboBox(FocusListener focusListener) {
this.cellDefaultValueComboBox = new JComboBox();
this.cellDefaultValueComboBox.setOpaque(true);
this.cellDefaultValueComboBox.setVisible(false);
this.cellDefaultValueComboBox.setBorder(new EmptyBorder(0, 0, 0, 0));
this.cellDefaultValueComboBox.addFocusListener(focusListener);
}
private void createCellDataTypesComponent() {
this.cellDataTypesComboBox = new JComboBox(typesMap.keySet().toArray());
this.cellDataTypesComboBox.setOpaque(true);
this.cellDataTypesComboBox.setVisible(false);
this.cellDataTypesComboBox.setBorder(new EmptyBorder(0, 0, 0, 0));
this.cellDataTypesComboBox.addActionListener(ev -> {
String typeName = (String) cellDataTypesComboBox.getSelectedItem();
cellDataTypeChanged(typeName, this.cellComponentRowIndex, this.cellComponentColumnIndex);
});
this.cellDataTypesComboBox.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent focusEvent) {
hideCurrentDisplayedCellComponent();
}
});
}
private void createCellTextComponent(FocusListener focusListener) {
this.cellTextComponent = new JTextField();
this.cellTextComponent.setOpaque(true);
this.cellTextComponent.setVisible(false);
this.cellTextComponent.setBorder(new EmptyBorder(0, 0, 0, 0));
this.cellTextComponent.addFocusListener(focusListener);
}
private void mouseClickOnCell(int clickedColumn, int clickedRow) {
if (clickedColumn == 0) {
if (canRemoveRow(clickedRow)) {
removeRow(clickedRow);
}
}
else if (clickedColumn == 6) {
showToolParameterEditorDialog(clickedRow);
} else if (clickedColumn == 4) {
showCellDataTypeComboBoxEditor(clickedColumn, clickedRow);
} else if (clickedColumn == 5) {
showCellDefaultValueComponent(clickedColumn, clickedRow);
} else if (clickedColumn == 1 || clickedColumn == 2 || clickedColumn == 3) {
showCellTextComponentEditor(clickedColumn, clickedRow);
}
}
private void showCellDefaultValueComponent(int clickedColumn, int clickedRow) {
ToolParameterDescriptor descriptor = this.operator.getToolParameterDescriptors().get(clickedRow);
String defaultValue = descriptor.getDefaultValue();
if (descriptor.getDataType() == String.class || descriptor.getDataType() == Integer.class || descriptor.getDataType() == Float.class) {
String[] valueSet = descriptor.getValueSet();
if (valueSet != null && valueSet.length > 0) {
DefaultComboBoxModel model = new DefaultComboBoxModel();
Object itemToSelect = null;
for (int i=0; i<valueSet.length; i++) {
model.addElement(valueSet[i]);
if (defaultValue != null && defaultValue.equals(valueSet[i])) {
itemToSelect = valueSet[i];
}
}
model.setSelectedItem(itemToSelect);
this.cellDefaultValueComboBox.setModel(model);
setCurrentCellComponentEditor(clickedColumn, clickedRow, this.cellDefaultValueComboBox);
} else {
this.cellTextComponent.setText(defaultValue);
setCurrentCellComponentEditor(clickedColumn, clickedRow, this.cellTextComponent);
}
} else if (descriptor.getDataType() == Boolean.class) {
this.cellDefaultValueCheckBox.setSelected(Boolean.parseBoolean(defaultValue));
setCurrentCellComponentEditor(clickedColumn, clickedRow, this.cellDefaultValueCheckBox);
} else if (descriptor.getDataType() == File.class) {
this.cellDefaultValueFile.setText(defaultValue);
setCurrentCellComponentEditor(clickedColumn, clickedRow, this.cellDefaultValueFile);
} else if (descriptor.getDataType() == String[].class) {
showCellDefaultValueList(clickedColumn, clickedRow);
}
}
private void showCellDefaultValueList(int clickedColumn, int clickedRow) {
ToolParameterDescriptor descriptor = this.operator.getToolParameterDescriptors().get(clickedRow);
String defaultValue = descriptor.getDefaultValue();
String[] valueSet = descriptor.getValueSet();
JList list = (JList)this.cellDefaultValueList.getViewport().getView();
DefaultListModel model = new DefaultListModel();
java.util.List<Integer> selectedIndices = new ArrayList<Integer>();
if (valueSet != null && valueSet.length > 0) {
for (int i=0; i<valueSet.length; i++) {
model.addElement(valueSet[i]);
}
String[] itemsToSelect = null;
if (!StringUtils.isNullOrEmpty(defaultValue)) {
itemsToSelect = defaultValue.split(ArrayConverter.SEPARATOR);
}
if (itemsToSelect != null && itemsToSelect.length > 0) {
for (int i=0; i<model.getSize(); i++) {
Object item = model.getElementAt(i);
for (int k=0; k<itemsToSelect.length; k++) {
if (item.equals(itemsToSelect[k])) {
selectedIndices.add(i);
break;
}
}
}
}
}
list.setModel(model);
int[] indices = new int[selectedIndices.size()];
for (int i=0; i<selectedIndices.size(); i++) {
indices[i] = selectedIndices.get(i).intValue();
}
list.setSelectedIndices(indices);
setCurrentCellComponentEditor(clickedColumn, clickedRow, this.cellDefaultValueList);
}
@Override
public void doLayout() {
super.doLayout();
if (hasValidCellComponent()) {
Rectangle tableCellBounds = getCellRect(this.cellComponentRowIndex, this.cellComponentColumnIndex, false);
this.currentDisplayedCellComponent.setBounds(tableCellBounds.x, tableCellBounds.y, tableCellBounds.width, tableCellBounds.height);
}
}
private boolean hasValidCellComponent() {
return (this.currentDisplayedCellComponent != null) && (this.cellComponentColumnIndex >= 0) && (this.cellComponentRowIndex >= 0);
}
private final void showCellDataTypeComboBoxEditor(int columnIndex, int rowIndex) {
Object cellValue = getValueAt(rowIndex, columnIndex);
String cellValueAsString = (cellValue == null) ? "" : cellValue.toString();
ActionListener[] listeners = this.cellDataTypesComboBox.getActionListeners();
for (int i=0; i<listeners.length; i++) {
this.cellDataTypesComboBox.removeActionListener(listeners[i]);
}
this.cellDataTypesComboBox.setSelectedItem(cellValueAsString);
for (int i=0; i<listeners.length; i++) {
this.cellDataTypesComboBox.addActionListener(listeners[i]);
}
setCurrentCellComponentEditor(columnIndex, rowIndex, this.cellDataTypesComboBox);
}
private void showCellTextComponentEditor(int columnIndex, int rowIndex) {
Object cellValue = getValueAt(rowIndex, columnIndex);
String cellValueAsString = (cellValue == null) ? "" : cellValue.toString();
this.cellTextComponent.setText(cellValueAsString);
setCurrentCellComponentEditor(columnIndex, rowIndex, this.cellTextComponent);
}
private final void setCurrentCellComponentEditor(int columnIndex, int rowIndex, JComponent cellComponent) {
if (this.currentDisplayedCellComponent != null && cellComponent != this.currentDisplayedCellComponent) {
this.currentDisplayedCellComponent.setVisible(false);
remove(this.currentDisplayedCellComponent);
fireTableRowsChanged();
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
currentDisplayedCellComponent = cellComponent;
cellComponentColumnIndex = columnIndex;
cellComponentRowIndex = rowIndex;
add(currentDisplayedCellComponent);
Rectangle tableCellBounds = getCellRect(cellComponentRowIndex, cellComponentColumnIndex, false);
currentDisplayedCellComponent.setBounds(tableCellBounds.x, tableCellBounds.y, tableCellBounds.width, tableCellBounds.height);
currentDisplayedCellComponent.setVisible(true);
currentDisplayedCellComponent.requestFocusInWindow();
}
});
}
private void hideCurrentDisplayedCellComponent(FocusEvent focusEvent) {
if (hasValidCellComponent()) {
ToolParameterDescriptor descriptor = operator.getToolParameterDescriptors().get(this.cellComponentRowIndex);
if (this.currentDisplayedCellComponent instanceof JTextField) {
String cellText = ((JTextField)this.currentDisplayedCellComponent).getText();
if (this.cellComponentColumnIndex == 1) {
setParameterNameAt(cellText, this.cellComponentRowIndex, this.cellComponentColumnIndex);
} else if (this.cellComponentColumnIndex == 2) {
descriptor.setDescription(cellText);
} else if (this.cellComponentColumnIndex == 3) {
descriptor.setLabel(cellText);
} else if (this.cellComponentColumnIndex == 5) {
descriptor.setDefaultValue(cellText);
}
} else if (this.currentDisplayedCellComponent instanceof JCheckBox) {
boolean isSelected = ((JCheckBox)this.currentDisplayedCellComponent).isSelected();
if (this.cellComponentColumnIndex == 5) {
descriptor.setDefaultValue(Boolean.toString(isSelected));
}
} else if (this.currentDisplayedCellComponent instanceof JComboBox) {
if (this.cellComponentColumnIndex == 5) {
String selectedItem = (String) ((JComboBox)this.currentDisplayedCellComponent).getSelectedItem();
descriptor.setDefaultValue(selectedItem);
}
} else if (this.currentDisplayedCellComponent instanceof FilePanel) {
if (this.cellComponentColumnIndex == 5) {
String filePath = ((FilePanel)this.currentDisplayedCellComponent).getText();
descriptor.setDefaultValue(filePath);
}
} else if ((this.currentDisplayedCellComponent instanceof JList) || (this.currentDisplayedCellComponent instanceof JScrollPane)) {
if (this.cellComponentColumnIndex == 5) {
JList list = null;
if (this.currentDisplayedCellComponent instanceof JList) {
list = (JList)this.currentDisplayedCellComponent;
} else {
JScrollPane scrollPane = (JScrollPane)this.currentDisplayedCellComponent;
list = (JList)scrollPane.getViewport().getView();
}
int[] indices = list.getSelectedIndices();
String defaultValue = "";
for (int i=0; i<indices.length; i++) {
if (i > 0) {
defaultValue += ",";
}
defaultValue += (String)list.getModel().getElementAt(indices[i]);
}
descriptor.setDefaultValue(defaultValue);
}
}
hideCurrentDisplayedCellComponent();
}
}
private void hideCurrentDisplayedCellComponent() {
remove(this.currentDisplayedCellComponent);
this.currentDisplayedCellComponent.setVisible(false);
resetCellComponentPosition();
requestFocusInWindow();
this.currentDisplayedCellComponent = null;
fireTableRowsChanged();
}
private void resetCellComponentPosition() {
this.cellComponentColumnIndex = -1;
this.cellComponentRowIndex = -1;
}
public void stopVariablesTableEditing() {
if (getEditingRow() >= 0 && getEditingColumn() >= 0) {
getCellEditor(getEditingRow(), getEditingColumn()).stopCellEditing();
}
}
private void removeRow(int rowIndex) {
ToolParameterDescriptor descriptor = operator.getToolParameterDescriptors().get(rowIndex);
operator.removeParamDescriptor(descriptor);
fireTableRowsChanged();
}
private boolean canRemoveRow(int rowIndex) {
ToolParameterDescriptor descriptor = operator.getToolParameterDescriptors().get(rowIndex);
String descriptorName = descriptor.getName();
return !ToolAdapterConstants.TOOL_SOURCE_PRODUCT_ID.equals(descriptorName) &&
!ToolAdapterConstants.TOOL_SOURCE_PRODUCT_FILE.equals(descriptorName) &&
!ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE.equals(descriptorName);
}
private boolean isTableCellEditable(int rowIndex, int columnIndex) {
ToolParameterDescriptor descriptor = operator.getToolParameterDescriptors().get(rowIndex);
String descriptorName = descriptor.getName();
if (ToolAdapterConstants.TOOL_SOURCE_PRODUCT_ID.equals(descriptorName) || ToolAdapterConstants.TOOL_SOURCE_PRODUCT_FILE.equals(descriptorName)) {
return false;
}
if (ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE.equals(descriptorName) && (columnIndex == 0 || columnIndex == 1 || columnIndex == 4 || columnIndex == 6)) {
return false;
}
return true;
}
public void addParameterToTable() {
String defaultParameterName = null;
int count = this.operator.getToolParameterDescriptors().size();
boolean canContinue = true;
int index = 0;
while (canContinue) {
index++;
canContinue = false;
defaultParameterName = "parameterName" + Integer.toString(index);
for (int i=0; i<count && !canContinue; i++) {
ToolParameterDescriptor param = this.operator.getToolParameterDescriptors().get(i);
if (param.getName().equals(defaultParameterName)) {
canContinue = true;
}
}
}
TemplateParameterDescriptor newParameter = new TemplateParameterDescriptor(defaultParameterName, String.class);
newParameter.setParameterType(ToolAdapterConstants.REGULAR_PARAM_MASK);
int rowIndex = 0;
addParameterToTable(newParameter, rowIndex);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//int rowIndex = operator.getToolParameterDescriptors().size() - 1;
showCellTextComponentEditor(1, rowIndex);
}
});
}
public void addParameterToTable(ToolParameterDescriptor param, int index) {
try {
operator.getToolParameterDescriptors().add(index, param);
PropertyDescriptor propertyDescriptor = ParameterDescriptorFactory.convert(param, new ParameterDescriptorFactory().getSourceProductMap());
propertyDescriptor.setDefaultValue(param.getDefaultValue());
DefaultPropertySetDescriptor propertySetDescriptor = new DefaultPropertySetDescriptor();
propertySetDescriptor.addPropertyDescriptor(propertyDescriptor);
PropertyContainer container = PropertyContainer.createMapBacked(new HashMap<>(), propertySetDescriptor);
context.getPropertySet().addProperties(container.getProperties());
createDefaultComponent(param, propertyDescriptor);
fireTableRowsChanged();
} catch (Exception ex){
logger.warning(ex.getMessage());
}
}
private void rebuildEditorCell(ToolParameterDescriptor descriptor, Map<String, Object> attributes) {
PropertySet propertySet = context.getPropertySet();
Property actualProperty = propertySet.getProperty(descriptor.getName());
propertySet.removeProperty(actualProperty);
PropertyDescriptor propertyDescriptor = null;
try {
propertyDescriptor = ParameterDescriptorFactory.convert(descriptor, new ParameterDescriptorFactory().getSourceProductMap());
} catch (ConversionException ex) {
logger.warning(ex.getMessage());
}
propertyDescriptor.setDefaultValue(descriptor.getDefaultValue());
if (attributes != null && attributes.size() > 0) {
for (Map.Entry<String, Object> entry : attributes.entrySet()) {
propertyDescriptor.setAttribute(entry.getKey(), entry.getValue());
}
}
DefaultPropertySetDescriptor propertySetDescriptor = new DefaultPropertySetDescriptor();
propertySetDescriptor.addPropertyDescriptor(propertyDescriptor);
PropertyContainer container = PropertyContainer.createMapBacked(new HashMap<>(), propertySetDescriptor);
Object defaultValue = null;
if (descriptor.getDefaultValue() != null) {
defaultValue = descriptor.getDefaultTypedValue();
}
try {
container.getProperty(propertyDescriptor.getName()).setValue(defaultValue);
} catch (ValidationException ex) {
logger.warning(ex.getMessage());
}
propertySet.addProperties(container.getProperties());
createDefaultComponent(descriptor, propertyDescriptor);
fireTableRowsChanged();
}
private void createDefaultComponent(ToolParameterDescriptor descriptor, PropertyDescriptor propertyDescriptor) {
if (descriptor.getDataType() == String.class || descriptor.getDataType() == Integer.class || descriptor.getDataType() == Float.class) {
} else if (descriptor.getDataType() == Boolean.class) {
} else if (descriptor.getDataType() == String[].class) {
} else if (descriptor.getDataType() == File.class) {
} else {
this.propertiesValueUIDescriptorMap.put(descriptor, PropertyMemberUIWrapperFactory.buildPropertyWrapper("defaultValue", descriptor, operator, context, null));
}
}
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component component = super.prepareRenderer(renderer, row, column);
ToolParameterDescriptor descriptor = operator.getToolParameterDescriptors().get(row);
switch (descriptor.getName()) {
case ToolAdapterConstants.TOOL_SOURCE_PRODUCT_ID:
case ToolAdapterConstants.TOOL_SOURCE_PRODUCT_FILE:
case ToolAdapterConstants.TOOL_TARGET_PRODUCT_ID:
case ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE:
component.setBackground(Color.lightGray);
break;
default:
component.setBackground(SystemColor.text);
component.setForeground(SystemColor.textText);
break;
}
return component;
}
@Override
public TableCellRenderer getCellRenderer(int row, int column) {
switch (column){
case 0:
case 5:
case 6:
return tableRenderer;
case 4:
ToolParameterDescriptor descriptor = operator.getToolParameterDescriptors().get(row);
if (descriptor.getName().equals(ToolAdapterConstants.TOOL_SOURCE_PRODUCT_ID)) {
return labelTypeCellRenderer;
} else {
return dataTypesComboCellRenderer;
}
default:
return super.getCellRenderer(row, column);
}
}
public BindingContext getBindingContext(){
return context;
}
public void showToolParameterEditorDialog(int rowIndex) {
ToolParameterDescriptor descriptor = operator.getToolParameterDescriptors().get(rowIndex);
if (!descriptor.isParameter() && descriptor.getDataType().equals(File.class)) {
try {
TemplateParameterEditorDialog editor = new TemplateParameterEditorDialog(appContext,(TemplateParameterDescriptor) descriptor, operator);
int returnCode = editor.show();
if (returnCode == AbstractDialog.ID_OK) {
rebuildEditorCell(descriptor, null);
}
}catch (Exception ex){
ex.printStackTrace();
Dialogs.showError(ex.getMessage());
}
} else {
ToolParameterEditorDialog editor = new ToolParameterEditorDialog(appContext, this.operator, descriptor);
int returnCode = editor.show();
if (returnCode == AbstractDialog.ID_OK) {
rebuildEditorCell(descriptor, null);
}
}
}
private void fireTableRowsChanged() {
((AbstractTableModel)getModel()).fireTableDataChanged();
}
public static boolean checkUniqueParameterName(ToolAdapterOperatorDescriptor operator, String parameterName, ToolParameterDescriptor descriptorToEdit) {
int count = operator.getToolParameterDescriptors().size();
for (int i=0; i<count; i++) {
ToolParameterDescriptor param = operator.getToolParameterDescriptors().get(i);
if (descriptorToEdit != param) {
if (param.getName().equals(parameterName)) {
Dialogs.showInformation("Duplicate parameter name.");
return false;
}
}
}
return true;
}
private void setParameterNameAt(String parameterName, int rowIndex, int columnIndex) {
ToolParameterDescriptor descriptor = this.operator.getToolParameterDescriptors().get(rowIndex);
if (!checkUniqueParameterName(this.operator, parameterName, descriptor)) {
return;
}
String oldName = descriptor.getName();
PropertySet propertySet = this.context.getPropertySet();
Property oldProperty = propertySet.getProperty(oldName);
Object defaultValue = (oldProperty == null) ? null : oldProperty.getValue();
descriptor.setName(parameterName);
//since the name is changed, the context must be changed also
propertySet.removeProperty(oldProperty);
try {
PropertyDescriptor propertyDescriptor = ParameterDescriptorFactory.convert(descriptor, new ParameterDescriptorFactory().getSourceProductMap());
if (defaultValue != null) {
String defaultValueAsString = ToolParameterEditorDialog.processDefaultValue(defaultValue);
descriptor.setDefaultValue(defaultValueAsString);
propertyDescriptor.setDefaultValue(defaultValue);
}
if (descriptor.getParameterType().equals(ToolAdapterConstants.FOLDER_PARAM_MASK)) {
propertyDescriptor.setAttribute("directory", true);
}
DefaultPropertySetDescriptor propertySetDescriptor = new DefaultPropertySetDescriptor();
propertySetDescriptor.addPropertyDescriptor(propertyDescriptor);
PropertyContainer container = PropertyContainer.createMapBacked(new HashMap<>(), propertySetDescriptor);
try {
container.setDefaultValues();
}catch (IllegalStateException ex){
logger.warning(ex.getMessage());
}
propertySet.addProperties(container.getProperties());
createDefaultComponent(descriptor, propertyDescriptor);
fireTableRowsChanged();
} catch (ConversionException e) {
logger.warning(e.getMessage());
Dialogs.showError(e.getMessage());
}
}
private void cellDataTypeChanged(Object aValue, int rowIndex, int columnIndex) {
ToolParameterDescriptor descriptor = operator.getToolParameterDescriptors().get(rowIndex);
if (descriptor.isTemplateParameter() &&
ToolAdapterConstants.TEMPLATE_PARAM_MASK.equals(descriptor.getParameterType()) &&
(((TemplateParameterDescriptor)descriptor).getTemplate() != null ||
((TemplateParameterDescriptor)descriptor).getParameterDescriptors().stream().findFirst().isPresent())) {
return;
}
CustomParameterClass customClass = (CustomParameterClass)typesMap.get(aValue);
if (customClass == null) {
customClass = CustomParameterClass.StringClass;
}
Map<String, Object> extra = null;
if (customClass.equals(CustomParameterClass.FolderClass)) {
extra = new HashMap<>();
extra.put("directory", Boolean.TRUE);
}
descriptor.setParameterType(customClass.getTypeMask());
if (descriptor.getDataType() != customClass.getParameterClass()) {
descriptor.setDataType(customClass.getParameterClass());
boolean canResetDefaultValue = true;
if (customClass.getParameterClass() == String.class || customClass.getParameterClass() == String[].class) {
canResetDefaultValue = false;
} else if (customClass.getParameterClass() == Integer.class) {
if (!StringUtils.isNullOrEmpty(descriptor.getDefaultValue())) {
IntegerConverter integerConverter = new IntegerConverter();
try {
Number number = integerConverter.parse(descriptor.getDefaultValue());
if (number != null) {
descriptor.setDefaultValue(number.toString());
canResetDefaultValue = false;
}
} catch (ConversionException e) {
// ignore exception and reset the default value
}
}
} else if (customClass.getParameterClass() == Float.class) {
if (!StringUtils.isNullOrEmpty(descriptor.getDefaultValue())) {
FloatConverter integerConverter = new FloatConverter();
try {
Number number = integerConverter.parse(descriptor.getDefaultValue());
if (number != null) {
descriptor.setDefaultValue(number.toString());
canResetDefaultValue = false;
}
} catch (ConversionException e) {
// ignore exception and reset the default value
}
}
}
if (canResetDefaultValue) {
descriptor.setDefaultValue(null); // reset the default value
}
descriptor.setValueSet(null); // reset the value set
rebuildEditorCell(descriptor, extra);
}
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
private class OperatorParametersTableNewTableModel extends AbstractTableModel {
private OperatorParametersTableNewTableModel() {
super();
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return operator.getToolParameterDescriptors().size();
}
@Override
public Object getValueAt(int row, int column) {
ToolParameterDescriptor descriptor = operator.getToolParameterDescriptors().get(row);
switch (column) {
case 0:
return false;
case 4:
String cellValue = null;
switch (descriptor.getName()) {
case ToolAdapterConstants.TOOL_SOURCE_PRODUCT_ID:
cellValue = Bundle.Type_ProductList_Text();
break;
case ToolAdapterConstants.TOOL_SOURCE_PRODUCT_FILE:
cellValue = Bundle.Type_FileListClass_Text();
break;
case ToolAdapterConstants.TOOL_TARGET_PRODUCT_FILE:
cellValue = Bundle.Type_RegularFileClass_Text();
break;
default:
if (CustomParameterClass.FolderClass.equals(CustomParameterClass.getObject(descriptor.getDataType(), descriptor.getParameterType()))) {
cellValue = Bundle.Type_FolderClass_Text();
} else {
CustomParameterClass item = CustomParameterClass.getObject(descriptor.getDataType(), descriptor.getParameterType());
cellValue = (String) typesMap.getKey(item);
}
break;
}
return cellValue;
case 5:
return descriptor.getDefaultValue();
case 6:
return false;
default:
try {
return descriptor.getAttribute(columnsMembers[column]);
} catch (PropertyAttributeException e) {
logger.warning(e.getMessage());
return String.format("Error: %s", e.getMessage());
}
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
}
private class MultiRenderer extends AbstractCellEditor implements TableCellRenderer {
private TableCellRenderer defaultRenderer;
private AbstractButton deleteButton;
private AbstractButton editButton;
private JCheckBox checkBoxRenderer;
private JTextField textComponentRenderer;
public MultiRenderer() {
checkBoxRenderer = new JCheckBox();
textComponentRenderer = new JTextField();
textComponentRenderer.setBorder(new EmptyBorder(0, 0, 0, 0));
defaultRenderer = new DefaultTableCellRenderer();
deleteButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("/org/esa/snap/resources/images/icons/DeleteShapeTool16.gif"), false);
editButton = new JButton("...");
deleteButton.addActionListener(e -> fireEditingStopped());
editButton.addActionListener(e -> fireEditingStopped());
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
ToolParameterDescriptor descriptor = operator.getToolParameterDescriptors().get(row);
switch (column) {
case 0:
return deleteButton;
case 5:
String defaultValue = descriptor.getDefaultValue();
if (descriptor.getDataType() == Boolean.class) {
this.checkBoxRenderer.setSelected(Boolean.parseBoolean(defaultValue));
return this.checkBoxRenderer;
} else if (descriptor.getDataType() == String.class || descriptor.getDataType() == Integer.class || descriptor.getDataType() == Float.class) {
this.textComponentRenderer.setText(defaultValue);
return this.textComponentRenderer;
} else if (descriptor.getDataType() == String[].class) {
this.textComponentRenderer.setText(defaultValue);
return this.textComponentRenderer;
} else if (descriptor.getDataType() == File.class) {
this.textComponentRenderer.setText(defaultValue);
return this.textComponentRenderer;
}
try {
return propertiesValueUIDescriptorMap.get(descriptor).getUIComponent();
} catch (Exception e) {
logger.warning(e.getMessage());
return null;
}
case 6:
return editButton;
default:
return defaultRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
}
@Override
public Object getCellEditorValue() {
return null;
}
}
}
| 45,590 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FolderEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/FolderEditor.java | package org.esa.snap.ui.tooladapter.model;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.swing.binding.Binding;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.ComponentAdapter;
import com.bc.ceres.swing.binding.PropertyEditor;
import com.bc.ceres.swing.binding.internal.TextComponentAdapter;
import javax.swing.*;
import java.awt.*;
import java.io.File;
/**
* Folder picker editor.
*
* @author Cosmin Cara
*/
public class FolderEditor extends PropertyEditor {
@Override
public boolean isValidFor(PropertyDescriptor propertyDescriptor) {
return File.class.isAssignableFrom(propertyDescriptor.getType())
&& Boolean.TRUE.equals(propertyDescriptor.getAttribute("directory"));
}
@Override
public JComponent createEditorComponent(PropertyDescriptor propertyDescriptor, BindingContext bindingContext) {
final JTextField textField = new JTextField();
final ComponentAdapter adapter = new TextComponentAdapter(textField);
final Binding binding = bindingContext.bind(propertyDescriptor.getName(), adapter);
final JPanel editorPanel = new JPanel(new BorderLayout(2, 2));
editorPanel.add(textField, BorderLayout.CENTER);
final JButton etcButton = new JButton("...");
final Dimension size = new Dimension(26, 16);
etcButton.setPreferredSize(size);
etcButton.setMinimumSize(size);
etcButton.addActionListener(e -> {
final JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File currentFolder = (File) binding.getPropertyValue();
if (currentFolder != null) {
fileChooser.setSelectedFile(currentFolder);
} else {
File selectedFolder = null;
Object value = propertyDescriptor.getDefaultValue();
if (value instanceof File) {
selectedFolder = (File) propertyDescriptor.getDefaultValue();
} else if (value != null) {
selectedFolder = new File(value.toString());
}
fileChooser.setSelectedFile(selectedFolder);
}
int i = fileChooser.showDialog(editorPanel, "Select");
if (i == JFileChooser.APPROVE_OPTION && fileChooser.getSelectedFile() != null) {
binding.setPropertyValue(fileChooser.getSelectedFile());
}
});
editorPanel.add(etcButton, BorderLayout.EAST);
return editorPanel;
}
}
| 2,619 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AutoCompleteTextArea.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/AutoCompleteTextArea.java | package org.esa.snap.ui.tooladapter.model;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Extension of JTextArea that allows autocompletion of entries, based on
* operator's system variables and parameters.
*
* @author Cosmin Cara
*/
public class AutoCompleteTextArea extends JTextArea {
private InputOptionsPanel suggestion;
private List<String> autoCompleteEntries;
private char triggerChar;
public AutoCompleteTextArea(String text, int rows, int columns) {
super(text, rows, columns);
addKeyListener(new KeyListener() {
private boolean triggerCharPressed;
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER ||
e.getKeyChar() == KeyEvent.VK_TAB ||
e.getKeyChar() == KeyEvent.VK_SPACE) {
if (suggestion != null && (triggerCharPressed || suggestion.isVisible())) {
if (suggestion.insertSelection()) {
//e.consume();
final int position = getCaretPosition();
SwingUtilities.invokeLater(() -> {
try {
getDocument().remove(position - 1, 1);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
});
}
}
triggerCharPressed = false;
}
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN && suggestion != null && triggerCharPressed) {
suggestion.moveDown();
} else if (e.getKeyCode() == KeyEvent.VK_UP && suggestion != null && triggerCharPressed) {
suggestion.moveUp();
} else if (e.getKeyChar() == triggerChar) {
triggerCharPressed = true;
SwingUtilities.invokeLater(AutoCompleteTextArea.this::showSuggestion);
} else if (Character.isLetterOrDigit(e.getKeyChar()) && triggerCharPressed || e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
SwingUtilities.invokeLater(AutoCompleteTextArea.this::showSuggestion);
} else if (Character.isWhitespace(e.getKeyChar()) || e.getKeyCode() == KeyEvent.VK_ESCAPE) {
triggerCharPressed = false;
hideSuggestion();
}
}
@Override
public void keyPressed(KeyEvent e) {
}
});
}
/**
* Sets the character that will trigger autocompletion
*/
public void setTriggerChar(char trigger) {
triggerChar = trigger;
}
/**
* Sets the list of autocompletion entries (suggestions)
*/
public void setAutoCompleteEntries(List<String> entries) {
autoCompleteEntries = entries;
}
protected void showSuggestion() {
hideSuggestion();
final int position = getCaretPosition();
Point location;
try {
location = modelToView(position).getLocation();
} catch (BadLocationException e) {
return;
}
String text = getText();
int start = Math.max(0, text.lastIndexOf(triggerChar, position));
if (start + 1 > position) {
return;
}
final String subWord = text.substring(start + 1, position);
if (suggestion == null) {
suggestion = new InputOptionsPanel(this);
}
List<String> filtered = autoCompleteEntries != null ? autoCompleteEntries.stream().filter(e -> e.startsWith(subWord)).collect(Collectors.toList()) :
(autoCompleteEntries = new ArrayList<>());
if (filtered.isEmpty()) {
hideSuggestion();
} else {
suggestion.setSuggestionList(subWord.isEmpty() ? autoCompleteEntries : filtered, subWord);
suggestion.show(position, location);
SwingUtilities.invokeLater(this::requestFocusInWindow);
}
}
protected void hideSuggestion() {
if (suggestion != null) {
suggestion.hide();
}
}
/**
* This will visually hold the current suggestions (if any).
*/
class InputOptionsPanel {
private JList<String> list;
private JPopupMenu popupMenu;
private String subWord;
private int insertionPosition;
private final JTextArea textArea;
public InputOptionsPanel(JTextArea parent) {
popupMenu = new JPopupMenu();
popupMenu.setOpaque(false);
popupMenu.setBorder(null);
textArea = parent;
}
public void hide() {
popupMenu.setVisible(false);
}
public void show(int position, Point location) {
this.insertionPosition = position;
popupMenu.show(textArea, location.x, textArea.getBaseline(0, 0) + location.y);
}
public boolean isVisible() { return popupMenu.isVisible(); }
public void setSuggestionList(List<String> entries, String subWord) {
popupMenu.removeAll();
this.subWord = subWord;
createSuggestionList(entries);
popupMenu.add(list, BorderLayout.CENTER);
}
public boolean insertSelection() {
if (list.getSelectedValue() != null) {
String text = textArea.getText();
try {
final String selectedSuggestion = list.getSelectedValue();
Document document = textArea.getDocument();
int insertIndex = text.lastIndexOf(subWord, insertionPosition);
document.remove(insertIndex, subWord.length());
document.insertString(insertIndex, selectedSuggestion, null);
return true;
} catch (BadLocationException ignored) {
textArea.setText(text);
}
hide();
}
return false;
}
public void moveUp() {
int index = Math.max(list.getSelectedIndex() - 1, 0);
selectIndex(index);
}
public void moveDown() {
int index = Math.min(list.getSelectedIndex() + 1, list.getModel().getSize() - 1);
selectIndex(index);
}
private void createSuggestionList(List<String> entries) {
if (list == null) {
list = new JList<>(entries.toArray(new String[entries.size()]));
list.setDoubleBuffered(true);
list.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 0));
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
insertSelection();
}
}
});
} else {
list.removeAll();
list.setListData(entries.toArray(new String[entries.size()]));
}
list.setSelectedIndex(0);
}
private void selectIndex(int index) {
final int position = textArea.getCaretPosition();
list.setSelectedIndex(index);
SwingUtilities.invokeLater(() -> textArea.setCaretPosition(position));
}
}
}
| 8,043 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OperatorsTableModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/OperatorsTableModel.java | package org.esa.snap.ui.tooladapter.model;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.tango.TangoIcons;
import javax.swing.ImageIcon;
import javax.swing.table.AbstractTableModel;
import java.util.List;
import java.util.logging.Logger;
/**
* @author Ramona Manda
*/
public class OperatorsTableModel extends AbstractTableModel {
private static ImageIcon STATUS_OK;
private static ImageIcon STATUS_NOK;
private String[] columnNames = {"Status", "Alias", "Description"};
//private boolean[] toolsChecked = null;
private List<ToolAdapterOperatorDescriptor> data = null;
static {
try {
STATUS_OK = new ImageIcon(OperatorsTableModel.class.getResource("/org/esa/snap/ui/tooladapter/dialogs/check_ok.png"));
} catch (Exception e) {
Logger.getLogger(OperatorsTableModel.class.getName()).warning("Image resource not loaded");
}
STATUS_NOK = TangoIcons.emblems_emblem_important(TangoIcons.Res.R16);
}
public OperatorsTableModel(List<ToolAdapterOperatorDescriptor> operators) {
this.data = operators;
//this.toolsChecked = new boolean[this.data.size()];
}
@Override
public int getRowCount() {
return data.size();
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
org.esa.snap.core.gpf.descriptor.dependency.Bundle bundle = data.get(rowIndex).getBundle();
return (bundle != null && bundle.isInstalled()) ? STATUS_OK : STATUS_NOK;
case 1:
//return toolsChecked[rowIndex];
return data.get(rowIndex).getAlias();
case 2:
//return data.get(rowIndex).getAlias();
return data.get(rowIndex).getDescription();
/*case 2:
return data.get(rowIndex).getDescription();*/
}
return "";
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Class getColumnClass(int c) {
if (c == 0) {
return ImageIcon.class;
} else {
return String.class;
}
}
@Override
public boolean isCellEditable(int row, int col) {
/*if (col == 0) {
return true;
} else {*/
return false;
// }
}
@Override
public void setValueAt(Object value, int row, int col) {
//this.toolsChecked[row] = (boolean) value;
}
/*public ToolAdapterOperatorDescriptor getFirstCheckedOperator() {
for (int i = 0; i < this.toolsChecked.length; i++) {
if (this.toolsChecked[i]) {
return this.data.get(i);
}
}
return null;
}*/
/* public List<ToolAdapterOperatorDescriptor> getCheckedOperators() {
List<ToolAdapterOperatorDescriptor> result = new ArrayList<>();
for (int i = 0; i < this.toolsChecked.length; i++) {
if (this.toolsChecked[i]) {
result.add(this.data.get(i));
}
}
return result;
}*/
public ToolAdapterOperatorDescriptor getObjectAt(int rowIndex) {
ToolAdapterOperatorDescriptor result = null;
if (rowIndex >= 0 && rowIndex <= this.data.size() - 1) {
result = this.data.get(rowIndex);
}
return result;
}
}
| 3,566 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FileListEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/FileListEditor.java | package org.esa.snap.ui.tooladapter.model;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.swing.binding.Binding;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.ComponentAdapter;
import com.bc.ceres.swing.binding.PropertyEditor;
import com.bc.ceres.swing.binding.internal.ListSelectionAdapter;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.esa.snap.utils.SpringUtilities;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import java.awt.*;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* Editor for properties of type File[].
*
* @author Cosmin Cara
*/
public class FileListEditor extends PropertyEditor {
@Override
public boolean isValidFor(PropertyDescriptor propertyDescriptor) {
return File[].class.isAssignableFrom(propertyDescriptor.getType());
}
@Override
public JComponent createEditorComponent(PropertyDescriptor propertyDescriptor, BindingContext bindingContext) {
JPanel panel = new JPanel(new SpringLayout());
DefaultListModel<File> listModel = new DefaultListModel<>();
JList<File> list = new JList<>(listModel);
ComponentAdapter adapter = new ListSelectionAdapter(list) {
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting() || getBinding().isAdjustingComponents()) {
return;
}
final Property model = getBinding().getContext().getPropertySet().getProperty(getBinding().getPropertyName());
try {
List<File> selectedValuesList = list.getSelectedValuesList();
model.setValue(selectedValuesList.toArray(new File[selectedValuesList.size()]));
// Now model is in sync with UI
getBinding().clearProblem();
} catch (ValidationException e) {
getBinding().reportProblem(e);
}
}
};
final Binding binding = bindingContext.bind(propertyDescriptor.getName(), adapter);
list.setMinimumSize(new Dimension(250, 24*5));
list.setPreferredSize(new Dimension(250, 24 * 5));
panel.add(new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
AbstractButton addFileBtn = ToolButtonFactory.createButton(UIUtils.loadImageIcon("/org/esa/snap/resources/images/icons/Add16.png"), false);
addFileBtn.setMaximumSize(new Dimension(20, 20));
addFileBtn.setAlignmentX(Component.LEFT_ALIGNMENT);
addFileBtn.addActionListener(e -> {
final JFileChooser fileChooser = new JFileChooser();
int i = fileChooser.showDialog(panel, "Select");
final File selectedFile = fileChooser.getSelectedFile();
if (i == JFileChooser.APPROVE_OPTION && selectedFile != null) {
listModel.addElement(selectedFile);
syncPropertyValue(binding, listModel);
}
});
AbstractButton removeFileBtn = ToolButtonFactory.createButton(UIUtils.loadImageIcon("/org/esa/snap/resources/images/icons/Remove16.png"), false);
removeFileBtn.setMaximumSize(new Dimension(20, 20));
removeFileBtn.setAlignmentX(Component.LEFT_ALIGNMENT);
removeFileBtn.addActionListener(e -> {
Object selection = list.getSelectedValue();
if (selection != null) {
listModel.removeElement(selection);
syncPropertyValue(binding, listModel);
}
});
JPanel buttonsPannel = new JPanel(new SpringLayout());
buttonsPannel.add(addFileBtn);
buttonsPannel.add(removeFileBtn);
SpringUtilities.makeCompactGrid(buttonsPannel, 2, 1, 0, 0, 0, 0);
panel.add(buttonsPannel);
SpringUtilities.makeCompactGrid(panel, 1, 2, 0, 0, 0, 0);
return panel;
}
private void syncPropertyValue(Binding binding, DefaultListModel<File> listModel) {
Object[] objects = listModel.toArray();
binding.setPropertyValue(Arrays.stream(objects)
.map(item -> new File(item.toString()))
.collect(Collectors.toList())
.toArray(new File[objects.length]));
}
} | 4,576 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PropertyMemberUIWrapperFactory.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/ui/tooladapter/model/PropertyMemberUIWrapperFactory.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * 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.ui.tooladapter.model;
import com.bc.ceres.binding.DefaultPropertySetDescriptor;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.ValueRange;
import com.bc.ceres.binding.ValueSet;
import com.bc.ceres.binding.converters.ArrayConverter;
import com.bc.ceres.binding.converters.StringConverter;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.PropertyEditor;
import com.bc.ceres.swing.binding.PropertyEditorRegistry;
import org.apache.commons.lang3.StringUtils;
import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory;
import org.esa.snap.core.gpf.descriptor.ParameterDescriptor;
import org.esa.snap.core.gpf.descriptor.PropertyAttributeException;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.ToolParameterDescriptor;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.FocusEvent;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* @author Ramona Manda
*/
public class PropertyMemberUIWrapperFactory {
public static PropertyMemberUIWrapper buildEmptyPropertyWrapper(){
return new PropertyMemberUIWrapper(null, null, null, null, -1, null) {
public String getErrorValueMessage(Object value) {
return null;
}
@Override
protected void setMemberValue(Object value) throws PropertyAttributeException { }
@Override
public String getMemberValue() {return null;}
@Override
protected JComponent buildUIComponent() {
return new JLabel();
}
@Override
protected String getValueFromUIComponent() throws PropertyAttributeException {
return null;
}
};
}
public static PropertyMemberUIWrapper buildPropertyWrapper(String attributeName, ToolParameterDescriptor property, ToolAdapterOperatorDescriptor opDescriptor, BindingContext context, PropertyMemberUIWrapper.CallBackAfterEdit callback) {
switch (attributeName) {
case "name":
return buildNamePropertyWrapper(attributeName, property, opDescriptor, context, 100, callback);
case "dataType":
return buildTypePropertyWrapper(attributeName, property, opDescriptor, context, 150, callback);
case "defaultValue":
return buildValuePropertyEditorWrapper(attributeName, property, opDescriptor, context, 250, callback);
default:
break;
}
/*if (attributeName.equals("name")) {
return buildNamePropertyWrapper(attributeName, property, opDescriptor, context, 100, callback);
}
if (attributeName.equals("dataType")) {
return buildTypePropertyWrapper(attributeName, property, opDescriptor, context, 150, callback);
}
if (attributeName.equals("defaultValue")) {
return buildValuePropertyEditorWrapper(attributeName, property, opDescriptor, context, 250, callback);
}*/
Method getter = null;
try {
getter = property.getClass().getSuperclass().getDeclaredMethod("is" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1));
} catch (NoSuchMethodException ignored) {
}
Object value = null;
try {
value = property.getAttribute(attributeName);
} catch (Exception ignored) {
}
//TODO class/superclass!
if (getter != null || (value != null && value.getClass().getSuperclass().equals(Boolean.class))) {
return buildBooleanPropertyWrapper(attributeName, property, opDescriptor, context, 30, callback);
}
try {
getter = property.getClass().getSuperclass().getDeclaredMethod("get" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1));
} catch (NoSuchMethodException ignored) {
}
if (getter != null && getter.getReturnType().equals(String.class)) {
return buildStringPropertyWrapper(attributeName, property, opDescriptor, context, 100, callback);
}
if (attributeName.equals("valueRange") || attributeName.equals("pattern") || attributeName.equals("valueSet")) {
return buildStringPropertyWrapper(attributeName, property, opDescriptor, context, 150, callback);
}
return buildEmptyWrapper(attributeName, property, opDescriptor, context, 100, callback);
}
private static Object parseAttributeValue(String attributeName, String value, ToolParameterDescriptor property) throws PropertyAttributeException {
if (value == null || value.length() == 0) {
return null;
}
Method getter = null;
try {
getter = property.getClass().getSuperclass().getDeclaredMethod("get" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1));
if (getter != null && getter.getReturnType().equals(String.class)) {
return value;
}
if (getter != null && getter.getReturnType().equals(String[].class)) {
Object[] items = ValueSet.parseValueSet(value, String.class).getItems();
String[] result = new String[items.length];
for (int i = 0; i < items.length; i++) {
result[i] = items[i].toString();
}
return result;
}
if (getter != null && getter.getReturnType().equals(ValueRange.class)) {
return ValueRange.parseValueRange(value);
}
if (getter != null && getter.getReturnType().equals(Pattern.class)) {
return Pattern.compile(value);
}
} catch (Exception ex) {
throw new PropertyAttributeException("Error on parsing the value " + value + " in order to set the value for attribute " + attributeName);
}
return value;
}
private static PropertyMemberUIWrapper buildStringPropertyWrapper(String attributeName, ToolParameterDescriptor property, ToolAdapterOperatorDescriptor opDescriptor, BindingContext context, int width, PropertyMemberUIWrapper.CallBackAfterEdit callback) {
return new PropertyMemberUIWrapper(attributeName, property, opDescriptor, context, width, callback) {
public String getErrorValueMessage(Object value) {
return null;
}
@Override
protected void setMemberValue(Object value) throws PropertyAttributeException {
property.setAttribute(attributeName, value);
}
@Override
public String getMemberValue() throws PropertyAttributeException {
Object obj = property.getAttribute(attributeName);
if (obj == null) {
return "";
}
if (obj instanceof String[]) {
return StringUtils.join(((String[]) obj), ArrayConverter.SEPARATOR);
}
return obj.toString();
}
@Override
protected JComponent buildUIComponent() throws Exception {
JTextField field = new JTextField(getMemberValue());
return field;
}
@Override
protected Object getValueFromUIComponent() throws PropertyAttributeException {
return PropertyMemberUIWrapperFactory.parseAttributeValue(attributeName, ((JTextField) UIComponent).getText(), property);
}
};
}
private static PropertyMemberUIWrapper buildBooleanPropertyWrapper(String attributeName, ToolParameterDescriptor property, ToolAdapterOperatorDescriptor opDescriptor, BindingContext context, int width, PropertyMemberUIWrapper.CallBackAfterEdit callback) {
return new PropertyMemberUIWrapper(attributeName, property, opDescriptor, context, width, callback) {
@Override
protected void setMemberValue(Object value) throws PropertyAttributeException {
property.setAttribute(attributeName, value);
}
@Override
public Boolean getMemberValue() throws PropertyAttributeException {
Object obj = property.getAttribute(attributeName);
return obj != null && (boolean) obj;
}
@Override
protected JComponent buildUIComponent() throws PropertyAttributeException {
JCheckBox button = new JCheckBox();
button.setSelected(getMemberValue());
return button;
}
@Override
protected Boolean getValueFromUIComponent() throws PropertyAttributeException {
return ((JCheckBox) UIComponent).isSelected();
}
};
}
private static PropertyMemberUIWrapper buildNamePropertyWrapper(String attributeName, ToolParameterDescriptor property, ToolAdapterOperatorDescriptor opDescriptor, BindingContext context, int width, PropertyMemberUIWrapper.CallBackAfterEdit callback) {
return new PropertyMemberUIWrapper(attributeName, property, opDescriptor, context, width, callback) {
public String getErrorValueMessage(Object value) {
if (value == null || !(value instanceof String) || ((String) value).length() == 0) {
return "Name of the property cannot be empty and must be a string!";
}
if (property.getName().equals(value)) {
return null;
}
//check if there is any other property with the same name, it should not!
for (ParameterDescriptor prop : opDescriptor.getParameterDescriptors()) {
if (prop != property && prop.getName().equals((value))) {
return "The operator must not have more then one parameter with the same name!";
}
}
return null;
}
@Override
protected void setMemberValue(Object value) throws PropertyAttributeException {
property.setName(value != null ? value.toString() : "null");
}
@Override
public String getMemberValue() {
return property.getName();
}
@Override
protected JComponent buildUIComponent() {
return new JTextField(getMemberValue());
}
@Override
protected String getValueFromUIComponent() throws PropertyAttributeException {
return ((JTextField) UIComponent).getText();
}
};
}
private static PropertyMemberUIWrapper buildTypePropertyWrapper(String attributeName, ToolParameterDescriptor property, ToolAdapterOperatorDescriptor opDescriptor, BindingContext context, int width, PropertyMemberUIWrapper.CallBackAfterEdit callback) {
return new PropertyMemberUIWrapper(attributeName, property, opDescriptor, context, width, callback) {
public String getErrorValueMessage(Object value) {
if (value == null) {
return "Type of the property cannot be empty!";
}
return null;
}
@Override
protected void setMemberValue(Object value) throws PropertyAttributeException {
property.setDataType(value != null ? (Class<?>) value : String.class);
}
@Override
public Class<?> getMemberValue() {
return property.getDataType();
}
@Override
protected JComponent buildUIComponent() {
return new JTextField(getMemberValue().getCanonicalName());
}
@Override
public boolean propertyUIComponentsNeedsRevalidation() {
return true;
}
@Override
protected Class<?> getValueFromUIComponent() throws PropertyAttributeException {
try {
return Class.forName(((JTextField) UIComponent).getText());
} catch (ClassNotFoundException ex) {
throw new PropertyAttributeException("Type of the property not found in the libraries");
}
}
};
}
private static PropertyMemberUIWrapper buildValuePropertyEditorWrapper(String attributeName, ToolParameterDescriptor property, ToolAdapterOperatorDescriptor opDescriptor, BindingContext context, int width, PropertyMemberUIWrapper.CallBackAfterEdit callback) {
return new PropertyMemberUIWrapper(attributeName, property, opDescriptor, context, width, callback) {
public String getErrorValueMessage(Object value) {
return null;
}
@Override
public void setMemberValue(Object value) throws PropertyAttributeException {
}
public JComponent reloadUIComponent(Class<?> newParamType) throws Exception{
property.setDataType(newParamType);
Property oldProp = context.getPropertySet().getProperty(property.getName());
Object dirAttr = null;
if(oldProp != null) {
PropertyDescriptor descriptor = ParameterDescriptorFactory.convert(property, new ParameterDescriptorFactory().getSourceProductMap());
dirAttr = descriptor.getAttribute("directory");
context.getPropertySet().removeProperty(oldProp);
}
PropertyDescriptor descriptor;
try {
descriptor = ParameterDescriptorFactory.convert(property, new ParameterDescriptorFactory().getSourceProductMap());
} catch (Exception ex) {
property.setDefaultValue(null);
descriptor = ParameterDescriptorFactory.convert(property, new ParameterDescriptorFactory().getSourceProductMap());
}
descriptor.setDefaultConverter();
try {
descriptor.setDefaultValue(property.getDefaultValue());
} catch (Exception ex) {
Logger.getLogger(PropertyMemberUIWrapper.class.getName()).warning(ex.getMessage());
}
try {
descriptor.setValueSet(ValueSet.parseValueSet(property.getValueSet(), new StringConverter()));
} catch (Exception ex) {
Logger.getLogger(PropertyMemberUIWrapper.class.getName()).warning(ex.getMessage());
}
DefaultPropertySetDescriptor propertySetDescriptor = new DefaultPropertySetDescriptor();
if (dirAttr != null) {
descriptor.setAttribute("directory", dirAttr);
}
propertySetDescriptor.addPropertyDescriptor(descriptor);
PropertyContainer container = PropertyContainer.createMapBacked(new HashMap<>(), propertySetDescriptor);
context.getPropertySet().addProperties(container.getProperties());
return super.reloadUIComponent(newParamType);
}
@Override
public Object getMemberValue() {
return property.getDefaultValue();
}
@Override
protected JComponent buildUIComponent() {
PropertyDescriptor propertydescriptor = context.getPropertySet().getDescriptor(property.getName());
PropertyEditor propertyEditor = PropertyEditorRegistry.getInstance().findPropertyEditor(
propertydescriptor);
return propertyEditor.createEditorComponent(propertydescriptor,
context);
}
@Override
protected Object getValueFromUIComponent() throws PropertyAttributeException {
return null;
}
@Override
public void focusLost(FocusEvent e){}
};
}
public static PropertyMemberUIWrapper buildEmptyWrapper(String attributeName, ToolParameterDescriptor property, ToolAdapterOperatorDescriptor opDescriptor, BindingContext context, int width, PropertyMemberUIWrapper.CallBackAfterEdit callback) {
return new PropertyMemberUIWrapper(attributeName, property, opDescriptor, context, width, callback) {
@Override
public String getErrorValueMessage(Object value) {
return null;
}
@Override
protected void setMemberValue(Object value) throws PropertyAttributeException {
}
@Override
public Object getMemberValue() {
return null;
}
@Override
protected JComponent buildUIComponent() {
return new JLabel("");
}
@Override
protected Object getValueFromUIComponent() {
return null;
}
};
}
}
| 18,168 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
InfoBuilder.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/modules/InfoBuilder.java | package org.esa.snap.modules;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Builder class for Nbm/Info/Info.xml
*
* @author Cosmin Cara
*/
public class InfoBuilder extends AbstractBuilder {
private String codebaseName;
private String distribution;
private int downloadSize;
private String homePage;
private boolean needsRestart;
private Date releaseDate;
private boolean isEssentialModule;
private boolean showInClient;
private String moduleName;
private String longDescription;
private String shortDescription;
private String displayCategory;
private String implementationVersion;
private String specificationVersion;
private String javaVersion;
private Map<String, String> dependencies;
public InfoBuilder() { this.dependencies = new HashMap<>(); }
public InfoBuilder codebase(String value) {
codebaseName = value;
return this;
}
public InfoBuilder distribution(String value) {
distribution = value;
return this;
}
public InfoBuilder downloadSize(int value) {
downloadSize = value;
return this;
}
public InfoBuilder homePage(String value) {
homePage = value;
return this;
}
public InfoBuilder longDescription(String value) {
longDescription = value;
return this;
}
public InfoBuilder shortDescription(String value) {
shortDescription = value;
return this;
}
public InfoBuilder displayCategory(String value) {
displayCategory = value;
return this;
}
public InfoBuilder implementationVersion(String value) {
implementationVersion = value;
return this;
}
public InfoBuilder specificationVersion(String value) {
specificationVersion = value;
return this;
}
public InfoBuilder javaVersion(String value) {
javaVersion = value;
return this;
}
public InfoBuilder dependency(String name, String version) {
dependencies.put(name, version);
return this;
}
public InfoBuilder releaseDate(Date value) {
releaseDate = value;
return this;
}
public InfoBuilder needsRestart(boolean value) {
needsRestart = value;
return this;
}
public InfoBuilder isEssentialModule(boolean value) {
isEssentialModule = value;
return this;
}
public InfoBuilder showInClient(boolean value) {
showInClient = value;
return this;
}
public InfoBuilder moduleName(String value) {
moduleName = value;
return this;
}
@Override
public String build(boolean standalone) {
StringBuilder xmlBuilder = new StringBuilder();
if (standalone) {
xmlBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
.append("<!DOCTYPE module PUBLIC \"-//NetBeans//DTD Autoupdate Module Info 2.5//EN\" \"http://www.netbeans.org/dtds/autoupdate-info-2_5.dtd\">");
}
xmlBuilder.append("<module codenamebase=\"").append(safeValue(codebaseName).toLowerCase()).append("\" ")
.append("distribution=\"").append(safeValue(distribution)).append("\" ")
.append("downloadsize=\"").append(downloadSize).append("\" ")
.append("homepage=\"").append(safeValue(homePage)).append("\" ")
.append("needsrestart=\"").append(safeValue(needsRestart)).append("\" ")
.append("releasedate=\"").append(new SimpleDateFormat("yyyy/MM/dd").format(releaseDate != null ? releaseDate : new Date())).append("\">\n")
.append("<manifest AutoUpdate-Essential-Module=\"").append(safeValue(isEssentialModule)).append("\" ")
.append("AutoUpdate-Show-In-Client=\"").append(safeValue(showInClient)).append("\" ")
.append("OpenIDE-Module=\"").append(safeValue(moduleName)).append("\" ")
.append("OpenIDE-Module-Display-Category=\"").append(safeValue(displayCategory)).append("\" ")
.append("OpenIDE-Module-Implementation-Version=\"").append(safeValue(implementationVersion)).append("\" ")
.append("OpenIDE-Module-Java-Dependencies=\"Java > ").append(safeValue(javaVersion)).append("\" ")
.append("OpenIDE-Module-Long-Description=\"<p>").append(safeValue(longDescription)).append("</p>\" ")
.append("OpenIDE-Module-Module-Dependencies=\"");
String depValues = "";
for (Map.Entry<String, String> entry : dependencies.entrySet()) {
depValues += entry.getKey() + " > " + entry.getValue() + ", ";
}
if (depValues.length() > 0) {
depValues = depValues.substring(0, depValues.length() - 2);
}
xmlBuilder.append(depValues);
xmlBuilder.append("\" ")
.append("OpenIDE-Module-Name=\"").append(moduleName).append("\" ")
.append("OpenIDE-Module-Requires=\"org.openide.modules.ModuleFormat1\" ")
.append("OpenIDE-Module-Short-Description=\"").append(shortDescription).append("\" ")
.append("OpenIDE-Module-Specification-Version=\"").append(safeValue(specificationVersion)).append("\"/>\n</module>");
return xmlBuilder.toString();
}
}
| 5,420 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ModulePackager.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/modules/ModulePackager.java | /*
* Copyright (C) 2014-2015 CS SI
*
* 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.modules;
import org.esa.snap.core.gpf.descriptor.OSFamily;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.dependency.Bundle;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterIO;
import org.openide.modules.Modules;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Utility class for creating at runtime a jar module
* for a tool adapter, so that it can be independently deployed.
*
* @author Cosmin Cara
*/
public final class ModulePackager {
private static final Manifest _manifest;
private static final Attributes.Name ATTR_DESCRIPTION_NAME;
private static final Attributes.Name ATTR_MODULE_NAME;
private static final Attributes.Name ATTR_MODULE_TYPE;
private static final Attributes.Name ATTR_MODULE_IMPLEMENTATION;
private static final Attributes.Name ATTR_MODULE_SPECIFICATION;
private static final Attributes.Name ATTR_MODULE_DEPENDENCIES;
private static final Attributes.Name ATTR_MODULE_ALIAS;
private static final File modulesPath;
private static final String layerXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE filesystem PUBLIC \"-//NetBeans//DTD Filesystem 1.1//EN\" \"http://www.netbeans.org/dtds/filesystem-1_1.dtd\">\n" +
"<filesystem>\n" +
" <folder name=\"Actions\">\n" +
" <folder name=\"Tools\">\n" +
" <file name=\"org-esa-snap-ui-tooladapter-actions-ExecuteToolAdapterAction.instance\"/>\n" +
" <attr name=\"displayName\" stringvalue=\"#NAME#\"/>\n" +
" <attr name=\"instanceCreate\" methodvalue=\"org.openide.awt.Actions.alwaysEnabled\"/>\n" +
" </folder>\n" +
" </folder>\n" +
" <folder name=\"Menu\">\n" +
" <folder name=\"Tools\">\n" +
" <folder name=\"External Tools\">\n" +
" <file name=\"org-esa-snap-ui-tooladapter-actions-ExecuteToolAdapterAction.shadow\">\n" +
" <attr name=\"originalFile\" stringvalue=\"Actions/Tools/org-esa-snap-ui-tooladapter-actions-ExecuteToolAdapterAction.instance\"/>\n" +
" <attr name=\"position\" intvalue=\"1000\"/>\n" +
" </file>\n" +
" </folder>\n" +
" </folder>\n" +
" </folder>\n" +
"</filesystem>";
private static final String LAYER_XML_PATH = "org/esa/snap/ui/tooladapter/layer.xml";
private static final String IMPLEMENTATION_VERSION;
private static final String SPECIFICATION_VERSION;
private static final String STA_MODULE = "org.esa.snap.snap.sta";
private static final String STA_UI_MODULE = "org.esa.snap.snap.sta.ui";
private static final String SNAP_RCP_MODULE = "org.esa.snap.snap.rcp";
private static final String SNAP_CORE_MODULE = "org.esa.snap.snap.core";
static {
String implementationVersion = Modules.getDefault().ownerOf(ModulePackager.class).getImplementationVersion();
IMPLEMENTATION_VERSION = implementationVersion.indexOf("-") > 0 ?
implementationVersion.substring(implementationVersion.indexOf("-") + 1) :
implementationVersion;
SPECIFICATION_VERSION = implementationVersion.indexOf("-") > 0 ?
implementationVersion.substring(0, implementationVersion.indexOf("-")) :
implementationVersion;
_manifest = new Manifest();
Attributes attributes = _manifest.getMainAttributes();
ATTR_DESCRIPTION_NAME = new Attributes.Name("OpenIDE-Module-Short-Description");
ATTR_MODULE_NAME = new Attributes.Name("OpenIDE-Module");
ATTR_MODULE_TYPE = new Attributes.Name("OpenIDE-Module-Type");
ATTR_MODULE_IMPLEMENTATION = new Attributes.Name("OpenIDE-Module-Implementation-Version");
ATTR_MODULE_SPECIFICATION = new Attributes.Name("OpenIDE-Module-Specification-Version");
ATTR_MODULE_ALIAS = new Attributes.Name("OpenIDE-Module-Alias");
ATTR_MODULE_DEPENDENCIES = new Attributes.Name("OpenIDE-Module-Module-Dependencies");
attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
attributes.put(new Attributes.Name("OpenIDE-Module-Java-Dependencies"), "Java > 1.8");
attributes.put(ATTR_MODULE_DEPENDENCIES, "org.esa.snap.snap.sta, org.esa.snap.snap.sta.ui");
attributes.put(new Attributes.Name("OpenIDE-Module-Display-Category"), "SNAP");
attributes.put(ATTR_MODULE_TYPE, "STA");
attributes.put(ATTR_DESCRIPTION_NAME, "External tool adapter");
modulesPath = ToolAdapterIO.getAdaptersPath().toFile();
}
public static void packModules(ModuleSuiteDescriptor suiteDescriptor, File suiteFile, Map<OSFamily, Bundle> bundles, ToolAdapterOperatorDescriptor... descriptors) throws IOException {
if (suiteFile != null && descriptors != null && descriptors.length > 0) {
if (descriptors.length == 1) {
packModule(descriptors[0], suiteFile);
} else {
Path suiteFilePath = suiteFile.toPath();
if (!Files.isDirectory(suiteFilePath)) {
suiteFilePath = suiteFilePath.getParent();
}
Map<String, String> dependentModules = new HashMap<>();
UpdateBuilder updateBuilder = new UpdateBuilder();
for (ToolAdapterOperatorDescriptor descriptor : descriptors) {
updateBuilder.moduleManifest(
packModule(descriptor, suiteFilePath.resolve(descriptor.getAlias() + ".nbm").toFile(), true));
dependentModules.put(normalize(descriptor.getName()), SPECIFICATION_VERSION);// descriptor.getVersion());
}
if (bundles != null) {
Arrays.stream(descriptors).forEach(d -> d.setBundles(bundles));
}
packSuite(suiteDescriptor, suiteFile, dependentModules, bundles);
Files.write(suiteFilePath.resolve("updates.xml"), updateBuilder.build(true).getBytes());
}
}
}
/**
* Packs the files associated with the given tool adapter operator descriptor into
* a NetBeans module file (nbm)
*
* @param descriptor The tool adapter descriptor
* @param nbmFile The target module file
*/
public static String packModule(ToolAdapterOperatorDescriptor descriptor, File nbmFile) throws IOException {
return packModule(descriptor, nbmFile, false);
}
private static String packModule(ToolAdapterOperatorDescriptor descriptor, File nbmFile, boolean isPartOfSuite) throws IOException {
byte[] byteBuffer;
String manifestXml = null;
try (final ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(nbmFile))) {
// create Info section
ZipEntry entry = new ZipEntry("Info/info.xml");
zipStream.putNextEntry(entry);
InfoBuilder infoBuilder = new InfoBuilder();
String javaVersion = System.getProperty("java.version");
try {
javaVersion = javaVersion.substring(0, javaVersion.indexOf("_"));
}catch(Exception ex){
javaVersion = javaVersion.substring(0, javaVersion.indexOf("."));
}
String descriptorName = normalize(descriptor.getName());
String description = descriptor.getDescription();
infoBuilder.moduleName(descriptorName)
.shortDescription(description)
.longDescription(description)
.displayCategory("SNAP")
.specificationVersion(SPECIFICATION_VERSION)
.implementationVersion(SPECIFICATION_VERSION)//descriptor.getVersion())
.codebase(descriptorName.toLowerCase())
.distribution(nbmFile.getName())
.downloadSize(0)
.homePage("https://github.com/senbox-org/s2tbx")
.needsRestart(true)
.releaseDate(new Date())
.isEssentialModule(false)
.showInClient(!isPartOfSuite)
.javaVersion(javaVersion)
.dependency(STA_MODULE, SPECIFICATION_VERSION)
.dependency(STA_UI_MODULE, SPECIFICATION_VERSION)
.dependency(SNAP_RCP_MODULE, SPECIFICATION_VERSION)
.dependency(SNAP_CORE_MODULE, SPECIFICATION_VERSION);
byteBuffer = infoBuilder.build(true).getBytes();
manifestXml = infoBuilder.build(false);
zipStream.write(byteBuffer, 0, byteBuffer.length);
zipStream.closeEntry();
// create META-INF section
entry = new ZipEntry("META-INF/MANIFEST.MF");
zipStream.putNextEntry(entry);
byteBuffer = new ManifestBuilder().build(true).getBytes();
zipStream.write(byteBuffer, 0, byteBuffer.length);
zipStream.closeEntry();
String jarName = descriptorName.replace(".", "-") + ".jar";
// create config section
entry = new ZipEntry("netbeans/config/Modules/" + descriptorName.replace(".", "-") + ".xml");
zipStream.putNextEntry(entry);
ModuleConfigBuilder mcb = new ModuleConfigBuilder();
byteBuffer = mcb.name(descriptorName)
.autoLoad(false)
.eager(false)
.enabled(true)
.jarName(jarName)
.reloadable(false)
.build(true).getBytes();
zipStream.write(byteBuffer, 0, byteBuffer.length);
zipStream.closeEntry();
// create modules section
entry = new ZipEntry("netbeans/modules/ext/");
zipStream.putNextEntry(entry);
zipStream.closeEntry();
entry = new ZipEntry("netbeans/modules/" + jarName);
zipStream.putNextEntry(entry);
zipStream.write(packAdapterJar(descriptor));
zipStream.closeEntry();
Map<OSFamily, Bundle> bundles = descriptor.getBundles();
if (!isPartOfSuite && bundles != null) {
for (Bundle bundle : bundles.values()) {
if (bundle.isLocal() && bundle.getTargetLocation() != null && bundle.getEntryPoint() != null) {
// lib folder
entry = new ZipEntry("netbeans/modules/lib/");
zipStream.putNextEntry(entry);
zipStream.closeEntry();
// bundle
String entryPoint = bundle.getEntryPoint();
File entryPointPath = bundle.getSource();
if (entryPointPath.exists()) {
entry = new ZipEntry("netbeans/modules/lib/" + entryPoint);
zipStream.putNextEntry(entry);
zipStream.write(Files.readAllBytes(entryPointPath.toPath()));
zipStream.closeEntry();
}
}
}
}
// create update_tracking section
entry = new ZipEntry("netbeans/update_tracking/");
zipStream.putNextEntry(entry);
zipStream.closeEntry();
}
return manifestXml;
}
/**
* Unpacks a jar file into the user modules location.
*
* @param jarFile The jar file to be unpacked
* @param unpackFolder The destination folder. If null, then the jar name will be used
*/
public static void unpackAdapterJar(File jarFile, File unpackFolder) throws IOException {
JarFile jar = new JarFile(jarFile);
Enumeration enumEntries = jar.entries();
if (unpackFolder == null) {
unpackFolder = new File(modulesPath, jarFile.getName().replace(".jar", ""));
}
if (!unpackFolder.exists()) {
Files.createDirectories(unpackFolder.toPath());
}
Attributes attributes = jar.getManifest().getMainAttributes();
if (attributes.containsKey(ATTR_MODULE_IMPLEMENTATION)) {
String version = attributes.getValue(ATTR_MODULE_IMPLEMENTATION);
File versionFile = new File(unpackFolder, "version.txt");
try (FileOutputStream fos = new FileOutputStream(versionFile)) {
fos.write(version.getBytes());
fos.close();
}
}
while (enumEntries.hasMoreElements()) {
JarEntry file = (JarEntry) enumEntries.nextElement();
File f = new File(unpackFolder, file.getName());
if (!f.toPath().normalize().startsWith(unpackFolder.toPath().normalize())) {
throw new IOException("Bad zip entry");
}
if (file.isDirectory()) {
Files.createDirectories(f.toPath());
continue;
} else {
Files.createDirectories(f.getParentFile().toPath());
}
try (InputStream is = jar.getInputStream(file)) {
try (FileOutputStream fos = new FileOutputStream(f)) {
while (is.available() > 0) {
fos.write(is.read());
}
fos.close();
}
is.close();
}
}
}
public static String getAdapterVersion(File jarFile) throws IOException {
String version = null;
JarFile jar = new JarFile(jarFile);
Attributes attributes = jar.getManifest().getMainAttributes();
if (attributes.containsKey(ATTR_MODULE_IMPLEMENTATION)) {
version = attributes.getValue(ATTR_MODULE_IMPLEMENTATION);
}
jar.close();
return version;
}
public static String getAdapterAlias(File jarFile) throws IOException {
String version = null;
JarFile jar = new JarFile(jarFile);
Attributes attributes = jar.getManifest().getMainAttributes();
if (attributes.containsKey(ATTR_MODULE_ALIAS)) {
version = attributes.getValue(ATTR_MODULE_ALIAS);
}
jar.close();
return version;
}
private static void packSuite(ModuleSuiteDescriptor descriptor, File nbmFile, Map<String, String> dependencies, Map<OSFamily, Bundle> bundles) throws IOException {
byte[] byteBuffer;
try (final ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(nbmFile))) {
// create Info section
ZipEntry entry = new ZipEntry("Info/info.xml");
zipStream.putNextEntry(entry);
InfoBuilder infoBuilder = new InfoBuilder();
String javaVersion = System.getProperty("java.version");
try {
javaVersion = javaVersion.substring(0, javaVersion.indexOf("_"));
}catch(Exception ex){
javaVersion = javaVersion.substring(0, javaVersion.indexOf("."));
}
String descriptorName = descriptor.getName();
String description = descriptor.getDescription();
infoBuilder.moduleName(descriptorName)
.shortDescription(description)
.longDescription(description)
.displayCategory("SNAP")
.specificationVersion(SPECIFICATION_VERSION)
.implementationVersion(IMPLEMENTATION_VERSION)
.codebase(descriptorName.toLowerCase())
.distribution(nbmFile.getName())
.downloadSize(0)
.homePage("https://github.com/senbox-org/s2tbx")
.needsRestart(true)
.releaseDate(new Date())
.isEssentialModule(false)
.showInClient(true)
.javaVersion(javaVersion)
.dependency(STA_MODULE, SPECIFICATION_VERSION)
.dependency(STA_UI_MODULE, SPECIFICATION_VERSION)
.dependency(SNAP_RCP_MODULE, SPECIFICATION_VERSION)
.dependency(SNAP_CORE_MODULE, SPECIFICATION_VERSION);
if (dependencies != null) {
for (Map.Entry<String, String> mapEntry : dependencies.entrySet()) {
infoBuilder.dependency(mapEntry.getKey(), mapEntry.getValue());
}
}
byteBuffer = infoBuilder.build(true).getBytes();
zipStream.write(byteBuffer, 0, byteBuffer.length);
zipStream.closeEntry();
// create META-INF section
entry = new ZipEntry("META-INF/MANIFEST.MF");
zipStream.putNextEntry(entry);
byteBuffer = new ManifestBuilder().build(true).getBytes();
zipStream.write(byteBuffer, 0, byteBuffer.length);
zipStream.closeEntry();
String jarName = descriptorName.replace(".", "-") + ".jar";
// create config section
entry = new ZipEntry("netbeans/config/Modules/" + descriptorName.replace(".", "-") + ".xml");
zipStream.putNextEntry(entry);
ModuleConfigBuilder mcb = new ModuleConfigBuilder();
byteBuffer = mcb.name(descriptorName)
.autoLoad(false)
.eager(false)
.enabled(true)
.jarName(jarName)
.reloadable(false)
.build(true).getBytes();
zipStream.write(byteBuffer, 0, byteBuffer.length);
zipStream.closeEntry();
entry = new ZipEntry("netbeans/modules/" + jarName);
zipStream.putNextEntry(entry);
zipStream.write(packSuiteJar(descriptor, dependencies));
zipStream.closeEntry();
if (bundles != null) {
for (Bundle bundle : bundles.values()) {
if (bundle.isLocal() && bundle.getTargetLocation() != null && bundle.getEntryPoint() != null) {
// lib folder
entry = new ZipEntry("netbeans/modules/lib/");
zipStream.putNextEntry(entry);
zipStream.closeEntry();
// bundle
String entryPoint = bundle.getEntryPoint();
File entryPointPath = bundle.getSource();
if (entryPointPath.exists()) {
entry = new ZipEntry("netbeans/modules/lib/" + entryPoint);
zipStream.putNextEntry(entry);
zipStream.write(Files.readAllBytes(entryPointPath.toPath()));
zipStream.closeEntry();
}
}
}
}
// create update_tracking section
entry = new ZipEntry("netbeans/update_tracking/");
zipStream.putNextEntry(entry);
zipStream.closeEntry();
}
}
private static byte[] packSuiteJar(ModuleSuiteDescriptor descriptor, Map<String, String> modules) throws IOException {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
attributes.put(ATTR_MODULE_NAME, descriptor.getName());
attributes.put(ATTR_DESCRIPTION_NAME, descriptor.getDescription());
attributes.put(ATTR_MODULE_SPECIFICATION, SPECIFICATION_VERSION);
attributes.put(new Attributes.Name("OpenIDE-Module-Java-Dependencies"), "Java > 1.8");
attributes.put(new Attributes.Name("OpenIDE-Module-Display-Category"), "SNAP");
attributes.put(ATTR_MODULE_TYPE, "STA");
String dependenciesValue = "org.esa.snap.snap.sta, org.esa.snap.snap.sta.ui";
for (Map.Entry<String, String> entry : modules.entrySet()) {
dependenciesValue += ", " + entry.getKey() + " > " + entry.getValue();
}
attributes.put(ATTR_MODULE_DEPENDENCIES, dependenciesValue);
ByteArrayOutputStream fOut = new ByteArrayOutputStream();
try (JarOutputStream jarOut = new JarOutputStream(fOut, manifest)) {
jarOut.close();
}
return fOut.toByteArray();
}
private static byte[] packAdapterJar(ToolAdapterOperatorDescriptor descriptor) throws IOException {
_manifest.getMainAttributes().put(ATTR_DESCRIPTION_NAME, descriptor.getAlias());
_manifest.getMainAttributes().put(ATTR_MODULE_NAME, descriptor.getName());
_manifest.getMainAttributes().put(ATTR_MODULE_IMPLEMENTATION, SPECIFICATION_VERSION);//descriptor.getVersion());
_manifest.getMainAttributes().put(ATTR_MODULE_SPECIFICATION, SPECIFICATION_VERSION);
_manifest.getMainAttributes().put(ATTR_MODULE_ALIAS, descriptor.getAlias());
File moduleFolder = new File(modulesPath, descriptor.getAlias());
ByteArrayOutputStream fOut = new ByteArrayOutputStream();
try (JarOutputStream jarOut = new JarOutputStream(fOut, _manifest)) {
File[] files = moduleFolder.listFiles();
if (files != null) {
for (File child : files) {
try {
// ModuleInstaller from adapter folder should not be included
if (child.getName().endsWith("ModuleInstaller.class")) {
//noinspection ResultOfMethodCallIgnored
child.delete();
} else {
addFile(child, jarOut);
}
} catch (Exception ignored) {
}
}
}
try {
String contents = layerXml.replace("#NAME#", descriptor.getLabel());
JarEntry entry = new JarEntry(LAYER_XML_PATH);
jarOut.putNextEntry(entry);
byte[] buffer = contents.getBytes();
jarOut.write(buffer, 0, buffer.length);
jarOut.closeEntry();
} catch (Exception ignored) {
ignored.printStackTrace();
}
jarOut.close();
}
return fOut.toByteArray();
}
/**
* Adds a file to the target jar stream.
*
* @param source The file to be added
* @param target The target jar stream
*/
private static void addFile(File source, JarOutputStream target) throws IOException {
String entryName = source.getPath().replace(modulesPath.getAbsolutePath(), "").replace("\\", "/").substring(1);
entryName = entryName.substring(entryName.indexOf("/") + 1);
if (!entryName.toLowerCase().endsWith("manifest.mf")) {
if (source.isDirectory()) {
if (!entryName.isEmpty()) {
if (!entryName.endsWith("/")) {
entryName += "/";
}
JarEntry entry = new JarEntry(entryName);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
target.closeEntry();
}
File[] files = source.listFiles();
if (files != null) {
for (File nestedFile : files) {
addFile(nestedFile, target);
}
}
return;
}
JarEntry entry = new JarEntry(entryName);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
writeBytes(source, target);
target.closeEntry();
}
}
/**
* Adds a compiled class file to the target jar stream.
*
* @param fromClass The class to be added
* @param target The target jar stream
*/
private static void addFile(Class fromClass, JarOutputStream target) throws IOException {
String classEntry = fromClass.getName().replace('.', '/') + ".class";
URL classURL = fromClass.getClassLoader().getResource(classEntry);
if (classURL != null) {
JarEntry entry = new JarEntry(classEntry);
target.putNextEntry(entry);
if (!classURL.toString().contains("!")) {
String fileName = classURL.getFile();
writeBytes(fileName, target);
} else {
try (InputStream stream = fromClass.getClassLoader().getResourceAsStream(classEntry)) {
writeBytes(stream, target);
}
}
target.closeEntry();
}
}
private static void writeBytes(String fileName, JarOutputStream target) throws IOException {
writeBytes(new File(fileName), target);
}
private static void writeBytes(File file, JarOutputStream target) throws IOException {
try (FileInputStream fileStream = new FileInputStream(file)) {
try (BufferedInputStream inputStream = new BufferedInputStream(fileStream)) {
byte[] buffer = new byte[1024];
while (true) {
int count = inputStream.read(buffer);
if (count == -1) {
break;
}
target.write(buffer, 0, count);
}
}
}
}
private static void writeBytes(InputStream stream, JarOutputStream target) throws IOException {
byte[] buffer = new byte[1024];
while (true) {
int count = stream.read(buffer);
if (count == -1) {
break;
}
target.write(buffer, 0, count);
}
}
private static String normalize(String input) {
if (input == null || input.isEmpty()) {
throw new IllegalArgumentException("Empty value");
}
return input.replace("-", ".").replace(" ", "_");
}
}
| 27,894 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ManifestBuilder.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/modules/ManifestBuilder.java | package org.esa.snap.modules;
import java.util.HashMap;
import java.util.Map;
/**
* Created by kraftek on 11/4/2016.
*/
public class ManifestBuilder extends AbstractBuilder {
private String version;
private String javaVersion;
private Map<String, String> properties;
public ManifestBuilder() {
version = "1.0";
javaVersion = System.getProperty("java.version");
try {
javaVersion = javaVersion.substring(0, javaVersion.indexOf("_"));
}catch(Exception ex){
javaVersion = javaVersion.substring(0, javaVersion.indexOf("."));
}
properties = new HashMap<>();
}
public ManifestBuilder version(String value) {
version = value;
return this;
}
public ManifestBuilder javaVersion(String value) {
javaVersion = value;
return this;
}
public ManifestBuilder property(String name, String value) {
properties.putIfAbsent(name, value);
return this;
}
@Override
public String build(boolean standalone) {
StringBuilder builder = new StringBuilder();
builder.append("Manifest-Version: ").append(safeValue(version)).append("\n")
.append("Created-By: ").append(safeValue(javaVersion)).append("\n");
for (Map.Entry<String, String> entry : properties.entrySet()) {
builder.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
return builder.toString();
}
}
| 1,511 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ModuleConfigBuilder.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/modules/ModuleConfigBuilder.java | package org.esa.snap.modules;
/**
* Created by kraftek on 11/4/2016.
*/
public class ModuleConfigBuilder extends AbstractBuilder {
/* xmlBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.append("<!DOCTYPE module PUBLIC \"-//NetBeans//DTD Module Status 1.0//EN\"\n\"http://www.netbeans.org/dtds/module-status-1_0.dtd\">\n")
.append("<module name=\"")
.append(descriptor.getName())
.append("\">\n<param name=\"autoload\">false</param><param name=\"eager\">false</param><param name=\"enabled\">true</param>\n")
.append("<param name=\"jar\">modules/")
.append(jarName)
.append("</param><param name=\"reloadable\">false</param>\n</module>");*/
private String moduleName;
private String jarName;
private boolean autoLoad;
private boolean eager;
private boolean enabled;
private boolean reloadable;
public ModuleConfigBuilder name(String value) {
moduleName = value;
return this;
}
public ModuleConfigBuilder jarName(String value) {
jarName = value;
return this;
}
public ModuleConfigBuilder autoLoad(boolean value) {
autoLoad = value;
return this;
}
public ModuleConfigBuilder eager(boolean value) {
eager = value;
return this;
}
public ModuleConfigBuilder enabled(boolean value) {
enabled = value;
return this;
}
public ModuleConfigBuilder reloadable(boolean value) {
reloadable = value;
return this;
}
@Override
public String build(boolean standalone) {
String xml = "";
if (standalone) {
xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<!DOCTYPE module PUBLIC \"-//NetBeans//DTD Module Status 1.0//EN\"\n\"http://www.netbeans.org/dtds/module-status-1_0.dtd\">\n";
}
xml += "<module name=\"" + safeValue(moduleName) + "\">\n" +
"<param name=\"autoload\">" + safeValue(autoLoad) + "</param>\n" +
"<param name=\"eager\">" + safeValue(eager) + "</param>\n" +
"<param name=\"enabled\">" + safeValue(enabled) + "</param>\n" +
"<param name=\"jar\">modules/" + safeValue(jarName) + "</param>\n" +
"<param name=\"reloadable\">" + safeValue(reloadable) + "</param>\n</module>";
return xml;
}
}
| 2,486 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractBuilder.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/modules/AbstractBuilder.java | package org.esa.snap.modules;
/**
* Created by kraftek on 11/4/2016.
*/
public abstract class AbstractBuilder {
public abstract String build(boolean standalone);
protected String safeValue(Object value) {
return value != null ? value.toString() : "";
}
}
| 280 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ModuleSuiteDescriptor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/modules/ModuleSuiteDescriptor.java | /*
*
* * Copyright (C) 2016 CS ROMANIA
* *
* * 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.modules;
/**
* Descriptor for a suite of modules.
*
* @author Cosmin Cara
*/
public class ModuleSuiteDescriptor {
private String name;
private String description;
private String version;
private String authors;
private String copyright;
public ModuleSuiteDescriptor() { }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
}
| 1,812 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
UpdateBuilder.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-ui/src/main/java/org/esa/snap/modules/UpdateBuilder.java | /*
*
* * Copyright (C) 2016 CS ROMANIA
* *
* * 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.modules;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.TreeSet;
/**
* @author kraftek
* @date 3/16/2017
*/
public class UpdateBuilder extends AbstractBuilder {
private Set<String> moduleManifests = new TreeSet<>();
public UpdateBuilder moduleManifest(String value) {
moduleManifests.add(value);
return this;
}
@Override
public String build(boolean standalone) {
StringBuilder xmlBuilder = new StringBuilder();
if (standalone) {
xmlBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n")
.append("<!DOCTYPE module_updates PUBLIC \"-//NetBeans//DTD Autoupdate Catalog 2.5//EN\")")
.append("\"http://www.netbeans.org/dtds/autoupdate-catalog-2_5.dtd\">");
}
LocalDateTime now = LocalDateTime.now();
xmlBuilder.append("<module_updates timestamp=\"")
.append(String.format("%02d",now.getHour())).append("/")
.append(String.format("%02d",now.getMinute())).append("/")
.append(String.format("%02d",now.getSecond())).append("/")
.append(String.format("%02d",now.getDayOfMonth())).append("/")
.append(String.format("%02d",now.getMonth().getValue())).append("/")
.append(String.format("%02d",now.getYear())).append("\">\n");
for (String moduleManifest : moduleManifests) {
xmlBuilder.append(moduleManifest).append("\n");
}
xmlBuilder.append("</module_updates>");
return xmlBuilder.toString();
}
}
| 2,347 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VirtualFileSystemView.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-virtual-file-system-ui/src/main/java/org/esa/snap/vfs/ui/file/chooser/VirtualFileSystemView.java | package org.esa.snap.vfs.ui.file.chooser;
import org.apache.commons.lang3.SystemUtils;
import org.esa.snap.vfs.NioFile;
import org.esa.snap.vfs.NioPaths;
import org.esa.snap.vfs.preferences.model.VFSRemoteFileRepository;
import org.esa.snap.vfs.remote.AbstractRemoteFileSystem;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.net.URI;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* FileSystemView component for VFS.
* FileSystemView that handles some specific VFS specific concepts.
*
* @author Adrian Drăghici
*/
public class VirtualFileSystemView extends FileSystemView {
/**
* The default name for a new directory.
*/
private static final String NEW_FOLDER_STRING = "New_Folder";
/**
* The default name for a next new directory.
*/
private static final String NEW_FOLDER_NEXT_STRING = "New_Folder_({0})";
private static final ImageIcon vfsRootIcon;
private static final ImageIcon vfsDirectoryIcon;
private static final ImageIcon vfsFileIcon;
private static final Logger logger = Logger.getLogger(VirtualFileSystemView.class.getName());
static {
vfsRootIcon = loadImageIcon("icons/vfs_root-23x16.png");
vfsDirectoryIcon = loadImageIcon("icons/vfs_folder-23x16.png");
vfsFileIcon = loadImageIcon("icons/vfs_file-23x16.png");
}
private final FileSystemView defaultFileSystemView;
private final Map<String, VirtualFileSystemHelper> vfsFileSystemViews;
/**
* Creates the FileSystemView component for VFS.
*
* @param defaultFileSystemView FileSystemView component for OS
* @param vfsRepositories The VFS Remote File Repositories
*/
protected VirtualFileSystemView(FileSystemView defaultFileSystemView, List<VFSRemoteFileRepository> vfsRepositories) {
super();
this.defaultFileSystemView = defaultFileSystemView;
this.vfsFileSystemViews = new HashMap<>();
for (VFSRemoteFileRepository vfsRemoteFileRepository : vfsRepositories) {
try {
VirtualFileSystemHelper vfsFileSystemView = new VirtualFileSystemHelper(vfsRemoteFileRepository);
String key = vfsFileSystemView.getRoot().toString();
this.vfsFileSystemViews.put(key, vfsFileSystemView);
} catch (Exception ex) {
logger.log(Level.SEVERE, "Unable to initialize " + vfsRemoteFileRepository.getName() + " VFS. Details: " + ex.getMessage(), ex);
}
}
}
/**
* Checks whether the given path is root for a VFS.
*
* @param path the path
* @return {@code True} if the given path is root for a VFS
*/
private static boolean isVirtualRoot(Path path) {
FileSystem fileSystem = path.getFileSystem();
if (fileSystem instanceof AbstractRemoteFileSystem) {
AbstractRemoteFileSystem remoteFileSystem = (AbstractRemoteFileSystem) fileSystem;
return remoteFileSystem.getRoot().equals(path);
}
return false;
}
/**
* Loads the icon from a path.
*
* @param imagePath the icon location path
* @return the icon
*/
private static ImageIcon loadImageIcon(String imagePath) {
URL imageURL = VirtualFileSystemView.class.getResource(imagePath);
return (imageURL == null) ? null : new ImageIcon(imageURL);
}
protected void notifyUser(String title, String message) {
logger.log(Level.FINE, () -> title + ": " + message);
}
private void notifyVFSError(Exception e) {
Throwable error = e;
while (error.getCause() != null) {
error = e.getCause();
}
if (error instanceof ConnectException || error instanceof UnknownHostException) {
notifyUser("VFS connection failure", "Unable to contact the VFS service.\nPlease check the connection or the Remote File Repository Address.");
} else if (error instanceof IOException) {
String report = error.getMessage().replaceAll("(.*)response code (.*)", "$2");
notifyUser("VFS access failure", "The VFS service reported \"" + report + "\" error.\nPlease check the Remote File Repository Configurations.");
} else {
notifyUser("VFS error", error.getMessage());
}
}
/**
* Gets the child of a file.
*
* @param parent a {@code File} object representing a directory or special folder
* @param fileName a name of a file or folder which exists in {@code parent}
* @return a File object. This is normally constructed with {@code new
* File(parent, fileName)} except when parent and child are both special folders, in which case the {@code File} is a wrapper containing a {@code NioShellFolder} object.
* @since 1.4
*/
@Override
public File getChild(File parent, String fileName) {
if (isVirtualFileItem(parent)) {
Path path = parent.toPath();
File[] children = getVirtualFiles(path, false);
for (File child : children) {
if (child.getName().equals(fileName)) {
return child;
}
}
return new NioFile(path.resolve(fileName).normalize());
}
return this.defaultFileSystemView.getChild(parent, fileName);
}
/**
* Checks if {@code f} represents a real directory or file as opposed to a special folder such as {@code "Desktop"}. Used by UI classes to decide if a folder is selectable when doing directory choosing.
*
* @param file a {@code File} object
* @return {@code true} if {@code f} is a real file or directory.
* @since 1.4
*/
@Override
public boolean isFileSystem(File file) {
if (isVirtualFileItem(file)) {
return isFileSystem(file.toPath());
}
return this.defaultFileSystemView.isFileSystem(file);
}
/**
* Creates a new folder with a default folder name.
*/
@Override
public File createNewFolder(File containingDir) throws IOException {
if (isVirtualFileItem(containingDir)) {
File newFolder = createFileObject(containingDir, NEW_FOLDER_STRING);
int i = 1;
while (Files.exists(newFolder.toPath())) {
newFolder = createFileObject(containingDir, MessageFormat.format(NEW_FOLDER_NEXT_STRING, i++));
}
Files.createDirectory(newFolder.toPath());
return newFolder;
}
return this.defaultFileSystemView.createNewFolder(containingDir);
}
/**
* Determines if the given file is a root in the navigable tree(s).
* Examples: Windows 98 has one root, the Desktop folder. DOS has one root per drive letter, {@code C:\}, {@code D:\}, etc. Unix has one root, the {@code "/"} directory.
* <p>
* The default implementation gets information from the {@code NioShellFolder} class.
*
* @param file a {@code File} object representing a directory
* @return {@code true} if {@code f} is a root in the navigable tree.
* @see #isFileSystemRoot
*/
@Override
public boolean isRoot(File file) {
if (isVirtualFileItem(file)) {
return isVirtualRoot(file.toPath());
}
return this.defaultFileSystemView.isRoot(file);
}
private File[] getOSRoots() {
File[] osRoots = this.defaultFileSystemView.getRoots();
if (SystemUtils.IS_OS_WINDOWS) {
try {
Class<?> nativeOsFileClass = Class.forName("sun.awt.shell.ShellFolder");
osRoots = (File[]) nativeOsFileClass.getMethod("get", String.class).invoke(null, "fileChooserComboBoxFolders");
} catch (Exception ignored) {
//leave default
}
}
return osRoots;
}
/**
* Gets all root directories on this system. For example, on OpenStack Swift, this would be the container directories.
*/
@Override
public File[] getRoots() {
File[] defaultRoots = getOSRoots();
Collection<VirtualFileSystemHelper> virtualFileSystemViews = this.vfsFileSystemViews.values();
File[] roots = new File[defaultRoots.length + virtualFileSystemViews.size()];
System.arraycopy(defaultRoots, 0, roots, 0, defaultRoots.length);
Iterator<VirtualFileSystemHelper> it = virtualFileSystemViews.iterator();
int index = defaultRoots.length;
while (it.hasNext()) {
VirtualFileSystemHelper value = it.next();
Path rootPath = value.getRoot();
roots[index++] = new NioFile(rootPath);
}
return roots;
}
/**
* Gets the list of shown (i.e. not hidden) files.
*
* @param dir the target dir
* @param useFileHiding the hiding flag
* @return the array of files
*/
@Override
public File[] getFiles(File dir, boolean useFileHiding) {
if (isVirtualFileItem(dir)) {
return getVirtualFiles(dir.toPath(), useFileHiding);
}
File[] localFiles = this.defaultFileSystemView.getFiles(dir, useFileHiding);
return fixPaths(localFiles, useFileHiding);
}
/**
* Returns the parent directory of {@code dir}.
*
* @param dir the {@code File} being queried
* @return the parent directory of {@code dir}, or
* {@code null} if {@code dir} is {@code null}
*/
@Override
public File getParentDirectory(File dir) {
if (dir == null) {
return null;
}
if (isVirtualFileItem(dir)) {
if (!Files.exists(dir.toPath())) {
return null;
}
Path parentPath = dir.toPath().getParent();
if (parentPath == null) {
return null;
}
if (!isFileSystem(parentPath)) {
return parentPath.toFile();
}
Path p = parentPath;
if (!Files.exists(p)) {
File ppsf = parentPath.getParent().toFile();
if (!isFileSystem(ppsf)) {
p = createFileSystemRoot(p.toFile()).toPath();
}
}
return p.toFile();
}
return this.defaultFileSystemView.getParentDirectory(dir);
}
/**
* Gets the Home Directory of FSW.
*
* @return the home directory
*/
@Override
public File getHomeDirectory() {
return this.defaultFileSystemView.getHomeDirectory();
}
/**
* Return the user's default starting directory for the file chooser.
*
* @return a {@code File} object representing the default starting folder
* @since 1.4
*/
@Override
public File getDefaultDirectory() {
return this.defaultFileSystemView.getDefaultDirectory();
}
/**
* Returns whether a file is hidden or not.
*/
@Override
public boolean isHiddenFile(File file) {
return this.defaultFileSystemView.isHiddenFile(file);
}
/**
* Is dir the root of a tree in the file system, such as a drive or partition. Example: Returns true for "C:\" on Windows 98.
*
* @param dir a {@code File} object representing a directory
* @return {@code true} if {@code f} is a root of a filesystem
* @see #isRoot
* @since 1.4
*/
@Override
public boolean isFileSystemRoot(File dir) {
if (isVirtualFileItem(dir)) {
return isVirtualRoot(dir.toPath());
}
return this.defaultFileSystemView.isFileSystemRoot(dir);
}
/**
* Used by UI classes to decide whether to display a special icon for drives or partitions, e.g. a "hard disk" icon.
* <p>
* The default implementation has no way of knowing, so always returns false.
*
* @param dir a directory
* @return {@code false} always
* @since 1.4
*/
@Override
public boolean isDrive(File dir) {
if (isVirtualFileItem(dir)) {
return false;
}
return this.defaultFileSystemView.isDrive(dir);
}
/**
* Used by UI classes to decide whether to display a special icon for a floppy disk. Implies isDrive(dir).
* <p>
* The default implementation has no way of knowing, so always returns false.
*
* @param dir a directory
* @return {@code false} always
* @since 1.4
*/
@Override
public boolean isFloppyDrive(File dir) {
if (isVirtualFileItem(dir)) {
return false;
}
return this.defaultFileSystemView.isFloppyDrive(dir);
}
/**
* Used by UI classes to decide whether to display a special icon for a computer node, e.g. "My Computer" or a network server.
* <p>
* The default implementation has no way of knowing, so always returns false.
*
* @param dir a directory
* @return {@code false} always
* @since 1.4
*/
@Override
public boolean isComputerNode(File dir) {
if (isVirtualFileItem(dir)) {
return false;
}
return this.defaultFileSystemView.isComputerNode(dir);
}
/**
* Returns a File object constructed from the given path string.
*/
@Override
public File createFileObject(String path) {
Path filePath = NioPaths.get(path);
return filePath.toFile();
}
/**
* Returns a File object constructed in dir from the given filename.
*/
@Override
public File createFileObject(File dir, String filename) {
Path filePath = dir.toPath().resolve(filename);
return filePath.toFile();
}
/**
* Creates a new {@code File} object for {@code f} with correct behavior for a file system root directory.
*
* @param file a {@code File} object representing a file system root directory, for example "/" on Unix or "C:\" on Windows.
* @return a new {@code File} object
* @since 1.4
*/
@Override
protected File createFileSystemRoot(File file) {
throw new UnsupportedOperationException();
}
/**
* Icon for a file, directory, or folder as it would be displayed in a system file browser. Example from Windows: the "M:\" directory displays a CD-ROM icon.
* <p>
* The default implementation gets information from the NioShellFolder class.
*
* @param file a {@code File} object
* @return an icon as it would be displayed by a native file chooser
* @see JFileChooser#getIcon
* @since 1.4
*/
@Override
public Icon getSystemIcon(File file) {
if (isVirtualFileItem(file)) {
AbstractRemoteFileSystem remoteFileSystem = (AbstractRemoteFileSystem) file.toPath().getFileSystem();
if (remoteFileSystem.getRoot().equals(file.toPath())) {
return vfsRootIcon;
}
if (Files.isDirectory(file.toPath())) {
return vfsDirectoryIcon;
}
return vfsFileIcon;
}
return this.defaultFileSystemView.getSystemIcon(file);
}
/**
* Name of a file, directory, or folder as it would be displayed in a system file browser. Example from Windows: the "M:\" directory displays as "CD-ROM (M:)"
* <p>
* The default implementation gets information from the NioShellFolder class.
*
* @param file a {@code File} object
* @return the file name as it would be displayed by a native file chooser
* @see JFileChooser#getName
* @since 1.4
*/
@Override
public String getSystemDisplayName(File file) {
if (isVirtualFileItem(file)) {
return file.toPath().getFileName().toString();
}
return this.defaultFileSystemView.getSystemDisplayName(file);
}
/**
* Type description for a file, directory, or folder as it would be displayed in a system file browser. Example from Windows: the "Desktop" folder is described as "Desktop".
* <p>
* Override for platforms with native NioShellFolder implementations.
*
* @param file a {@code File} object
* @return the file type description as it would be displayed by a native file chooser or null if no native information is available.
* @see JFileChooser#getTypeDescription
* @since 1.4
*/
@Override
public String getSystemTypeDescription(File file) {
if (isVirtualFileItem(file)) {
return null;
}
return this.defaultFileSystemView.getSystemTypeDescription(file);
}
/**
* Returns true if the file (directory) can be visited.
* Returns false if the directory cannot be traversed.
*
* @param file the {@code File}
* @return {@code true} if the file/directory can be traversed, otherwise {@code false}
* @see JFileChooser#isTraversable
* @see javax.swing.filechooser.FileView#isTraversable
* @since 1.4
*/
@Override
public Boolean isTraversable(File file) {
if (isVirtualFileItem(file)) {
return isFileSystemRoot(file) || isComputerNode(file) || file.isDirectory();
}
return this.defaultFileSystemView.isTraversable(file);
}
/**
* Converts given file paths from native class for OS used by FSW (which is considered to not use NIO API) to base {@code File}.
* Fix the issue with large paths (>256 characters) on Windows OS. (the goal)
*/
private File[] fixPaths(File[] filesPaths, boolean useFileHiding) {
List<File> files = new ArrayList<>();
for (File filePath : filesPaths) {
if (!useFileHiding || !isHiddenFile(filePath)) {
String windowsShareStartPath = "\\\\";
if (filePath.getPath().startsWith(windowsShareStartPath)) { // is a Windows network path
String[] fParts = filePath.getPath().split(windowsShareStartPath);
if (fParts.length == 4) {
String host = fParts[2];
String share = fParts[3];
filePath = NioPaths.get(windowsShareStartPath + host + '\\' + share).toFile();
}
} else {
filePath = new File(filePath.getPath());
}
if (filePath.exists()) {
files.add(filePath);
}
}
}
return files.toArray(new File[0]);
}
/**
* Checks whether the given file path is VFS path.
*
* @param file the path
* @return {@code True} if the given file path is VFS path
*/
private boolean isVirtualFileItem(File file) {
String scheme = file.toURI().getScheme();
for (VirtualFileSystemHelper vfsFileSystemView : this.vfsFileSystemViews.values()) {
URI uriRoot = vfsFileSystemView.getRoot().toUri();
if (uriRoot.getScheme().equals(scheme)) {
return true;
}
}
return false;
}
/**
* Checks whether the given path represents a File System
*
* @param path the path
* @return {@code True} if the given file path represents a File System
*/
private boolean isFileSystem(Path path) {
return !(Files.isSymbolicLink(path) && Files.isDirectory(path));
}
/**
* Gets the list of shown (i.e. not hidden) VFS files.
*
* @param dirPath the target dir path
* @param useFileHiding the hiding flag
* @return the list of VFS files
*/
private File[] getVirtualFiles(Path dirPath, boolean useFileHiding) {
String pathName = dirPath.toString();
DirectoryStream<Path> stream = null;
try {
VirtualFileSystemHelper vfsFileSystemView = this.vfsFileSystemViews.get(pathName);
if (vfsFileSystemView != null) {
return vfsFileSystemView.getRootDirectories();
}
List<File> files = new ArrayList<>();
if (!isVirtualRoot(dirPath) && Files.isDirectory(dirPath)) {
DirectoryStream.Filter<Path> filter = entry -> !(useFileHiding && Files.isHidden(entry));
stream = Files.newDirectoryStream(dirPath, filter);
for (Path path : stream) {
files.add(path.toFile());
}
return files.toArray(new File[0]);
}
} catch (Exception ex) {
logger.log(Level.SEVERE, "Unable to get files. Details: " + ex.getMessage(), ex);
notifyVFSError(ex);
} finally {
if (stream != null) {
try {
stream.close();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Unable to close the stream. Details: " + ex.getMessage(), ex);
}
}
}
return new File[0];
}
}
| 21,460 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VirtualFileSystemHelper.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-virtual-file-system-ui/src/main/java/org/esa/snap/vfs/ui/file/chooser/VirtualFileSystemHelper.java | package org.esa.snap.vfs.ui.file.chooser;
import org.esa.snap.vfs.NioFile;
import org.esa.snap.vfs.VFS;
import org.esa.snap.vfs.preferences.model.VFSRemoteFileRepository;
import org.esa.snap.vfs.remote.AbstractRemoteFileSystem;
import org.esa.snap.vfs.remote.AbstractRemoteFileSystemProvider;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* VirtualFileSystemHelper component for JFileChooser.
*
* @author Jean Coravu
* @author Adrian Drăghici
*/
public class VirtualFileSystemHelper {
private final AbstractRemoteFileSystem fileSystem;
/**
* Creates the FileSystemView component for VFS.
*
* @param vfsRemoteFileRepository The VFS Remote File Repository
*/
public VirtualFileSystemHelper(VFSRemoteFileRepository vfsRemoteFileRepository) throws URISyntaxException {
AbstractRemoteFileSystemProvider fileSystemProvider = (AbstractRemoteFileSystemProvider) VFS.getInstance().getFileSystemProviderByScheme(vfsRemoteFileRepository.getScheme());
URI uri = new URI(vfsRemoteFileRepository.getScheme(), vfsRemoteFileRepository.getRoot(), null);
Map<String, ?> env = Collections.emptyMap();
this.fileSystem = fileSystemProvider.getFileSystemOrCreate(uri, env);
}
/**
* Gets the VFS path of root
*
* @return The VFS path of root
*/
public Path getRoot() {
return this.fileSystem.getRoot();
}
public File[] getRootDirectories() {
List<File> roots = new ArrayList<>();
for (Path p : this.fileSystem.getRootDirectories()) {
roots.add(new VFSFileSystemRoot(p));
}
return roots.toArray(new File[0]);
}
/**
* FileSystemRoot for FSW VFS roots.
* Used for creating custom {@code File} objects which represent the root of a VFS in FSW.
*/
private static class VFSFileSystemRoot extends NioFile {
/**
* Creates the FileSystemRoot for FSW VFS roots.
*
* @param p The target file
*/
private VFSFileSystemRoot(Path p) {
super(p);
}
/**
* Tests whether the file denoted by this abstract pathname is a directory.
* For our scope this method will always returns <code>true</code>.
*
* @return <code>true</code> if and only if the file denoted by this abstract pathname exists <em>and</em> is a directory; <code>false</code> otherwise
* @throws SecurityException If a security manager exists and its <code>{@link java.lang.SecurityManager#checkRead(java.lang.String)}</code> method denies read access to the file
*/
@Override
public boolean isDirectory() {
return true;
}
/**
* Tests whether this abstract pathname is absolute. The definition of absolute pathname is system dependent. On UNIX systems, a pathname is absolute if its prefix is <code>"/"</code>. On Microsoft Windows systems, a pathname is absolute if its prefix is a drive specifier followed by
* <code>"\\"</code>, or if its prefix is <code>"\\\\"</code>.
* For our scope this method will always returns <code>false</code>.
*
* @return <code>true</code> if this abstract pathname is absolute,
* <code>false</code> otherwise
*/
@Override
public boolean isAbsolute() {
return false;
}
/**
* Tests whether the file or directory denoted by this abstract pathname exists.
* For our scope this method will always returns <code>true</code>.
*
* @return <code>true</code> if and only if the file or directory denoted by this abstract pathname exists; <code>false</code> otherwise
* @throws SecurityException If a security manager exists and its <code>{@link java.lang.SecurityManager#checkRead(java.lang.String)}</code> method denies read access to the file or directory
*/
@Override
public boolean exists() {
return true;
}
/**
* Returns the name of the file or directory denoted by this abstract pathname. This is just the last name in the pathname's name sequence. If the pathname's name sequence is empty, then the empty string is returned.
*
* @return The name of the file or directory denoted by this abstract pathname, or the empty string if this pathname's name sequence is empty
*/
@Override
public String getName() {
String name = super.getName();
if (name.isEmpty()) {
name = super.getPath();
}
return name;
}
/**
* Converts this abstract pathname into a pathname string. The resulting string uses the {@link #separator default name-separator character} to separate the names in the name sequence.
*
* @return The string form of this abstract pathname
*/
@Override
public String getPath() {
return super.getPath();
}
}
}
| 5,229 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ComputeSlopeAspectOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-dem-ui/src/main/java/org/esa/snap/dem/gpf/ui/ComputeSlopeAspectOpUI.java | /*
* Copyright (C) 2020 by SkyWatch Space Applications
*
* 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.dem.gpf.ui;
import org.esa.snap.core.dataop.dem.ElevationModelDescriptor;
import org.esa.snap.core.dataop.dem.ElevationModelRegistry;
import org.esa.snap.core.dataop.resamp.ResamplingFactory;
import org.esa.snap.dem.dataio.DEMFactory;
import org.esa.snap.graphbuilder.gpf.ui.BaseOperatorUI;
import org.esa.snap.graphbuilder.gpf.ui.OperatorUIUtils;
import org.esa.snap.graphbuilder.gpf.ui.UIValidation;
import org.esa.snap.graphbuilder.rcp.utils.DialogUtils;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AppContext;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.Map;
/**
* User interface for ComputeSlopeAspectOp
*/
public class ComputeSlopeAspectOpUI extends BaseOperatorUI {
private final JComboBox<String> demName = new JComboBox<>(DEMFactory.getDEMNameList());
private static final String externalDEMStr = "External DEM";
private final JCheckBox externalDEMApplyEGMCheckBox = new JCheckBox("External DEM Apply EGM");
private final JTextField demBandName = new JTextField("");
private final JLabel demBandNameLabel = new JLabel("Elevation Band Name:");
private static final String bandDEMStr = "Band DEM";
private final JComboBox<String> demResamplingMethod = new JComboBox<>(ResamplingFactory.resamplingNames);
private final JLabel demResamplingMethodLabel = new JLabel("DEM Resampling Method:");
private final JTextField externalDEMFile = new JTextField("");
private final JTextField externalDEMNoDataValue = new JTextField("");
private final JButton externalDEMBrowseButton = new JButton("...");
private final JLabel externalDEMFileLabel = new JLabel("External DEM:");
private final JLabel externalDEMNoDataValueLabel = new JLabel("DEM No Data Value:");
private Double extNoDataValue = 0.0;
private Boolean externalDEMApplyEGM = false;
private final DialogUtils.TextAreaKeyListener textAreaKeyListener = new DialogUtils.TextAreaKeyListener();
@Override
public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) {
demName.addItem(externalDEMStr);
demName.addItem(bandDEMStr);
initializeOperatorUI(operatorName, parameterMap);
final JComponent panel = createPanel();
initParameters();
demName.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent event) {
if (((String) demName.getSelectedItem()).startsWith(externalDEMStr)) {
enableExternalDEM(true);
} else {
externalDEMFile.setText("");
enableExternalDEM(false);
}
if (((String) demName.getSelectedItem()).startsWith(bandDEMStr)) {
enableBandDEM(true);
} else {
enableBandDEM(false);
}
}
});
externalDEMFile.setColumns(30);
enableExternalDEM(((String) demName.getSelectedItem()).startsWith(externalDEMStr));
enableBandDEM(((String) demName.getSelectedItem()).startsWith(bandDEMStr));
externalDEMBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final File file = Dialogs.requestFileForOpen("External DEM File", false, null, DEMFactory.LAST_EXTERNAL_DEM_DIR_KEY);
externalDEMFile.setText(file.getAbsolutePath());
extNoDataValue = OperatorUIUtils.getNoDataValue(file);
externalDEMNoDataValue.setText(String.valueOf(extNoDataValue));
}
});
externalDEMNoDataValue.addKeyListener(textAreaKeyListener);
externalDEMApplyEGMCheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
externalDEMApplyEGM = (e.getStateChange() == ItemEvent.SELECTED);
}
});
return new JScrollPane(panel);
}
@Override
public void initParameters() {
final String demNameParam = (String) paramMap.get("demName");
if (demNameParam != null) {
ElevationModelDescriptor descriptor = ElevationModelRegistry.getInstance().getDescriptor(demNameParam);
if(descriptor != null) {
demName.setSelectedItem(DEMFactory.getDEMDisplayName(descriptor));
} else {
demName.setSelectedItem(demNameParam);
}
}
demResamplingMethod.setSelectedItem(paramMap.get("demResamplingMethod"));
final File extFile = (File) paramMap.get("externalDEMFile");
if (extFile != null) {
externalDEMFile.setText(extFile.getAbsolutePath());
extNoDataValue = (Double) paramMap.get("externalDEMNoDataValue");
if (extNoDataValue != null && !textAreaKeyListener.isChangedByUser()) {
externalDEMNoDataValue.setText(String.valueOf(extNoDataValue));
}
}
externalDEMApplyEGMCheckBox.setSelected(externalDEMApplyEGM);
demBandName.setText(String.valueOf(paramMap.get("demBandName")));
}
@Override
public UIValidation validateParameters() {
return new UIValidation(UIValidation.State.OK, "");
}
@Override
public void updateParameters() {
paramMap.put("demName", (DEMFactory.getProperDEMName((String) demName.getSelectedItem())));
paramMap.put("demResamplingMethod", demResamplingMethod.getSelectedItem());
final String extFileStr = externalDEMFile.getText();
if (!extFileStr.isEmpty()) {
paramMap.put("externalDEMFile", new File(extFileStr));
paramMap.put("externalDEMNoDataValue", Double.parseDouble(externalDEMNoDataValue.getText()));
}
paramMap.put("externalDEMApplyEGM", externalDEMApplyEGM);
paramMap.put("demBandName", demBandName.getText());
}
private JComponent createPanel() {
final JPanel contentPane = new JPanel(new GridBagLayout());
final GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
gbc.gridx = 0;
DialogUtils.addComponent(contentPane, gbc, "Digital Elevation Model:", demName);
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, externalDEMFileLabel, externalDEMFile);
gbc.gridx = 2;
contentPane.add(externalDEMBrowseButton, gbc);
DialogUtils.addComponent(contentPane, gbc, demBandNameLabel, demBandName);
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, externalDEMNoDataValueLabel, externalDEMNoDataValue);
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, demResamplingMethodLabel, demResamplingMethod);
gbc.gridy++;
contentPane.add(externalDEMApplyEGMCheckBox, gbc);
gbc.gridy++;
DialogUtils.fillPanel(contentPane, gbc);
return contentPane;
}
private void enableExternalDEM(boolean flag) {
DialogUtils.enableComponents(externalDEMFileLabel, externalDEMFile, flag);
DialogUtils.enableComponents(externalDEMNoDataValueLabel, externalDEMNoDataValue, flag);
externalDEMBrowseButton.setVisible(flag);
externalDEMApplyEGMCheckBox.setVisible(flag);
}
private void enableBandDEM(boolean flag) {
DialogUtils.enableComponents(demBandNameLabel, demBandName, flag);
DialogUtils.enableComponents(demResamplingMethodLabel, demResamplingMethod, !flag);
}
}
| 8,381 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AddElevationOpUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-dem-ui/src/main/java/org/esa/snap/dem/gpf/ui/AddElevationOpUI.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* 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.dem.gpf.ui;
import org.esa.snap.core.dataop.dem.ElevationModelDescriptor;
import org.esa.snap.core.dataop.dem.ElevationModelRegistry;
import org.esa.snap.dem.dataio.DEMFactory;
import org.esa.snap.dem.gpf.AddElevationOp;
import org.esa.snap.graphbuilder.gpf.ui.BaseOperatorUI;
import org.esa.snap.graphbuilder.gpf.ui.OperatorUIUtils;
import org.esa.snap.graphbuilder.gpf.ui.UIValidation;
import org.esa.snap.graphbuilder.rcp.utils.DialogUtils;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AppContext;
import javax.swing.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.Map;
/**
* User interface for CreateElevationBandOp
*/
public class AddElevationOpUI extends BaseOperatorUI {
private final JComboBox<String> demName = new JComboBox<>(DEMFactory.getDEMNameList());
private final JComboBox demResamplingMethod = new JComboBox<>(DEMFactory.getDEMResamplingMethods());
private final JTextField externalDEMFile = new JTextField("");
private final JTextField externalDEMNoDataValue = new JTextField("");
private final JButton externalDEMBrowseButton = new JButton("...");
private final JLabel externalDEMFileLabel = new JLabel("External DEM:");
private final JLabel externalDEMNoDataValueLabel = new JLabel("DEM No Data Value:");
private Double extNoDataValue = 0.0;
private final DialogUtils.TextAreaKeyListener textAreaKeyListener = new DialogUtils.TextAreaKeyListener();
private static final String externalDEMStr = AddElevationOp.externalDEMStr;
private final JTextField elevationBandName = new JTextField("");
@Override
public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) {
demName.addItem(externalDEMStr);
initializeOperatorUI(operatorName, parameterMap);
final JComponent panel = createPanel();
initParameters();
demName.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent event) {
if (((String) demName.getSelectedItem()).startsWith(externalDEMStr)) {
enableExternalDEM(true);
} else {
externalDEMFile.setText("");
enableExternalDEM(false);
}
}
});
externalDEMFile.setColumns(30);
enableExternalDEM(((String) demName.getSelectedItem()).startsWith(externalDEMStr));
externalDEMBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final File file = Dialogs.requestFileForOpen("External DEM File", false, null, DEMFactory.LAST_EXTERNAL_DEM_DIR_KEY);
externalDEMFile.setText(file.getAbsolutePath());
extNoDataValue = OperatorUIUtils.getNoDataValue(file);
externalDEMNoDataValue.setText(String.valueOf(extNoDataValue));
}
});
externalDEMNoDataValue.addKeyListener(textAreaKeyListener);
return new JScrollPane(panel);
}
@Override
public void initParameters() {
final String demNameParam = (String) paramMap.get("demName");
if (demNameParam != null) {
ElevationModelDescriptor descriptor = ElevationModelRegistry.getInstance().getDescriptor(demNameParam);
if(descriptor != null) {
demName.setSelectedItem(DEMFactory.getDEMDisplayName(descriptor));
} else {
demName.setSelectedItem(demNameParam);
}
}
demResamplingMethod.setSelectedItem(paramMap.get("demResamplingMethod"));
final File extFile = (File) paramMap.get("externalDEMFile");
if (extFile != null) {
externalDEMFile.setText(extFile.getAbsolutePath());
extNoDataValue = (Double) paramMap.get("externalDEMNoDataValue");
if (extNoDataValue != null && !textAreaKeyListener.isChangedByUser()) {
externalDEMNoDataValue.setText(String.valueOf(extNoDataValue));
}
}
elevationBandName.setText(String.valueOf(paramMap.get("elevationBandName")));
}
@Override
public UIValidation validateParameters() {
return new UIValidation(UIValidation.State.OK, "");
}
@Override
public void updateParameters() {
paramMap.put("demName", DEMFactory.getProperDEMName((String) demName.getSelectedItem()));
paramMap.put("demResamplingMethod", demResamplingMethod.getSelectedItem());
final String extFileStr = externalDEMFile.getText();
if (!extFileStr.isEmpty()) {
paramMap.put("externalDEMFile", new File(extFileStr));
paramMap.put("externalDEMNoDataValue", Double.parseDouble(externalDEMNoDataValue.getText()));
}
paramMap.put("elevationBandName", elevationBandName.getText());
}
private JComponent createPanel() {
final JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
final GridBagConstraints gbc = DialogUtils.createGridBagConstraints();
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, "Digital Elevation Model:", demName);
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, externalDEMFileLabel, externalDEMFile);
gbc.gridx = 2;
contentPane.add(externalDEMBrowseButton, gbc);
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, externalDEMNoDataValueLabel, externalDEMNoDataValue);
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, "DEM Resampling Method:", demResamplingMethod);
gbc.gridy++;
DialogUtils.addComponent(contentPane, gbc, "Elevation Band Name:", elevationBandName);
gbc.gridy++;
DialogUtils.fillPanel(contentPane, gbc);
return contentPane;
}
private void enableExternalDEM(boolean flag) {
DialogUtils.enableComponents(externalDEMFileLabel, externalDEMFile, flag);
DialogUtils.enableComponents(externalDEMNoDataValueLabel, externalDEMNoDataValue, flag);
externalDEMBrowseButton.setVisible(flag);
}
}
| 7,095 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AddElevationAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-dem-ui/src/main/java/org/esa/snap/dem/rcp/AddElevationAction.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* 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.dem.rcp;
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.Validator;
import com.bc.ceres.binding.ValueSet;
import com.bc.ceres.glevel.support.AbstractMultiLevelSource;
import com.bc.ceres.glevel.support.DefaultMultiLevelImage;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.ComponentAdapter;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.GeoCoding;
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.ProductNode;
import org.esa.snap.core.dataop.dem.ElevationModel;
import org.esa.snap.core.dataop.dem.ElevationModelDescriptor;
import org.esa.snap.core.dataop.dem.ElevationModelRegistry;
import org.esa.snap.core.dataop.resamp.Resampling;
import org.esa.snap.core.dataop.resamp.ResamplingFactory;
import org.esa.snap.core.image.RasterDataNodeSampleOpImage;
import org.esa.snap.core.image.ResolutionLevel;
import org.esa.snap.dem.dataio.DEMFactory;
import org.esa.snap.engine_utilities.datamodel.Unit;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.ModalDialog;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.HelpCtx;
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 javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.event.ActionEvent;
import java.awt.image.RenderedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
@ActionID(
category = "Tools",
id = "AddElevationAction"
)
@ActionRegistration(
displayName = "#CTL_AddElevationAction_MenuText",
popupText = "#CTL_AddElevationAction_MenuText"
)
@ActionReferences({
@ActionReference(
path = "Menu/Raster/DEM Tools",
position = 250
),
@ActionReference(
path = "Shortcuts",
name = "D-E"
),
@ActionReference(
path = "Context/Product/Product",
position = 20
),
@ActionReference(
path = "Context/Product/RasterDataNode",
position = 10
),
})
@NbBundle.Messages({
"CTL_AddElevationAction_MenuText=Add Elevation Band",
"CTL_AddElevationAction_ShortDescription=Create a new elevation band from a DEM"
})
public class AddElevationAction extends AbstractAction implements ContextAwareAction, LookupListener, HelpCtx.Provider {
private static final String HELP_ID = "createElevation";
private final Lookup lkp;
private Product product;
public static final String DIALOG_TITLE = "Add Elevation Band";
public static final String DEFAULT_ELEVATION_BAND_NAME = "elevation";
public static final String DEFAULT_LATITUDE_BAND_NAME = "corr_latitude";
public static final String DEFAULT_LONGITUDE_BAND_NAME = "corr_longitude";
public AddElevationAction() {
this(Utilities.actionsGlobalContext());
}
public AddElevationAction(Lookup lkp) {
super(Bundle.CTL_AddElevationAction_MenuText());
this.lkp = lkp;
Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class);
lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext));
setEnableState();
putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_AddElevationAction_ShortDescription());
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new AddElevationAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
}
private void setEnableState() {
ProductNode productNode = lkp.lookup(ProductNode.class);
boolean state = false;
if (productNode != null) {
product = productNode.getProduct();
state = product.getSceneGeoCoding() != null;
}
setEnabled(state);
}
@Override
public void actionPerformed(ActionEvent event) {
final DialogData dialogData = requestDialogData(product);
if (dialogData == null) {
return;
}
final String demName = DEMFactory.getProperDEMName(dialogData.demName);
final ElevationModelRegistry elevationModelRegistry = ElevationModelRegistry.getInstance();
final ElevationModelDescriptor demDescriptor = elevationModelRegistry.getDescriptor(demName);
if (demDescriptor == null) {
Dialogs.showError(DIALOG_TITLE, "The DEM '" + demName + "' is not supported.");
return;
}
Resampling resampling = Resampling.BILINEAR_INTERPOLATION;
if (dialogData.resamplingMethod != null) {
resampling = ResamplingFactory.createResampling(dialogData.resamplingMethod);
}
computeBands(product,
demDescriptor,
dialogData.outputElevationBand ? dialogData.elevationBandName : null,
resampling);
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(HELP_ID);
}
private static void computeBands(final Product product,
final ElevationModelDescriptor demDescriptor,
final String elevationBandName,
final Resampling resampling) {
final ElevationModel dem = demDescriptor.createDem(resampling);
if (elevationBandName != null) {
addElevationBand(product, dem, elevationBandName);
}
}
private static void addElevationBand(Product product, ElevationModel dem, String elevationBandName) {
final GeoCoding geoCoding = product.getSceneGeoCoding();
ElevationModelDescriptor demDescriptor = dem.getDescriptor();
final float noDataValue = dem.getDescriptor().getNoDataValue();
final Band elevationBand = product.addBand(elevationBandName, ProductData.TYPE_FLOAT32);
elevationBand.setNoDataValueUsed(true);
elevationBand.setNoDataValue(noDataValue);
elevationBand.setUnit(Unit.METERS);
elevationBand.setDescription(demDescriptor.getName());
elevationBand.setSourceImage(createElevationSourceImage(dem, geoCoding, elevationBand));
}
private static RenderedImage createElevationSourceImage(final ElevationModel dem, final GeoCoding geoCoding, final Band band) {
return new DefaultMultiLevelImage(new AbstractMultiLevelSource(band.createMultiLevelModel()) {
@Override
protected RenderedImage createImage(final int level) {
return new ElevationSourceImage(dem, geoCoding, band, ResolutionLevel.create(getModel(), level));
}
});
}
private static boolean isOrtorectifiable(Product product) {
return product.getNumBands() > 0 && product.getBandAt(0).canBeOrthorectified();
}
private DialogData requestDialogData(final Product product) {
boolean ortorectifiable = isOrtorectifiable(product);
String[] demNames = DEMFactory.getDEMNameList();
// sort the list
final List<String> sortedDEMNames = Arrays.asList(demNames);
java.util.Collections.sort(sortedDEMNames);
demNames = sortedDEMNames.toArray(new String[sortedDEMNames.size()]);
final DialogData dialogData = new DialogData("SRTM 3sec (Auto Download)", ResamplingFactory.BILINEAR_INTERPOLATION_NAME, ortorectifiable);
PropertySet propertySet = PropertyContainer.createObjectBacked(dialogData);
configureDemNameProperty(propertySet, "demName", demNames, "SRTM 3sec (Auto Download)");
configureDemNameProperty(propertySet, "resamplingMethod", ResamplingFactory.resamplingNames,
ResamplingFactory.BILINEAR_INTERPOLATION_NAME);
configureBandNameProperty(propertySet, "elevationBandName", product);
configureBandNameProperty(propertySet, "latitudeBandName", product);
configureBandNameProperty(propertySet, "longitudeBandName", product);
final BindingContext ctx = new BindingContext(propertySet);
JList demList = new JList();
demList.setVisibleRowCount(10);
ctx.bind("demName", new SingleSelectionListComponentAdapter(demList));
JTextField elevationBandNameField = new JTextField();
elevationBandNameField.setColumns(10);
ctx.bind("elevationBandName", elevationBandNameField);
JCheckBox outputDemCorrectedBandsChecker = new JCheckBox("Output DEM-corrected bands");
ctx.bind("outputDemCorrectedBands", outputDemCorrectedBandsChecker);
JLabel latitudeBandNameLabel = new JLabel("Latitude band name:");
JTextField latitudeBandNameField = new JTextField();
latitudeBandNameField.setEnabled(ortorectifiable);
ctx.bind("latitudeBandName", latitudeBandNameField).addComponent(latitudeBandNameLabel);
ctx.bindEnabledState("latitudeBandName", true, "outputGeoCodingBands", true);
JLabel longitudeBandNameLabel = new JLabel("Longitude band name:");
JTextField longitudeBandNameField = new JTextField();
longitudeBandNameField.setEnabled(ortorectifiable);
ctx.bind("longitudeBandName", longitudeBandNameField).addComponent(longitudeBandNameLabel);
ctx.bindEnabledState("longitudeBandName", true, "outputGeoCodingBands", true);
TableLayout tableLayout = new TableLayout(2);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayout.setTablePadding(4, 4);
tableLayout.setCellColspan(0, 0, 2);
tableLayout.setCellColspan(1, 0, 2);
/* tableLayout.setCellColspan(3, 0, 2);
tableLayout.setCellWeightX(0, 0, 1.0);
tableLayout.setRowWeightX(1, 1.0);
tableLayout.setCellWeightX(2, 1, 1.0);
tableLayout.setCellWeightX(4, 1, 1.0);
tableLayout.setCellWeightX(5, 1, 1.0);
tableLayout.setCellPadding(4, 0, new Insets(0, 24, 0, 4));
tableLayout.setCellPadding(5, 0, new Insets(0, 24, 0, 4)); */
JPanel parameterPanel = new JPanel(tableLayout);
/*row 0*/
parameterPanel.add(new JLabel("Digital elevation model (DEM):"));
parameterPanel.add(new JScrollPane(demList));
/*row 1*/
parameterPanel.add(new JLabel("Resampling method:"));
final JComboBox resamplingCombo = new JComboBox(DEMFactory.getDEMResamplingMethods());
parameterPanel.add(resamplingCombo);
ctx.bind("resamplingMethod", resamplingCombo);
parameterPanel.add(new JLabel("Elevation band name:"));
parameterPanel.add(elevationBandNameField);
if (ortorectifiable) {
/*row 2*/
parameterPanel.add(outputDemCorrectedBandsChecker);
/*row 3*/
parameterPanel.add(latitudeBandNameLabel);
parameterPanel.add(latitudeBandNameField);
/*row 4*/
parameterPanel.add(longitudeBandNameLabel);
parameterPanel.add(longitudeBandNameField);
outputDemCorrectedBandsChecker.setSelected(ortorectifiable);
outputDemCorrectedBandsChecker.setEnabled(ortorectifiable);
}
final ModalDialog dialog = new ModalDialog(SnapApp.getDefault().getMainFrame(), DIALOG_TITLE, ModalDialog.ID_OK_CANCEL, HELP_ID);
dialog.setContent(parameterPanel);
if (dialog.show() == ModalDialog.ID_OK) {
return dialogData;
}
return null;
}
private static void configureDemNameProperty(PropertySet propertySet, String propertyName, String[] demNames, String defaultValue) {
PropertyDescriptor descriptor = propertySet.getProperty(propertyName).getDescriptor();
descriptor.setValueSet(new ValueSet(demNames));
descriptor.setDefaultValue(defaultValue);
descriptor.setNotNull(true);
descriptor.setNotEmpty(true);
}
private static void configureBandNameProperty(PropertySet propertySet, String propertyName, Product product) {
Property property = propertySet.getProperty(propertyName);
PropertyDescriptor descriptor = property.getDescriptor();
descriptor.setNotNull(true);
descriptor.setNotEmpty(true);
descriptor.setValidator(new BandNameValidator(product));
setValidBandName(property, product);
}
private static void setValidBandName(Property property, Product product) {
String bandName = (String) property.getValue();
String bandNameStub = bandName;
for (int i = 2; product.containsBand(bandName); i++) {
bandName = String.format("%s_%d", bandNameStub, i);
}
try {
property.setValue(bandName);
} catch (ValidationException e) {
throw new IllegalStateException(e);
}
}
private static class SingleSelectionListComponentAdapter extends ComponentAdapter implements ListSelectionListener, PropertyChangeListener {
private final JList list;
public SingleSelectionListComponentAdapter(JList list) {
this.list = list;
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
@Override
public JComponent[] getComponents() {
return new JComponent[]{list};
}
@Override
public void bindComponents() {
updateListModel();
getPropertyDescriptor().addAttributeChangeListener(this);
list.addListSelectionListener(this);
}
@Override
public void unbindComponents() {
getPropertyDescriptor().removeAttributeChangeListener(this);
list.removeListSelectionListener(this);
}
@Override
public void adjustComponents() {
Object value = getBinding().getPropertyValue();
if (value != null) {
list.setSelectedValue(value, true);
} else {
list.clearSelection();
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getSource() == getPropertyDescriptor() && evt.getPropertyName().equals("valueSet")) {
updateListModel();
}
}
private PropertyDescriptor getPropertyDescriptor() {
return getBinding().getContext().getPropertySet().getDescriptor(getBinding().getPropertyName());
}
private void updateListModel() {
ValueSet valueSet = getPropertyDescriptor().getValueSet();
if (valueSet != null) {
list.setListData(valueSet.getItems());
adjustComponents();
}
}
@Override
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
return;
}
if (getBinding().isAdjustingComponents()) {
return;
}
final Property property = getBinding().getContext().getPropertySet().getProperty(getBinding().getPropertyName());
Object selectedValue = list.getSelectedValue();
try {
property.setValue(selectedValue);
// Now model is in sync with UI
getBinding().clearProblem();
} catch (ValidationException e) {
getBinding().reportProblem(e);
}
}
}
private static class BandNameValidator implements Validator {
private final Product product;
public BandNameValidator(Product product) {
this.product = product;
}
@Override
public void validateValue(Property property, Object value) throws ValidationException {
final String bandName = value.toString().trim();
if (!ProductNode.isValidNodeName(bandName)) {
throw new ValidationException(MessageFormat.format("The band name ''{0}'' appears not to be valid.\n" +
"Please choose another one.",
bandName
));
} else if (product.containsBand(bandName)) {
throw new ValidationException(MessageFormat.format("The selected product already contains a band named ''{0}''.\n" +
"Please choose another one.",
bandName
));
}
}
}
private static class ElevationSourceImage extends RasterDataNodeSampleOpImage {
private final ElevationModel dem;
private final GeoCoding geoCoding;
private double noDataValue;
public ElevationSourceImage(ElevationModel dem, GeoCoding geoCoding, Band band, ResolutionLevel level) {
super(band, level);
this.dem = dem;
this.geoCoding = geoCoding;
noDataValue = band.getNoDataValue();
}
@Override
protected double computeSample(int sourceX, int sourceY) {
try {
return dem.getElevation(geoCoding.getGeoPos(new PixelPos(sourceX, sourceY), null));
} catch (Exception e) {
return noDataValue;
}
}
}
private static class DialogData {
String demName;
String resamplingMethod;
boolean outputElevationBand;
boolean outputDemCorrectedBands;
String elevationBandName = DEFAULT_ELEVATION_BAND_NAME;
String latitudeBandName = DEFAULT_LATITUDE_BAND_NAME;
String longitudeBandName = DEFAULT_LONGITUDE_BAND_NAME;
public DialogData(String demName, String resamplingMethod, boolean ortorectifiable) {
this.demName = demName;
this.resamplingMethod = resamplingMethod;
outputElevationBand = true;
outputDemCorrectedBands = ortorectifiable;
}
}
}
| 19,775 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.