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 |
---|---|---|---|---|---|---|---|---|---|---|---|
OperatorMenuTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/test/java/org/esa/snap/core/gpf/ui/OperatorMenuTest.java | /*
* Copyright (C) 2014 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui;
import com.bc.ceres.binding.dom.DefaultDomElement;
import com.thoughtworks.xstream.io.xml.xppdom.XppDom;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.ui.DefaultAppContext;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import java.awt.GraphicsEnvironment;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class OperatorMenuTest {
private static OperatorParameterSupportTest.TestOpSpi testOpSpi;
@BeforeClass
public static void beforeClass() {
Assume.assumeFalse("Cannot run in headless", GraphicsEnvironment.isHeadless());
testOpSpi = new OperatorParameterSupportTest.TestOpSpi();
GPF.getDefaultInstance().getOperatorSpiRegistry().addOperatorSpi(testOpSpi);
}
@AfterClass
public static void afterClass() {
if(testOpSpi != null) {
GPF.getDefaultInstance().getOperatorSpiRegistry().removeOperatorSpi(testOpSpi);
}
}
@Test
public void testOperatorAboutText() throws Exception {
DefaultAppContext appContext = new DefaultAppContext("test");
final OperatorMenu support = new OperatorMenu(null, testOpSpi.getOperatorDescriptor(), null, appContext, "");
assertEquals("Tester", support.getOperatorName());
String operatorDescription = support.getOperatorAboutText();
assertTrue(operatorDescription.length() > 80);
}
@Test
public void testEscapingXmlParameters() throws Exception {
DefaultDomElement domElement = new DefaultDomElement("parameter");
String unescapedString = "12 < 13 && 56 > 42 & \"true\" + 'a name'";
String escapedString = "12 < 13 && 56 > 42 & "true" + 'a name'";
domElement.addChild(new DefaultDomElement("expression", unescapedString));
DefaultDomElement withAttribute = new DefaultDomElement("withAttribute");
withAttribute.setAttribute("attrib", unescapedString);
domElement.addChild(withAttribute);
OperatorMenu.escapeXmlElements(domElement);
assertEquals(escapedString, domElement.getChild("expression").getValue());
assertEquals(escapedString, domElement.getChild("withAttribute").getAttribute("attrib"));
String xmlString = domElement.toXml();
XppDom readDomElement = OperatorMenu.createDom(xmlString);
assertEquals(unescapedString, readDomElement.getChild("expression").getValue());
assertEquals(unescapedString, readDomElement.getChild("withAttribute").getAttribute("attrib"));
}
}
| 3,385 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VariablesTableAdapterTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/test/java/org/esa/snap/core/gpf/ui/mosaic/VariablesTableAdapterTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.mosaic;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.swing.binding.BindingContext;
import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory;
import org.esa.snap.core.gpf.common.MosaicOp;
import org.junit.Before;
import org.junit.Test;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import static org.junit.Assert.*;
public class VariablesTableAdapterTest {
private BindingContext bindingContext;
@Before
public void before() {
final PropertyContainer pc = ParameterDescriptorFactory.createMapBackedOperatorPropertyContainer("Mosaic");
bindingContext = new BindingContext(pc);
}
@Test
public void variablesProperty() {
final JTable table = new JTable();
bindingContext.bind("variables", new VariablesTableAdapter(table));
assertTrue(table.getModel() instanceof DefaultTableModel);
final DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
tableModel.addRow(new String[]{"", ""});
tableModel.addRow(new String[]{"", ""});
assertEquals(2, table.getRowCount());
table.setValueAt("a", 0, 0);
assertEquals("a", table.getValueAt(0, 0));
table.setValueAt("A", 0, 1);
assertEquals("A", table.getValueAt(0, 1));
table.setValueAt("b", 1, 0);
assertEquals("b", table.getValueAt(1, 0));
table.setValueAt("B", 1, 1);
assertEquals("B", table.getValueAt(1, 1));
bindingContext.getPropertySet().setValue("variables", new MosaicOp.Variable[]{
new MosaicOp.Variable("d", "D")
});
assertEquals(1, table.getRowCount());
assertEquals("d", table.getValueAt(0, 0));
assertEquals("D", table.getValueAt(0, 1));
}
}
| 2,551 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ConditionsTableAdapterTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/test/java/org/esa/snap/core/gpf/ui/mosaic/ConditionsTableAdapterTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.mosaic;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.swing.binding.BindingContext;
import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory;
import org.esa.snap.core.gpf.common.MosaicOp;
import org.junit.Before;
import org.junit.Test;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import static org.junit.Assert.*;
public class ConditionsTableAdapterTest {
private BindingContext bindingContext;
@Before
public void before() {
final PropertyContainer pc = ParameterDescriptorFactory.createMapBackedOperatorPropertyContainer("Mosaic");
bindingContext = new BindingContext(pc);
}
@Test
public void variablesProperty() {
final JTable table = new JTable();
bindingContext.bind("conditions", new ConditionsTableAdapter(table));
assertTrue(table.getModel() instanceof DefaultTableModel);
final DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
tableModel.addRow((Object[]) null);
tableModel.addRow((Object[]) null);
assertEquals(2, table.getRowCount());
table.setValueAt("a", 0, 0);
assertEquals("a", table.getValueAt(0, 0));
table.setValueAt("A", 0, 1);
assertEquals("A", table.getValueAt(0, 1));
table.setValueAt(true, 0, 2);
assertEquals(true, table.getValueAt(0, 2));
table.setValueAt("b", 1, 0);
assertEquals("b", table.getValueAt(1, 0));
table.setValueAt("B", 1, 1);
assertEquals("B", table.getValueAt(1, 1));
table.setValueAt(false, 1, 2);
assertEquals(false, table.getValueAt(1, 2));
bindingContext.getPropertySet().setValue("conditions", new MosaicOp.Condition[]{
new MosaicOp.Condition("d", "D", true)
});
assertEquals(1, table.getRowCount());
assertEquals("d", table.getValueAt(0, 0));
assertEquals("D", table.getValueAt(0, 1));
assertEquals(true, table.getValueAt(0, 2));
}
}
| 2,787 | 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-gpf-ui/src/main/java/org/esa/snap/core/gpf/docs/package-info.java | @HelpSetRegistration(helpSet = "help.hs", position = 3000)
package org.esa.snap.core.gpf.docs;
import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration;
| 158 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OperatorParameterSupport.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/OperatorParameterSupport.java | /*
* Copyright (C) 2011 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui;
import com.bc.ceres.binding.*;
import com.bc.ceres.binding.dom.DefaultDomConverter;
import com.bc.ceres.binding.dom.DefaultDomElement;
import com.bc.ceres.binding.dom.DomElement;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.gpf.Operator;
import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory;
import org.esa.snap.core.gpf.descriptor.OperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.PropertySetDescriptorFactory;
import java.util.HashMap;
import java.util.Map;
/**
* WARNING: This class belongs to a preliminary API and may change in future releases.
* <p>
* Support for operator parameters input/output.
*
* @author Norman Fomferra
* @author Marco Zühlke
*/
public class OperatorParameterSupport {
private static final ParameterUpdater DEFAULT = new ParameterUpdater() {
@Override
public void handleParameterSaveRequest(Map<String, Object> parameterMap) {
}
@Override
public void handleParameterLoadRequest(Map<String, Object> parameterMap) {
}
};
private ParameterDescriptorFactory descriptorFactory;
private Map<String, Object> parameterMap;
private PropertySet propertySet;
private ParameterUpdater parameterUpdater;
private PropertySetDescriptor propertySetDescriptor;
private Class<? extends Operator> operatorType;
/**
* Creates a parameter support for the operator described by the given {@link OperatorDescriptor}.
*
* @param operatorDescriptor The operator descriptor.
*/
public OperatorParameterSupport(OperatorDescriptor operatorDescriptor) {
this(operatorDescriptor, null, null, null);
}
/**
* Creates a parameter support for the operator described by the given {@link OperatorDescriptor}.
* <p>
* If a property set and a parameter map are given the client as to keep them in sync.
* The {@code parameterUpdater} will be called before each save and after each load request to
* enable custom updating.
*
* @param operatorDescriptor The operator descriptor.
* @param propertySet The property set (can be null). If supplied a parameter map is required as well.
* @param parameterMap the parameter map (can be null)
* @param parameterUpdater The parameter updater (can be null)
*/
public OperatorParameterSupport(OperatorDescriptor operatorDescriptor,
PropertySet propertySet,
Map<String, Object> parameterMap,
ParameterUpdater parameterUpdater) {
Assert.notNull(operatorDescriptor, "operatorDescriptor");
init(null, operatorDescriptor, propertySet, parameterMap, parameterUpdater);
}
private void init(Class<? extends Operator> opType,
OperatorDescriptor operatorDescriptor,
PropertySet propertySet,
Map<String, Object> parameterMap,
ParameterUpdater parameterUpdater) {
Assert.argument(parameterMap != null || propertySet == null, "parameterMap != null || propertySet == null");
this.descriptorFactory = new ParameterDescriptorFactory();
if (parameterMap == null) {
parameterMap = new HashMap<>();
}
this.parameterMap = parameterMap;
this.operatorType = opType != null ? opType : operatorDescriptor.getOperatorClass();
if (propertySet == null) {
if (operatorDescriptor != null) {
try {
propertySetDescriptor = PropertySetDescriptorFactory.createForOperator(operatorDescriptor, descriptorFactory.getSourceProductMap());
} catch (ConversionException e) {
throw new IllegalStateException("Not able to init OperatorParameterSupport.", e);
}
propertySet = PropertyContainer.createMapBacked(this.parameterMap, propertySetDescriptor);
propertySet.setDefaultValues();
} else {
propertySetDescriptor = DefaultPropertySetDescriptor.createFromClass(operatorType, descriptorFactory);
propertySet = PropertyContainer.createMapBacked(this.parameterMap, propertySetDescriptor);
propertySet.setDefaultValues();
}
}
this.propertySet = propertySet;
if (parameterUpdater == null) {
parameterUpdater = DEFAULT;
}
this.parameterUpdater = parameterUpdater;
}
public PropertySet getPropertySet() {
return propertySet;
}
public Map<String, Object> getParameterMap() {
return parameterMap;
}
public void fromDomElement(DomElement parametersElement) throws ValidationException, ConversionException {
parameterMap.clear();
propertySet.setDefaultValues();
DefaultDomConverter domConverter = createDomConverter();
domConverter.convertDomToValue(parametersElement, propertySet);
parameterUpdater.handleParameterLoadRequest(parameterMap);
}
public DomElement toDomElement() throws ValidationException, ConversionException {
parameterUpdater.handleParameterSaveRequest(parameterMap);
DefaultDomConverter domConverter = createDomConverter();
DefaultDomElement parametersElement = new DefaultDomElement("parameters");
domConverter.convertValueToDom(propertySet, parametersElement);
return parametersElement;
}
private DefaultDomConverter createDomConverter() {
return new DefaultDomConverter(operatorType, descriptorFactory, propertySetDescriptor);
}
}
| 6,443 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ParameterUpdater.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/ParameterUpdater.java | /*
* Copyright (C) 2011 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui;
import com.bc.ceres.binding.ConversionException;
import com.bc.ceres.binding.ValidationException;
import java.util.Map;
/**
* WARNING: This class belongs to a preliminary API and may change in future releases.
*
* Enables reaction to parameter save and load request.
*
* @author Marco Zühlke
*/
public interface ParameterUpdater {
/**
* Called before the parameter map is saved. The implementer should update the given map.
*
* @param parameterMap The parameter map
*/
void handleParameterSaveRequest(Map<String,Object> parameterMap) throws ValidationException, ConversionException;
/**
* Called after the parameter map has been loaded. Implementers
* should update internal model from the given map.
*
* @param parameterMap The parameter map
*/
void handleParameterLoadRequest(Map<String,Object> parameterMap) throws ValidationException, ConversionException;
}
| 1,691 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OperatorMenu.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/OperatorMenu.java | /*
* Copyright (C) 2014 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui;
import com.bc.ceres.binding.dom.DomElement;
import com.bc.ceres.binding.dom.XppDomElement;
import com.thoughtworks.xstream.io.copy.HierarchicalStreamCopier;
import com.thoughtworks.xstream.io.xml.XppDomWriter;
import com.thoughtworks.xstream.io.xml.XppReader;
import com.thoughtworks.xstream.io.xml.xppdom.XppDom;
import org.apache.commons.text.StringEscapeUtils;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.gpf.Operator;
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.util.Debug;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AbstractDialog;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.help.HelpDisplayer;
import org.xmlpull.mxp1.MXParser;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.*;
/**
* WARNING: This class belongs to a preliminary API and may change in future releases.
* <p>
* Provides an operator menu with action for loading, saving and displaying the parameters of an operator
* in the file menu section and actions for help and about in the help menu section.
*
* @author Norman Fomferra
* @author Marco Zühlke
*/
public class OperatorMenu {
private final Component parentComponent;
private final OperatorParameterSupport parameterSupport;
private final OperatorDescriptor opDescriptor;
private final AppContext appContext;
private final String helpId;
private final Action loadParametersAction;
private final Action saveParametersAction;
private final Action displayParametersAction;
private final Action aboutAction;
private final String lastDirPreferenceKey;
public OperatorMenu(Component parentComponent,
OperatorDescriptor opDescriptor,
OperatorParameterSupport parameterSupport,
AppContext appContext,
String helpId) {
this.parentComponent = parentComponent;
this.parameterSupport = parameterSupport;
this.opDescriptor = opDescriptor;
this.appContext = appContext;
this.helpId = helpId;
lastDirPreferenceKey = opDescriptor.getName() + ".lastDir";
loadParametersAction = new LoadParametersAction();
saveParametersAction = new SaveParametersAction();
displayParametersAction = new DisplayParametersAction();
aboutAction = new AboutOperatorAction();
}
static XppDom createDom(String xml) {
XppDomWriter domWriter = new XppDomWriter();
new HierarchicalStreamCopier().copy(new XppReader(new StringReader(xml), new MXParser()), domWriter);
return domWriter.getConfiguration();
}
static void escapeXmlElements(DomElement domElement) {
domElement.setValue(StringEscapeUtils.ESCAPE_XML10.translate(domElement.getValue()));
String[] attributeNames = domElement.getAttributeNames();
for (String attributeName : attributeNames) {
domElement.setAttribute(attributeName, StringEscapeUtils.ESCAPE_XML10.translate(domElement.getAttribute(attributeName)));
}
DomElement[] children = domElement.getChildren();
for (DomElement child : children) {
escapeXmlElements(child);
}
}
private static String makeHtmlConform(String text) {
return text.replace("\n", "<br/>");
}
private static OperatorDescriptor getOperatorDescriptor(Class<? extends Operator> opType) {
String operatorAlias = OperatorSpi.getOperatorAlias(opType);
OperatorDescriptor operatorDescriptor;
OperatorSpiRegistry spiRegistry = GPF.getDefaultInstance().getOperatorSpiRegistry();
operatorDescriptor = spiRegistry.getOperatorSpi(operatorAlias).getOperatorDescriptor();
if (operatorDescriptor == null) {
Class<?>[] declaredClasses = opType.getDeclaredClasses();
for (Class<?> declaredClass : declaredClasses) {
if (OperatorSpi.class.isAssignableFrom(declaredClass)) {
operatorDescriptor = spiRegistry.getOperatorSpi(declaredClass.getName()).getOperatorDescriptor();
}
}
}
if (operatorDescriptor == null) {
throw new IllegalStateException("Not able to find SPI for operator class '" + opType.getName() + "'");
}
return operatorDescriptor;
}
/**
* Creates the default menu.
*
* @return The menu
*/
public JMenuBar createDefaultMenu() {
JMenu fileMenu = new JMenu("File");
fileMenu.add(loadParametersAction);
fileMenu.add(saveParametersAction);
fileMenu.addSeparator();
fileMenu.add(displayParametersAction);
JMenu helpMenu = new JMenu("Help");
helpMenu.add(createHelpMenuItem());
helpMenu.add(aboutAction);
final JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
menuBar.add(helpMenu);
return menuBar;
}
private JMenuItem createHelpMenuItem() {
JMenuItem menuItem = new JMenuItem("Help");
if (helpId != null && !helpId.isEmpty()) {
menuItem.addActionListener(e -> HelpDisplayer.show(helpId));
} else {
menuItem.setEnabled(false);
}
return menuItem;
}
private FileNameExtensionFilter createParameterFileFilter() {
return new FileNameExtensionFilter("GPF Parameter Files (XML)", "xml");
}
private void showInformationDialog(String title, Component component) {
final ModalDialog modalDialog = new ModalDialog(UIUtils.getRootWindow(parentComponent),
title,
AbstractDialog.ID_OK,
null); /*I18N*/
modalDialog.setContent(component);
modalDialog.show();
}
String getOperatorName() {
return opDescriptor.getAlias() != null ? opDescriptor.getAlias() : opDescriptor.getName();
}
@SuppressWarnings("ConcatenationWithEmptyString")
String getOperatorAboutText() {
return makeHtmlConform(String.format("" +
"<html>" +
"<h2>%s Operator</h2>" +
"<table>" +
"<tr><td><b>Name:</b></td><td><code>%s</code></td></tr>" +
"<tr><td><b>Version:</b></td><td>%s</td></tr>" +
"<tr><td><b>Full name:</b></td><td><code>%s</code></td></tr>" +
"<tr><td><b>Description:</b></td><td>%s</td></tr>" +
"<tr><td><b>Authors:</b></td><td>%s</td></tr>" +
"<tr><td><b>Copyright:</b></td><td>%s</td></tr></table></html>",
getOperatorName(),
getOperatorName(),
opDescriptor.getVersion(),
opDescriptor.getName(),
opDescriptor.getDescription(),
opDescriptor.getAuthors(),
opDescriptor.getCopyright()
));
}
private void applyCurrentDirectory(JFileChooser fileChooser) {
if (appContext != null) {
String homeDirPath = SystemUtils.getUserHomeDir().getPath();
String lastDir = appContext.getPreferences().getPropertyString(lastDirPreferenceKey, homeDirPath);
fileChooser.setCurrentDirectory(new File(lastDir));
}
}
private void preserveCurrentDirectory(JFileChooser fileChooser) {
if (appContext != null) {
String lastDir = fileChooser.getCurrentDirectory().getAbsolutePath();
appContext.getPreferences().setPropertyString(lastDirPreferenceKey, lastDir);
}
}
private class LoadParametersAction extends AbstractAction {
private static final String TITLE = "Load Parameters";
LoadParametersAction() {
super(TITLE + "...");
}
@Override
public void actionPerformed(ActionEvent event) {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter parameterFileFilter = createParameterFileFilter();
fileChooser.addChoosableFileFilter(parameterFileFilter);
fileChooser.setFileFilter(parameterFileFilter);
fileChooser.setDialogTitle(TITLE);
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
applyCurrentDirectory(fileChooser);
int response = fileChooser.showDialog(parentComponent, "Load");
if (JFileChooser.APPROVE_OPTION == response) {
try {
preserveCurrentDirectory(fileChooser);
readFromFile(fileChooser.getSelectedFile());
} catch (Exception e) {
Debug.trace(e);
AbstractDialog.showErrorDialog(parentComponent, "Could not load parameters.\n" + e.getMessage(), TITLE);
}
}
}
@Override
public boolean isEnabled() {
return super.isEnabled() && parameterSupport != null;
}
private void readFromFile(File selectedFile) throws Exception {
try (FileReader reader = new FileReader(selectedFile)) {
DomElement domElement = readXml(reader);
parameterSupport.fromDomElement(domElement);
}
}
private DomElement readXml(Reader reader) throws IOException {
try (BufferedReader br = new BufferedReader(reader)) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
return new XppDomElement(createDom(sb.toString()));
}
}
}
private class SaveParametersAction extends AbstractAction {
private static final String TITLE = "Save Parameters";
SaveParametersAction() {
super(TITLE + "...");
}
@Override
public void actionPerformed(ActionEvent event) {
JFileChooser fileChooser = new JFileChooser();
final FileNameExtensionFilter parameterFileFilter = createParameterFileFilter();
fileChooser.addChoosableFileFilter(parameterFileFilter);
fileChooser.setFileFilter(parameterFileFilter);
fileChooser.setDialogTitle(TITLE);
fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
applyCurrentDirectory(fileChooser);
int response = fileChooser.showDialog(parentComponent, "Save");
if (JFileChooser.APPROVE_OPTION == response) {
try {
preserveCurrentDirectory(fileChooser);
File selectedFile = fileChooser.getSelectedFile();
selectedFile = FileUtils.ensureExtension(selectedFile,
"." + parameterFileFilter.getExtensions()[0]);
DomElement domElement = parameterSupport.toDomElement();
escapeXmlElements(domElement);
String xmlString = domElement.toXml();
writeToFile(xmlString, selectedFile);
} catch (Exception e) {
Debug.trace(e);
Dialogs.showError(TITLE, "Could not load parameters.\n" + e.getMessage());
}
}
}
@Override
public boolean isEnabled() {
return super.isEnabled() && parameterSupport != null;
}
private void writeToFile(String s, File outputFile) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) {
bw.write(s);
}
}
}
private class DisplayParametersAction extends AbstractAction {
private static final String TITLE = "Display Parameters";
DisplayParametersAction() {
super(TITLE + "...");
}
@Override
public void actionPerformed(ActionEvent event) {
String parameterXml;
try {
DomElement domElement = parameterSupport.toDomElement();
parameterXml = domElement.toXml();
} catch (Exception e) {
Debug.trace(e);
Dialogs.showError(TITLE, "Failed to convert parameters to XML." + e.getMessage());
return;
}
JTextArea textArea = new JTextArea(parameterXml);
textArea.setEditable(false);
JScrollPane textAreaScrollPane = new JScrollPane(textArea);
textAreaScrollPane.setPreferredSize(new Dimension(360, 360));
showInformationDialog(getOperatorName() + " Parameters", textAreaScrollPane);
}
@Override
public boolean isEnabled() {
return super.isEnabled() && parameterSupport != null;
}
}
private class AboutOperatorAction extends AbstractAction {
AboutOperatorAction() {
super("About...");
}
@Override
public void actionPerformed(ActionEvent event) {
showInformationDialog("About " + getOperatorName(), new JLabel(getOperatorAboutText()));
}
}
}
| 14,318 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SingleTargetProductDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/SingleTargetProductDialog.java | /*
* Copyright (C) 2011 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.core.SubProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.gpf.Operator;
import org.esa.snap.core.gpf.OperatorCancelException;
import org.esa.snap.core.gpf.OperatorException;
import org.esa.snap.core.gpf.common.WriteOp;
import org.esa.snap.core.gpf.internal.OperatorExecutor;
import org.esa.snap.core.gpf.internal.OperatorProductReader;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.file.SaveProductAsAction;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.ModelessDialog;
import javax.swing.AbstractButton;
import javax.swing.JOptionPane;
import java.awt.Toolkit;
import java.io.File;
import java.text.MessageFormat;
import java.util.concurrent.ExecutionException;
import java.util.prefs.Preferences;
/**
* WARNING: This class belongs to a preliminary API and may change in future releases.
*
* @author Norman Fomferra
* @author Marco Peters
*/
public abstract class SingleTargetProductDialog extends ModelessDialog {
protected TargetProductSelector targetProductSelector;
protected AppContext appContext;
private long createTargetProductTime;
protected SingleTargetProductDialog(AppContext appContext, String title, String helpID) {
this(appContext, title, ID_APPLY_CLOSE_HELP, helpID);
}
protected SingleTargetProductDialog(AppContext appContext, String title, int buttonMask, String helpID) {
this(appContext, title, buttonMask, helpID, new TargetProductSelectorModel());
}
protected SingleTargetProductDialog(AppContext appContext, String title, int buttonMask, String helpID, TargetProductSelectorModel model) {
this(appContext, title, buttonMask, helpID, model, false);
}
protected SingleTargetProductDialog(AppContext appContext, String title, int buttonMask, String helpID, TargetProductSelectorModel model, boolean alwaysWriteOutput) {
super(appContext.getApplicationWindow(), title, buttonMask, helpID);
this.appContext = appContext;
targetProductSelector = new TargetProductSelector(model, alwaysWriteOutput);
String homeDirPath = SystemUtils.getUserHomeDir().getPath();
String saveDir = appContext.getPreferences().getPropertyString(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, homeDirPath);
targetProductSelector.getModel().setProductDir(new File(saveDir));
if (!alwaysWriteOutput) {
targetProductSelector.getOpenInAppCheckBox().setText("Open in " + appContext.getApplicationName());
}
targetProductSelector.getModel().getValueContainer().addPropertyChangeListener(evt -> {
if (evt.getPropertyName().equals("saveToFileSelected") ||
evt.getPropertyName().equals("openInAppSelected")) {
updateRunButton();
}
});
AbstractButton button = getButton(ID_APPLY);
button.setText("Run");
button.setMnemonic('R');
updateRunButton();
}
private void updateRunButton() {
AbstractButton button = getButton(ID_APPLY);
boolean save = targetProductSelector.getModel().isSaveToFileSelected();
boolean open = targetProductSelector.getModel().isOpenInAppSelected();
String toolTipText = "";
boolean enabled = true;
if (save && open) {
toolTipText = "Save target product and open it in " + getAppContext().getApplicationName();
} else if (save) {
toolTipText = "Save target product";
} else if (open) {
toolTipText = "Open target product in " + getAppContext().getApplicationName();
} else {
enabled = false;
}
button.setToolTipText(toolTipText);
button.setEnabled(enabled);
}
public AppContext getAppContext() {
return appContext;
}
public TargetProductSelector getTargetProductSelector() {
return targetProductSelector;
}
@Override
protected void onApply() {
if (!canApply()) {
return;
}
String productDir = targetProductSelector.getModel().getProductDir().getAbsolutePath();
appContext.getPreferences().setPropertyString(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, productDir);
Product targetProduct = null;
try {
long t0 = System.currentTimeMillis();
targetProduct = createTargetProduct();
createTargetProductTime = System.currentTimeMillis() - t0;
if (targetProduct == null) {
throw new NullPointerException("Target product is null.");
}
} catch (Throwable t) {
handleInitialisationError(t);
}
if (targetProduct == null) {
return;
}
targetProduct.setName(targetProductSelector.getModel().getProductName());
if (targetProductSelector.getModel().isSaveToFileSelected()) {
targetProduct.setFileLocation(targetProductSelector.getModel().getProductFile());
final ProgressMonitorSwingWorker worker = new ProductWriterSwingWorker(targetProduct);
worker.executeWithBlocking();
} else if (targetProductSelector.getModel().isOpenInAppSelected()) {
appContext.getProductManager().addProduct(targetProduct);
showOpenInAppInfo();
}
}
protected void handleInitialisationError(Throwable t) {
String msg;
if (t instanceof OperatorCancelException) {
msg = MessageFormat.format("An internal error occurred during the target product initialisation.\n{0}",
formatThrowable(t));
showErrorDialog(msg);
return;
}
if (isInternalException(t)) {
msg = MessageFormat.format("An internal error occurred during the target product initialisation.\n{0}",
formatThrowable(t));
} else {
msg = MessageFormat.format("A problem occurred during the target product initialisation.\n{0}",
formatThrowable(t));
}
appContext.handleError(msg, t);
}
protected void handleProcessingError(Throwable t) {
String msg;
if (t instanceof OperatorCancelException) {
return;
}
if (isInternalException(t)) {
msg = MessageFormat.format("An internal error occurred during the target product processing.\n{0}",
formatThrowable(t));
} else {
msg = MessageFormat.format("A problem occurred during the target product processing.\n{0}",
formatThrowable(t));
}
appContext.handleError(msg, t);
}
private boolean isInternalException(Throwable t) {
return (t instanceof RuntimeException && !(t instanceof OperatorException)) || t instanceof Error;
}
private String formatThrowable(Throwable t) {
return MessageFormat.format("Type: {0}\nMessage: {1}\n",
t.getClass().getSimpleName(),
t.getMessage());
}
protected boolean canApply() {
final String productName = targetProductSelector.getModel().getProductName();
if (productName == null || productName.isEmpty()) {
showErrorDialog("Please specify a target product name.");
targetProductSelector.getProductNameTextField().requestFocus();
return false;
}
if (targetProductSelector.getModel().isOpenInAppSelected()) {
final Product existingProduct = appContext.getProductManager().getProduct(productName);
if (existingProduct != null) {
String message = MessageFormat.format(
"<html>A product with the name ''{0}'' is already opened in {1}.<br><br>" +
"Do you want to continue?",
productName, appContext.getApplicationName()
);
final int answer = JOptionPane.showConfirmDialog(getJDialog(), message,
getTitle(), JOptionPane.YES_NO_OPTION);
if (answer != JOptionPane.YES_OPTION) {
return false;
}
}
}
if (targetProductSelector.getModel().isSaveToFileSelected()) {
File productFile = targetProductSelector.getModel().getProductFile();
if (productFile.exists()) {
String message = MessageFormat.format(
"<html>The specified output file<br>\"{0}\"<br> already exists.<br><br>" +
"Do you want to overwrite the existing file?",
productFile.getPath()
);
final int answer = JOptionPane.showConfirmDialog(getJDialog(), message,
getTitle(), JOptionPane.YES_NO_OPTION);
if (answer != JOptionPane.YES_OPTION) {
return false;
}
}
}
return true;
}
private void showSaveInfo(long saveTime) {
File productFile = getTargetProductSelector().getModel().getProductFile();
final String message = MessageFormat.format(
"<html>The target product has been successfully written to<br>{0}<br>" +
"Total time spend for processing: {1}",
formatFile(productFile),
formatDuration(saveTime)
);
showSuppressibleInformationDialog(message, "saveInfo");
}
protected void showOpenInAppInfo() {
final String message = MessageFormat.format(
"<html>The target product has successfully been created and opened in {0}.<br><br>" +
"Actual processing of source to target data will be performed only on demand,<br>" +
"for example, if the target product is saved or an image view is opened.",
appContext.getApplicationName()
);
showSuppressibleInformationDialog(message, "openInAppInfo");
}
private void showSaveAndOpenInAppInfo(long saveTime) {
File productFile = getTargetProductSelector().getModel().getProductFile();
final String message = MessageFormat.format(
"<html>The target product has been successfully written to<br>" +
"<p>{0}</p><br>" +
"and has been opened in {1}.<br><br>" +
"Total time spend for processing: {2}<br>",
formatFile(productFile),
appContext.getApplicationName(),
formatDuration(saveTime)
);
showSuppressibleInformationDialog(message, "saveAndOpenInAppInfo");
}
String formatFile(File file) {
return FileUtils.getDisplayText(file, 54);
}
String formatDuration(long millis) {
long seconds = millis / 1000;
millis -= seconds * 1000;
long minutes = seconds / 60;
seconds -= minutes * 60;
long hours = minutes / 60;
minutes -= hours * 60;
return String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, millis);
}
/**
* Shows an information dialog on top of this dialog.
* The shown dialog will contain a user option allowing to not show the message anymore.
*
* @param infoMessage The message.
* @param propertyName The (simple) property name used to store the user option in the application's preferences.
*/
public void showSuppressibleInformationDialog(String infoMessage, String propertyName) {
Dialogs.showInformation(getTitle(), infoMessage, getQualifiedPropertyName(propertyName));
}
/**
* Creates the desired target product.
* Usually, this method will be implemented by invoking one of the multiple {@link GPF GPF}
* {@code createProduct} methods.
* <p>
* The method should throw a {@link OperatorException} in order to signal "nominal" processing errors,
* other exeption types are treated as internal errors.
*
* @return The target product.
* @throws Exception if an error occurs, an {@link OperatorException} is signaling "nominal" processing errors.
*/
protected abstract Product createTargetProduct() throws Exception;
private class ProductWriterSwingWorker extends ProgressMonitorSwingWorker<Product, Object> {
private Product targetProduct;
private long saveTime;
private ProductWriterSwingWorker(Product targetProduct) {
super(getJDialog(), "Writing Target Product");
this.targetProduct = targetProduct;
}
@Override
protected Product doInBackground(ProgressMonitor pm) throws Exception {
final TargetProductSelectorModel model = getTargetProductSelector().getModel();
pm.beginTask("Writing...", model.isOpenInAppSelected() ? 100 : 95);
saveTime = 0L;
Product product = null;
try {
long t0 = System.currentTimeMillis();
Operator execOp = null;
if (targetProduct.getProductReader() instanceof OperatorProductReader) {
final OperatorProductReader opReader = (OperatorProductReader) targetProduct.getProductReader();
Operator operator = opReader.getOperatorContext().getOperator();
if (operator.getSpi().getOperatorDescriptor().isAutoWriteDisabled()) {
execOp = operator;
}
}
if (execOp == null) {
WriteOp writeOp = new WriteOp(targetProduct, model.getProductFile(), model.getFormatName());
writeOp.setDeleteOutputOnFailure(true);
writeOp.setWriteEntireTileRows(true);
writeOp.setClearCacheAfterRowWrite(false);
execOp = writeOp;
}
final OperatorExecutor executor = OperatorExecutor.create(execOp);
executor.execute(SubProgressMonitor.create(pm, 95));
saveTime = System.currentTimeMillis() - t0;
if (model.isOpenInAppSelected()) {
File targetFile = model.getProductFile();
if (!targetFile.exists())
targetFile = targetProduct.getFileLocation();
if (targetFile.exists()) {
targetProduct.dispose();
targetProduct = null;
product = ProductIO.readProduct(targetFile);
}
pm.worked(5);
}
} finally {
pm.done();
if (targetProduct != null) {
targetProduct.dispose();
targetProduct = null;
}
final Preferences preferences = SnapApp.getDefault().getPreferences();
if (preferences.getBoolean(GPF.BEEP_AFTER_PROCESSING_PROPERTY, false)) {
Toolkit.getDefaultToolkit().beep();
}
}
return product;
}
@Override
protected void done() {
final TargetProductSelectorModel model = getTargetProductSelector().getModel();
long totalSaveTime = saveTime + createTargetProductTime;
try {
final Product targetProduct = get();
if (model.isOpenInAppSelected()) {
appContext.getProductManager().addProduct(targetProduct);
showSaveAndOpenInAppInfo(totalSaveTime);
} else {
showSaveInfo(totalSaveTime);
}
} catch (InterruptedException e) {
// ignore
} catch (ExecutionException e) {
handleProcessingError(e.getCause());
} catch (Throwable t) {
handleProcessingError(t);
}
}
}
}
| 17,344 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultSingleTargetProductDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/DefaultSingleTargetProductDialog.java | /*
* Copyright (C) 2014 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui;
import 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.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.PropertyPane;
import com.bc.ceres.swing.selection.AbstractSelectionChangeListener;
import com.bc.ceres.swing.selection.Selection;
import com.bc.ceres.swing.selection.SelectionChangeEvent;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNodeEvent;
import org.esa.snap.core.datamodel.ProductNodeListener;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.gpf.OperatorSpi;
import org.esa.snap.core.gpf.descriptor.OperatorDescriptor;
import org.esa.snap.core.gpf.internal.RasterDataNodeValues;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.UIUtils;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.border.EmptyBorder;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* WARNING: This class belongs to a preliminary API and may change in future releases.
*
* @author Norman Fomferra
* @version $Revision: 8343 $ $Date: 2010-02-10 18:31:57 +0100 (Mi, 10 Feb 2010) $
*/
public class DefaultSingleTargetProductDialog extends SingleTargetProductDialog {
private final String operatorName;
private final OperatorDescriptor operatorDescriptor;
private DefaultIOParametersPanel ioParametersPanel;
private final OperatorParameterSupport parameterSupport;
private final BindingContext bindingContext;
private JTabbedPane form;
private PropertyDescriptor[] rasterDataNodeTypeProperties;
private String targetProductNameSuffix;
private ProductChangedHandler productChangedHandler;
public static SingleTargetProductDialog createDefaultDialog(String operatorName, AppContext appContext) {
return new DefaultSingleTargetProductDialog(operatorName, appContext, operatorName, null);
}
public DefaultSingleTargetProductDialog(String operatorName, AppContext appContext, String title, String helpID, boolean targetProductSelectorDisplay) {
super(appContext, title, ID_APPLY_CLOSE, helpID);
this.operatorName = operatorName;
targetProductNameSuffix = "";
OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(operatorName);
if (operatorSpi == null) {
throw new IllegalArgumentException("No SPI found for operator name '" + operatorName + "'");
}
operatorDescriptor = operatorSpi.getOperatorDescriptor();
ioParametersPanel = new DefaultIOParametersPanel(getAppContext(), operatorDescriptor, getTargetProductSelector(), targetProductSelectorDisplay);
parameterSupport = new OperatorParameterSupport(operatorDescriptor);
final ArrayList<SourceProductSelector> sourceProductSelectorList = ioParametersPanel.getSourceProductSelectorList();
final PropertySet propertySet = parameterSupport.getPropertySet();
bindingContext = new BindingContext(propertySet);
if (propertySet.getProperties().length > 0) {
if (!sourceProductSelectorList.isEmpty()) {
Property[] properties = propertySet.getProperties();
List<PropertyDescriptor> rdnTypeProperties = new ArrayList<>(properties.length);
for (Property property : properties) {
PropertyDescriptor parameterDescriptor = property.getDescriptor();
if (parameterDescriptor.getAttribute(RasterDataNodeValues.ATTRIBUTE_NAME) != null) {
rdnTypeProperties.add(parameterDescriptor);
}
}
rasterDataNodeTypeProperties = rdnTypeProperties.toArray(
new PropertyDescriptor[rdnTypeProperties.size()]);
}
}
productChangedHandler = new ProductChangedHandler();
if (!sourceProductSelectorList.isEmpty()) {
sourceProductSelectorList.get(0).addSelectionChangeListener(productChangedHandler);
}
}
public DefaultSingleTargetProductDialog(String operatorName, AppContext appContext, String title, String helpID) {
this(operatorName, appContext, title, helpID, true);
}
@Override
public int show() {
ioParametersPanel.initSourceProductSelectors();
if (form == null) {
initForm();
if (getJDialog().getJMenuBar() == null) {
final OperatorMenu operatorMenu = createDefaultMenuBar();
getJDialog().setJMenuBar(operatorMenu.createDefaultMenu());
}
}
setContent(form);
return super.show();
}
@Override
public void hide() {
productChangedHandler.releaseProduct();
ioParametersPanel.releaseSourceProductSelectors();
super.hide();
}
@Override
protected Product createTargetProduct() throws Exception {
final HashMap<String, Product> sourceProducts = ioParametersPanel.createSourceProductsMap();
return GPF.createProduct(operatorName, parameterSupport.getParameterMap(), sourceProducts);
}
protected DefaultIOParametersPanel getDefaultIOParametersPanel() {
return ioParametersPanel;
}
public String getTargetProductNameSuffix() {
return targetProductNameSuffix;
}
public void setTargetProductNameSuffix(String suffix) {
targetProductNameSuffix = suffix;
}
public BindingContext getBindingContext() {
return bindingContext;
}
private void initForm() {
form = new JTabbedPane();
//only add ioParametersPanel if there are input or target products
if(ioParametersPanel.getTargetProductSelectorDisplay() || ioParametersPanel.getSourceProductSelectorList().size() > 0) {
form.add("I/O Parameters", ioParametersPanel);
} else {
//if there is no ioParametersPanel, the size of the form could be too small
form.setPreferredSize(new Dimension(400, 300));
}
if (bindingContext.getPropertySet().getProperties().length > 0) {
final PropertyPane parametersPane = new PropertyPane(bindingContext);
final JPanel parametersPanel = parametersPane.createPanel();
parametersPanel.setBorder(new EmptyBorder(4, 4, 4, 4));
form.add("Processing Parameters", new JScrollPane(parametersPanel));
updateSourceProduct();
}
}
private OperatorMenu createDefaultMenuBar() {
return new OperatorMenu(getJDialog(),
operatorDescriptor,
parameterSupport,
getAppContext(),
getHelpID());
}
private void updateSourceProduct() {
try {
Property property = bindingContext.getPropertySet().getProperty(UIUtils.PROPERTY_SOURCE_PRODUCT);
if (property != null) {
property.setValue(productChangedHandler.currentProduct);
}
} catch (ValidationException e) {
throw new IllegalStateException("Property '" + UIUtils.PROPERTY_SOURCE_PRODUCT + "' must be of type " + Product.class + ".", e);
}
}
private class ProductChangedHandler extends AbstractSelectionChangeListener implements ProductNodeListener {
private Product currentProduct;
public void releaseProduct() {
if (currentProduct != null) {
currentProduct.removeProductNodeListener(this);
currentProduct = null;
updateSourceProduct();
}
}
@Override
public void selectionChanged(SelectionChangeEvent event) {
Selection selection = event.getSelection();
if (selection != null) {
final Product selectedProduct = (Product) selection.getSelectedValue();
if (selectedProduct != currentProduct) {
if (currentProduct != null) {
currentProduct.removeProductNodeListener(this);
}
currentProduct = selectedProduct;
if (currentProduct != null) {
currentProduct.addProductNodeListener(this);
}
if(getTargetProductSelector() != null){
updateTargetProductName();
}
updateValueSets(currentProduct);
updateSourceProduct();
}
}
}
@Override
public void nodeAdded(ProductNodeEvent event) {
handleProductNodeEvent();
}
@Override
public void nodeChanged(ProductNodeEvent event) {
handleProductNodeEvent();
}
@Override
public void nodeDataChanged(ProductNodeEvent event) {
handleProductNodeEvent();
}
@Override
public void nodeRemoved(ProductNodeEvent event) {
handleProductNodeEvent();
}
private void updateTargetProductName() {
String productName = "";
if (currentProduct != null) {
productName = currentProduct.getName();
}
final TargetProductSelectorModel targetProductSelectorModel = getTargetProductSelector().getModel();
targetProductSelectorModel.setProductName(productName + getTargetProductNameSuffix());
}
private void handleProductNodeEvent() {
updateValueSets(currentProduct);
}
private void updateValueSets(Product product) {
if (rasterDataNodeTypeProperties != null) {
for (PropertyDescriptor propertyDescriptor : rasterDataNodeTypeProperties) {
updateValueSet(propertyDescriptor, product);
}
}
}
}
private static void updateValueSet(PropertyDescriptor propertyDescriptor, Product product) {
String[] values = new String[0];
if (product != null) {
Object object = propertyDescriptor.getAttribute(RasterDataNodeValues.ATTRIBUTE_NAME);
if (object != null) {
@SuppressWarnings("unchecked")
Class<? extends RasterDataNode> rasterDataNodeType = (Class<? extends RasterDataNode>) object;
boolean includeEmptyValue = !propertyDescriptor.isNotNull() && !propertyDescriptor.isNotEmpty() &&
!propertyDescriptor.getType().isArray();
values = RasterDataNodeValues.getNames(product, rasterDataNodeType, includeEmptyValue);
}
}
propertyDescriptor.setValueSet(new ValueSet(values));
}
}
| 11,786 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SourceProductSelector.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/SourceProductSelector.java | /*
* Copyright (C) 2012 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.selection.SelectionChangeListener;
import com.bc.ceres.swing.selection.support.ComboBoxSelectionContext;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.dataio.ProductIOPlugInManager;
import org.esa.snap.core.dataio.ProductReaderPlugIn;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductFilter;
import org.esa.snap.core.datamodel.ProductManager;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.actions.file.OpenProductAction;
import org.esa.snap.ui.AbstractDialog;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.SnapFileChooser;
import org.openide.util.Utilities;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
* WARNING: This class belongs to a preliminary API and may change in future releases.
* todo - add capability to select/add/remove multiple soures (nf - 27.11.2007)
* todo - add capability to specify optional sources
*
* @author Ralf Quast
* @version $Revision$ $Date$
*/
public class SourceProductSelector {
private AppContext appContext;
private ProductFilter productFilter;
private Product extraProduct;
private File currentDirectory;
private DefaultComboBoxModel<Object> productListModel;
private JLabel productNameLabel;
private JButton productFileChooserButton;
private JComboBox<Object> productNameComboBox;
private final ProductManager.Listener productManagerListener;
private ComboBoxSelectionContext selectionContext;
private boolean enableEmptySelection;
public SourceProductSelector(AppContext appContext) {
this(appContext, false);
}
public SourceProductSelector(AppContext appContext, boolean enableEmptySelection) {
this(appContext, "Name:", enableEmptySelection);
}
public SourceProductSelector(AppContext appContext, String labelText) {
this(appContext, labelText, false);
}
public SourceProductSelector(AppContext appContext, String labelText, boolean enableEmptySelection) {
this.appContext = appContext;
this.enableEmptySelection = enableEmptySelection;
productListModel = new DefaultComboBoxModel<>();
productNameLabel = new JLabel(labelText);
productFileChooserButton = new JButton(new ProductFileChooserAction());
final Dimension size = new Dimension(26, 16);
productFileChooserButton.setPreferredSize(size);
productFileChooserButton.setMinimumSize(size);
productNameComboBox = new JComboBox<>(productListModel);
productNameComboBox.setPrototypeDisplayValue("[1] 123456789 123456789 12345");
productNameComboBox.setRenderer(new ProductListCellRenderer());
productNameComboBox.addPopupMenuListener(new ProductPopupMenuListener());
productNameComboBox.addActionListener(e -> {
final Object selected = productNameComboBox.getSelectedItem();
if (selected != null && selected instanceof Product) {
Product product = (Product) selected;
if (product.getFileLocation() != null) {
productNameComboBox.setToolTipText(product.getFileLocation().getPath());
} else {
productNameComboBox.setToolTipText(product.getDisplayName());
}
} else {
productNameComboBox.setToolTipText("Select a source product.");
}
});
productFilter = ProductFilter.ALL;
selectionContext = new ComboBoxSelectionContext(productNameComboBox);
productManagerListener = new ProductManager.Listener() {
@Override
public void productAdded(ProductManager.Event event) {
addProduct(event.getProduct());
}
@Override
public void productRemoved(ProductManager.Event event) {
Product product = event.getProduct();
if (productListModel.getSelectedItem() == product) {
productListModel.setSelectedItem(null);
}
productListModel.removeElement(product);
}
};
}
/**
* @return the product filter, default is a filter which accepts all products
*/
public ProductFilter getProductFilter() {
return productFilter;
}
/**
* @param productFilter the product filter
*/
public void setProductFilter(ProductFilter productFilter) {
this.productFilter = productFilter;
}
public synchronized void initProducts() {
productListModel.removeAllElements();
if (enableEmptySelection) {
productListModel.addElement(null);
}
for (Product product : appContext.getProductManager().getProducts()) {
addProduct(product);
}
Product selectedProduct = appContext.getSelectedProduct();
final ProductNode productNode = Utilities.actionsGlobalContext().lookup(ProductNode.class);
if (productNode != null) {
// user would want to apply operation to the selected productNode rather than the productSceneView
selectedProduct = productNode.getProduct();
}
if (enableEmptySelection) {
productListModel.setSelectedItem(null);
} else if (selectedProduct != null && productFilter.accept(selectedProduct)) {
productListModel.setSelectedItem(selectedProduct);
}
appContext.getProductManager().addListener(productManagerListener);
}
public int getProductCount() {
if (enableEmptySelection) {
return productListModel.getSize() - 1;
} else {
return productListModel.getSize();
}
}
public void setSelectedIndex(int index) {
productListModel.setSelectedItem(productListModel.getElementAt(index));
}
public Product getSelectedProduct() {
return (Product) productListModel.getSelectedItem();
}
public void setCurrentDirectory(File directory) {
if (directory != null && directory.isDirectory()) {
currentDirectory = directory;
}
}
public File getCurrentDirectory() {
return currentDirectory;
}
public void setSelectedProduct(Product product) {
if (product == null) {
productListModel.setSelectedItem(null);
return;
}
if (productListModelContains(product)) {
productListModel.setSelectedItem(product);
} else {
if (productFilter.accept(product)) {
if (extraProduct != null) {
productListModel.removeElement(extraProduct);
extraProduct.dispose();
}
productListModel.addElement(product);
productListModel.setSelectedItem(product);
extraProduct = product;
}
}
}
public synchronized void releaseProducts() {
appContext.getProductManager().removeListener(productManagerListener);
if (extraProduct != null && getSelectedProduct() != extraProduct) {
extraProduct.dispose();
}
extraProduct = null;
productListModel.removeAllElements();
}
public void addSelectionChangeListener(SelectionChangeListener listener) {
selectionContext.addSelectionChangeListener(listener);
}
public void removeSelectionChangeListener(SelectionChangeListener listener) {
selectionContext.removeSelectionChangeListener(listener);
}
private void addProduct(Product product) {
if (productFilter.accept(product)) {
productListModel.addElement(product);
}
}
// UI Components
/////////////////////////////////////
public JComboBox<Object> getProductNameComboBox() {
return productNameComboBox;
}
public JLabel getProductNameLabel() {
return productNameLabel;
}
public JButton getProductFileChooserButton() {
return productFileChooserButton;
}
private boolean productListModelContains(Product product) {
for (int i = 0; i < productListModel.getSize(); i++) {
Object listProduct = productListModel.getElementAt(i);
if (listProduct == null) {
continue;
}
if (listProduct.equals(product)) {
return true;
}
}
return false;
}
public JPanel createDefaultPanel() {
return createDefaultPanel("Source Product");
}
public JPanel createDefaultPanel(String borderTitle) {
final JPanel subPanel = new JPanel(new BorderLayout(3, 3));
subPanel.add(getProductNameComboBox(), BorderLayout.CENTER);
subPanel.add(getProductFileChooserButton(), BorderLayout.EAST);
final TableLayout tableLayout = new TableLayout(1);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setTableWeightX(1.0);
tableLayout.setRowFill(0, TableLayout.Fill.HORIZONTAL);
tableLayout.setRowFill(1, TableLayout.Fill.HORIZONTAL);
tableLayout.setTablePadding(3, 3);
JPanel panel = new JPanel(tableLayout);
panel.add(getProductNameLabel());
panel.add(subPanel);
if (StringUtils.isNotNullAndNotEmpty(borderTitle)) {
panel.setBorder(BorderFactory.createTitledBorder(borderTitle));
panel.add(tableLayout.createVerticalSpacer());
}
return panel;
}
private class ProductFileChooserAction extends AbstractAction {
private String APPROVE_BUTTON_TEXT = "Select";
private JFileChooser chooser;
private ProductFileChooserAction() {
super("...");
chooser = new SnapFileChooser();
chooser.setDialogTitle("Select Source Product");
final Iterator<ProductReaderPlugIn> iterator = ProductIOPlugInManager.getInstance().getAllReaderPlugIns();
List<SnapFileFilter> sortedFileFilters = SnapFileFilter.getSortedFileFilters(iterator);
for (SnapFileFilter fileFilter : sortedFileFilters) {
chooser.addChoosableFileFilter(fileFilter);
}
chooser.setAcceptAllFileFilterUsed(true);
chooser.setFileFilter(chooser.getAcceptAllFileFilter());
}
@Override
public void actionPerformed(ActionEvent event) {
final Window window = SwingUtilities.getWindowAncestor((JComponent) event.getSource());
String homeDirPath = SystemUtils.getUserHomeDir().getPath();
String openDir = appContext.getPreferences().getPropertyString(OpenProductAction.PREFERENCES_KEY_LAST_PRODUCT_DIR,
homeDirPath);
currentDirectory = new File(openDir);
chooser.setCurrentDirectory(currentDirectory);
if (chooser.showDialog(window, APPROVE_BUTTON_TEXT) == JFileChooser.APPROVE_OPTION) {
SwingWorker cursorWorker = new CursorWorker(window, chooser);
cursorWorker.execute();
currentDirectory = chooser.getCurrentDirectory();
appContext.getPreferences().setPropertyString(OpenProductAction.PREFERENCES_KEY_LAST_PRODUCT_DIR,
currentDirectory.getAbsolutePath());
}
}
}
private class CursorWorker extends SwingWorker<Product, Void> {
private final Component window;
private final JFileChooser chooser;
private Cursor defaultCursor;
private File file;
public CursorWorker(Component window, JFileChooser chooser) {
this.window = window;
this.chooser = chooser;
}
@Override
protected Product doInBackground() throws Exception {
Product product = null;
try {
defaultCursor = window.getCursor();
window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
file = chooser.getSelectedFile();
product = ProductIO.readProduct(file);
} catch (IOException e) {
handleError(e.getMessage());
}
return product;
}
@Override
protected void done() {
Product product = null;
try {
product = get();
if (product == null) {
throw new IOException(MessageFormat.format("File ''{0}'' could not be read.", this.file.getPath()));
}
if (productFilter.accept(product)) {
setSelectedProduct(product);
} else {
final String message = String.format("Product [%s] is not a valid source.",
product.getFileLocation().getCanonicalPath());
handleError(message);
product.dispose();
}
} catch (InterruptedException | IOException | ExecutionException e) {
if (product != null) {
product.dispose();
}
handleError(e.getMessage());
e.printStackTrace();
} finally {
window.setCursor(defaultCursor);
}
}
private void handleError(final String message) {
SwingUtilities.invokeLater(() -> {
AbstractDialog.showWarningDialog(window, message, "Error");
});
}
}
private static class ProductListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
final Component cellRendererComponent =
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (cellRendererComponent instanceof JLabel) {
final JLabel label = (JLabel) cellRendererComponent;
if (value instanceof Product) {
final Product product = (Product) value;
label.setText(product.getDisplayName());
} else {
label.setText(" ");
}
}
return cellRendererComponent;
}
}
/**
* To let the popup menu be wider than the closed combobox.
* Adapted an idea from http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6257236
*/
private static class ProductPopupMenuListener implements PopupMenuListener {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
JComboBox box = (JComboBox) e.getSource();
Object comp = box.getUI().getAccessibleChild(box, 0);
if (!(comp instanceof JPopupMenu)) {
return;
}
JComponent scrollPane = (JComponent) ((JPopupMenu) comp).getComponent(0);
Dimension size = new Dimension();
size.width = scrollPane.getPreferredSize().width;
final int boxItemCount = box.getModel().getSize();
for (int i = 0; i < boxItemCount; i++) {
final JLabel label = new JLabel();
Object elementAt = box.getModel().getElementAt(i);
if (elementAt != null && elementAt instanceof Product) {
label.setText(((Product) elementAt).getDisplayName());
}
size.width = Math.max(label.getPreferredSize().width, size.width);
}
size.height = scrollPane.getPreferredSize().height;
scrollPane.setPreferredSize(size);
scrollPane.setMaximumSize(size);
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
}
}
| 17,926 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultIOParametersPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/DefaultIOParametersPanel.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.swing.TableLayout;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductFilter;
import org.esa.snap.core.gpf.descriptor.OperatorDescriptor;
import org.esa.snap.core.gpf.descriptor.SourceProductDescriptor;
import org.esa.snap.ui.AppContext;
import javax.swing.*;
import java.util.ArrayList;
import java.util.HashMap;
/**
* WARNING: This class belongs to a preliminary API and may change in future releases.
*/
public class DefaultIOParametersPanel extends JPanel {
private final ArrayList<SourceProductSelector> sourceProductSelectorList;
private final HashMap<SourceProductDescriptor, SourceProductSelector> sourceProductSelectorMap;
private final AppContext appContext;
private final boolean targetProductSelectorDisplay;
public DefaultIOParametersPanel(AppContext appContext, OperatorDescriptor descriptor, TargetProductSelector targetProductSelector, boolean targetProductSelectorDisplay) {
this.appContext = appContext;
this.targetProductSelectorDisplay = targetProductSelectorDisplay;
sourceProductSelectorList = new ArrayList<>(3);
sourceProductSelectorMap = new HashMap<>(3);
// Fetch source products
createSourceProductSelectors(descriptor);
if (!sourceProductSelectorList.isEmpty()) {
setSourceProductSelectorLabels();
setSourceProductSelectorToolTipTexts();
}
final TableLayout tableLayout = new TableLayout(1);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setTableWeightX(1.0);
tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayout.setTablePadding(3, 3);
setLayout(tableLayout);
int countSPS = sourceProductSelectorList.size();
if (countSPS == 1) {
for (SourceProductSelector selector : sourceProductSelectorList) {
add(selector.createDefaultPanel());
}
} else {
final TableLayout tableLayoutSPS = new TableLayout(1);
tableLayoutSPS.setTableAnchor(TableLayout.Anchor.WEST);
tableLayoutSPS.setTableWeightX(1.0);
tableLayoutSPS.setTableFill(TableLayout.Fill.HORIZONTAL);
JPanel panel = new JPanel(tableLayoutSPS);
panel.setBorder(BorderFactory.createTitledBorder("Source Products"));
for (SourceProductSelector selector : sourceProductSelectorList) {
panel.add(selector.createDefaultPanel(""));
}
add(panel);
}
if (targetProductSelectorDisplay) {
add(targetProductSelector.createDefaultPanel());
}
add(tableLayout.createVerticalSpacer());
}
public DefaultIOParametersPanel(AppContext appContext, OperatorDescriptor descriptor, TargetProductSelector targetProductSelector) {
this(appContext, descriptor, targetProductSelector, true);
}
public boolean getTargetProductSelectorDisplay() {
return targetProductSelectorDisplay;
}
public ArrayList<SourceProductSelector> getSourceProductSelectorList() {
return sourceProductSelectorList;
}
public void initSourceProductSelectors() {
for (SourceProductSelector sourceProductSelector : sourceProductSelectorList) {
sourceProductSelector.initProducts();
}
}
public void releaseSourceProductSelectors() {
for (SourceProductSelector sourceProductSelector : sourceProductSelectorList) {
sourceProductSelector.releaseProducts();
}
}
public HashMap<String, Product> createSourceProductsMap() {
final HashMap<String, Product> sourceProducts = new HashMap<>(8);
for (SourceProductDescriptor descriptor : sourceProductSelectorMap.keySet()) {
final SourceProductSelector selector = sourceProductSelectorMap.get(descriptor);
String alias = descriptor.getAlias();
String key = alias != null ? alias : descriptor.getName();
sourceProducts.put(key, selector.getSelectedProduct());
}
return sourceProducts;
}
private void createSourceProductSelectors(OperatorDescriptor operatorDescriptor) {
for (SourceProductDescriptor descriptor : operatorDescriptor.getSourceProductDescriptors()) {
final ProductFilter productFilter = new AnnotatedSourceProductFilter(descriptor);
SourceProductSelector sourceProductSelector = new SourceProductSelector(appContext, descriptor.isOptional());
sourceProductSelector.setProductFilter(productFilter);
sourceProductSelectorList.add(sourceProductSelector);
sourceProductSelectorMap.put(descriptor, sourceProductSelector);
}
}
private void setSourceProductSelectorLabels() {
for (SourceProductDescriptor descriptor : sourceProductSelectorMap.keySet()) {
final SourceProductSelector selector = sourceProductSelectorMap.get(descriptor);
String label = descriptor.getLabel();
String alias = descriptor.getAlias();
if (label == null && alias != null) {
label = alias;
}
if (label == null) {
label = PropertyDescriptor.createDisplayName(descriptor.getName());
}
if (!label.endsWith(":")) {
label += ":";
}
if (descriptor.isOptional()) {
label += " (optional)";
}
selector.getProductNameLabel().setText(label);
}
}
private void setSourceProductSelectorToolTipTexts() {
for (SourceProductDescriptor descriptor : sourceProductSelectorMap.keySet()) {
final String description = descriptor.getDescription();
if (description != null) {
final SourceProductSelector selector = sourceProductSelectorMap.get(descriptor);
selector.getProductNameComboBox().setToolTipText(description);
}
}
}
private static class AnnotatedSourceProductFilter implements ProductFilter {
private final SourceProductDescriptor productDescriptor;
private AnnotatedSourceProductFilter(SourceProductDescriptor productDescriptor) {
this.productDescriptor = productDescriptor;
}
@Override
public boolean accept(Product product) {
String productType = productDescriptor.getProductType();
if (productType != null && !product.getProductType().matches(productType)) {
return false;
}
for (String bandName : productDescriptor.getBands()) {
if (!product.containsBand(bandName)) {
return false;
}
}
return true;
}
}
}
| 7,666 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultOperatorAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/DefaultOperatorAction.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.ui.ModelessDialog;
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* <p><b>WARNING:</b> This class belongs to a preliminary API and may change in future releases.<p>
* <p>An action which creates a default dialog for an operator given by the
* action property action property {@code operatorName}.</p>
* <p>Optionally the dialog title can be set via the {@code dialogTitle} property and
* the ID of the help page can be given using the {@code helpId} property. If not given the
* name of the operator will be used instead. Also optional the
* file name suffix for the target product can be given via the {@code targetProductNameSuffix} property.</p>
*
* @author Norman Fomferra
* @author Marco Zuehlke
*/
public class DefaultOperatorAction extends AbstractSnapAction {
private static final Set<String> KNOWN_KEYS = new HashSet<>(Arrays.asList("displayName", "operatorName", "dialogTitle", "helpId", "targetProductNameSuffix"));
private ModelessDialog dialog;
public static DefaultOperatorAction create(Map<String, Object> properties) {
DefaultOperatorAction action = new DefaultOperatorAction();
for (Map.Entry<String, Object> entry : properties.entrySet()) {
if (KNOWN_KEYS.contains(entry.getKey())) {
action.putValue(entry.getKey(), entry.getValue());
}
}
return action;
}
public String getOperatorName() {
Object value = getValue("operatorName");
if (value instanceof String) {
return (String) value;
}
return null;
}
public void setOperatorName(String operatorName) {
putValue("operatorName", operatorName);
}
public String getDialogTitle() {
Object value = getValue("dialogTitle");
if (value instanceof String) {
return (String) value;
}
return null;
}
public void setDialogTitle(String dialogTitle) {
putValue("dialogTitle", dialogTitle);
}
public String getTargetProductNameSuffix() {
Object value = getValue("targetProductNameSuffix");
if (value instanceof String) {
return (String) value;
}
return null;
}
public void setTargetProductNameSuffix(String targetProductNameSuffix) {
putValue("targetProductNameSuffix", targetProductNameSuffix);
}
@Override
public void actionPerformed(ActionEvent e) {
if (dialog == null) {
dialog = createOperatorDialog();
}
dialog.show();
}
protected ModelessDialog createOperatorDialog() {
DefaultSingleTargetProductDialog productDialog = new DefaultSingleTargetProductDialog(getOperatorName(), getAppContext(),
getDialogTitle(), getHelpId());
if (getTargetProductNameSuffix() != null) {
productDialog.setTargetProductNameSuffix(getTargetProductNameSuffix());
}
return productDialog;
}
}
| 3,954 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TargetProductSelectorModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/TargetProductSelectorModel.java | /*
* Copyright (C) 2014 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui;
import 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.binding.validators.NotNullValidator;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.dataio.ProductIOPlugInManager;
import org.esa.snap.core.dataio.ProductWriterPlugIn;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.core.util.io.FileUtils;
import java.io.File;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Iterator;
/**
* WARNING: This class belongs to a preliminary API and may change in future releases.
*
* @author Ralf Quast
* @version $Revision$ $Date$
*/
@SuppressWarnings({"UnusedDeclaration"})
public class TargetProductSelectorModel {
public static final String PROPERTY_PRODUCT_NAME = "productName";
public static final String PROPERTY_SAVE_TO_FILE_SELECTED = "saveToFileSelected";
public static final String PROEPRTY_OPEN_IN_APP_SELECTED = "openInAppSelected";
public static final String PROPERTY_PRODUCT_DIR = "productDir";
public static final String PROPERTY_FORMAT_NAME = "formatName";
private static final String ENVISAT_FORMAT_NAME = "ENVISAT";
// used by object binding
private String productName;
private boolean saveToFileSelected;
private boolean openInAppSelected;
private File productDir;
private String formatName;
private String[] formatNames;
private final PropertyContainer propertyContainer;
public TargetProductSelectorModel() {
this(ProductIOPlugInManager.getInstance().getAllProductWriterFormatStrings());
}
public TargetProductSelectorModel(String[] formatNames) {
propertyContainer = PropertyContainer.createObjectBacked(this);
PropertyDescriptor productNameDescriptor = propertyContainer.getDescriptor(PROPERTY_PRODUCT_NAME);
productNameDescriptor.setValidator(new ProductNameValidator());
productNameDescriptor.setDisplayName("target product name");
PropertyDescriptor productDirDescriptor = propertyContainer.getDescriptor("productDir");
productDirDescriptor.setValidator(new NotNullValidator());
productDirDescriptor.setDisplayName("target product directory");
setOpenInAppSelected(true);
setSaveToFileSelected(true);
this.formatNames = formatNames;
if (StringUtils.contains(this.formatNames, ProductIO.DEFAULT_FORMAT_NAME)) {
setFormatName(ProductIO.DEFAULT_FORMAT_NAME);
} else {
setFormatName(formatNames[0]);
}
propertyContainer.addPropertyChangeListener(evt -> {
String propertyName = evt.getPropertyName();
switch (propertyName) {
case "saveToFileSelected": {
boolean changesToDeselected = !(Boolean) evt.getNewValue();
if (changesToDeselected) {
setOpenInAppSelected(true);
} else if (!canReadOutputFormat()) {
setOpenInAppSelected(false);
}
break;
}
case "openInAppSelected": {
boolean changesToDeselected = !(Boolean) evt.getNewValue();
if (changesToDeselected) {
setSaveToFileSelected(true);
}
break;
}
case "formatName":
if (!canReadOutputFormat()) {
setOpenInAppSelected(false);
}
break;
}
});
}
public static TargetProductSelectorModel createEnvisatTargetProductSelectorModel() {
return new EnvisatTargetProductSelectorModel();
}
public String getProductName() {
return productName;
}
public boolean isSaveToFileSelected() {
return saveToFileSelected;
}
public boolean isOpenInAppSelected() {
return openInAppSelected;
}
public File getProductDir() {
return productDir;
}
public File getProductFile() {
return new File(productDir, getProductFileName());
}
String getProductFileName() {
String productFileName = productName;
Iterator<ProductWriterPlugIn> iterator = ProductIOPlugInManager.getInstance().getWriterPlugIns(formatName);
if (iterator.hasNext()) {
final ProductWriterPlugIn writerPlugIn = iterator.next();
boolean ok = false;
for (String extension : writerPlugIn.getDefaultFileExtensions()) {
if (productFileName.endsWith(extension)) {
ok = true;
break;
}
}
if (!ok) {
productFileName = productFileName.concat(writerPlugIn.getDefaultFileExtensions()[0]);
}
}
return productFileName;
}
public String getFormatName() {
return formatName;
}
public String[] getFormatNames() {
return formatNames;
}
public boolean canReadOutputFormat() {
return ProductIOPlugInManager.getInstance().getReaderPlugIns(formatName).hasNext();
}
public void setProductName(String productName) {
setPropertyContainerValue(PROPERTY_PRODUCT_NAME, productName);
}
public void setSaveToFileSelected(boolean saveToFileSelected) {
setPropertyContainerValue(PROPERTY_SAVE_TO_FILE_SELECTED, saveToFileSelected);
}
public void setOpenInAppSelected(boolean openInAppSelected) {
setPropertyContainerValue(PROEPRTY_OPEN_IN_APP_SELECTED, openInAppSelected);
}
public void setProductDir(File productDir) {
setPropertyContainerValue(PROPERTY_PRODUCT_DIR, productDir);
}
public void setFormatName(String formatName) {
setPropertyContainerValue(PROPERTY_FORMAT_NAME, formatName);
}
public PropertyContainer getValueContainer() {
return propertyContainer;
}
private void setPropertyContainerValue(String name, Object value) {
propertyContainer.setValue(name, value);
}
private static class ProductNameValidator implements Validator {
@Override
public void validateValue(Property property, Object value) throws ValidationException {
final String name = (String) value;
if (!ProductNode.isValidNodeName(name)) {
final String message = MessageFormat.format("The product name ''{0}'' is not valid.\n\n"
+ "Names must not start with a dot and must not\n"
+ "contain any of the following characters: \\/:*?\"<>|",
name);
throw new ValidationException(message);
}
}
}
public static class EnvisatTargetProductSelectorModel extends TargetProductSelectorModel {
private EnvisatTargetProductSelectorModel() {
super(createFormats());
}
@Override
public File getProductFile() {
if (!ENVISAT_FORMAT_NAME.equals(getFormatName())) {
return super.getProductFile();
}
final String productName = getProductName();
return new File(getProductDir(), FileUtils.ensureExtension(productName, ".N1"));
}
private static String[] createFormats() {
final String[] productWriterFormatStrings = ProductIOPlugInManager.getInstance().getAllProductWriterFormatStrings();
final String[] formatNames = Arrays.copyOf(productWriterFormatStrings,
productWriterFormatStrings.length + 1);
formatNames[formatNames.length - 1] = ENVISAT_FORMAT_NAME;
return formatNames;
}
}
}
| 8,864 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CollocationCrsForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/CollocationCrsForm.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui;
import com.bc.ceres.swing.selection.AbstractSelectionChangeListener;
import com.bc.ceres.swing.selection.SelectionChangeEvent;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.util.GeoUtils;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.crs.CrsForm;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.GeneralPath;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* @author Marco Peters
* @since BEAM 4.7
*/
public class CollocationCrsForm extends CrsForm {
private SourceProductSelector collocateProductSelector;
public CollocationCrsForm(AppContext appContext) {
super(appContext);
}
@Override
protected String getLabelText() {
return "Use CRS of";
}
@Override
public CoordinateReferenceSystem getCRS(GeoPos referencePos) {
Product collocationProduct = collocateProductSelector.getSelectedProduct();
if (collocationProduct != null) {
return collocationProduct.getSceneGeoCoding().getMapCRS();
}
return null;
}
@Override
protected JRadioButton createRadioButton() {
final JRadioButton button = super.createRadioButton();
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final boolean collocate = button.isSelected();
getCrsUI().firePropertyChange("collocate", !collocate, collocate);
}
});
return button;
}
@Override
public void prepareShow() {
collocateProductSelector.initProducts();
}
@Override
public void prepareHide() {
collocateProductSelector.releaseProducts();
}
@Override
protected JComponent createCrsComponent() {
collocateProductSelector = new SourceProductSelector(getAppContext(), "Product:");
collocateProductSelector.setProductFilter(new CollocateProductFilter());
collocateProductSelector.addSelectionChangeListener(new AbstractSelectionChangeListener() {
@Override
public void selectionChanged(SelectionChangeEvent event) {
fireCrsChanged();
}
});
final JPanel panel = new JPanel(new BorderLayout(2, 2));
panel.add(collocateProductSelector.getProductNameComboBox(), BorderLayout.CENTER);
panel.add(collocateProductSelector.getProductFileChooserButton(), BorderLayout.EAST);
panel.addPropertyChangeListener("enabled", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
collocateProductSelector.getProductNameComboBox().setEnabled(panel.isEnabled());
collocateProductSelector.getProductFileChooserButton().setEnabled(panel.isEnabled());
final boolean collocate = getRadioButton().isSelected();
getCrsUI().firePropertyChange("collocate", !collocate, collocate);
}
});
return panel;
}
public Product getCollocationProduct() {
return collocateProductSelector.getSelectedProduct();
}
private class CollocateProductFilter implements ProductFilter {
@Override
public boolean accept(Product collocationProduct) {
final Product referenceProduct = getReferenceProduct();
if (referenceProduct == collocationProduct ||
collocationProduct.getSceneGeoCoding() == null) {
return false;
}
if (referenceProduct == null) {
return true;
}
final GeoCoding geoCoding = collocationProduct.getSceneGeoCoding();
if (geoCoding.canGetGeoPos() && geoCoding.canGetPixelPos() && (geoCoding instanceof CrsGeoCoding)) {
final GeneralPath[] sourcePath = GeoUtils.createGeoBoundaryPaths(referenceProduct);
final GeneralPath[] collocationPath = GeoUtils.createGeoBoundaryPaths(collocationProduct);
for (GeneralPath path : sourcePath) {
Rectangle bounds = path.getBounds();
for (GeneralPath colPath : collocationPath) {
if (colPath.getBounds().intersects(bounds)) {
return true;
}
}
}
}
return false;
}
}
}
| 5,373 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TargetProductSelector.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/TargetProductSelector.java | /*
* Copyright (C) 2014 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import org.esa.snap.ui.FileChooserFactory;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
/**
* WARNING: This class belongs to a preliminary API and may change in future releases.
*
* @author Ralf Quast
* @version $Revision$ $Date$
*/
public class TargetProductSelector {
private JLabel productNameLabel;
private JTextField productNameTextField;
private JCheckBox saveToFileCheckBox;
private JLabel saveToFileLabel;
private JLabel productDirLabel;
private JTextField productDirTextField;
private JButton productDirChooserButton;
private JComboBox<String> formatNameComboBox;
private JCheckBox openInAppCheckBox;
private TargetProductSelectorModel model;
private final boolean alwaysWriteOutput;
public TargetProductSelector() {
this(new TargetProductSelectorModel(), false);
}
public TargetProductSelector(TargetProductSelectorModel model) {
this(model, false);
}
public TargetProductSelector(TargetProductSelectorModel model, boolean alwaysWriteOutput) {
this.model = model;
this.alwaysWriteOutput = alwaysWriteOutput;
initComponents();
bindComponents();
updateUIState();
}
private void initComponents() {
productNameLabel = new JLabel("Name: ");
productNameTextField = new JTextField(25);
productDirLabel = new JLabel("Directory:");
productDirTextField = new JTextField(25);
productDirChooserButton = new JButton(new ProductDirChooserAction());
final Dimension size = new Dimension(26, 16);
productDirChooserButton.setPreferredSize(size);
productDirChooserButton.setMinimumSize(size);
if (!alwaysWriteOutput) {
saveToFileCheckBox = new JCheckBox("Save as:");
formatNameComboBox = new JComboBox<>(model.getFormatNames());
openInAppCheckBox = new JCheckBox("Open in application");
} else {
saveToFileLabel = new JLabel("Save as: ");
formatNameComboBox = new JComboBox<>(model.getFormatNames());
}
}
private void bindComponents() {
final BindingContext bc = new BindingContext(model.getValueContainer());
bc.bind("productName", productNameTextField);
bc.bind("productDir", productDirTextField);
if (!alwaysWriteOutput) {
bc.bind("saveToFileSelected", saveToFileCheckBox);
bc.bind("openInAppSelected", openInAppCheckBox);
bc.bind("formatName", formatNameComboBox);
} else {
bc.bind("formatName", formatNameComboBox);
}
model.getValueContainer().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if (propertyName.equals(TargetProductSelectorModel.PROPERTY_PRODUCT_DIR)) {
productDirTextField.setToolTipText(model.getProductDir().getPath());
} else {
updateUIState();
}
}
});
}
public TargetProductSelectorModel getModel() {
return model;
}
public JLabel getProductNameLabel() {
return productNameLabel;
}
public JTextField getProductNameTextField() {
return productNameTextField;
}
public JCheckBox getSaveToFileCheckBox() {
return saveToFileCheckBox;
}
public JLabel getSaveToFileLabel() {
return saveToFileLabel;
}
public JLabel getProductDirLabel() {
return productDirLabel;
}
public JTextField getProductDirTextField() {
return productDirTextField;
}
public JButton getProductDirChooserButton() {
return productDirChooserButton;
}
public JComboBox<String> getFormatNameComboBox() {
return formatNameComboBox;
}
public JCheckBox getOpenInAppCheckBox() {
return openInAppCheckBox;
}
public JPanel createDefaultPanel() {
final JPanel subPanel1 = new JPanel(new BorderLayout(3, 3));
subPanel1.add(getProductNameLabel(), BorderLayout.NORTH);
subPanel1.add(getProductNameTextField(), BorderLayout.CENTER);
JPanel subPanel2 = null;
if (!alwaysWriteOutput) {
subPanel2 = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
subPanel2.add(getSaveToFileCheckBox());
subPanel2.add(getFormatNameComboBox());
} else {
subPanel2 = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
subPanel2.add(getSaveToFileLabel());
subPanel2.add(getFormatNameComboBox());
}
final JPanel subPanel3 = new JPanel(new BorderLayout(3, 3));
subPanel3.add(getProductDirLabel(), BorderLayout.NORTH);
subPanel3.add(getProductDirTextField(), BorderLayout.CENTER);
subPanel3.add(getProductDirChooserButton(), BorderLayout.EAST);
final TableLayout tableLayout = new TableLayout(1);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayout.setTableWeightX(1.0);
tableLayout.setCellPadding(0, 0, new Insets(3, 3, 3, 3));
tableLayout.setCellPadding(1, 0, new Insets(3, 3, 3, 3));
tableLayout.setCellPadding(2, 0, new Insets(0, 24, 3, 3));
tableLayout.setCellPadding(3, 0, new Insets(3, 3, 3, 3));
final JPanel panel = new JPanel(tableLayout);
panel.setBorder(BorderFactory.createTitledBorder("Target Product"));
panel.add(subPanel1);
panel.add(subPanel2);
panel.add(subPanel3);
if (!alwaysWriteOutput) {
panel.add(getOpenInAppCheckBox());
}
return panel;
}
private void updateUIState() {
if (model.isSaveToFileSelected()) {
if (!alwaysWriteOutput) {
openInAppCheckBox.setEnabled(model.canReadOutputFormat());
formatNameComboBox.setEnabled(true);
} else {
formatNameComboBox.setEnabled(true);
}
productDirLabel.setEnabled(true);
productDirTextField.setEnabled(true);
productDirChooserButton.setEnabled(true);
} else {
if (!alwaysWriteOutput) {
openInAppCheckBox.setEnabled(true);
formatNameComboBox.setEnabled(false);
} else {
formatNameComboBox.setEnabled(false);
}
productDirLabel.setEnabled(false);
productDirTextField.setEnabled(false);
productDirChooserButton.setEnabled(false);
}
}
public void setEnabled(boolean enabled) {
productNameLabel.setEnabled(enabled);
if (!alwaysWriteOutput) {
saveToFileCheckBox.setEnabled(enabled);
formatNameComboBox.setEnabled(enabled);
openInAppCheckBox.setEnabled(enabled);
} else {
formatNameComboBox.setEnabled(enabled);
}
productNameTextField.setEnabled(enabled);
productDirLabel.setEnabled(enabled);
productDirTextField.setEnabled(enabled);
productDirChooserButton.setEnabled(enabled);
}
private class ProductDirChooserAction extends AbstractAction {
private static final String APPROVE_BUTTON_TEXT = "Select";
public ProductDirChooserAction() {
super("...");
}
@Override
public void actionPerformed(ActionEvent event) {
Window windowAncestor = null;
if (event.getSource() instanceof JComponent) {
JComponent eventSource = (JComponent) event.getSource();
windowAncestor = SwingUtilities.getWindowAncestor(eventSource);
}
final JFileChooser chooser = FileChooserFactory.getInstance().createDirChooser(model.getProductDir());
chooser.setDialogTitle("Select Target Directory");
if (chooser.showDialog(windowAncestor, APPROVE_BUTTON_TEXT) == JFileChooser.APPROVE_OPTION) {
final File selectedDir = chooser.getSelectedFile();
if (selectedDir != null) {
model.setProductDir(selectedDir);
} else {
model.setProductDir(new File("."));
}
}
}
}
}
| 9,866 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ResamplingRowModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/resample/ResamplingRowModel.java | package org.esa.snap.core.gpf.ui.resample;
import org.esa.snap.core.gpf.common.resample.BandResamplingPreset;
import org.netbeans.swing.outline.RowModel;
/**
* Created by obarrile on 22/04/2019.
*/
public class ResamplingRowModel implements RowModel {
BandResamplingPreset[] bandResamplingPresets;
BandsTreeModel myModel;
public ResamplingRowModel(BandResamplingPreset[] bandResamplingPresets, BandsTreeModel myModel) {
this.bandResamplingPresets = bandResamplingPresets;
this.myModel = myModel;
}
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
default:
assert false;
}
return null;
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int column) {
return column == 0 ? "Upsampling" : "Downsampling";
}
@Override
public Object getValueFor(Object node, int column) {
String stringNode = (String) node;
for(BandResamplingPreset bandResamplingPreset : bandResamplingPresets) {
if(bandResamplingPreset.getBandName().equals(stringNode)) {
if(column == 0) {
return bandResamplingPreset.getUpsamplingAlias();
}
if(column == 1) {
return bandResamplingPreset.getDownsamplingAlias();
}
}
}
return null;
}
@Override
public boolean isCellEditable(Object node, int column) {
return true;
}
@Override
public void setValueFor(Object node, int column, Object value) {
String stringNode = (String) node;
for(BandResamplingPreset bandResamplingPreset : bandResamplingPresets) {
if(bandResamplingPreset.getBandName().equals(stringNode)) {
if(column == 0) {
bandResamplingPreset.setUpsamplingAlias((String) value);
}
if(column == 1) {
bandResamplingPreset.setDownsamplingAlias((String) value);
}
}
}
//setValue to Children
int childCount = myModel.getChildCount(stringNode);
for ( int i = 0 ; i < childCount ; i++) {
setValueFor(myModel.getChild(stringNode,i),column, value);
}
}
} | 2,485 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ResamplingAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/resample/ResamplingAction.java | package org.esa.snap.core.gpf.ui.resample;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.Resampler;
import org.esa.snap.core.gpf.common.resample.ResamplingOp;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.ui.AppContext;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import org.openide.util.lookup.ServiceProvider;
import java.awt.event.ActionEvent;
/**
* Action to access the Resampling Op.
*
* @author Tonio Fincke
*/
@ActionID(category = "Operators", id = "org.esa.snap.core.gpf.ui.resample.ResamplingAction")
@ActionRegistration(displayName = "#CTL_ResamplingAction_Name")
@ActionReferences({@ActionReference(path = "Menu/Raster/Geometric", position = 20)})
@NbBundle.Messages({"CTL_ResamplingAction_Name=Resampling",
"CTL_ResamplingAction_Description=Uses the SNAP resampling op to resample all bands of a product to the same size.",
"CTL_ResamplingAction_OpName=Resampling Operator",
"CTL_ResamplingAction_Help=resampleAction"})
@ServiceProvider(service = Resampler.class)
public class ResamplingAction extends AbstractSnapAction implements Resampler {
@Override
public void actionPerformed(ActionEvent e) {
final Product product = SnapApp.getDefault().getSelectedProduct(SnapApp.SelectionSourceHint.AUTO);
resample(product, false);
}
@Override
public String getName() {
return Bundle.CTL_ResamplingAction_OpName();
}
@Override
public String getDescription() {
return Bundle.CTL_ResamplingAction_Description();
}
@Override
public boolean canResample(Product multiSizeProduct) {
return ResamplingOp.canBeApplied(multiSizeProduct);
}
@Override
public Product resample(Product multiSizeProduct) {
return resample(multiSizeProduct, true);
}
public Product resample(Product product, boolean modal) {
final AppContext appContext = SnapApp.getDefault().getAppContext();
final ResamplingDialog resamplingDialog = new ResamplingDialog(appContext, product, modal);
resamplingDialog.show();
return resamplingDialog.getTargetProduct();
}
}
| 2,356 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BandsTreeModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/resample/BandsTreeModel.java | package org.esa.snap.core.gpf.ui.resample;
import org.esa.snap.core.datamodel.Product;
import javax.swing.tree.TreeModel;
import java.util.ArrayList;
/**
* Created by obarrile on 22/04/2019.
*/
public class BandsTreeModel implements TreeModel {
private String[] productBandNames;
ArrayList<String> listGroups = new ArrayList<>();
ArrayList<String> bandsWithoutGroup = new ArrayList<>();
private int totalRows;
private String[] rows;
public BandsTreeModel(Product product) {
this.productBandNames = product.getBandNames().clone();
if(product.getAutoGrouping()!= null) {
for (int i = 0 ; i < product.getAutoGrouping().size() ; i++) {
for(String bandName : product.getBandNames()) {
if (bandName.startsWith(product.getAutoGrouping().get(i)[0])) {
if(!listGroups.contains(product.getAutoGrouping().get(i)[0])) {
listGroups.add(product.getAutoGrouping().get(i)[0]);
}
}
}
}
for(String bandName : product.getBandNames()) {
boolean inGroup = false;
for (int i = 0 ; i < listGroups.size() ; i++) {
if (bandName.startsWith(listGroups.get(i))) {
inGroup = true;
break;
}
}
if(!inGroup) {
bandsWithoutGroup.add(bandName);
}
}
} else {
for(String bandName : product.getBandNames()) {
bandsWithoutGroup.add(bandName);
}
}
totalRows = 1 + listGroups.size() + product.getNumBands();
rows = new String[totalRows];
rows[0]=new String ("Bands");
for(int i = 0 ; i < listGroups.size() ; i++) {
rows[1+i] = new String(listGroups.get(i));
}
for(int i = 0 ; i < product.getNumBands() ; i++) {
rows[1+listGroups.size()+i] = new String(product.getBandAt(i).getName());
}
}
public int getTotalRows() {
return totalRows;
}
public String[] getRows() {
return rows;
}
@Override
public void addTreeModelListener(javax.swing.event.TreeModelListener l) {
//do nothing
}
@Override
public Object getChild(Object parent, int index) {
String parentString = (String) parent;
ArrayList<String> autogroupingBands = new ArrayList<>();
if(parentString.equals("Bands")) {
if (index < listGroups.size()) {
return listGroups.get(index);
} else {
return bandsWithoutGroup.get(index-listGroups.size());
}
}
for (int i = 0 ; i < listGroups.size() ; i++) {
if(listGroups.get(i).equals(parentString)) {
String[] bandNames = productBandNames;
ArrayList<String> autoGroupingBands = new ArrayList<>();
for(String bandName : bandNames) {
if(bandName.startsWith(parentString)) {
autoGroupingBands.add(bandName);
}
}
return autoGroupingBands.get(index);
}
}
return null;
}
@Override
public int getChildCount(Object parent) {
String parentString = (String) parent;
if(parentString.equals("Bands")) {
if(listGroups.size() == 0) {
return productBandNames.length;
} else {
return (bandsWithoutGroup.size() + listGroups.size());
}
}
for (int i = 0 ; i < listGroups.size() ; i++) {
if(listGroups.get(i).equals(parentString)) {
String[] bandNames = productBandNames;
ArrayList<String> autoGroupingBands = new ArrayList<>();
for(String bandName : bandNames) {
if(bandName.startsWith(parentString)) {
autoGroupingBands.add(bandName);
}
}
return autoGroupingBands.size();
}
}
return 0;
}
@Override
public int getIndexOfChild(Object parent, Object child) {
String parentString = (String) parent;
String childString = (String) child;
if(parentString.equals("Bands")) {
if(listGroups.size() == 0) {
String[] bands = productBandNames;
for(int i = 0 ; i < bands.length ; i++) {
if(bands[i].equals(childString)) {
return i;
}
}
} else {
for (int i = 0 ; i < listGroups.size() ; i++) {
if(listGroups.get(i).equals(child)) {
return i;
}
}
String[] bands = productBandNames;
for(int i = 0 ; i < bands.length ; i++) {
if(bands[i].equals(childString)) {
return (i+listGroups.size());
}
}
}
}
for (int i = 0 ; i < listGroups.size() ; i++) {
if(listGroups.get(i).equals(parentString)) {
String[] bandNames = productBandNames;
ArrayList<String> autoGroupingBands = new ArrayList<>();
for(String bandName : bandNames) {
if(bandName.startsWith(parentString)) {
autoGroupingBands.add(bandName);
}
}
return autoGroupingBands.indexOf(child);
}
}
return -1;
}
@Override
public Object getRoot() {
return "Bands";
}
@Override
public boolean isLeaf(Object node) {
String stringNode = (String) node;
String[] bandNames = productBandNames;
for(String bandName : bandNames) {
if(bandName.equals(stringNode)) {
return true;
}
}
return false;
}
@Override
public void removeTreeModelListener(javax.swing.event.TreeModelListener l) {
//do nothing
}
@Override
public void valueForPathChanged(javax.swing.tree.TreePath path, Object newValue) {
//do nothing
}
}
| 6,447 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ResamplingUtils.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/resample/ResamplingUtils.java | package org.esa.snap.core.gpf.ui.resample;
import org.esa.snap.core.gpf.GPF;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import java.util.Set;
/**
* Created by obarrile on 22/04/2019.
*/
public class ResamplingUtils {
public static String RESAMPLING_PRESET_FOLDER = "resampling_presets";
public static void setUpUpsamplingColumn(JTable table,
TableColumn upsamplingColumn, String defaultUpsampling) {
//Set up the editor for the upsampling
JComboBox comboBox = new JComboBox();
//TODO use registry when agreement with other teams. By the moment, they are available only the options in the old resampling
comboBox.addItem("Nearest");
comboBox.addItem("Bilinear");
comboBox.addItem("Bicubic");
if(defaultUpsampling != null) {
comboBox.setSelectedItem(defaultUpsampling);
}
upsamplingColumn.setCellEditor(new DefaultCellEditor(comboBox));
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
upsamplingColumn.setCellRenderer(renderer);
}
public static void setUpDownsamplingColumn(JTable table,
TableColumn downsamplingColumn, String defaultDownsampling) {
//Set up the editor for the downsampling
JComboBox comboBox = new JComboBox();
for ( String alias : (Set<String>) GPF.getDefaultInstance().getDownsamplerSpiRegistry().getAliases()) {
comboBox.addItem(alias);
}
if(defaultDownsampling != null) {
comboBox.setSelectedItem(defaultDownsampling);
}
downsamplingColumn.setCellEditor(new DefaultCellEditor(comboBox));
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
downsamplingColumn.setCellRenderer(renderer);
}
}
| 2,080 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ResamplingDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/resample/ResamplingDialog.java | package org.esa.snap.core.gpf.ui.resample;
import com.bc.ceres.binding.ConversionException;
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.ValueRange;
import com.bc.ceres.binding.ValueSet;
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.selection.AbstractSelectionChangeListener;
import com.bc.ceres.swing.selection.Selection;
import com.bc.ceres.swing.selection.SelectionChangeEvent;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.CrsGeoCoding;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNodeEvent;
import org.esa.snap.core.datamodel.ProductNodeGroup;
import org.esa.snap.core.datamodel.ProductNodeListener;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.datamodel.TiePointGrid;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.gpf.OperatorSpi;
import org.esa.snap.core.gpf.common.resample.BandResamplingPreset;
import org.esa.snap.core.gpf.common.resample.ResampleUtils;
import org.esa.snap.core.gpf.common.resample.ResamplingPreset;
import org.esa.snap.core.gpf.descriptor.OperatorDescriptor;
import org.esa.snap.core.gpf.ui.DefaultIOParametersPanel;
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.SourceProductSelector;
import org.esa.snap.core.gpf.ui.TargetProductSelectorModel;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.tango.TangoIcons;
import org.esa.snap.ui.AbstractDialog;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.SnapFileChooser;
import org.netbeans.swing.outline.DefaultOutlineModel;
import org.netbeans.swing.outline.Outline;
import org.netbeans.swing.outline.OutlineModel;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
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.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* @author Tonio Fincke
*/
class ResamplingDialog extends SingleTargetProductDialog {
private final String operatorName;
private final OperatorDescriptor operatorDescriptor;
private final String REFERENCE_BAND_TOOLTIP_TEXT = "<html>Set the reference band.<br/>" +
"All other bands will be resampled to match its size and resolution.</html>";
private final String TARGET_WIDTH_AND_HEIGHT_TOOLTIP_TEXT =
"<html>Set explicitly the width and height of the resampled product.<br/>" +
"This option is only available when all bands have the same offset.</html>";
private final String TARGET_RESOLUTION_TOOLTIP_TEXT = "<html>Define the target resolution of the resampled product.<br/>" +
"This option is only available for products with a geocoding based on a cartographic map CRS.</html>";
private static final String REFERENCE_BAND_NAME_PROPERTY_NAME = "referenceBandName";
private static final String TARGET_WIDTH_PROPERTY_NAME = "targetWidth";
private static final String TARGET_HEIGHT_PROPERTY_NAME = "targetHeight";
private static final String TARGET_RESOLUTION_PROPERTY_NAME = "targetResolution";
private static final int REFERENCE_BAND_NAME_PANEL_INDEX = 0;
private static final int TARGET_WIDTH_AND_HEIGHT_PANEL_INDEX = 1;
private static final int TARGET_RESOLUTION_PANEL_INDEX = 2;
private DefaultIOParametersPanel ioParametersPanel;
private final OperatorParameterSupport parameterSupport;
private final BindingContext bindingContext;
private JTabbedPane form;
private String targetProductNameSuffix;
private ProductChangedHandler productChangedHandler;
private Product targetProduct;
private JRadioButton referenceBandButton;
private JRadioButton widthAndHeightButton;
private JRadioButton resolutionButton;
private ReferenceBandNameBoxPanel referenceBandNameBoxPanel;
private TargetWidthAndHeightPanel targetWidthAndHeightPanel;
private TargetResolutionPanel targetResolutionPanel;
private JPanel advancedMethodDefinitionPanel;
private JPanel loadPresetPanel;
JCheckBox advancedMethodCheckBox;
JPanel upsamplingMethodPanel;
JPanel downsamplingMethodPanel;
JPanel flagDownsamplingMethodPanel;
private BandResamplingPreset[] bandResamplingPresets;
OutlineModel mdl = null;
Outline outline1 = null;
ResamplingRowModel resamplingRowModel;
ResamplingDialog(AppContext appContext, Product product, boolean modal) {
super(appContext, "Resampling", ID_APPLY_CLOSE, "resampleAction");
this.operatorName = "Resample";
targetProductNameSuffix = "_resampled";
getTargetProductSelector().getModel().setSaveToFileSelected(false);
getJDialog().setModal(modal);
OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(operatorName);
if (operatorSpi == null) {
throw new IllegalArgumentException("No SPI found for operator name '" + operatorName + "'");
}
operatorDescriptor = operatorSpi.getOperatorDescriptor();
ioParametersPanel = new DefaultIOParametersPanel(getAppContext(), operatorDescriptor, getTargetProductSelector(), true);
targetProduct = null;
parameterSupport = new OperatorParameterSupport(operatorDescriptor, null, null, new ResamplingParameterUpdater());
final ArrayList<SourceProductSelector> sourceProductSelectorList = ioParametersPanel.getSourceProductSelectorList();
final PropertySet propertySet = parameterSupport.getPropertySet();
bindingContext = new BindingContext(propertySet);
final Property referenceBandNameProperty = bindingContext.getPropertySet().getProperty(REFERENCE_BAND_NAME_PROPERTY_NAME);
referenceBandNameProperty.getDescriptor().addAttributeChangeListener(evt -> {
if (evt.getPropertyName().equals("valueSet")) {
final Object[] valueSetItems = ((ValueSet) evt.getNewValue()).getItems();
if (valueSetItems.length > 0) {
try {
referenceBandNameProperty.setValue(valueSetItems[0].toString());
} catch (ValidationException e) {
//don't set it then
}
}
}
});
final ValueRange valueRange = new ValueRange(0, Integer.MAX_VALUE);
bindingContext.getPropertySet().getProperty(TARGET_WIDTH_PROPERTY_NAME).getDescriptor().setValueRange(valueRange);
bindingContext.getPropertySet().getProperty(TARGET_HEIGHT_PROPERTY_NAME).getDescriptor().setValueRange(valueRange);
bindingContext.getPropertySet().getProperty(TARGET_RESOLUTION_PROPERTY_NAME).getDescriptor().setValueRange(valueRange);
productChangedHandler = new ProductChangedHandler();
sourceProductSelectorList.get(0).initProducts();
sourceProductSelectorList.get(0).setSelectedProduct(product);
sourceProductSelectorList.get(0).addSelectionChangeListener(productChangedHandler);
}
@Override
public int show() {
if (form == null) {
initForm();
if (getJDialog().getJMenuBar() == null) {
final OperatorMenu operatorMenu = createDefaultMenuBar();
getJDialog().setJMenuBar(operatorMenu.createDefaultMenu());
}
}
ioParametersPanel.initSourceProductSelectors();
setContent(form);
return super.show();
}
@Override
public void hide() {
productChangedHandler.releaseProduct();
ioParametersPanel.releaseSourceProductSelectors();
super.hide();
}
@Override
protected void onApply() {
super.onApply();
if (targetProduct != null && getJDialog().isModal()) {
close();
}
}
@Override
protected Product createTargetProduct() throws Exception {
final HashMap<String, Product> sourceProducts = ioParametersPanel.createSourceProductsMap();
final HashMap<String, Object> resampParams = new HashMap<>();
if(referenceBandButton.isSelected()) {
resampParams.put("referenceBandName", referenceBandNameBoxPanel.getSelectedReferenceBand());
} else if (widthAndHeightButton.isSelected()) {
resampParams.put("targetWidth", targetWidthAndHeightPanel.getWidthSelected());
resampParams.put("targetHeight", targetWidthAndHeightPanel.getHeightSelected());
} else if (resolutionButton.isSelected()) {
resampParams.put("targetResolution", targetResolutionPanel.getResolutionSelected());
}
resampParams.put("upsamplingMethod", parameterSupport.getParameterMap().get("upsamplingMethod"));
resampParams.put("downsamplingMethod", parameterSupport.getParameterMap().get("downsamplingMethod"));
resampParams.put("flagDownsamplingMethod", parameterSupport.getParameterMap().get("flagDownsamplingMethod"));
if(advancedMethodCheckBox.isSelected()) {
resampParams.put("bandResamplings", generateBandResamplings(sourceProducts.get("sourceProduct")));
}
resampParams.put("resampleOnPyramidLevels", parameterSupport.getParameterMap().get("resampleOnPyramidLevels"));
targetProduct = GPF.createProduct(operatorName, resampParams, sourceProducts);
return targetProduct;
}
private String generateBandResamplings(Product sourceProduct) {
updateResamplingPreset();
String bandResamplingsString = "";
for(String bandName : sourceProduct.getBandNames()) {
for(BandResamplingPreset bandResamplingPreset : bandResamplingPresets) {
if(bandResamplingPreset.getBandName().equals(bandName)){
if(!bandResamplingsString.isEmpty()) {
bandResamplingsString = bandResamplingsString + ResamplingPreset.STRING_SEPARATOR;
}
bandResamplingsString = bandResamplingsString + bandResamplingPreset.getBandName() + BandResamplingPreset.SEPARATOR
+ bandResamplingPreset.getDownsamplingAlias() + BandResamplingPreset.SEPARATOR + bandResamplingPreset.getUpsamplingAlias();
}
}
}
return bandResamplingsString;
}
Product getTargetProduct() {
return targetProduct;
}
private void initForm() {
form = new JTabbedPane();
form.add("I/O Parameters", ioParametersPanel);
form.add("Resampling Parameters", new JScrollPane(createParametersPanel()));
reactToSourceProductChange(ioParametersPanel.getSourceProductSelectorList().get(0).getSelectedProduct());
}
private JPanel createParametersPanel() {
final PropertyEditorRegistry registry = PropertyEditorRegistry.getInstance();
final PropertySet propertySet = bindingContext.getPropertySet();
final TableLayout tableLayout = new TableLayout(1);
tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST);
tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayout.setTableWeightX(1.0);
tableLayout.setTablePadding(4, 4);
final TableLayout defineTargetResolutionPanelLayout = new TableLayout(2);
defineTargetResolutionPanelLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST);
defineTargetResolutionPanelLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
defineTargetResolutionPanelLayout.setColumnWeightX(1, 1.0);
defineTargetResolutionPanelLayout.setTablePadding(4, 5);
final JPanel defineTargetSizePanel = new JPanel(defineTargetResolutionPanelLayout);
defineTargetSizePanel.setBorder(BorderFactory.createTitledBorder("Define size of resampled product"));
final ButtonGroup targetSizeButtonGroup = new ButtonGroup();
referenceBandButton = new JRadioButton("By reference band from source product:");
referenceBandButton.setToolTipText(REFERENCE_BAND_TOOLTIP_TEXT);
widthAndHeightButton = new JRadioButton("By target width and height:");
widthAndHeightButton.setToolTipText(TARGET_WIDTH_AND_HEIGHT_TOOLTIP_TEXT);
resolutionButton = new JRadioButton("By pixel resolution (in m):");
resolutionButton.setToolTipText(TARGET_RESOLUTION_TOOLTIP_TEXT);
targetSizeButtonGroup.add(referenceBandButton);
targetSizeButtonGroup.add(widthAndHeightButton);
targetSizeButtonGroup.add(resolutionButton);
defineTargetSizePanel.add(referenceBandButton);
referenceBandNameBoxPanel = new ReferenceBandNameBoxPanel();
defineTargetSizePanel.add(referenceBandNameBoxPanel);
defineTargetSizePanel.add(widthAndHeightButton);
targetWidthAndHeightPanel = new TargetWidthAndHeightPanel();
defineTargetSizePanel.add(targetWidthAndHeightPanel);
defineTargetSizePanel.add(resolutionButton);
targetResolutionPanel = new TargetResolutionPanel();
defineTargetSizePanel.add(targetResolutionPanel);
referenceBandButton.addActionListener(e -> {
if (referenceBandButton.isSelected()) {
enablePanel(REFERENCE_BAND_NAME_PANEL_INDEX);
}
});
widthAndHeightButton.addActionListener(e -> {
if (widthAndHeightButton.isSelected()) {
enablePanel(TARGET_WIDTH_AND_HEIGHT_PANEL_INDEX);
}
});
resolutionButton.addActionListener(e -> {
if (resolutionButton.isSelected()) {
enablePanel(TARGET_RESOLUTION_PANEL_INDEX);
}
});
referenceBandButton.setSelected(true);
final TableLayout tableLayoutMethodDefinition = new TableLayout(1);
tableLayoutMethodDefinition.setTableAnchor(TableLayout.Anchor.NORTHWEST);
tableLayoutMethodDefinition.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayoutMethodDefinition.setTableWeightX(1.0);
tableLayoutMethodDefinition.setTablePadding(4, 4);
JPanel methodDefinitionPanel = new JPanel(tableLayoutMethodDefinition);
methodDefinitionPanel.setBorder(BorderFactory.createTitledBorder("Define resampling algorithm"));
upsamplingMethodPanel = createPropertyPanel(propertySet, "upsamplingMethod", registry);
downsamplingMethodPanel = createPropertyPanel(propertySet, "downsamplingMethod", registry);
flagDownsamplingMethodPanel = createPropertyPanel(propertySet, "flagDownsamplingMethod", registry);
//Create advancedMethodDefinitionPanel
advancedMethodDefinitionPanel = createAdvancedMethodDefinitionPanel();
//Create load preset panel
loadPresetPanel = createLoadSavePresetPanel();
methodDefinitionPanel.add(upsamplingMethodPanel);
methodDefinitionPanel.add(tableLayout.createVerticalSpacer());
methodDefinitionPanel.add(downsamplingMethodPanel);
methodDefinitionPanel.add(tableLayout.createVerticalSpacer());
methodDefinitionPanel.add(flagDownsamplingMethodPanel);
methodDefinitionPanel.add(tableLayout.createVerticalSpacer());
methodDefinitionPanel.add(createAdvancedCheckBoxPanel());
methodDefinitionPanel.add(advancedMethodDefinitionPanel);
methodDefinitionPanel.add(loadPresetPanel);
final JPanel resampleOnPyramidLevelsPanel = createPropertyPanel(propertySet, "resampleOnPyramidLevels", registry);
//Add all panels
final JPanel parametersPanel = new JPanel(tableLayout);
parametersPanel.setBorder(new EmptyBorder(4, 4, 4, 4));
parametersPanel.add(defineTargetSizePanel);
parametersPanel.add(methodDefinitionPanel);
parametersPanel.add(resampleOnPyramidLevelsPanel);
parametersPanel.add(tableLayout.createVerticalSpacer());
return parametersPanel;
}
private void enablePanel(int panelIndex) {
referenceBandNameBoxPanel.setEnabled(panelIndex == 0);
targetWidthAndHeightPanel.setEnabled(panelIndex == 1);
targetResolutionPanel.setEnabled(panelIndex == 2);
}
private JPanel createPropertyPanel(PropertySet propertySet, String propertyName, PropertyEditorRegistry registry) {
final PropertyDescriptor descriptor = propertySet.getProperty(propertyName).getDescriptor();
PropertyEditor propertyEditor = registry.findPropertyEditor(descriptor);
JComponent[] components = propertyEditor.createComponents(descriptor, bindingContext);
final JPanel propertyPanel = new JPanel(new GridLayout(1, components.length));
for (int i = components.length - 1; i >= 0; i--) {
propertyPanel.add(components[i]);
}
return propertyPanel;
}
private void setEnableRec(Component container, boolean enable){
container.setEnabled(enable);
try {
Component[] components= ((Container) container).getComponents();
for (int i = 0; i < components.length; i++) {
setEnableRec(components[i], enable);
}
} catch (ClassCastException e) {
}
}
private JPanel createAdvancedCheckBoxPanel() {
advancedMethodCheckBox = new JCheckBox("Advanced Method Definition by Band", false);
advancedMethodCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
advancedMethodDefinitionPanel.setVisible(true);
loadPresetPanel.setVisible(true);
setEnableRec(upsamplingMethodPanel,false);
setEnableRec(downsamplingMethodPanel,false);
setEnableRec(flagDownsamplingMethodPanel,false);
} else {
advancedMethodDefinitionPanel.setVisible(false);
loadPresetPanel.setVisible(false);
setEnableRec(upsamplingMethodPanel,true);
setEnableRec(downsamplingMethodPanel,true);
setEnableRec(flagDownsamplingMethodPanel,true);
}
}
});
final JPanel propertyPanel = new JPanel(new GridLayout(1, 1));
propertyPanel.add(advancedMethodCheckBox);
return propertyPanel;
}
private JPanel createAdvancedMethodDefinitionPanel() {
final TableLayout tableLayoutMethodDefinition = new TableLayout(1);
tableLayoutMethodDefinition.setTableAnchor(TableLayout.Anchor.NORTHWEST);
tableLayoutMethodDefinition.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayoutMethodDefinition.setTableWeightX(1.0);
tableLayoutMethodDefinition.setTablePadding(4, 4);
JPanel panel = new JPanel(tableLayoutMethodDefinition);
if(ioParametersPanel.getSourceProductSelectorList().get(0).getSelectedProduct() != null) {
BandsTreeModel myModel = new BandsTreeModel(ioParametersPanel.getSourceProductSelectorList().get(0).getSelectedProduct());
bandResamplingPresets = new BandResamplingPreset[myModel.getTotalRows()];
for(int i = 0 ; i < myModel.getTotalRows() ; i++) {
bandResamplingPresets[i] = new BandResamplingPreset(myModel.getRows()[i], (String) (parameterSupport.getParameterMap().get("downsamplingMethod")) , (String) (parameterSupport.getParameterMap().get("upsamplingMethod")));
}
resamplingRowModel = new ResamplingRowModel(bandResamplingPresets, myModel);
mdl = DefaultOutlineModel.createOutlineModel(
myModel, resamplingRowModel, true, "Bands");
outline1 = new Outline();
outline1.setRootVisible(false);
outline1.setModel(mdl);
ResamplingUtils.setUpUpsamplingColumn(outline1,outline1.getColumnModel().getColumn(1), (String) parameterSupport.getParameterMap().get("upsamplingMethod"));
ResamplingUtils.setUpDownsamplingColumn(outline1,outline1.getColumnModel().getColumn(2), (String) parameterSupport.getParameterMap().get("downsamplingMethod"));
JScrollPane tableContainer = new JScrollPane(outline1);
panel.add(tableContainer);
panel.setVisible(false);
}
return panel;
}
private JPanel createLoadSavePresetPanel() {
final TableLayout tableLayoutMethodDefinition = new TableLayout(2);
tableLayoutMethodDefinition.setTableAnchor(TableLayout.Anchor.NORTHWEST);
tableLayoutMethodDefinition.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayoutMethodDefinition.setTableWeightX(1.0);
tableLayoutMethodDefinition.setTablePadding(4, 4);
JPanel panel = new JPanel(tableLayoutMethodDefinition);
//Add Load preset button
final ImageIcon loadIcon = TangoIcons.actions_document_open(TangoIcons.Res.R22);
JButton loadButton = new JButton("Import Preset...", loadIcon);
loadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SnapFileChooser fileChooser = new SnapFileChooser(SystemUtils.getAuxDataPath().resolve(ResamplingUtils.RESAMPLING_PRESET_FOLDER).toFile());
fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.setDialogTitle("Select resampling preset");
SnapFileFilter fileFilter = new SnapFileFilter("ResPreset", ".res", "Resampling preset files");
fileChooser.addChoosableFileFilter(fileFilter);
fileChooser.setFileFilter(fileFilter);
fileChooser.setDialogType(SnapFileChooser.OPEN_DIALOG);
File selectedFile;
while (true) {
int i = fileChooser.showDialog(panel, null);
if (i == SnapFileChooser.APPROVE_OPTION) {
selectedFile = fileChooser.getSelectedFile();
try {
ResamplingPreset resamplingPreset = ResamplingPreset.loadResamplingPreset(selectedFile);
//check that bands corresponds with opened product
if(!resamplingPreset.isCompatibleWithProduct(ioParametersPanel.getSourceProductSelectorList().get(0).getSelectedProduct())) {
AbstractDialog.showWarningDialog(panel,
"Resampling preset incompatible with selected input product.",
"Resampling preset incompatibility");
break;
}
//TODO that check upsampling and resampling method exist
bandResamplingPresets = resamplingPreset.getBandResamplingPresets().toArray(new BandResamplingPreset[resamplingPreset.getBandResamplingPresets().size()]);
for(BandResamplingPreset bandResamplingPreset : resamplingPreset.getBandResamplingPresets()) {
resamplingRowModel.setValueFor(bandResamplingPreset.getBandName(),0,bandResamplingPreset.getUpsamplingAlias());
resamplingRowModel.setValueFor(bandResamplingPreset.getBandName(),1,bandResamplingPreset.getDownsamplingAlias());
advancedMethodDefinitionPanel.repaint();
}
} catch (IOException e1) {
AbstractDialog.showWarningDialog(panel,
"Cannot load resampling preset.",
"Cannot load resampling preset.");
}
break;
} else {
// Canceled
selectedFile = null;
break;
}
}
}
});
panel.add(loadButton);
//Add Save preset button
final ImageIcon saveIcon = TangoIcons.actions_document_save_as(TangoIcons.Res.R22);
JButton saveButton = new JButton("Save Preset", saveIcon);
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SnapFileChooser fileChooser = new SnapFileChooser(SystemUtils.getAuxDataPath().resolve(ResamplingUtils.RESAMPLING_PRESET_FOLDER).toFile());
fileChooser.setAcceptAllFileFilterUsed(true);
fileChooser.setDialogTitle("Select resampling preset");
SnapFileFilter fileFilter = new SnapFileFilter("ResPreset", ".res", "Resampling preset files");
fileChooser.addChoosableFileFilter(fileFilter);
fileChooser.setFileFilter(fileFilter);
fileChooser.setDialogType(SnapFileChooser.SAVE_DIALOG);
File selectedFile;
while (true) {
int i = fileChooser.showDialog(panel, null);
if (i == SnapFileChooser.APPROVE_OPTION) {
selectedFile = fileChooser.getSelectedFile();
if (!selectedFile.exists()) {
break;
}
i = JOptionPane.showConfirmDialog(panel,
"The file\n" + selectedFile + "\nalready exists.\nOverwrite?",
"File exists", JOptionPane.YES_NO_CANCEL_OPTION);
if (i == JOptionPane.CANCEL_OPTION) {
// Canceled
selectedFile = null;
break;
} else if (i == JOptionPane.YES_OPTION) {
// Overwrite existing file
break;
}
} else {
// Canceled
selectedFile = null;
break;
}
}
if(selectedFile != null) {
//update BandResamplingPresets with values of table
updateResamplingPreset();
ResamplingPreset auxPreset = new ResamplingPreset(selectedFile.getName(),bandResamplingPresets);
auxPreset.saveToFile(selectedFile, ioParametersPanel.getSourceProductSelectorList().get(0).getSelectedProduct());
}
}
});
panel.add(saveButton);
panel.setVisible(false);
return panel;
}
private OperatorMenu createDefaultMenuBar() {
return new OperatorMenu(getJDialog(),
operatorDescriptor,
parameterSupport,
getAppContext(),
getHelpID());
}
private void reactToSourceProductChange(Product product) {
referenceBandNameBoxPanel.reactToSourceProductChange(product);
targetWidthAndHeightPanel.reactToSourceProductChange(product);
targetResolutionPanel.reactToSourceProductChange(product);
if (product != null) {
referenceBandButton.setEnabled(product.getBandNames().length > 0);
final ProductNodeGroup<Band> productBands = product.getBandGroup();
final ProductNodeGroup<TiePointGrid> productTiePointGrids = product.getTiePointGridGroup();
double xOffset = Double.NaN;
double yOffset = Double.NaN;
if (productBands.getNodeCount() > 0) {
xOffset = productBands.get(0).getImageToModelTransform().getTranslateX();
yOffset = productBands.get(0).getImageToModelTransform().getTranslateY();
} else if (productTiePointGrids.getNodeCount() > 0) {
xOffset = productTiePointGrids.get(0).getImageToModelTransform().getTranslateX();
yOffset = productTiePointGrids.get(0).getImageToModelTransform().getTranslateY();
}
boolean allowToSetWidthAndHeight = true;
if (!Double.isNaN(xOffset) && !Double.isNaN(yOffset)) {
allowToSetWidthAndHeight = allOffsetsAreEqual(productBands, xOffset, yOffset) &&
allOffsetsAreEqual(productTiePointGrids, xOffset, yOffset);
}
widthAndHeightButton.setEnabled(allowToSetWidthAndHeight);
final GeoCoding sceneGeoCoding = product.getSceneGeoCoding();
resolutionButton.setEnabled(sceneGeoCoding instanceof CrsGeoCoding &&
ResampleUtils.allGridsAlignAtUpperLeftPixel(product));
}
if (referenceBandButton.isEnabled()) {
referenceBandButton.setSelected(true);
referenceBandNameBoxPanel.setEnabled(true);
} else if (widthAndHeightButton.isEnabled()) {
widthAndHeightButton.setSelected(true);
} else if (resolutionButton.isEnabled()) {
resolutionButton.setSelected(true);
}
if(product != null) {
advancedMethodDefinitionPanel.removeAll();
BandsTreeModel myModel = new BandsTreeModel(product);
bandResamplingPresets = new BandResamplingPreset[myModel.getTotalRows()];
for(int i = 0 ; i < myModel.getTotalRows() ; i++) {
bandResamplingPresets[i] = new BandResamplingPreset(myModel.getRows()[i], (String) (parameterSupport.getParameterMap().get("downsamplingMethod")),(String) (parameterSupport.getParameterMap().get("upsamplingMethod")));
}
resamplingRowModel = new ResamplingRowModel(bandResamplingPresets, myModel);
//Create the Outline's model, consisting of the TreeModel and the RowModel
mdl = DefaultOutlineModel.createOutlineModel(
myModel, resamplingRowModel, true, "Products");
Outline outline1 = new Outline();
outline1.setRootVisible(false);
outline1.setModel(mdl);
ResamplingUtils.setUpUpsamplingColumn(outline1,outline1.getColumnModel().getColumn(1), (String) parameterSupport.getParameterMap().get("upsamplingMethod"));
ResamplingUtils.setUpDownsamplingColumn(outline1,outline1.getColumnModel().getColumn(2), (String) parameterSupport.getParameterMap().get("downsamplingMethod"));
JScrollPane tableContainer = new JScrollPane(outline1);
advancedMethodDefinitionPanel.add(tableContainer);
advancedMethodDefinitionPanel.revalidate();
advancedMethodDefinitionPanel.setVisible(advancedMethodCheckBox.isSelected());
}
}
private void updateResamplingPreset() {
if(bandResamplingPresets == null) {
return;
}
for (BandResamplingPreset bandResamplingPreset : bandResamplingPresets) {
bandResamplingPreset.setUpsamplingAlias((String) resamplingRowModel.getValueFor(bandResamplingPreset.getBandName(),0));
bandResamplingPreset.setDownsamplingAlias((String) resamplingRowModel.getValueFor(bandResamplingPreset.getBandName(),1));
}
}
private RasterDataNode getAnyRasterDataNode(Product product) {
RasterDataNode node = null;
if (product != null) {
final ProductNodeGroup<Band> bandGroup = product.getBandGroup();
if (bandGroup.getNodeCount() == 0) {
final ProductNodeGroup<TiePointGrid> tiePointGridGroup = product.getTiePointGridGroup();
if (tiePointGridGroup.getNodeCount() > 0) {
node = tiePointGridGroup.get(0);
}
} else {
node = bandGroup.get(0);
}
}
return node;
}
private boolean allOffsetsAreEqual(ProductNodeGroup productNodeGroup, double xOffset, double yOffset) {
for (int i = 0; i < productNodeGroup.getNodeCount(); i++) {
final double nodeXOffset = ((RasterDataNode) productNodeGroup.get(i)).getImageToModelTransform().getTranslateX();
final double nodeYOffset = ((RasterDataNode) productNodeGroup.get(i)).getImageToModelTransform().getTranslateY();
if (Math.abs(nodeXOffset - xOffset) > 1e-8 || Math.abs(nodeYOffset - yOffset) > 1e-8) {
return false;
}
}
return true;
}
private class TargetResolutionPanel extends JPanel {
private JSpinner resolutionSpinner;
private JLabel targetResolutionTargetWidthLabel;
private JLabel targetResolutionTargetHeightLabel;
private final JLabel targetResolutionTargetWidthNameLabel;
private final JLabel targetResolutionNameTargetHeightLabel;
TargetResolutionPanel() {
setToolTipText(TARGET_RESOLUTION_TOOLTIP_TEXT);
resolutionSpinner = new JSpinner(new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1));
resolutionSpinner.setEnabled(false);
resolutionSpinner.addChangeListener(e -> updateTargetResolution());
final GridLayout layout = new GridLayout(3, 1);
layout.setVgap(2);
setLayout(layout);
JPanel targetResolutionTargetWidthPanel = new JPanel(new GridLayout(1, 2));
targetResolutionTargetWidthNameLabel = new JLabel("Resulting target width: ");
targetResolutionTargetWidthNameLabel.setEnabled(false);
targetResolutionTargetWidthPanel.add(targetResolutionTargetWidthNameLabel);
targetResolutionTargetWidthLabel = new JLabel();
targetResolutionTargetWidthLabel.setEnabled(false);
targetResolutionTargetWidthPanel.add(targetResolutionTargetWidthLabel);
JPanel targetResolutionTargetHeightPanel = new JPanel(new GridLayout(1, 2));
targetResolutionNameTargetHeightLabel = new JLabel("Resulting target height: ");
targetResolutionNameTargetHeightLabel.setEnabled(false);
targetResolutionTargetHeightPanel.add(targetResolutionNameTargetHeightLabel);
targetResolutionTargetHeightLabel = new JLabel();
targetResolutionTargetHeightLabel.setEnabled(false);
targetResolutionTargetHeightPanel.add(targetResolutionTargetHeightLabel);
add(resolutionSpinner);
add(targetResolutionTargetWidthPanel);
add(targetResolutionTargetHeightPanel);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
resolutionSpinner.setEnabled(enabled);
targetResolutionTargetWidthLabel.setEnabled(enabled);
targetResolutionTargetHeightLabel.setEnabled(enabled);
targetResolutionTargetWidthNameLabel.setEnabled(enabled);
targetResolutionNameTargetHeightLabel.setEnabled(enabled);
if (enabled) {
updateTargetResolution();
}
}
private void updateTargetResolution() {
bindingContext.getPropertySet().setValue(REFERENCE_BAND_NAME_PROPERTY_NAME, null);
bindingContext.getPropertySet().setValue(TARGET_WIDTH_PROPERTY_NAME, null);
bindingContext.getPropertySet().setValue(TARGET_HEIGHT_PROPERTY_NAME, null);
bindingContext.getPropertySet().setValue(TARGET_RESOLUTION_PROPERTY_NAME, Integer.parseInt(resolutionSpinner.getValue().toString()));
updateTargetResolutionTargetWidthAndHeight();
}
private void updateTargetResolutionTargetWidthAndHeight() {
final Product selectedProduct = ioParametersPanel.getSourceProductSelectorList().get(0).getSelectedProduct();
final RasterDataNode node = getAnyRasterDataNode(selectedProduct);
int targetWidth = 0;
int targetHeight = 0;
if (node != null) {
final int resolution = Integer.parseInt(resolutionSpinner.getValue().toString());
final double nodeResolution = node.getImageToModelTransform().getScaleX();
targetWidth = (int) (node.getRasterWidth() * (nodeResolution / resolution));
targetHeight = (int) (node.getRasterHeight() * (nodeResolution / resolution));
}
targetResolutionTargetWidthLabel.setText("" + targetWidth);
targetResolutionTargetHeightLabel.setText("" + targetHeight);
}
private void reactToSourceProductChange(Product product) {
if (product != null) {
resolutionSpinner.setValue(determineResolutionFromProduct(product));
} else {
resolutionSpinner.setValue(0);
}
}
private void handleParameterLoadRequest(Map<String, Object> parameterMap) {
if (parameterMap.containsKey(TARGET_RESOLUTION_PROPERTY_NAME)) {
resolutionSpinner.setValue(parameterMap.get(TARGET_RESOLUTION_PROPERTY_NAME));
resolutionButton.setSelected(true);
enablePanel(TARGET_RESOLUTION_PANEL_INDEX);
}
}
private int determineResolutionFromProduct(Product product) {
final RasterDataNode node = getAnyRasterDataNode(product);
if (node != null) {
return (int) node.getImageToModelTransform().getScaleX();
}
return 1;
}
public Object getResolutionSelected() {
return resolutionSpinner.getValue();
}
}
private class TargetWidthAndHeightPanel extends JPanel {
private JSpinner widthSpinner;
private JSpinner heightSpinner;
private double targetWidthHeightRatio;
private final JLabel targetWidthNameLabel;
private final JLabel targetHeightNameLabel;
private final JLabel widthHeightRatioNameLabel;
private JLabel widthHeightRatioLabel;
private boolean updatingTargetWidthAndHeight;
TargetWidthAndHeightPanel() {
setToolTipText(TARGET_WIDTH_AND_HEIGHT_TOOLTIP_TEXT);
updatingTargetWidthAndHeight = false;
targetWidthHeightRatio = 1.0;
final GridLayout layout = new GridLayout(3, 2);
layout.setVgap(2);
setLayout(layout);
targetWidthNameLabel = new JLabel("Target width:");
targetWidthNameLabel.setEnabled(false);
add(targetWidthNameLabel);
widthSpinner = new JSpinner(new SpinnerNumberModel(100, 0, 1000000, 1));
widthSpinner.setEnabled(false);
add(widthSpinner);
targetHeightNameLabel = new JLabel("Target height:");
targetHeightNameLabel.setEnabled(false);
add(targetHeightNameLabel);
heightSpinner = new JSpinner(new SpinnerNumberModel(100, 0, 1000000, 1));
heightSpinner.setEnabled(false);
add(heightSpinner);
widthHeightRatioNameLabel = new JLabel("Width / height ratio: ");
widthHeightRatioNameLabel.setEnabled(false);
add(widthHeightRatioNameLabel);
widthHeightRatioLabel = new JLabel();
widthHeightRatioLabel.setEnabled(false);
add(widthHeightRatioLabel);
widthSpinner.addChangeListener(e -> updateTargetWidth());
heightSpinner.addChangeListener(e -> updateTargetHeight());
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
widthSpinner.setEnabled(enabled);
heightSpinner.setEnabled(enabled);
widthHeightRatioLabel.setEnabled(enabled);
targetWidthNameLabel.setEnabled(enabled);
targetHeightNameLabel.setEnabled(enabled);
widthHeightRatioNameLabel.setEnabled(enabled);
if (enabled) {
updateTargetWidthAndHeight();
}
}
private void updateTargetWidth() {
if (!updatingTargetWidthAndHeight) {
updatingTargetWidthAndHeight = true;
final int targetWidth = Integer.parseInt(widthSpinner.getValue().toString());
final int targetHeight = (int) (targetWidth / targetWidthHeightRatio);
heightSpinner.setValue(targetHeight);
updateTargetWidthAndHeight();
updatingTargetWidthAndHeight = false;
}
}
private void updateTargetHeight() {
if (!updatingTargetWidthAndHeight) {
updatingTargetWidthAndHeight = true;
final int targetHeight = Integer.parseInt(heightSpinner.getValue().toString());
final int targetWidth = (int) (targetHeight * targetWidthHeightRatio);
widthSpinner.setValue(targetWidth);
updateTargetWidthAndHeight();
updatingTargetWidthAndHeight = false;
}
}
private void updateTargetWidthAndHeight() {
bindingContext.getPropertySet().setValue(REFERENCE_BAND_NAME_PROPERTY_NAME, null);
bindingContext.getPropertySet().setValue(TARGET_WIDTH_PROPERTY_NAME, Integer.parseInt(widthSpinner.getValue().toString()));
bindingContext.getPropertySet().setValue(TARGET_HEIGHT_PROPERTY_NAME, Integer.parseInt(heightSpinner.getValue().toString()));
bindingContext.getPropertySet().setValue(TARGET_RESOLUTION_PROPERTY_NAME, null);
}
private void reactToSourceProductChange(Product product) {
if (product != null) {
targetWidthHeightRatio = product.getSceneRasterWidth() / (double) product.getSceneRasterHeight();
widthSpinner.setValue(product.getSceneRasterWidth());
heightSpinner.setValue(product.getSceneRasterHeight());
} else {
targetWidthHeightRatio = 1.0;
widthSpinner.setValue(0);
heightSpinner.setValue(0);
}
widthHeightRatioLabel.setText(String.format("%.5f", targetWidthHeightRatio));
}
private void handleParameterLoadRequest(Map<String, Object> parameterMap) {
if (parameterMap.containsKey(TARGET_WIDTH_PROPERTY_NAME) &&
parameterMap.containsKey(TARGET_HEIGHT_PROPERTY_NAME)) {
widthSpinner.setValue(parameterMap.get(TARGET_WIDTH_PROPERTY_NAME));
heightSpinner.setValue(parameterMap.get(TARGET_HEIGHT_PROPERTY_NAME));
widthAndHeightButton.setSelected(true);
enablePanel(TARGET_WIDTH_AND_HEIGHT_PANEL_INDEX);
}
}
public Object getWidthSelected(){
return widthSpinner.getValue();
}
public Object getHeightSelected(){
return heightSpinner.getValue();
}
}
private class ReferenceBandNameBoxPanel extends JPanel {
private JComboBox<String> referenceBandNameBox;
private JLabel referenceBandTargetWidthLabel;
private JLabel referenceBandTargetHeightLabel;
private final JLabel referenceBandTargetHeightNameLabel;
private final JLabel referenceBandTargetWidthNameLabel;
ReferenceBandNameBoxPanel() {
setToolTipText(REFERENCE_BAND_TOOLTIP_TEXT);
referenceBandNameBox = new JComboBox<>();
referenceBandNameBox.addActionListener(e -> {
updateReferenceBandTargetWidthAndHeight();
});
final GridLayout referenceBandNameBoxPanelLayout = new GridLayout(3, 1);
referenceBandNameBoxPanelLayout.setVgap(2);
setLayout(referenceBandNameBoxPanelLayout);
add(referenceBandNameBox);
JPanel referenceBandNameTargetWidthPanel = new JPanel(new GridLayout(1, 2));
referenceBandTargetWidthNameLabel = new JLabel("Resulting target width: ");
referenceBandNameTargetWidthPanel.add(referenceBandTargetWidthNameLabel);
referenceBandTargetWidthLabel = new JLabel();
referenceBandNameTargetWidthPanel.add(referenceBandTargetWidthLabel);
JPanel referenceBandNameTargetHeightPanel = new JPanel(new GridLayout(1, 2));
referenceBandTargetHeightNameLabel = new JLabel("Resulting target height: ");
referenceBandNameTargetHeightPanel.add(referenceBandTargetHeightNameLabel);
referenceBandTargetHeightLabel = new JLabel();
referenceBandNameTargetHeightPanel.add(referenceBandTargetHeightLabel);
add(referenceBandNameTargetWidthPanel);
add(referenceBandNameTargetHeightPanel);
referenceBandNameBox.addActionListener(e -> updateReferenceBandName());
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
referenceBandNameBox.setEnabled(enabled);
referenceBandTargetWidthLabel.setEnabled(enabled);
referenceBandTargetHeightLabel.setEnabled(enabled);
referenceBandTargetWidthNameLabel.setEnabled(enabled);
referenceBandTargetHeightNameLabel.setEnabled(enabled);
if (enabled) {
updateReferenceBandName();
}
}
private void updateReferenceBandTargetWidthAndHeight() {
if (referenceBandNameBox.getSelectedItem() != null) {
final String bandName = referenceBandNameBox.getSelectedItem().toString();
final Band band = ioParametersPanel.getSourceProductSelectorList().get(0).getSelectedProduct().getBand(bandName);
referenceBandTargetWidthLabel.setText("" + band.getRasterWidth());
referenceBandTargetHeightLabel.setText("" + band.getRasterHeight());
}
}
private void updateReferenceBandName() {
if (referenceBandNameBox.getSelectedItem() != null) {
bindingContext.getPropertySet().setValue(REFERENCE_BAND_NAME_PROPERTY_NAME, referenceBandNameBox.getSelectedItem().toString());
} else {
bindingContext.getPropertySet().setValue(REFERENCE_BAND_NAME_PROPERTY_NAME, null);
}
bindingContext.getPropertySet().setValue(TARGET_WIDTH_PROPERTY_NAME, null);
bindingContext.getPropertySet().setValue(TARGET_HEIGHT_PROPERTY_NAME, null);
bindingContext.getPropertySet().setValue(TARGET_RESOLUTION_PROPERTY_NAME, null);
}
private void reactToSourceProductChange(Product product) {
referenceBandNameBox.removeAllItems();
String[] bandNames = new String[0];
if (product != null) {
bandNames = product.getBandNames();
}
bindingContext.getPropertySet().getProperty(REFERENCE_BAND_NAME_PROPERTY_NAME).getDescriptor().setValueSet(new ValueSet(bandNames));
referenceBandNameBox.setModel(new DefaultComboBoxModel<>(bandNames));
updateReferenceBandTargetWidthAndHeight();
}
private void handleParameterLoadRequest(Map<String, Object> parameterMap) {
if (parameterMap.containsKey(REFERENCE_BAND_NAME_PROPERTY_NAME)) {
referenceBandNameBox.setSelectedItem(parameterMap.get(REFERENCE_BAND_NAME_PROPERTY_NAME));
referenceBandButton.setSelected(true);
enablePanel(REFERENCE_BAND_NAME_PANEL_INDEX);
}
}
public String getSelectedReferenceBand() {
return referenceBandNameBox.getSelectedItem().toString();
}
}
private class ProductChangedHandler extends AbstractSelectionChangeListener implements ProductNodeListener {
private Product currentProduct;
public void releaseProduct() {
if (currentProduct != null) {
currentProduct.removeProductNodeListener(this);
currentProduct = null;
}
}
@Override
public void selectionChanged(SelectionChangeEvent event) {
Selection selection = event.getSelection();
if (selection != null) {
final Product selectedProduct = (Product) selection.getSelectedValue();
if (selectedProduct != currentProduct) {
if (currentProduct != null) {
currentProduct.removeProductNodeListener(this);
}
currentProduct = selectedProduct;
if (currentProduct != null) {
currentProduct.addProductNodeListener(this);
}
if (getTargetProductSelector() != null) {
updateTargetProductName();
}
reactToSourceProductChange(currentProduct);
}
}
}
@Override
public void nodeAdded(ProductNodeEvent event) {
handleProductNodeEvent();
}
@Override
public void nodeChanged(ProductNodeEvent event) {
handleProductNodeEvent();
}
@Override
public void nodeDataChanged(ProductNodeEvent event) {
handleProductNodeEvent();
}
@Override
public void nodeRemoved(ProductNodeEvent event) {
handleProductNodeEvent();
}
private void updateTargetProductName() {
String productName = "";
if (currentProduct != null) {
productName = currentProduct.getName();
}
final TargetProductSelectorModel targetProductSelectorModel = getTargetProductSelector().getModel();
targetProductSelectorModel.setProductName(productName + targetProductNameSuffix);
}
private void handleProductNodeEvent() {
reactToSourceProductChange(currentProduct);
}
}
private class ResamplingParameterUpdater implements ParameterUpdater {
@Override
public void handleParameterSaveRequest(Map<String, Object> parameterMap) throws ValidationException, ConversionException {
}
@Override
public void handleParameterLoadRequest(Map<String, Object> parameterMap) throws ValidationException, ConversionException {
referenceBandNameBoxPanel.handleParameterLoadRequest(parameterMap);
targetWidthAndHeightPanel.handleParameterLoadRequest(parameterMap);
targetResolutionPanel.handleParameterLoadRequest(parameterMap);
}
}
}
| 51,430 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OrthorectificationAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/reproject/OrthorectificationAction.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.reproject;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.ui.ModelessDialog;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import java.awt.event.ActionEvent;
/**
* Geographic collocation action.
*
* @author Norman Fomferra
*/
@ActionID(category = "Operators", id = "org.esa.snap.core.gpf.ui.reproject.OrthorectificationAction")
@ActionRegistration(displayName = "#CTL_OrthorectificationAction_Name")
@ActionReference(path = "Menu/Optical/Geometric", position = 10)
@NbBundle.Messages("CTL_OrthorectificationAction_Name=Orthorectification")
public class OrthorectificationAction extends AbstractSnapAction {
private ModelessDialog dialog;
@Override
public void actionPerformed(ActionEvent e) {
if (dialog == null) {
dialog = new ReprojectionDialog(true, Bundle.CTL_OrthorectificationAction_Name(),
"orthorectificationAction", getAppContext());
}
dialog.show();
}
}
| 1,854 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ReprojectionDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/reproject/ReprojectionDialog.java | /*
* Copyright (C) 2014 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.reproject;
import com.bc.ceres.binding.ConversionException;
import com.bc.ceres.binding.ValidationException;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.dataop.dem.ElevationModelDescriptor;
import org.esa.snap.core.dataop.dem.ElevationModelRegistry;
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.ui.AppContext;
import org.esa.snap.ui.DefaultAppContext;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import java.util.HashMap;
import java.util.Map;
class ReprojectionDialog extends SingleTargetProductDialog {
private static final String OPERATOR_NAME = "Reproject";
private final ReprojectionForm form;
public static void main(String[] args) {
final DefaultAppContext context = new DefaultAppContext("Reproj");
final ReprojectionDialog dialog = new ReprojectionDialog(true, "ReproTestDialog", null, context);
dialog.show();
}
ReprojectionDialog(boolean orthorectify, final String title, final String helpID, AppContext appContext) {
super(appContext, title, ID_APPLY_CLOSE, helpID);
form = new ReprojectionForm(getTargetProductSelector(), orthorectify, appContext);
final OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(OPERATOR_NAME);
ParameterUpdater parameterUpdater = new ReprojectionParameterUpdater();
OperatorParameterSupport parameterSupport = new OperatorParameterSupport(operatorSpi.getOperatorDescriptor(),
null,
null,
parameterUpdater);
OperatorMenu operatorMenu = new OperatorMenu(this.getJDialog(),
operatorSpi.getOperatorDescriptor(),
parameterSupport,
appContext,
helpID);
getJDialog().setJMenuBar(operatorMenu.createDefaultMenu());
}
@Override
protected boolean verifyUserInput() {
if (form.getSourceProduct() == null) {
showErrorDialog("No product to reproject selected.");
return false;
}
final CoordinateReferenceSystem crs = form.getSelectedCrs();
if (crs == null) {
showErrorDialog("No 'Coordinate Reference System' selected.");
return false;
}
String externalDemName = form.getExternalDemName();
if (externalDemName != null) {
final ElevationModelRegistry elevationModelRegistry = ElevationModelRegistry.getInstance();
final ElevationModelDescriptor demDescriptor = elevationModelRegistry.getDescriptor(externalDemName);
if (demDescriptor == null) {
showErrorDialog("The DEM '" + externalDemName + "' is not supported.");
close();
return false;
}
}
return true;
}
@Override
protected Product createTargetProduct() throws Exception {
final Map<String, Product> productMap = form.getProductMap();
final Map<String, Object> parameterMap = new HashMap<>();
form.updateParameterMap(parameterMap);
return GPF.createProduct(OPERATOR_NAME, parameterMap, productMap);
}
@Override
public int show() {
form.prepareShow();
setContent(form);
return super.show();
}
@Override
public void hide() {
form.prepareHide();
super.hide();
}
private class ReprojectionParameterUpdater implements ParameterUpdater {
@Override
public void handleParameterSaveRequest(Map<String, Object> parameterMap) {
form.updateParameterMap(parameterMap);
}
@Override
public void handleParameterLoadRequest(Map<String, Object> parameterMap) throws ValidationException, ConversionException {
form.updateFormModel(parameterMap);
}
}
}
| 5,212 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ReprojectionAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/reproject/ReprojectionAction.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.reproject;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.ui.ModelessDialog;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import java.awt.event.ActionEvent;
/**
* Geographic collocation action.
*
* @author Norman Fomferra
*/
@ActionID(category = "Operators", id = "org.esa.snap.core.gpf.ui.reproject.ReprojectionAction")
@ActionRegistration(displayName = "#CTL_ReprojectionAction_Name")
@ActionReference(path = "Menu/Raster/Geometric", position = 10)
@NbBundle.Messages("CTL_ReprojectionAction_Name=Reprojection")
public class ReprojectionAction extends AbstractSnapAction {
private ModelessDialog dialog;
@Override
public void actionPerformed(ActionEvent e) {
if (dialog == null) {
dialog = new ReprojectionDialog(false, Bundle.CTL_ReprojectionAction_Name(),
"reprojectionAction", getAppContext());
}
dialog.show();
}
}
| 1,811 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ReprojectionForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/reproject/ReprojectionForm.java | /*
* Copyright (C) 2011 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.reproject;
import com.bc.ceres.binding.ConversionException;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.selection.AbstractSelectionChangeListener;
import com.bc.ceres.swing.selection.SelectionChangeEvent;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.ImageGeometry;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductFilter;
import org.esa.snap.core.gpf.ui.CollocationCrsForm;
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.param.ParamParseException;
import org.esa.snap.core.param.ParamValidateException;
import org.esa.snap.core.util.ProductUtils;
import org.esa.snap.ui.AbstractDialog;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.DemSelector;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.crs.CrsForm;
import org.esa.snap.ui.crs.CrsSelectionPanel;
import org.esa.snap.ui.crs.CustomCrsForm;
import org.esa.snap.ui.crs.OutputGeometryForm;
import org.esa.snap.ui.crs.OutputGeometryFormModel;
import org.esa.snap.ui.crs.PredefinedCrsForm;
import org.geotools.referencing.AbstractReferenceSystem;
import org.geotools.referencing.CRS;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.crs.ProjectedCRS;
import org.opengis.referencing.datum.GeodeticDatum;
import org.opengis.referencing.operation.OperationMethod;
import org.opengis.referencing.operation.Projection;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
/**
* @author Marco Zuehlke
* @author Marco Peters
* @since BEAM 4.7
*/
class ReprojectionForm extends JTabbedPane {
private static final String[] RESAMPLING_IDENTIFIER = {"Nearest", "Bilinear", "Bicubic"};
private final boolean orthoMode;
private final String targetProductSuffix;
private final AppContext appContext;
private final SourceProductSelector sourceProductSelector;
private final TargetProductSelector targetProductSelector;
private final Model reprojectionModel;
private final PropertyContainer reprojectionContainer;
private DemSelector demSelector;
private CrsSelectionPanel crsSelectionPanel;
private OutputGeometryFormModel outputGeometryModel;
private JButton outputParamButton;
private InfoForm infoForm;
private CoordinateReferenceSystem crs;
private CollocationCrsForm collocationCrsUI;
private CustomCrsForm customCrsUI;
ReprojectionForm(TargetProductSelector targetProductSelector, boolean orthorectify, AppContext appContext) {
this.targetProductSelector = targetProductSelector;
this.orthoMode = orthorectify;
this.appContext = appContext;
this.sourceProductSelector = new SourceProductSelector(appContext, "Source Product:");
if (orthoMode) {
targetProductSuffix = "orthorectified";
this.sourceProductSelector.setProductFilter(new OrthorectifyProductFilter());
} else {
targetProductSuffix = "reprojected";
this.sourceProductSelector.setProductFilter(new GeoCodingProductFilter());
}
this.reprojectionModel = new Model();
this.reprojectionContainer = PropertyContainer.createObjectBacked(reprojectionModel);
createUI();
}
void updateParameterMap(Map<String, Object> parameterMap) {
parameterMap.clear();
parameterMap.put("resamplingName", reprojectionModel.resamplingName);
parameterMap.put("includeTiePointGrids", reprojectionModel.includeTiePointGrids);
parameterMap.put("addDeltaBands", reprojectionModel.addDeltaBands);
parameterMap.put("noDataValue", reprojectionModel.noDataValue);
if (!collocationCrsUI.getRadioButton().isSelected()) {
CoordinateReferenceSystem selectedCrs = getSelectedCrs();
if (selectedCrs != null) {
if(selectedCrs instanceof AbstractReferenceSystem) {
// Sometimes it can happen that strict mode fails. But the WKT is still valid and usable. Strict mode is anabled by default.
parameterMap.put("crs", ((AbstractReferenceSystem)selectedCrs).toWKT(2, false));
}else {
parameterMap.put("crs", selectedCrs.toWKT());
}
}
}
if (orthoMode) {
parameterMap.put("orthorectify", orthoMode);
if (demSelector.isUsingExternalDem()) {
parameterMap.put("elevationModelName", demSelector.getDemName());
} else {
parameterMap.put("elevationModelName", null);
}
}
if (!reprojectionModel.preserveResolution && outputGeometryModel != null) {
PropertySet container = outputGeometryModel.getPropertySet();
parameterMap.put("referencePixelX", container.getValue("referencePixelX"));
parameterMap.put("referencePixelY", container.getValue("referencePixelY"));
parameterMap.put("easting", container.getValue("easting"));
parameterMap.put("northing", container.getValue("northing"));
parameterMap.put("orientation", container.getValue("orientation"));
parameterMap.put("pixelSizeX", container.getValue("pixelSizeX"));
parameterMap.put("pixelSizeY", container.getValue("pixelSizeY"));
parameterMap.put("width", container.getValue("width"));
parameterMap.put("height", container.getValue("height"));
}
}
public void updateFormModel(Map<String, Object> parameterMap) throws ValidationException, ConversionException {
Property[] properties = reprojectionContainer.getProperties();
for (Property property : properties) {
String propertyName = property.getName();
Object newValue = parameterMap.get(propertyName);
if (newValue != null) {
property.setValue(newValue);
}
}
if (orthoMode) {
Object elevationModelName = parameterMap.get("elevationModelName");
if (elevationModelName instanceof String) {
try {
demSelector.setDemName((String) elevationModelName);
} catch (ParamValidateException e) {
throw new ValidationException(e.getMessage(), e);
} catch (ParamParseException e) {
throw new ConversionException(e.getMessage(), e);
}
}
}
Object crsAsWKT = parameterMap.get("crs");
if (crsAsWKT instanceof String) {
try {
CoordinateReferenceSystem crs;
crs = CRS.parseWKT((String) crsAsWKT);
if (crs instanceof ProjectedCRS) {
ProjectedCRS projectedCRS = (ProjectedCRS) crs;
Projection conversionFromBase = projectedCRS.getConversionFromBase();
OperationMethod operationMethod = conversionFromBase.getMethod();
ParameterValueGroup parameterValues = conversionFromBase.getParameterValues();
GeodeticDatum geodeticDatum = projectedCRS.getDatum();
customCrsUI.setCustom(geodeticDatum, operationMethod, parameterValues);
} else {
throw new ConversionException("Failed to convert CRS from WKT.");
}
} catch (FactoryException e) {
throw new ConversionException("Failed to convert CRS from WKT.", e);
}
}
if (parameterMap.containsKey("referencePixelX")) {
PropertyContainer propertySet = PropertyContainer.createMapBacked(parameterMap);
outputGeometryModel = new OutputGeometryFormModel(propertySet);
reprojectionContainer.setValue(Model.PRESERVE_RESOLUTION, false);
} else {
outputGeometryModel = null;
reprojectionContainer.setValue(Model.PRESERVE_RESOLUTION, true);
}
updateCRS();
}
Map<String, Product> getProductMap() {
final Map<String, Product> productMap = new HashMap<>(5);
productMap.put("source", getSourceProduct());
if (collocationCrsUI.getRadioButton().isSelected()) {
productMap.put("collocateWith", collocationCrsUI.getCollocationProduct());
}
return productMap;
}
Product getSourceProduct() {
return sourceProductSelector.getSelectedProduct();
}
CoordinateReferenceSystem getSelectedCrs() {
return crs;
}
void prepareShow() {
sourceProductSelector.initProducts();
crsSelectionPanel.prepareShow();
}
void prepareHide() {
sourceProductSelector.releaseProducts();
crsSelectionPanel.prepareHide();
if (outputGeometryModel != null) {
outputGeometryModel.setSourceProduct(null);
}
}
String getExternalDemName() {
if (orthoMode && demSelector.isUsingExternalDem()) {
return demSelector.getDemName();
}
return null;
}
private void createUI() {
addTab("I/O Parameters", createIOPanel());
addTab("Reprojection Parameters", createParametersPanel());
}
private JPanel createIOPanel() {
final TableLayout tableLayout = new TableLayout(1);
tableLayout.setTableWeightX(1.0);
tableLayout.setTableWeightY(0.0);
tableLayout.setTableFill(TableLayout.Fill.BOTH);
tableLayout.setTablePadding(3, 3);
final JPanel ioPanel = new JPanel(tableLayout);
ioPanel.add(createSourceProductPanel());
ioPanel.add(targetProductSelector.createDefaultPanel());
ioPanel.add(tableLayout.createVerticalSpacer());
return ioPanel;
}
private JPanel createParametersPanel() {
final JPanel parameterPanel = new JPanel();
final TableLayout layout = new TableLayout(1);
layout.setTablePadding(4, 4);
layout.setTableFill(TableLayout.Fill.HORIZONTAL);
layout.setTableAnchor(TableLayout.Anchor.WEST);
layout.setTableWeightX(1.0);
parameterPanel.setLayout(layout);
customCrsUI = new CustomCrsForm(appContext);
CrsForm predefinedCrsUI = new PredefinedCrsForm(appContext);
collocationCrsUI = new CollocationCrsForm(appContext);
CrsForm[] crsForms = new CrsForm[]{customCrsUI, predefinedCrsUI, collocationCrsUI};
crsSelectionPanel = new CrsSelectionPanel(crsForms);
sourceProductSelector.addSelectionChangeListener(new AbstractSelectionChangeListener() {
@Override
public void selectionChanged(SelectionChangeEvent event) {
final Product product = (Product) event.getSelection().getSelectedValue();
crsSelectionPanel.setReferenceProduct(product);
}
});
parameterPanel.add(crsSelectionPanel);
if (orthoMode) {
demSelector = new DemSelector();
parameterPanel.add(demSelector);
}
parameterPanel.add(createOuputSettingsPanel());
infoForm = new InfoForm();
parameterPanel.add(infoForm.createUI());
crsSelectionPanel.addPropertyChangeListener("crs", evt -> updateCRS());
updateCRS();
return parameterPanel;
}
private void updateCRS() {
final Product sourceProduct = getSourceProduct();
try {
if (sourceProduct != null) {
crs = crsSelectionPanel.getCrs(ProductUtils.getCenterGeoPos(sourceProduct));
if (crs != null) {
infoForm.setCrsInfoText(crs.getName().getCode(), crs.toString());
} else {
infoForm.setCrsErrorText("No valid 'Coordinate Reference System' selected.");
}
} else {
infoForm.setCrsErrorText("No source product selected.");
crs = null;
}
} catch (FactoryException e) {
infoForm.setCrsErrorText(e.getMessage());
crs = null;
}
if (outputGeometryModel != null) {
outputGeometryModel.setTargetCrs(crs);
}
updateOutputParameterState();
}
private void updateProductSize() {
int width = 0;
int height = 0;
final Product sourceProduct = getSourceProduct();
if (sourceProduct != null && crs != null) {
if (!reprojectionModel.preserveResolution && outputGeometryModel != null) {
PropertySet container = outputGeometryModel.getPropertySet();
width = container.getValue("width");
height = container.getValue("height");
} else {
ImageGeometry iGeometry;
final Product collocationProduct = collocationCrsUI.getCollocationProduct();
if (collocationCrsUI.getRadioButton().isSelected() && collocationProduct != null) {
iGeometry = ImageGeometry.createCollocationTargetGeometry(sourceProduct, collocationProduct);
} else {
iGeometry = ImageGeometry.createTargetGeometry(sourceProduct, crs,
null, null, null, null,
null, null, null, null,
null);
}
Rectangle imageRect = iGeometry.getImageRect();
width = imageRect.width;
height = imageRect.height;
}
}
infoForm.setWidth(width);
infoForm.setHeight(height);
}
private class InfoForm {
private JLabel widthLabel;
private JLabel heightLabel;
private JLabel centerLatLabel;
private JLabel centerLonLabel;
private JLabel crsLabel;
private String wkt;
private JButton wktButton;
void setWidth(int width) {
widthLabel.setText(Integer.toString(width));
}
void setHeight(int height) {
heightLabel.setText(Integer.toString(height));
}
void setCenterPos(GeoPos geoPos) {
if (geoPos != null) {
centerLatLabel.setText(geoPos.getLatString());
centerLonLabel.setText(geoPos.getLonString());
} else {
centerLatLabel.setText("");
centerLonLabel.setText("");
}
}
void setCrsErrorText(String infoText) {
setCrsInfoText("<html><b>" + infoText + "</b>", null);
}
void setCrsInfoText(String infoText, String wkt) {
this.wkt = wkt;
crsLabel.setText(infoText);
boolean hasWKT = (wkt != null);
wktButton.setEnabled(hasWKT);
}
JPanel createUI() {
widthLabel = new JLabel();
heightLabel = new JLabel();
centerLatLabel = new JLabel();
centerLonLabel = new JLabel();
crsLabel = new JLabel();
final TableLayout tableLayout = new TableLayout(5);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayout.setTablePadding(4, 4);
tableLayout.setColumnWeightX(0, 0.0);
tableLayout.setColumnWeightX(1, 0.0);
tableLayout.setColumnWeightX(2, 1.0);
tableLayout.setColumnWeightX(3, 0.0);
tableLayout.setColumnWeightX(4, 1.0);
tableLayout.setCellColspan(2, 1, 3);
tableLayout.setCellPadding(0, 3, new Insets(4, 24, 4, 20));
tableLayout.setCellPadding(1, 3, new Insets(4, 24, 4, 20));
final JPanel panel = new JPanel(tableLayout);
panel.setBorder(BorderFactory.createTitledBorder("Output Information"));
panel.add(new JLabel("Scene width:"));
panel.add(widthLabel);
panel.add(new JLabel("pixel"));
panel.add(new JLabel("Center longitude:"));
panel.add(centerLonLabel);
panel.add(new JLabel("Scene height:"));
panel.add(heightLabel);
panel.add(new JLabel("pixel"));
panel.add(new JLabel("Center latitude:"));
panel.add(centerLatLabel);
panel.add(new JLabel("CRS:"));
panel.add(crsLabel);
wktButton = new JButton("Show WKT");
wktButton.addActionListener(e -> {
JTextArea wktArea = new JTextArea(30, 40);
wktArea.setEditable(false);
wktArea.setText(wkt);
final JScrollPane scrollPane = new JScrollPane(wktArea);
final ModalDialog dialog = new ModalDialog(appContext.getApplicationWindow(),
"Coordinate reference system as well known text",
scrollPane,
ModalDialog.ID_OK, null);
dialog.show();
});
wktButton.setEnabled(false);
panel.add(wktButton);
return panel;
}
}
private JPanel createOuputSettingsPanel() {
final TableLayout tableLayout = new TableLayout(3);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayout.setColumnFill(0, TableLayout.Fill.NONE);
tableLayout.setTablePadding(4, 4);
tableLayout.setColumnPadding(0, new Insets(4, 4, 4, 20));
tableLayout.setColumnWeightX(0, 0.0);
tableLayout.setColumnWeightX(1, 0.0);
tableLayout.setColumnWeightX(2, 1.0);
tableLayout.setCellColspan(0, 1, 2);
tableLayout.setCellPadding(1, 0, new Insets(4, 24, 4, 20));
final JPanel outputSettingsPanel = new JPanel(tableLayout);
outputSettingsPanel.setBorder(BorderFactory.createTitledBorder("Output Settings"));
final BindingContext context = new BindingContext(reprojectionContainer);
final JCheckBox preserveResolutionCheckBox = new JCheckBox("Preserve resolution");
context.bind(Model.PRESERVE_RESOLUTION, preserveResolutionCheckBox);
collocationCrsUI.getCrsUI().addPropertyChangeListener("collocate", evt -> {
final boolean collocate = (Boolean) evt.getNewValue();
reprojectionContainer.setValue(Model.PRESERVE_RESOLUTION,
collocate || reprojectionModel.preserveResolution);
preserveResolutionCheckBox.setEnabled(!collocate);
});
outputSettingsPanel.add(preserveResolutionCheckBox);
JCheckBox includeTPcheck = new JCheckBox("Reproject tie-point grids", true);
context.bind(Model.REPROJ_TIEPOINTS, includeTPcheck);
outputSettingsPanel.add(includeTPcheck);
outputParamButton = new JButton("Output Parameters...");
outputParamButton.setEnabled(!reprojectionModel.preserveResolution);
outputParamButton.addActionListener(new OutputParamActionListener());
outputSettingsPanel.add(outputParamButton);
outputSettingsPanel.add(new JLabel("No-data value:"));
final JTextField noDataField = new JTextField();
outputSettingsPanel.add(noDataField);
context.bind(Model.NO_DATA_VALUE, noDataField);
JCheckBox addDeltaBandsChecker = new JCheckBox("Add delta lat/lon bands");
outputSettingsPanel.add(addDeltaBandsChecker);
context.bind(Model.ADD_DELTA_BANDS, addDeltaBandsChecker);
outputSettingsPanel.add(new JLabel("Resampling method:"));
JComboBox<String> resampleComboBox = new JComboBox<>(RESAMPLING_IDENTIFIER);
resampleComboBox.setPrototypeDisplayValue(RESAMPLING_IDENTIFIER[0]);
context.bind(Model.RESAMPLING_NAME, resampleComboBox);
outputSettingsPanel.add(resampleComboBox);
reprojectionContainer.addPropertyChangeListener(Model.PRESERVE_RESOLUTION, evt -> updateOutputParameterState());
return outputSettingsPanel;
}
private void updateOutputParameterState() {
outputParamButton.setEnabled(!reprojectionModel.preserveResolution && (crs != null));
updateProductSize();
}
private JPanel createSourceProductPanel() {
final JPanel panel = sourceProductSelector.createDefaultPanel();
sourceProductSelector.getProductNameLabel().setText("Name:");
sourceProductSelector.getProductNameComboBox().setPrototypeDisplayValue(
"MER_RR__1PPBCM20030730_071000_000003972018_00321_07389_0000.N1");
sourceProductSelector.addSelectionChangeListener(new AbstractSelectionChangeListener() {
@Override
public void selectionChanged(SelectionChangeEvent event) {
final Product sourceProduct = getSourceProduct();
updateTargetProductName(sourceProduct);
GeoPos centerGeoPos = null;
if (sourceProduct != null) {
centerGeoPos = ProductUtils.getCenterGeoPos(sourceProduct);
}
infoForm.setCenterPos(centerGeoPos);
if (outputGeometryModel != null) {
outputGeometryModel.setSourceProduct(sourceProduct);
}
updateCRS();
}
});
return panel;
}
private void updateTargetProductName(Product selectedProduct) {
final TargetProductSelectorModel selectorModel = targetProductSelector.getModel();
if (selectedProduct != null) {
final String productName = MessageFormat.format("{0}_" + targetProductSuffix, selectedProduct.getName());
selectorModel.setProductName(productName);
} else if (selectorModel.getProductName() == null) {
selectorModel.setProductName(targetProductSuffix);
}
}
private class OutputParamActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
try {
final Product sourceProduct = getSourceProduct();
if (sourceProduct == null) {
showWarningMessage("Please select a product to reproject.\n");
return;
}
if (crs == null) {
showWarningMessage("Please specify a 'Coordinate Reference System' first.\n");
return;
}
OutputGeometryFormModel workCopy;
if (outputGeometryModel != null) {
workCopy = new OutputGeometryFormModel(outputGeometryModel);
} else {
final Product collocationProduct = collocationCrsUI.getCollocationProduct();
if (collocationCrsUI.getRadioButton().isSelected() && collocationProduct != null) {
workCopy = new OutputGeometryFormModel(sourceProduct, collocationProduct);
} else {
workCopy = new OutputGeometryFormModel(sourceProduct, crs);
}
}
final OutputGeometryForm form = new OutputGeometryForm(workCopy);
final ModalDialog outputParametersDialog = new OutputParametersDialog(appContext.getApplicationWindow(),
sourceProduct, workCopy);
outputParametersDialog.setContent(form);
if (outputParametersDialog.show() == ModalDialog.ID_OK) {
outputGeometryModel = workCopy;
updateProductSize();
}
} catch (Exception e) {
appContext.handleError("Could not create a 'Coordinate Reference System'.\n" +
e.getMessage(), e);
}
}
}
private void showWarningMessage(String message) {
AbstractDialog.showWarningDialog(getParent(), message, "Reprojection");
}
private class OutputParametersDialog extends ModalDialog {
private static final String TITLE = "Output Parameters";
private final Product sourceProduct;
private final OutputGeometryFormModel outputGeometryFormModel;
public OutputParametersDialog(Window parent, Product sourceProduct,
OutputGeometryFormModel outputGeometryFormModel) {
super(parent, TITLE, ModalDialog.ID_OK_CANCEL | ModalDialog.ID_RESET, null);
this.sourceProduct = sourceProduct;
this.outputGeometryFormModel = outputGeometryFormModel;
}
@Override
protected void onReset() {
final Product collocationProduct = collocationCrsUI.getCollocationProduct();
ImageGeometry imageGeometry;
if (collocationCrsUI.getRadioButton().isSelected() && collocationProduct != null) {
imageGeometry = ImageGeometry.createCollocationTargetGeometry(sourceProduct, collocationProduct);
} else {
imageGeometry = ImageGeometry.createTargetGeometry(sourceProduct, crs,
null, null, null, null,
null, null, null, null, null);
}
outputGeometryFormModel.resetToDefaults(imageGeometry);
}
}
private static class Model {
private static final String PRESERVE_RESOLUTION = "preserveResolution";
private static final String REPROJ_TIEPOINTS = "includeTiePointGrids";
private static final String ADD_DELTA_BANDS = "addDeltaBands";
private static final String NO_DATA_VALUE = "noDataValue";
private static final String RESAMPLING_NAME = "resamplingName";
private boolean preserveResolution = true;
private boolean includeTiePointGrids = true;
private boolean addDeltaBands = false;
private double noDataValue = Double.NaN;
private String resamplingName = RESAMPLING_IDENTIFIER[0];
}
private static class OrthorectifyProductFilter implements ProductFilter {
@Override
public boolean accept(Product product) {
return product.canBeOrthorectified();
}
}
private static class GeoCodingProductFilter implements ProductFilter {
@Override
public boolean accept(Product product) {
final GeoCoding geoCoding = product.getSceneGeoCoding();
return geoCoding != null && geoCoding.canGetGeoPos() && geoCoding.canGetPixelPos();
}
}
}
| 28,582 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ConditionsTableAdapter.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/mosaic/ConditionsTableAdapter.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.mosaic;
import org.esa.snap.core.gpf.common.MosaicOp;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
class ConditionsTableAdapter extends AbstractTableAdapter {
ConditionsTableAdapter(JTable table) {
super(table);
}
@Override
public void tableChanged(TableModelEvent e) {
final TableModel tableModel = (TableModel) e.getSource();
final MosaicOp.Condition[] conditions = new MosaicOp.Condition[tableModel.getRowCount()];
for (int i = 0; i < conditions.length; i++) {
conditions[i] = new MosaicOp.Condition((String) tableModel.getValueAt(i, 0),
(String) tableModel.getValueAt(i, 1),
Boolean.TRUE.equals(tableModel.getValueAt(i, 2)));
}
getBinding().setPropertyValue(conditions);
}
@Override
protected final DefaultTableModel createTableModel(int rowCount) {
return new DefaultTableModel(new String[]{"Name", "Expression", "Output"}, rowCount);
}
}
| 1,912 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MosaicIOPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/mosaic/MosaicIOPanel.java | /*
* Copyright (C) 2011 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.mosaic;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.selection.AbstractSelectionChangeListener;
import com.bc.ceres.swing.selection.SelectionChangeEvent;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.dataio.ProductIOPlugInManager;
import org.esa.snap.core.dataio.ProductReader;
import org.esa.snap.core.dataio.ProductWriterPlugIn;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductFilter;
import org.esa.snap.core.gpf.OperatorException;
import org.esa.snap.core.gpf.common.MosaicOp;
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.PropertyMap;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.rcp.actions.file.SaveProductAsAction;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.io.FileArrayEditor;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
/**
* @author Marco Peters
* @since BEAM 4.7
*/
class MosaicIOPanel extends JPanel {
private static final String INPUT_PRODUCT_DIR_KEY = "gpf.mosaic.input.product.dir";
private final AppContext appContext;
private final MosaicFormModel mosaicModel;
private final PropertySet propertySet;
private final TargetProductSelector targetProductSelector;
private final SourceProductSelector updateProductSelector;
private FileArrayEditor sourceFileEditor;
MosaicIOPanel(AppContext appContext, MosaicFormModel mosaicModel, TargetProductSelector selector) {
this.appContext = appContext;
this.mosaicModel = mosaicModel;
propertySet = mosaicModel.getPropertySet();
final FileArrayEditor.EditorParent context = new FileArrayEditorContext(appContext);
sourceFileEditor = new FileArrayEditor(context, "Source products") {
@Override
protected JFileChooser createFileChooserDialog() {
final JFileChooser fileChooser = super.createFileChooserDialog();
fileChooser.setDialogTitle("Mosaic - Open Source Product(s)");
return fileChooser;
}
};
targetProductSelector = selector;
updateProductSelector = new SourceProductSelector(appContext);
updateProductSelector.setProductFilter(new UpdateProductFilter());
init();
propertySet.addPropertyChangeListener(MosaicFormModel.PROPERTY_UPDATE_MODE, evt -> {
if (Boolean.TRUE.equals(evt.getNewValue())) {
propertySet.setValue(MosaicFormModel.PROPERTY_UPDATE_PRODUCT,
updateProductSelector.getSelectedProduct());
} else {
updateProductSelector.setSelectedProduct(null);
}
});
propertySet.addPropertyChangeListener(MosaicFormModel.PROPERTY_UPDATE_PRODUCT,
new TargetProductSelectorUpdater());
}
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());
add(createTargetProductPanel());
updateProductSelector.addSelectionChangeListener(new AbstractSelectionChangeListener() {
@Override
public void selectionChanged(SelectionChangeEvent event) {
final Product product = (Product) event.getSelection().getSelectedValue();
try {
if (product != null) {
final Map<String, Object> map = MosaicOp.getOperatorParameters(product);
final Stream<Map.Entry<String, Object>> entrySetStream = map.entrySet().stream();
final Stream<Map.Entry<String, Object>> filteredStream = entrySetStream.filter(entry -> propertySet.getProperty(entry.getKey()) != null);
filteredStream.forEach(entry -> propertySet.setValue(entry.getKey(), entry.getValue()));
}
propertySet.setValue(MosaicFormModel.PROPERTY_UPDATE_PRODUCT, product);
} catch (OperatorException e) {
appContext.handleError("Selected product cannot be used for update mode.", e);
}
}
});
}
private JPanel createSourceProductsPanel() {
final FileArrayEditor.FileArrayEditorListener listener = files -> {
final SwingWorker worker = new SwingWorker() {
@Override
protected Object doInBackground() throws Exception {
mosaicModel.setSourceProducts(files);
return null;
}
@Override
protected void done() {
try {
get();
} catch (Exception e) {
final String msg = String.format("Cannot display source products.\n%s", e.getMessage());
appContext.handleError(msg, e);
}
}
};
worker.execute();
};
sourceFileEditor.setListener(listener);
JButton addFileButton = sourceFileEditor.createAddFileButton();
JButton removeFileButton = sourceFileEditor.createRemoveFileButton();
final TableLayout tableLayout = new TableLayout(1);
tableLayout.setTablePadding(4, 4);
tableLayout.setTableWeightX(1.0);
tableLayout.setTableWeightY(0.0);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setTableFill(TableLayout.Fill.BOTH);
final JPanel sourceProductPanel = new JPanel(tableLayout);
sourceProductPanel.setBorder(BorderFactory.createTitledBorder("Source Products"));
final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
buttonPanel.add(addFileButton);
buttonPanel.add(removeFileButton);
tableLayout.setRowPadding(0, new Insets(1, 4, 1, 4));
sourceProductPanel.add(buttonPanel);
final JComponent fileArrayComponent = sourceFileEditor.createFileArrayComponent();
tableLayout.setRowWeightY(1, 1.0);
sourceProductPanel.add(fileArrayComponent);
return sourceProductPanel;
}
private JPanel createTargetProductPanel() {
final TableLayout tableLayout = new TableLayout(1);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setTableFill(TableLayout.Fill.BOTH);
tableLayout.setTableWeightX(1.0);
tableLayout.setTableWeightY(1.0);
tableLayout.setTablePadding(3, 3);
final JPanel targetProductPanel = new JPanel(tableLayout);
targetProductPanel.setBorder(BorderFactory.createTitledBorder("Target Product"));
final JCheckBox updateTargetCheckBox = new JCheckBox("Update target product", false);
final BindingContext context = new BindingContext(propertySet);
context.bind(MosaicFormModel.PROPERTY_UPDATE_MODE, updateTargetCheckBox);
targetProductPanel.add(updateTargetCheckBox);
final CardLayout cards = new CardLayout(0, 3);
final JPanel subPanel = new JPanel(cards);
final JPanel newProductSelectorPanel = createTargetProductSelectorPanel(targetProductSelector);
final JPanel updateProductSelectorPanel = createUpdateProductSelectorPanel(updateProductSelector);
final String newProductKey = "NEW_PRODUCT";
final String updateProductKey = "UPDATE_PRODUCT";
subPanel.add(newProductSelectorPanel, newProductKey);
subPanel.add(updateProductSelectorPanel, updateProductKey);
updateTargetCheckBox.addActionListener(e -> {
if (updateTargetCheckBox.isSelected()) {
prepareHideTargetProductSelector();
prepareShowUpdateProductSelector();
cards.show(subPanel, updateProductKey);
} else {
prepareShowTargetProductSelector();
prepareHideUpdateProductSelector();
cards.show(subPanel, newProductKey);
}
});
cards.show(subPanel, newProductKey);
targetProductPanel.add(subPanel);
targetProductPanel.add(targetProductSelector.getOpenInAppCheckBox());
return targetProductPanel;
}
private JPanel createUpdateProductSelectorPanel(final SourceProductSelector selector) {
final JPanel subPanel = new JPanel(new BorderLayout(3, 3));
subPanel.add(selector.getProductNameComboBox(), BorderLayout.CENTER);
subPanel.add(selector.getProductFileChooserButton(), BorderLayout.EAST);
final TableLayout tableLayout = new TableLayout(1);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setTableWeightX(1.0);
tableLayout.setRowFill(0, TableLayout.Fill.HORIZONTAL);
tableLayout.setRowFill(1, TableLayout.Fill.HORIZONTAL);
tableLayout.setTablePadding(3, 3);
JPanel panel = new JPanel(tableLayout);
panel.add(selector.getProductNameLabel());
panel.add(subPanel);
panel.add(tableLayout.createVerticalSpacer());
return panel;
}
private static JPanel createTargetProductSelectorPanel(final TargetProductSelector selector) {
final JPanel subPanel1 = new JPanel(new BorderLayout(3, 3));
subPanel1.add(selector.getProductNameLabel(), BorderLayout.NORTH);
subPanel1.add(selector.getProductNameTextField(), BorderLayout.CENTER);
final JPanel subPanel2 = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
subPanel2.add(selector.getSaveToFileCheckBox());
subPanel2.add(selector.getFormatNameComboBox());
final JPanel subPanel3 = new JPanel(new BorderLayout(3, 3));
subPanel3.add(selector.getProductDirLabel(), BorderLayout.NORTH);
subPanel3.add(selector.getProductDirTextField(), BorderLayout.CENTER);
subPanel3.add(selector.getProductDirChooserButton(), BorderLayout.EAST);
final TableLayout tableLayout = new TableLayout(1);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayout.setTableWeightX(1.0);
tableLayout.setCellPadding(0, 0, new Insets(3, 3, 3, 3));
tableLayout.setCellPadding(1, 0, new Insets(3, 0, 3, 3));
tableLayout.setCellPadding(2, 0, new Insets(0, 21, 3, 3));
final JPanel panel = new JPanel(tableLayout);
panel.add(subPanel1);
panel.add(subPanel2);
panel.add(subPanel3);
return panel;
}
void prepareShow() {
prepareShowTargetProductSelector();
if (mosaicModel.isUpdateMode()) {
prepareShowUpdateProductSelector();
}
}
private void prepareShowUpdateProductSelector() {
updateProductSelector.initProducts();
}
private void prepareShowTargetProductSelector() {
try {
final List<File> files = sourceFileEditor.getFiles();
mosaicModel.setSourceProducts(files.toArray(new File[files.size()]));
} catch (IOException ignore) {
}
}
void prepareHide() {
prepareHideUpdateProductSelector();
prepareHideTargetProductSelector();
}
private void prepareHideUpdateProductSelector() {
updateProductSelector.releaseProducts();
}
private void prepareHideTargetProductSelector() {
try {
mosaicModel.setSourceProducts(new File[0]);
} catch (IOException ignore) {
}
}
private static class FileArrayEditorContext implements FileArrayEditor.EditorParent {
private final AppContext applicationContext;
private FileArrayEditorContext(AppContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public File getUserInputDir() {
return getInputProductDir();
}
@Override
public void setUserInputDir(File newDir) {
setInputProductDir(newDir);
}
private void setInputProductDir(final File currentDirectory) {
applicationContext.getPreferences().setPropertyString(INPUT_PRODUCT_DIR_KEY,
currentDirectory.getAbsolutePath());
}
private File getInputProductDir() {
final String path = applicationContext.getPreferences().getPropertyString(INPUT_PRODUCT_DIR_KEY);
final File inputProductDir;
if (path != null) {
inputProductDir = new File(path);
} else {
inputProductDir = null;
}
return inputProductDir;
}
}
private class TargetProductSelectorUpdater implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
final Product product = (Product) evt.getNewValue();
final TargetProductSelectorModel selectorModel = targetProductSelector.getModel();
if (product != null) {
final String formatName = product.getProductReader().getReaderPlugIn().getFormatNames()[0];
final ProductIOPlugInManager ioPlugInManager = ProductIOPlugInManager.getInstance();
final Iterator<ProductWriterPlugIn> writerIterator = ioPlugInManager.getWriterPlugIns(formatName);
if (writerIterator.hasNext()) {
selectorModel.setFormatName(formatName);
} else {
final String errMsg = "Cannot write to update product.";
final String iseMsg = String.format("No product writer found for format '%s'", formatName);
appContext.handleError(errMsg, new IllegalStateException(iseMsg));
}
final File fileLocation = product.getFileLocation();
final String fileName = FileUtils.getFilenameWithoutExtension(fileLocation);
final File fileDir = fileLocation.getParentFile();
selectorModel.setProductName(fileName);
selectorModel.setProductDir(fileDir);
} else {
selectorModel.setFormatName(ProductIO.DEFAULT_FORMAT_NAME);
selectorModel.setProductName("mosaic");
String homeDirPath = SystemUtils.getUserHomeDir().getPath();
final PropertyMap prefs = appContext.getPreferences();
String saveDir = prefs.getPropertyString(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, homeDirPath);
selectorModel.setProductDir(new File(saveDir));
}
}
}
public class UpdateProductFilter implements ProductFilter {
@Override
public boolean accept(Product product) {
ProductReader productReader = product.getProductReader();
if (productReader != null) {
final String formatName = productReader.getReaderPlugIn().getFormatNames()[0];
final ProductIOPlugInManager ioPlugInManager = ProductIOPlugInManager.getInstance();
final Iterator<ProductWriterPlugIn> writerIterator = ioPlugInManager.getWriterPlugIns(formatName);
if (writerIterator.hasNext()) {
try {
MosaicOp.getOperatorParameters(product);
} catch (OperatorException e) {
return false;
}
return true;
}
}
return false;
}
}
}
| 17,409 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MosaicFormModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/mosaic/MosaicFormModel.java | /*
* Copyright (C) 2014 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.mosaic;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.accessors.MapEntryAccessor;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.datamodel.CrsGeoCoding;
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.gpf.GPF;
import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory;
import org.esa.snap.core.gpf.common.MosaicOp;
import org.esa.snap.core.util.math.MathUtils;
import org.esa.snap.ui.BoundsInputPanel;
import org.esa.snap.ui.WorldMapPaneDataModel;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.geometry.Envelope;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.TransformException;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author Marco Peters
* @author Ralf Quast
* @since BEAM 4.7
*/
class MosaicFormModel {
public static final String PROPERTY_UPDATE_PRODUCT = "updateProduct";
public static final String PROPERTY_UPDATE_MODE = "updateMode";
public static final String PROPERTY_SHOW_SOURCE_PRODUCTS = "showSourceProducts";
public static final String PROPERTY_ELEVATION_MODEL_NAME = "elevationModelName";
public static final String PROPERTY_ORTHORECTIFY = "orthorectify";
public static final String PROPERTY_WEST_BOUND = "westBound";
public static final String PROPERTY_NORTH_BOUND = "northBound";
public static final String PROPERTY_EAST_BOUND = "eastBound";
public static final String PROPERTY_SOUTH_BOUND = "southBound";
public static final String PROPERTY_CRS = "crs";
public static final String PROPERTY_PIXEL_SIZE_X = "pixelSizeX";
public static final String PROPERTY_PIXEL_SIZE_Y = "pixelSizeY";
public static final String PROPERTY_MAX_VALUE = "maxValue";
public static final String PROPERTY_MIN_VALUE = "minValue";
private final PropertySet container;
private final Map<String, Object> parameterMap = new HashMap<>();
private final Map<File, Product> sourceProductMap = Collections.synchronizedMap(new HashMap<>());
private final WorldMapPaneDataModel worldMapModel = new WorldMapPaneDataModel();
private MosaicForm parentForm;
MosaicFormModel(MosaicForm parentForm) {
this.parentForm = parentForm;
container = ParameterDescriptorFactory.createMapBackedOperatorPropertyContainer("Mosaic", parameterMap);
addTransientProperty(PROPERTY_UPDATE_PRODUCT, Product.class);
addTransientProperty(PROPERTY_UPDATE_MODE, Boolean.class);
addTransientProperty(PROPERTY_SHOW_SOURCE_PRODUCTS, Boolean.class);
container.setDefaultValues();
container.setValue(PROPERTY_UPDATE_MODE, false);
container.setValue(PROPERTY_SHOW_SOURCE_PRODUCTS, false);
container.addPropertyChangeListener(PROPERTY_SHOW_SOURCE_PRODUCTS, evt -> {
if (Boolean.TRUE.equals(evt.getNewValue())) {
final Collection<Product> products = sourceProductMap.values();
worldMapModel.setProducts(products.toArray(new Product[0]));
} else {
worldMapModel.setProducts(null);
}
});
}
private void addTransientProperty(String propertyName, Class<?> propertyType) {
PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, propertyType);
descriptor.setTransient(true);
container.addProperty(new Property(descriptor,
new MapEntryAccessor(parameterMap, propertyName)));
}
void setSourceProducts(File[] files) throws IOException {
boolean changeSourceProducts = false;
if (files != null && files.length > 0) {
final List<File> fileList = Arrays.asList(files);
final Iterator<Map.Entry<File, Product>> iterator = sourceProductMap.entrySet().iterator();
while (iterator.hasNext()) {
final Map.Entry<File, Product> entry = iterator.next();
if (!fileList.contains(entry.getKey())) {
final Product product = entry.getValue();
worldMapModel.removeProduct(product);
iterator.remove();
if (product != null) {
product.dispose();
}
changeSourceProducts = true;
}
}
for (int i = 0; i < files.length; i++) {
final File file = files[i];
Product product = sourceProductMap.get(file);
if (product == null) {
product = ProductIO.readProduct(file);
sourceProductMap.put(file, product);
if (Boolean.TRUE.equals(getPropertyValue(PROPERTY_SHOW_SOURCE_PRODUCTS))) {
worldMapModel.addProduct(product);
}
changeSourceProducts = true;
}
final int refNo = i + 1;
if (product.getRefNo() != refNo) {
product.resetRefNo();
product.setRefNo(refNo);
}
}
}
/* update region selectable map bounds according to the SourceProducts status: REMOVE or NEW product(s) */
if (changeSourceProducts) updateRegionSelectableMapBounds(files);
}
void updateRegionSelectableMapBounds(File[] files){
/* set default values in case files.length == 0 */
double southBoundVal = 35.0;
double northBoundVal = 75.0;
double westBoundVal = -15.0;
double eastBoundVal = 30.0;
if ( (files.length >= 1) && (sourceProductMap.get(files[0]) != null) ) {
southBoundVal = computeLatitude(sourceProductMap.get(files[0]), PROPERTY_MIN_VALUE);
northBoundVal = computeLatitude(sourceProductMap.get(files[0]), PROPERTY_MAX_VALUE);
westBoundVal = computeLongitude(sourceProductMap.get(files[0]), PROPERTY_MIN_VALUE);
eastBoundVal = computeLongitude(sourceProductMap.get(files[0]), PROPERTY_MAX_VALUE);
}
for (int i = 1; i < files.length; i++) {
if (sourceProductMap.get(files[i]) != null) {
double southBoundValTemp = computeLatitude(sourceProductMap.get(files[i]), PROPERTY_MIN_VALUE);
double northBoundValTemp = computeLatitude(sourceProductMap.get(files[i]), PROPERTY_MAX_VALUE);
double westBoundValTemp = computeLongitude(sourceProductMap.get(files[i]), PROPERTY_MIN_VALUE);
double eastBoundValTemp = computeLongitude(sourceProductMap.get(files[i]), PROPERTY_MAX_VALUE);
if (southBoundValTemp < southBoundVal) southBoundVal = southBoundValTemp;
if (northBoundValTemp > northBoundVal) northBoundVal = northBoundValTemp;
if (westBoundValTemp < westBoundVal) westBoundVal = westBoundValTemp;
if (eastBoundValTemp > eastBoundVal) eastBoundVal = eastBoundValTemp;
}
}
parentForm.setCardinalBounds(southBoundVal, northBoundVal, westBoundVal,eastBoundVal);
}
double computeLatitude(Product product, String level){
Double[] latitudePoints = {
product.getSceneGeoCoding().getGeoPos(new PixelPos(0.5, 0.5), null).getLat(),
product.getSceneGeoCoding().getGeoPos(new PixelPos(0.5, product.getSceneRasterHeight() - 0.5), null).getLat(),
product.getSceneGeoCoding().getGeoPos(new PixelPos(product.getSceneRasterWidth() - 0.5, 0.5), null).getLat(),
product.getSceneGeoCoding().getGeoPos(new PixelPos(product.getSceneRasterWidth() - 0.5, product.getSceneRasterHeight() - 0.5), null).getLat()
};
switch(level) {
case PROPERTY_MIN_VALUE :
return Collections.min(Arrays.asList(latitudePoints));
case PROPERTY_MAX_VALUE :
return Collections.max(Arrays.asList(latitudePoints));
default :
return Double.MAX_VALUE;
}
}
double computeLongitude(Product product, String level){
Double[] longitudePoints = {
product.getSceneGeoCoding().getGeoPos(new PixelPos(0.5, 0.5), null).getLon(),
product.getSceneGeoCoding().getGeoPos(new PixelPos(0.5, product.getSceneRasterHeight() - 0.5), null).getLon(),
product.getSceneGeoCoding().getGeoPos(new PixelPos(product.getSceneRasterWidth() - 0.5, 0.5), null).getLon(),
product.getSceneGeoCoding().getGeoPos(new PixelPos(product.getSceneRasterWidth() - 0.5, product.getSceneRasterHeight() - 0.5), null).getLon()
};
switch(level) {
case PROPERTY_MIN_VALUE :
return Collections.min(Arrays.asList(longitudePoints));
case PROPERTY_MAX_VALUE :
return Collections.max(Arrays.asList(longitudePoints));
default :
return Double.MAX_VALUE;
}
}
Map<String, Object> getParameterMap() {
return parameterMap;
}
Map<String, Product> getSourceProductMap() {
final HashMap<String, Product> map = new HashMap<>(sourceProductMap.size());
for (final Product product : sourceProductMap.values()) {
map.put(GPF.SOURCE_PRODUCT_FIELD_NAME + product.getRefNo(), product);
}
if (Boolean.TRUE.equals(container.getValue(PROPERTY_UPDATE_MODE))) {
final Product updateProduct = getUpdateProduct();
if (updateProduct != null) {
map.put(PROPERTY_UPDATE_PRODUCT, updateProduct);
}
}
return map;
}
boolean isUpdateMode() {
return Boolean.TRUE.equals(getPropertyValue(PROPERTY_UPDATE_MODE));
}
Product getUpdateProduct() {
final Object value = getPropertyValue(PROPERTY_UPDATE_PRODUCT);
if (value instanceof Product) {
return (Product) value;
}
return null;
}
void setUpdateProduct(Product product) {
setPropertyValue(PROPERTY_UPDATE_PRODUCT, product);
if (product != null && product.getSceneGeoCoding() != null && product.getSceneGeoCoding().getMapCRS() != null) {
setTargetCRS(product.getSceneGeoCoding().getMapCRS().toWKT());
}
}
MosaicOp.Variable[] getVariables() {
return (MosaicOp.Variable[]) getPropertyValue("variables");
}
MosaicOp.Condition[] getConditions() {
return (MosaicOp.Condition[]) getPropertyValue("conditions");
}
PropertySet getPropertySet() {
return container;
}
public Object getPropertyValue(String propertyName) {
return container.getValue(propertyName);
}
public void setPropertyValue(String propertyName, Object value) {
container.setValue(propertyName, value);
}
public Product getReferenceProduct() throws IOException {
for (Product product : sourceProductMap.values()) {
if (product.getRefNo() == 1) {
return product;
}
}
return null;
}
public Product getBoundaryProduct() throws FactoryException, TransformException {
final CoordinateReferenceSystem mapCRS = getTargetCRS();
if (mapCRS != null) {
final ReferencedEnvelope envelope = getTargetEnvelope();
final Envelope mapEnvelope = envelope.transform(mapCRS, true);
final double pixelSizeX = (Double) getPropertyValue(PROPERTY_PIXEL_SIZE_X);
final double pixelSizeY = (Double) getPropertyValue(PROPERTY_PIXEL_SIZE_Y);
final int w = MathUtils.floorInt(mapEnvelope.getSpan(0) / pixelSizeX);
final int h = MathUtils.floorInt(mapEnvelope.getSpan(1) / pixelSizeY);
final Product product = new Product("mosaic", "MosaicBounds", w, h);
final GeoCoding geoCoding = new CrsGeoCoding(mapCRS,
w, h,
mapEnvelope.getMinimum(0),
mapEnvelope.getMaximum(1),
pixelSizeX, pixelSizeY);
product.setSceneGeoCoding(geoCoding);
return product;
}
return null;
}
void setTargetCRS(String crs) {
setPropertyValue("crs", crs);
}
CoordinateReferenceSystem getTargetCRS() throws FactoryException {
final String crs = (String) getPropertyValue("crs");
if (crs == null) {
return null;
}
try {
return CRS.parseWKT(crs);
} catch (FactoryException ignored) {
return CRS.decode(crs, true);
}
}
ReferencedEnvelope getTargetEnvelope() {
final double west = (Double) getPropertyValue(BoundsInputPanel.PROPERTY_WEST_BOUND);
final double north = (Double) getPropertyValue(BoundsInputPanel.PROPERTY_NORTH_BOUND);
final double east = (Double) getPropertyValue(BoundsInputPanel.PROPERTY_EAST_BOUND);
final double south = (Double) getPropertyValue(BoundsInputPanel.PROPERTY_SOUTH_BOUND);
final Rectangle2D bounds = new Rectangle2D.Double();
bounds.setFrameFromDiagonal(west, north, east, south);
return new ReferencedEnvelope(bounds, DefaultGeographicCRS.WGS84);
}
public WorldMapPaneDataModel getWorldMapModel() {
return worldMapModel;
}
public String getElevationModelName() {
boolean orthorectify = (boolean) getPropertyValue(PROPERTY_ORTHORECTIFY);
if (orthorectify) {
return (String) getPropertyValue(PROPERTY_ELEVATION_MODEL_NAME);
}
return null;
}
}
| 15,080 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MosaicMapProjectionPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/mosaic/MosaicMapProjectionPanel.java | /*
* Copyright (C) 2011 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.mosaic;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.dataop.dem.ElevationModelDescriptor;
import org.esa.snap.core.dataop.dem.ElevationModelRegistry;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.BoundsInputPanel;
import org.esa.snap.ui.RegionSelectableWorldMapPane;
import org.esa.snap.ui.WorldMapPaneDataModel;
import org.esa.snap.ui.crs.CrsForm;
import org.esa.snap.ui.crs.CrsSelectionPanel;
import org.esa.snap.ui.crs.CustomCrsForm;
import org.esa.snap.ui.crs.PredefinedCrsForm;
import org.geotools.referencing.wkt.UnformattableObjectException;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
/**
* @author Marco Peters
* @since BEAM 4.7
*/
class MosaicMapProjectionPanel extends JPanel {
private final AppContext appContext;
private final MosaicFormModel mosaicModel;
private CrsSelectionPanel crsSelectionPanel;
private BoundsInputPanel boundsInputPanel;
private final BindingContext bindingCtx;
private String[] demValueSet;
MosaicMapProjectionPanel(AppContext appContext, MosaicFormModel mosaicModel) {
this.appContext = appContext;
this.mosaicModel = mosaicModel;
bindingCtx = new BindingContext(mosaicModel.getPropertySet());
init();
createUI();
updateForCrsChanged();
bindingCtx.adjustComponents();
}
public BindingContext getBindingContext() {
return bindingCtx;
}
private void init() {
final ElevationModelDescriptor[] descriptors = ElevationModelRegistry.getInstance().getAllDescriptors();
demValueSet = new String[descriptors.length];
for (int i = 0; i < descriptors.length; i++) {
demValueSet[i] = descriptors[i].getName();
}
if (demValueSet.length > 0) {
mosaicModel.getPropertySet().setValue(MosaicFormModel.PROPERTY_ELEVATION_MODEL_NAME, demValueSet[0]);
}
bindingCtx.addPropertyChangeListener(MosaicFormModel.PROPERTY_UPDATE_MODE, evt -> {
final Boolean updateMode = (Boolean) evt.getNewValue();
boolean enabled1 = !updateMode;
crsSelectionPanel.setEnabled(enabled1);
});
}
private void createUI() {
final TableLayout layout = new TableLayout(1);
layout.setTableAnchor(TableLayout.Anchor.WEST);
layout.setTableFill(TableLayout.Fill.BOTH);
layout.setTableWeightX(1.0);
layout.setTableWeightY(0.0);
layout.setRowWeightY(2, 1.0);
layout.setTablePadding(3, 3);
setLayout(layout);
CrsForm customCrsUI = new CustomCrsForm(appContext);
CrsForm predefinedCrsUI = new PredefinedCrsForm(appContext);
crsSelectionPanel = new CrsSelectionPanel(customCrsUI, predefinedCrsUI);
crsSelectionPanel.addPropertyChangeListener(MosaicFormModel.PROPERTY_CRS, evt -> updateForCrsChanged());
add(crsSelectionPanel);
add(createOrthorectifyPanel());
add(createMosaicBoundsPanel());
}
private void updateForCrsChanged() {
final float lon = (float) mosaicModel.getTargetEnvelope().getMedian(0);
final float lat = (float) mosaicModel.getTargetEnvelope().getMedian(1);
try {
final CoordinateReferenceSystem crs = crsSelectionPanel.getCrs(new GeoPos(lat, lon));
if (crs != null) {
updatePixelUnit(crs);
mosaicModel.setTargetCRS(convertToWkt(crs));
} else {
mosaicModel.setTargetCRS(null);
}
} catch (FactoryException ignored) {
mosaicModel.setTargetCRS(null);
}
}
private String convertToWkt(CoordinateReferenceSystem crs) {
// according to GeoTools it is better to use to String or the Formattable directly
// https://osgeo-org.atlassian.net/browse/GEOS-4746
// But first try toWKT(), there must be a reason for being strict in this method.
try {
return crs.toWKT();
} catch (UnformattableObjectException e) {
SystemUtils.LOG.log(Level.WARNING, "Could not strictly convert CRS to WKT. " +
"Used lenient method instead.", e);
return crs.toString();
}
}
private void updatePixelUnit(CoordinateReferenceSystem crs) {
boundsInputPanel.updatePixelUnit(crs);
}
private JPanel createMosaicBoundsPanel() {
final TableLayout layout = new TableLayout(1);
layout.setTableAnchor(TableLayout.Anchor.WEST);
layout.setTableFill(TableLayout.Fill.BOTH);
layout.setTableWeightX(1.0);
layout.setTableWeightY(0.0);
layout.setRowWeightY(1, 1.0);
layout.setRowAnchor(2, TableLayout.Anchor.EAST);
layout.setRowFill(2, TableLayout.Fill.NONE);
layout.setTablePadding(3, 3);
final JPanel panel = new JPanel(layout);
panel.setBorder(BorderFactory.createTitledBorder("Mosaic Bounds"));
final WorldMapPaneDataModel worldMapModel = mosaicModel.getWorldMapModel();
setMapBoundary(worldMapModel);
final JPanel worldMapPanel = new RegionSelectableWorldMapPane(worldMapModel, bindingCtx).createUI();
bindingCtx.addPropertyChangeListener(new MapBoundsChangeListener());
worldMapPanel.setMinimumSize(new Dimension(250, 125));
worldMapPanel.setBorder(BorderFactory.createEtchedBorder());
final JCheckBox showSourceProductsCheckBox = new JCheckBox("Display source products");
bindingCtx.bind(MosaicFormModel.PROPERTY_SHOW_SOURCE_PRODUCTS, showSourceProductsCheckBox);
boundsInputPanel = new BoundsInputPanel(bindingCtx, MosaicFormModel.PROPERTY_UPDATE_MODE);
panel.add(boundsInputPanel.createBoundsInputPanel(true));
panel.add(worldMapPanel);
panel.add(showSourceProductsCheckBox);
return panel;
}
private JPanel createOrthorectifyPanel() {
final TableLayout layout = new TableLayout(2);
layout.setTableAnchor(TableLayout.Anchor.WEST);
layout.setTableFill(TableLayout.Fill.HORIZONTAL);
layout.setTableWeightX(1.0);
layout.setTableWeightY(1.0);
layout.setTablePadding(3, 3);
final JPanel panel = new JPanel(layout);
panel.setBorder(BorderFactory.createTitledBorder("Orthorectification"));
final JCheckBox orthoCheckBox = new JCheckBox("Orthorectify input products");
bindingCtx.bind(MosaicFormModel.PROPERTY_ORTHORECTIFY, orthoCheckBox);
bindingCtx.bindEnabledState(MosaicFormModel.PROPERTY_ORTHORECTIFY, false, MosaicFormModel.PROPERTY_UPDATE_MODE, true);
final JComboBox<String> demComboBox = new JComboBox<>(new DefaultComboBoxModel<>(demValueSet));
bindingCtx.bind(MosaicFormModel.PROPERTY_ELEVATION_MODEL_NAME, demComboBox);
bindingCtx.addPropertyChangeListener(evt -> {
if (MosaicFormModel.PROPERTY_ORTHORECTIFY.equals(evt.getPropertyName()) ||
MosaicFormModel.PROPERTY_UPDATE_MODE.equals(evt.getPropertyName())) {
final PropertySet propertySet = bindingCtx.getPropertySet();
boolean updateMode = Boolean.TRUE.equals(propertySet.getValue(MosaicFormModel.PROPERTY_UPDATE_MODE));
boolean orthorectify = Boolean.TRUE.equals(propertySet.getValue(MosaicFormModel.PROPERTY_ORTHORECTIFY));
demComboBox.setEnabled(orthorectify && !updateMode);
}
});
layout.setCellColspan(0, 0, 2);
panel.add(orthoCheckBox);
layout.setCellWeightX(1, 0, 0.0);
panel.add(new JLabel("Elevation model:"));
layout.setCellWeightX(1, 1, 1.0);
panel.add(demComboBox);
return panel;
}
private void setMapBoundary(WorldMapPaneDataModel worldMapModel) {
Product boundaryProduct;
try {
boundaryProduct = mosaicModel.getBoundaryProduct();
} catch (Throwable ignored) {
boundaryProduct = null;
}
worldMapModel.setSelectedProduct(boundaryProduct);
}
public void prepareShow() {
crsSelectionPanel.prepareShow();
}
public void prepareHide() {
crsSelectionPanel.prepareHide();
}
private class MapBoundsChangeListener implements PropertyChangeListener {
private final List<String> knownProperties;
private MapBoundsChangeListener() {
knownProperties = Arrays.asList(
MosaicFormModel.PROPERTY_WEST_BOUND, MosaicFormModel.PROPERTY_NORTH_BOUND, MosaicFormModel.PROPERTY_EAST_BOUND, MosaicFormModel.PROPERTY_SOUTH_BOUND, MosaicFormModel.PROPERTY_CRS);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (knownProperties.contains(evt.getPropertyName())) {
setMapBoundary(mosaicModel.getWorldMapModel());
}
}
}
}
| 10,288 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractTableAdapter.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/mosaic/AbstractTableAdapter.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.mosaic;
import com.bc.ceres.swing.binding.ComponentAdapter;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import java.lang.reflect.Field;
import java.util.Vector;
abstract class AbstractTableAdapter extends ComponentAdapter implements TableModelListener {
private final JTable table;
protected AbstractTableAdapter(
JTable table) {
this.table = table;
}
JTable getTable() {
return table;
}
@Override
public final JComponent[] getComponents() {
return new JComponent[]{table};
}
@Override
public final void bindComponents() {
table.setModel(createTableModel(0));
adjustTableModel();
table.getModel().addTableModelListener(this);
}
@Override
public final void unbindComponents() {
table.getModel().removeTableModelListener(this);
}
@Override
public final void adjustComponents() {
adjustTableModel();
}
@Override
public abstract void tableChanged(TableModelEvent e);
protected abstract DefaultTableModel createTableModel(int rowCount);
private void adjustTableModel() {
final DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
final Object value = getBinding().getPropertyValue();
if (value instanceof Object[]) {
final Object[] items = (Object[]) value;
// 1. add missing rows to model
for (int i = tableModel.getRowCount(); i < items.length; i++) {
tableModel.addRow((Object[]) null);
}
// 2. remove redundant rows from model
for (int i = items.length; i < tableModel.getRowCount(); i++) {
tableModel.removeRow(i);
}
// 3. update cell values
for (int i = 0; i < items.length; i++) {
final Object item = items[i];
final Field[] fields = item.getClass().getDeclaredFields();
for (int k = 0; k < fields.length; k++) {
final Field field = fields[k];
final boolean accessible = field.isAccessible();
if (!accessible) {
field.setAccessible(true);
}
try {
Vector dataVector = tableModel.getDataVector();
Vector row = (Vector)dataVector.elementAt(i);
// 1. add missing columns to row
for (int l = row.size(); l < fields.length; l++) {
row.add(null);
}
// 2. remove redundant columns from row
for (int l = fields.length; l < row.size(); l++) {
row.remove(l);
}
tableModel.setValueAt(field.get(item), i, k);
} catch (IllegalAccessException e) {
// ignore
}
if (!accessible) {
field.setAccessible(false);
}
}
}
}
}
}
| 4,072 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VariablesTableAdapter.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/mosaic/VariablesTableAdapter.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.mosaic;
import org.esa.snap.core.gpf.common.MosaicOp;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
class VariablesTableAdapter extends AbstractTableAdapter {
VariablesTableAdapter(JTable table) {
super(table);
}
@Override
public void tableChanged(TableModelEvent e) {
final TableModel tableModel = (TableModel) e.getSource();
final MosaicOp.Variable[] variables = new MosaicOp.Variable[tableModel.getRowCount()];
for (int i = 0; i < variables.length; i++) {
variables[i] = new MosaicOp.Variable((String) tableModel.getValueAt(i, 0),
(String) tableModel.getValueAt(i, 1));
}
getBinding().setPropertyValue(variables);
}
@Override
protected final DefaultTableModel createTableModel(int rowCount) {
return new DefaultTableModel(new String[]{"Name", "Expression"}, rowCount);
}
}
| 1,790 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MosaicDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/mosaic/MosaicDialog.java | /*
* Copyright (C) 2014 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.mosaic;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.dataop.barithm.BandArithmetic;
import org.esa.snap.core.dataop.dem.ElevationModelDescriptor;
import org.esa.snap.core.dataop.dem.ElevationModelRegistry;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.gpf.OperatorSpi;
import org.esa.snap.core.gpf.common.MosaicOp;
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.core.gpf.ui.TargetProductSelector;
import org.esa.snap.core.jexp.ParseException;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.ui.AppContext;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import java.util.Map;
class MosaicDialog extends SingleTargetProductDialog {
private final MosaicForm form;
MosaicDialog(final String title, final String helpID, AppContext appContext) {
super(appContext, title, ID_APPLY_CLOSE, helpID);
final TargetProductSelector selector = getTargetProductSelector();
selector.getModel().setSaveToFileSelected(true);
selector.getModel().setProductName("mosaic");
selector.getSaveToFileCheckBox().setEnabled(false);
form = new MosaicForm(selector, appContext);
final OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi("Mosaic");
MosaicFormModel formModel = form.getFormModel();
OperatorParameterSupport parameterSupport = new OperatorParameterSupport(operatorSpi.getOperatorDescriptor(),
formModel.getPropertySet(),
formModel.getParameterMap(),
null);
OperatorMenu operatorMenu = new OperatorMenu(this.getJDialog(),
operatorSpi.getOperatorDescriptor(),
parameterSupport,
appContext,
helpID);
getJDialog().setJMenuBar(operatorMenu.createDefaultMenu());
}
@Override
protected boolean verifyUserInput() {
final MosaicFormModel mosaicModel = form.getFormModel();
if (!verifySourceProducts(mosaicModel)) {
return false;
}
if (!verifyTargetCrs(mosaicModel)) {
return false;
}
if (!verifyVariablesAndConditions(mosaicModel)) {
return false;
}
if (mosaicModel.isUpdateMode() && mosaicModel.getUpdateProduct() == null) {
showErrorDialog("No product to update specified.");
return false;
}
final String productName = getTargetProductSelector().getModel().getProductName();
if (!mosaicModel.isUpdateMode() && StringUtils.isNullOrEmpty(productName)) {
showErrorDialog("No name for the target product specified.");
return false;
}
final boolean varsNotSpecified = mosaicModel.getVariables() == null || mosaicModel.getVariables().length == 0;
final boolean condsNotSpecified =
mosaicModel.getConditions() == null || mosaicModel.getConditions().length == 0;
if (varsNotSpecified && condsNotSpecified) {
showErrorDialog("No variables or conditions specified.");
return false;
}
return verifyDEM(mosaicModel);
}
@Override
protected Product createTargetProduct() throws Exception {
final MosaicFormModel formModel = form.getFormModel();
return GPF.createProduct("Mosaic", formModel.getParameterMap(), formModel.getSourceProductMap());
}
@Override
public int show() {
form.prepareShow();
setContent(form);
return super.show();
}
@Override
public void hide() {
form.prepareHide();
super.hide();
}
private boolean verifyVariablesAndConditions(MosaicFormModel mosaicModel) {
final Map<String, Product> sourceProductMap = mosaicModel.getSourceProductMap();
final MosaicOp.Variable[] variables = mosaicModel.getVariables();
final MosaicOp.Condition[] conditions = mosaicModel.getConditions();
for (Map.Entry<String, Product> entry : sourceProductMap.entrySet()) {
final String productIdentifier = entry.getKey();
final Product product = entry.getValue();
if (variables != null) {
for (MosaicOp.Variable variable : variables) {
if (!isExpressionValidForProduct(variable.getName(), variable.getExpression(), productIdentifier, product)) {
return false;
}
}
}
if (conditions != null) {
for (MosaicOp.Condition condition : conditions) {
if (!isExpressionValidForProduct(condition.getName(), condition.getExpression(), productIdentifier, product)) {
return false;
}
}
}
}
return true;
}
private boolean isExpressionValidForProduct(String expressionName, String expression, String productIdentifier, Product product) {
try {
BandArithmetic.parseExpression(expression, new Product[]{product}, 0);
return true;
} catch (ParseException e) {
final String msg = String.format("Expression '%s' is invalid for product '%s'.\n%s",
expressionName,
productIdentifier,
e.getMessage());
showErrorDialog(msg);
e.printStackTrace();
return false;
}
}
private boolean verifyTargetCrs(MosaicFormModel formModel) {
try {
final CoordinateReferenceSystem crs = formModel.getTargetCRS();
if (crs == null) {
showErrorDialog("No 'Coordinate Reference System' selected.");
return false;
}
} catch (FactoryException e) {
e.printStackTrace();
showErrorDialog("No 'Coordinate Reference System' selected.\n" + e.getMessage());
return false;
}
return true;
}
private boolean verifySourceProducts(MosaicFormModel formModel) {
final Map<String, Product> sourceProductMap = formModel.getSourceProductMap();
if (sourceProductMap == null || sourceProductMap.isEmpty()) {
showErrorDialog("No source products specified.");
return false;
}
for (Map.Entry<String, Product> productEntry : sourceProductMap.entrySet()) {
if (productEntry.getValue().isMultiSize()) {
showErrorDialog(String.format("Product '%s' contains bands of different sizes. " +
"Currently it is not possible to use it for mosaicking.",
productEntry.getKey()));
return false;
}
}
return true;
}
private boolean verifyDEM(MosaicFormModel formModel) {
String externalDemName = formModel.getElevationModelName();
if (externalDemName != null) {
final ElevationModelRegistry elevationModelRegistry = ElevationModelRegistry.getInstance();
final ElevationModelDescriptor demDescriptor = elevationModelRegistry.getDescriptor(externalDemName);
if (demDescriptor == null) {
showErrorDialog("The DEM '" + externalDemName + "' is not supported.");
return false;
}
}
return true;
}
}
| 8,793 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MosaicExpressionsPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/mosaic/MosaicExpressionsPanel.java | /*
* Copyright (C) 2011 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.mosaic;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.jexp.impl.Tokenizer;
import org.esa.snap.core.util.ArrayUtils;
import org.esa.snap.core.util.MouseEventFilterFactory;
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.product.BandChooser;
import org.esa.snap.ui.product.ProductExpressionPane;
import org.esa.snap.ui.tool.ToolButtonFactory;
import javax.swing.AbstractButton;
import javax.swing.AbstractCellEditor;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class MosaicExpressionsPanel extends JPanel {
private static final int PREFERRED_TABLE_WIDTH = 520;
private final AppContext appContext;
private final BindingContext bindingCtx;
private JTable variablesTable;
private JTable conditionsTable;
private MosaicFormModel mosaicModel;
MosaicExpressionsPanel(AppContext appContext, MosaicFormModel model) {
this.appContext = appContext;
mosaicModel = model;
this.bindingCtx = new BindingContext(model.getPropertySet());
init();
}
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(1.0);
tableLayout.setTablePadding(3, 3);
setLayout(tableLayout);
add(createVariablesPanel());
add(createConditionsPanel());
}
private Component createVariablesPanel() {
final String labelName = "Variables"; /*I18N*/
final TableLayout layout = new TableLayout(1);
layout.setTableAnchor(TableLayout.Anchor.WEST);
layout.setTableFill(TableLayout.Fill.BOTH);
layout.setTablePadding(3, 3);
layout.setTableWeightX(1.0);
layout.setTableWeightY(1.0);
layout.setRowWeightY(0, 0.0);
final JPanel panel = new JPanel(layout);
panel.setBorder(BorderFactory.createTitledBorder(labelName));
panel.setName(labelName);
panel.add(createVariablesButtonPanel(labelName));
panel.add(createVariablesTable(labelName));
return panel;
}
private JPanel createVariablesButtonPanel(String labelName) {
final JPanel variableButtonsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
variableButtonsPanel.setName(labelName);
final Component bandFilterButton = createBandFilterButton();
bandFilterButton.setName(labelName + "_bandFilter");
variableButtonsPanel.add(bandFilterButton);
final Component newVariableButton = createNewVariableButton();
newVariableButton.setName(labelName + "_newVariable");
variableButtonsPanel.add(newVariableButton);
final Component removeVariableButton = createRemoveVariableButton();
removeVariableButton.setName(labelName + "_removeVariable");
variableButtonsPanel.add(removeVariableButton);
final Component moveVariableUpButton = createMoveVariableUpButton();
moveVariableUpButton.setName(labelName + "moveVariableUp");
variableButtonsPanel.add(moveVariableUpButton);
final Component moveVariableDownButton = createMoveVariableDownButton();
moveVariableDownButton.setName(labelName + "moveVariableDown");
variableButtonsPanel.add(moveVariableDownButton);
bindingCtx.addPropertyChangeListener("updateMode", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
final boolean enabled = Boolean.FALSE.equals(evt.getNewValue());
bandFilterButton.setEnabled(enabled);
newVariableButton.setEnabled(enabled);
removeVariableButton.setEnabled(enabled);
moveVariableUpButton.setEnabled(enabled);
moveVariableDownButton.setEnabled(enabled);
}
});
return variableButtonsPanel;
}
private Component createConditionsPanel() {
final String labelName = "Conditions";
final TableLayout layout = new TableLayout(1);
layout.setTableAnchor(TableLayout.Anchor.WEST);
layout.setTableFill(TableLayout.Fill.BOTH);
layout.setTablePadding(3, 3);
layout.setTableWeightX(1.0);
layout.setTableWeightY(0.0);
layout.setRowWeightY(1, 1.0);
final JPanel panel = new JPanel(layout);
panel.setName(labelName);
panel.setBorder(BorderFactory.createTitledBorder(labelName));
final JPanel conditionsButtonsPanel = createConditionsButtonPanel(labelName);
panel.add(conditionsButtonsPanel);
panel.add(createConditionsTable(labelName));
panel.add(createCombinePanel());
return panel;
}
private JPanel createConditionsButtonPanel(String labelName) {
final JPanel conditionButtonsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
conditionButtonsPanel.setName(labelName);
final Component newConditionButton = createNewConditionButton();
newConditionButton.setName(labelName + "_newCondition");
conditionButtonsPanel.add(newConditionButton);
final Component removeConditionButton = createRemoveConditionButton();
removeConditionButton.setName(labelName + "_removeCondition");
conditionButtonsPanel.add(removeConditionButton);
final Component moveConditionUpButton = createMoveConditionUpButton();
moveConditionUpButton.setName(labelName + "moveConditionUp");
conditionButtonsPanel.add(moveConditionUpButton);
final Component moveConditionDownButton = createMoveConditionDownButton();
moveConditionDownButton.setName(labelName + "moveConditionDown");
conditionButtonsPanel.add(moveConditionDownButton);
bindingCtx.addPropertyChangeListener("updateMode", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
final boolean enabled = Boolean.FALSE.equals(evt.getNewValue());
newConditionButton.setEnabled(enabled);
removeConditionButton.setEnabled(enabled);
moveConditionUpButton.setEnabled(enabled);
moveConditionDownButton.setEnabled(enabled);
}
});
return conditionButtonsPanel;
}
private JPanel createCombinePanel() {
final JPanel combinePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
final JComboBox combineComboBox = new JComboBox();
bindingCtx.bind("combine", combineComboBox);
bindingCtx.bindEnabledState("combine", false, "updateMode", true);
final String displayName = bindingCtx.getPropertySet().getDescriptor("combine").getDisplayName();
combinePanel.add(new JLabel(displayName + ":"));
combinePanel.add(combineComboBox);
return combinePanel;
}
private Component createNewConditionButton() {
AbstractButton newConditionsButton = createButton("icons/Plus24.gif", "newCondition");
newConditionsButton.setToolTipText("Add new processing condition"); /*I18N*/
newConditionsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final int rows = conditionsTable.getRowCount();
addRow(conditionsTable, new Object[]{"condition_" + rows, "", false}); /*I18N*/
}
});
return newConditionsButton;
}
private Component createRemoveConditionButton() {
AbstractButton removeConditionButton = createButton("icons/Minus24.gif", "removeCondition");
removeConditionButton.setToolTipText("Remove selected rows."); /*I18N*/
removeConditionButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
removeRows(conditionsTable, conditionsTable.getSelectedRows());
}
});
return removeConditionButton;
}
private Component createMoveConditionUpButton() {
AbstractButton moveConditionUpButton = createButton("icons/MoveUp24.gif", "moveConditionUp");
moveConditionUpButton.setToolTipText("Move up selected rows."); /*I18N*/
moveConditionUpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moveRowsUp(conditionsTable, conditionsTable.getSelectedRows());
}
});
return moveConditionUpButton;
}
private Component createMoveConditionDownButton() {
AbstractButton moveConditionDownButton = createButton("icons/MoveDown24.gif", "moveConditionDown");
moveConditionDownButton.setToolTipText("Move down selected rows."); /*I18N*/
moveConditionDownButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moveRowsDown(conditionsTable, conditionsTable.getSelectedRows());
}
});
return moveConditionDownButton;
}
private JScrollPane createConditionsTable(final String labelName) {
conditionsTable = new JTable() {
private static final long serialVersionUID = 1L;
@Override
public Class getColumnClass(int column) {
if (column == 2) {
return Boolean.class;
} else {
return super.getColumnClass(column);
}
}
};
conditionsTable.setName(labelName);
conditionsTable.setRowSelectionAllowed(true);
bindingCtx.bind("conditions", new ConditionsTableAdapter(conditionsTable));
bindingCtx.bindEnabledState("conditions", false, "updateMode", true);
conditionsTable.addMouseListener(createExpressionEditorMouseListener(conditionsTable, true));
final JTableHeader tableHeader = conditionsTable.getTableHeader();
tableHeader.setName(labelName);
tableHeader.setReorderingAllowed(false);
tableHeader.setResizingAllowed(true);
final TableColumnModel columnModel = conditionsTable.getColumnModel();
columnModel.setColumnSelectionAllowed(false);
final TableColumn nameColumn = columnModel.getColumn(0);
nameColumn.setPreferredWidth(100);
nameColumn.setCellRenderer(new TCR());
final TableColumn expressionColumn = columnModel.getColumn(1);
expressionColumn.setPreferredWidth(360);
expressionColumn.setCellRenderer(new TCR());
final ExprEditor cellEditor = new ExprEditor(true);
expressionColumn.setCellEditor(cellEditor);
bindingCtx.addPropertyChangeListener("updateMode", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
final boolean enabled = Boolean.FALSE.equals(evt.getNewValue());
cellEditor.button.setEnabled(enabled);
}
});
final TableColumn outputColumn = columnModel.getColumn(2);
outputColumn.setPreferredWidth(40);
final JScrollPane pane = new JScrollPane(conditionsTable);
pane.setName(labelName);
pane.setPreferredSize(new Dimension(PREFERRED_TABLE_WIDTH, 80));
return pane;
}
private Component createBandFilterButton() {
AbstractButton variableFilterButton = createButton("icons/Copy16.gif", "bandButton");
variableFilterButton.setToolTipText("Choose the bands to process"); /*I18N*/
variableFilterButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Product product;
try {
product = mosaicModel.getReferenceProduct();
} catch (IOException ioe) {
appContext.handleError(ioe.getMessage(), ioe);
return;
}
if (product != null) {
final String[] availableBandNames = product.getBandNames();
final Band[] allBands = product.getBands();
final List dataVector = ((DefaultTableModel) variablesTable.getModel()).getDataVector();
final List<Band> existingBands = new ArrayList<Band>(dataVector.size());
for (Object aDataVector : dataVector) {
List row = (List) aDataVector;
final String name = (String) row.get(0);
final String expression = (String) row.get(1);
if (name == null || expression == null
|| !StringUtils.contains(availableBandNames, name.trim())
|| !name.trim().equals(expression.trim())) {
continue;
}
existingBands.add(product.getBand(name.trim()));
}
final BandChooser bandChooser = new BandChooser(appContext.getApplicationWindow(), "Band Chooser",
null,
allBands, /*I18N*/
existingBands.toArray(
new Band[existingBands.size()]), true
);
if (bandChooser.show() == ModalDialog.ID_OK) {
final Band[] selectedBands = bandChooser.getSelectedBands();
for (Band selectedBand : selectedBands) {
if (!existingBands.contains(selectedBand)) {
final String name = selectedBand.getName();
final String expression = Tokenizer.createExternalName(name);
addRow(variablesTable, new Object[]{name, expression});
} else {
existingBands.remove(selectedBand);
}
}
final int[] rowsToRemove = new int[0];
final List newDataVector = ((DefaultTableModel) variablesTable.getModel()).getDataVector();
for (Band existingBand : existingBands) {
String bandName = existingBand.getName();
final int rowIndex = getBandRow(newDataVector, bandName);
if (rowIndex > -1) {
ArrayUtils.addToArray(rowsToRemove, rowIndex);
}
}
removeRows(variablesTable, rowsToRemove);
}
}
}
});
return variableFilterButton;
}
private static int getBandRow(List newDataVector, String bandName) {
for (int i = 0; i < newDataVector.size(); i++) {
List row = (List) newDataVector.get(i);
if (bandName.equals(row.get(0)) && bandName.equals(row.get(1))) {
return i;
}
}
return -1;
}
private Component createNewVariableButton() {
AbstractButton newVariableButton = createButton("icons/Plus24.gif", "newVariable");
newVariableButton.setToolTipText("Add new processing variable"); /*I18N*/
newVariableButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final int rows = variablesTable.getRowCount();
addRow(variablesTable, new Object[]{"variable_" + rows, ""}); /*I18N*/
}
});
return newVariableButton;
}
private Component createRemoveVariableButton() {
AbstractButton removeVariableButton = createButton("icons/Minus24.gif", "removeVariable");
removeVariableButton.setToolTipText("Remove selected rows."); /*I18N*/
removeVariableButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
removeRows(variablesTable, variablesTable.getSelectedRows());
}
});
return removeVariableButton;
}
private Component createMoveVariableUpButton() {
AbstractButton moveVariableUpButton = createButton("icons/MoveUp24.gif", "moveVariableUp");
moveVariableUpButton.setToolTipText("Move up selected rows."); /*I18N*/
moveVariableUpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moveRowsUp(variablesTable, variablesTable.getSelectedRows());
}
});
return moveVariableUpButton;
}
private Component createMoveVariableDownButton() {
AbstractButton moveVariableDownButton = createButton("icons/MoveDown24.gif", "moveVariableDown");
moveVariableDownButton.setToolTipText("Move down selected rows."); /*I18N*/
moveVariableDownButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moveRowsDown(variablesTable, variablesTable.getSelectedRows());
}
});
return moveVariableDownButton;
}
private JScrollPane createVariablesTable(final String labelName) {
variablesTable = new JTable();
variablesTable.setName(labelName);
variablesTable.setRowSelectionAllowed(true);
bindingCtx.bind("variables", new VariablesTableAdapter(variablesTable));
bindingCtx.bindEnabledState("variables", false, "updateMode", true);
variablesTable.addMouseListener(createExpressionEditorMouseListener(variablesTable, false));
final JTableHeader tableHeader = variablesTable.getTableHeader();
tableHeader.setName(labelName);
tableHeader.setReorderingAllowed(false);
tableHeader.setResizingAllowed(true);
final TableColumnModel columnModel = variablesTable.getColumnModel();
columnModel.setColumnSelectionAllowed(false);
final TableColumn nameColumn = columnModel.getColumn(0);
nameColumn.setPreferredWidth(100);
nameColumn.setCellRenderer(new TCR());
final TableColumn expressionColumn = columnModel.getColumn(1);
expressionColumn.setPreferredWidth(400);
expressionColumn.setCellRenderer(new TCR());
final ExprEditor exprEditor = new ExprEditor(false);
expressionColumn.setCellEditor(exprEditor);
bindingCtx.addPropertyChangeListener("updateMode", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
final boolean enabled = Boolean.FALSE.equals(evt.getNewValue());
exprEditor.button.setEnabled(enabled);
}
});
final JScrollPane scrollPane = new JScrollPane(variablesTable);
scrollPane.setName(labelName);
scrollPane.setPreferredSize(new Dimension(PREFERRED_TABLE_WIDTH, 150));
return scrollPane;
}
private static AbstractButton createButton(final String path, String name) {
final AbstractButton button = ToolButtonFactory.createButton(UIUtils.loadImageIcon(path), false);
button.setName(name);
return button;
}
private MouseListener createExpressionEditorMouseListener(final JTable table, final boolean booleanExpected) {
final MouseAdapter mouseListener = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
final int column = table.getSelectedColumn();
if (column == 1) {
table.removeEditor();
final int row = table.getSelectedRow();
final String[] value = new String[]{(String) table.getValueAt(row, column)};
final int i = editExpression(value, booleanExpected);
if (ModalDialog.ID_OK == i) {
table.setValueAt(value[0], row, column);
}
}
}
}
};
return MouseEventFilterFactory.createFilter(mouseListener);
}
private int editExpression(String[] value, final boolean booleanExpected) {
Product product;
try {
product = mosaicModel.getReferenceProduct();
} catch (IOException ioe) {
appContext.handleError(ioe.getMessage(), ioe);
return 0;
}
if (product == null) {
final String msg = "No source product specified.";
appContext.handleError(msg, new IllegalStateException(msg));
return 0;
}
final ProductExpressionPane pep;
if (booleanExpected) {
pep = ProductExpressionPane.createBooleanExpressionPane(new Product[]{product}, product,
appContext.getPreferences());
} else {
pep = ProductExpressionPane.createGeneralExpressionPane(new Product[]{product}, product,
appContext.getPreferences());
}
pep.setCode(value[0]);
final int i = pep.showModalDialog(appContext.getApplicationWindow(), value[0]);
if (i == ModalDialog.ID_OK) {
value[0] = pep.getCode();
}
return i;
}
private class ExprEditor extends AbstractCellEditor implements TableCellEditor {
private final JButton button;
private String[] value;
private ExprEditor(final boolean booleanExpected) {
button = new JButton("...");
final Dimension preferredSize = button.getPreferredSize();
preferredSize.setSize(25, preferredSize.getHeight());
button.setPreferredSize(preferredSize);
value = new String[1];
final ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final int i = editExpression(value, booleanExpected);
if (i == ModalDialog.ID_OK) {
fireEditingStopped();
} else {
fireEditingCanceled();
}
}
};
button.addActionListener(actionListener);
}
/**
* Returns the value contained in the editor.
*
* @return the value contained in the editor
*/
@Override
public Object getCellEditorValue() {
return value[0];
}
/**
* Sets an initial <code>value</code> for the editor. This will cause the editor to <code>stopEditing</code>
* and lose any partially edited value if the editor is editing when this method is called. <p>
* <p>
* Returns the component that should be added to the client's <code>Component</code> hierarchy. Once installed
* in the client's hierarchy this component will then be able to draw and receive user input.
*
* @param table the <code>JTable</code> that is asking the editor to edit; can be <code>null</code>
* @param value the value of the cell to be edited; it is up to the specific editor to interpret and draw the
* value. For example, if value is the string "true", it could be rendered as a string or it could be rendered
* as a check box that is checked. <code>null</code> is a valid value
* @param isSelected true if the cell is to be rendered with highlighting
* @param row the row of the cell being edited
* @param column the column of the cell being edited
* @return the component for editing
*/
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
int column) {
final JPanel renderPanel = new JPanel(new BorderLayout());
final DefaultTableCellRenderer defaultRenderer = new DefaultTableCellRenderer();
final Component label = defaultRenderer.getTableCellRendererComponent(table, value, isSelected,
false, row, column);
renderPanel.add(label);
renderPanel.add(button, BorderLayout.EAST);
this.value[0] = (String) value;
return renderPanel;
}
}
private static void addRow(final JTable table, final Object[] rowData) {
table.removeEditor();
((DefaultTableModel) table.getModel()).addRow(rowData);
final int row = table.getRowCount() - 1;
final int numCols = table.getColumnModel().getColumnCount();
for (int i = 0; i < Math.min(numCols, rowData.length); i++) {
Object o = rowData[i];
table.setValueAt(o, row, i);
}
selectRows(table, row, row);
}
private static void moveRowsDown(final JTable table, final int[] rows) {
final int maxRow = table.getRowCount() - 1;
for (int row1 : rows) {
if (row1 == maxRow) {
return;
}
}
table.removeEditor();
int[] selectedRows = rows.clone();
for (int i = rows.length - 1; i > -1; i--) {
int row = rows[i];
((DefaultTableModel) table.getModel()).moveRow(row, row, row + 1);
selectedRows[i] = row + 1;
}
selectRows(table, selectedRows);
}
private static void moveRowsUp(final JTable table, final int[] rows) {
for (int row1 : rows) {
if (row1 == 0) {
return;
}
}
table.removeEditor();
int[] selectedRows = rows.clone();
for (int i = 0; i < rows.length; i++) {
int row = rows[i];
((DefaultTableModel) table.getModel()).moveRow(row, row, row - 1);
selectedRows[i] = row - 1;
}
selectRows(table, selectedRows);
}
private static void removeRows(final JTable table, final int[] rows) {
table.removeEditor();
for (int i = rows.length - 1; i > -1; i--) {
int row = rows[i];
((DefaultTableModel) table.getModel()).removeRow(row);
}
}
private static void selectRows(final JTable table, final int[] rows) {
final ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.clearSelection();
for (int row : rows) {
selectionModel.addSelectionInterval(row, row);
}
}
private static void selectRows(JTable table, int min, int max) {
final int numRows = max + 1 - min;
if (numRows <= 0) {
return;
}
selectRows(table, prepareRows(numRows, min));
}
private static int[] prepareRows(final int numRows, int min) {
final int[] rows = new int[numRows];
for (int i = 0; i < rows.length; i++) {
rows[i] = min + i;
}
return rows;
}
private static class TCR extends JLabel implements TableCellRenderer {
private static final Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
/**
* Creates a <code>JLabel</code> instance with no image and with an empty string for the title. The label is
* centered vertically in its display area. The label's contents, once set, will be displayed on the leading
* edge of the label's display area.
*/
private TCR() {
setOpaque(true);
setBorder(noFocusBorder);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
final boolean enabled = table.isEnabled();
setText((String) value);
if (isSelected) {
super.setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
} else if (!enabled) {
super.setForeground(UIManager.getColor("TextField.inactiveForeground"));
super.setBackground(table.getBackground());
} else {
super.setForeground(table.getForeground());
super.setBackground(table.getBackground());
}
setFont(table.getFont());
if (hasFocus) {
setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
if (table.isCellEditable(row, column)) {
super.setForeground(UIManager.getColor("Table.focusCellForeground"));
super.setBackground(UIManager.getColor("Table.focusCellBackground"));
}
} else {
setBorder(noFocusBorder);
}
setValue(value);
return this;
}
private void setValue(Object value) {
setText(value == null ? "" : value.toString());
}
}
}
| 31,884 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MosaicAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/mosaic/MosaicAction.java | /*
* Copyright (C) 2011 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.mosaic;
import org.esa.snap.core.gpf.GPF;
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;
/**
* Mosaicking action.
*
* @author Norman Fomferra
*/
@ActionID(category = "Operators", id = "org.esa.snap.core.gpf.ui.mosaic.MosaicAction")
@ActionRegistration(displayName = "#CTL_MosaicAction_Name")
@ActionReference(path = "Menu/Raster/Geometric", position = 30)
@NbBundle.Messages("CTL_MosaicAction_Name=Mosaicking")
public class MosaicAction extends AbstractSnapAction {
private ModelessDialog dialog;
@Override
public void actionPerformed(ActionEvent e) {
if (dialog == null) {
dialog = new MosaicDialog(Bundle.CTL_MosaicAction_Name(),
"mosaicAction", getAppContext());
}
dialog.show();
}
@Override
public boolean isEnabled() {
return GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi("Mosaic") != null;
}
}
| 1,923 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MosaicForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/mosaic/MosaicForm.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.core.gpf.ui.mosaic;
import org.esa.snap.core.gpf.ui.TargetProductSelector;
import org.esa.snap.ui.AppContext;
import javax.swing.JTabbedPane;
/**
* @author Marco Peters
* @since BEAM 4.7
*/
public class MosaicForm extends JTabbedPane {
private final AppContext appContext;
private final MosaicFormModel mosaicModel;
private MosaicIOPanel ioPanel;
private MosaicMapProjectionPanel mapProjectionPanel;
public MosaicForm(TargetProductSelector targetProductSelector, AppContext appContext) {
this.appContext = appContext;
mosaicModel = new MosaicFormModel(this);
createUI(targetProductSelector);
}
private void createUI(TargetProductSelector selector) {
ioPanel = new MosaicIOPanel(appContext, mosaicModel, selector);
mapProjectionPanel = new MosaicMapProjectionPanel(appContext, mosaicModel);
MosaicExpressionsPanel expressionsPanel = new MosaicExpressionsPanel(appContext, mosaicModel);
addTab("I/O Parameters", ioPanel); /*I18N*/
addTab("Map Projection Definition", mapProjectionPanel); /*I18N*/
addTab("Variables & Conditions", expressionsPanel); /*I18N*/
}
MosaicFormModel getFormModel() {
return mosaicModel;
}
void prepareShow() {
ioPanel.prepareShow();
mapProjectionPanel.prepareShow();
}
void prepareHide() {
mapProjectionPanel.prepareHide();
ioPanel.prepareHide();
}
void setCardinalBounds(double southBoundValue, double northBoundValue, double westBoundValue, double eastBoundValue){
mapProjectionPanel.getBindingContext().getPropertySet().setValue(MosaicFormModel.PROPERTY_SOUTH_BOUND, southBoundValue);
mapProjectionPanel.getBindingContext().getPropertySet().setValue(MosaicFormModel.PROPERTY_NORTH_BOUND, northBoundValue);
mapProjectionPanel.getBindingContext().getPropertySet().setValue(MosaicFormModel.PROPERTY_WEST_BOUND, westBoundValue);
mapProjectionPanel.getBindingContext().getPropertySet().setValue(MosaicFormModel.PROPERTY_EAST_BOUND, eastBoundValue);
}
}
| 2,842 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
GPFController.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gpf-ui/src/main/java/org/esa/snap/core/gpf/ui/preferences/GPFController.java | /*
*
* * Copyright (C) 2012 Brockmann Consult GmbH ([email protected])
* *
* * This program is free software; you can redistribute it and/or modify it
* * under the terms of the GNU General Public License as published by the Free
* * Software Foundation; either version 3 of the License, or (at your option)
* * any later version.
* * This program is distributed in the hope that it will be useful, but WITHOUT
* * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* * more details.
* *
* * You should have received a copy of the GNU General Public License along
* * with this program; if not, see http://www.gnu.org/licenses/
*
*/
package org.esa.snap.core.gpf.ui.preferences;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.PropertyEditorRegistry;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.rcp.preferences.DefaultConfigController;
import org.esa.snap.rcp.preferences.Preference;
import org.netbeans.spi.options.OptionsPanelController;
import org.openide.util.HelpCtx;
import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Insets;
/**
* @author muhammad.bc.
*/
@OptionsPanelController.SubRegistration(location = "GeneralPreferences",
displayName = "#AdvancedOption_DisplayName_GPF_Ui",
keywords = "#AdvancedOption_Keyboard_GPF_Ui",
keywordsCategory = "GPF",
id = "GPF",
position = 10)
@org.openide.util.NbBundle.Messages({
"AdvancedOption_DisplayName_GPF_Ui=GPF",
"AdvancedOption_Keyboard_GPF_Ui=GPF,sound beep"
})
public class GPFController extends DefaultConfigController {
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx("gpf.option.controller");
}
static class GPFBean {
@Preference(label = "Beep when processing has finished",
key = GPF.BEEP_AFTER_PROCESSING_PROPERTY)
boolean beepSound = false;
}
protected PropertySet createPropertySet() {
return createPropertySet(new GPFBean());
}
@Override
protected JPanel createPanel(BindingContext context) {
TableLayout tableLayout = new TableLayout(1);
tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST);
tableLayout.setTablePadding(new Insets(4, 10, 0, 0));
tableLayout.setTableFill(TableLayout.Fill.BOTH);
tableLayout.setColumnWeightX(0, 1.0);
JPanel pageUI = new JPanel(tableLayout);
PropertyEditorRegistry registry = PropertyEditorRegistry.getInstance();
Property beepSound = context.getPropertySet().getProperty(GPF.BEEP_AFTER_PROCESSING_PROPERTY);
JComponent[] beepSoundComponent = registry.findPropertyEditor(beepSound.getDescriptor()).createComponents(beepSound.getDescriptor(), context);
pageUI.add(beepSoundComponent[0]);
tableLayout.setTableFill(TableLayout.Fill.VERTICAL);
pageUI.add(tableLayout.createVerticalSpacer());
JPanel parent = new JPanel(new BorderLayout());
parent.add(pageUI, BorderLayout.CENTER);
parent.add(Box.createHorizontalStrut(100), BorderLayout.EAST);
return parent;
}
}
| 3,429 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MissionParameterListener.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/MissionParameterListener.java | package org.esa.snap.product.library.ui.v2;
import org.esa.snap.product.library.ui.v2.repository.AbstractProductsRepositoryPanel;
/**
* The listener interface for receiving the event when the mission is changed in tre combo box component.
*
* Created by jcoravu on 21/8/2019.
*/
public interface MissionParameterListener {
public void newSelectedMission(String mission, AbstractProductsRepositoryPanel parentDataSource);
}
| 434 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductLibraryV2Action.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/ProductLibraryV2Action.java | package org.esa.snap.product.library.ui.v2;
import org.esa.snap.product.library.ui.v2.repository.AbstractProductsRepositoryPanel;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import javax.swing.*;
import java.awt.event.ActionListener;
/**
* The action class containing information about the option from the popup menu.
*
* Created by jcoravu on 21/7/2020.
*/
public abstract class ProductLibraryV2Action extends JMenuItem implements ActionListener {
protected ProductLibraryToolViewV2 productLibraryToolView;
public ProductLibraryV2Action(String text) {
super(text);
addActionListener(this);
}
public final void setProductLibraryToolView(ProductLibraryToolViewV2 productLibraryToolView) {
if (productLibraryToolView == null) {
throw new NullPointerException("The product library tool view is null.");
}
this.productLibraryToolView = productLibraryToolView;
}
public boolean canAddItemToPopupMenu(AbstractProductsRepositoryPanel visibleProductsRepositoryPanel, RepositoryProduct[] selectedProducts) {
return true;
}
}
| 1,138 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductLibraryToolViewV2.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/ProductLibraryToolViewV2.java | /*
* Copyright (C) 2016 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.product.library.ui.v2;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.auth.Credentials;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.engine_utilities.datamodel.AbstractMetadata;
import org.esa.snap.engine_utilities.util.Pair;
import org.esa.snap.graphbuilder.gpf.ui.OperatorUIRegistry;
import org.esa.snap.graphbuilder.rcp.dialogs.BatchGraphDialog;
import org.esa.snap.graphbuilder.rcp.utils.ClipboardUtils;
import org.esa.snap.product.library.ui.v2.preferences.RepositoriesCredentialsControllerUI;
import org.esa.snap.product.library.ui.v2.repository.AbstractProductsRepositoryPanel;
import org.esa.snap.product.library.ui.v2.repository.RepositorySelectionPanel;
import org.esa.snap.product.library.ui.v2.repository.local.AddLocalRepositoryFolderTimerRunnable;
import org.esa.snap.product.library.ui.v2.repository.local.AllLocalProductsRepositoryPanel;
import org.esa.snap.product.library.ui.v2.repository.local.AttributesParameterComponent;
import org.esa.snap.product.library.ui.v2.repository.local.CopyLocalProductsRunnable;
import org.esa.snap.product.library.ui.v2.repository.local.DeleteAllLocalRepositoriesTimerRunnable;
import org.esa.snap.product.library.ui.v2.repository.local.DeleteLocalProductsRunnable;
import org.esa.snap.product.library.ui.v2.repository.local.ExportLocalProductListPathsRunnable;
import org.esa.snap.product.library.ui.v2.repository.local.LocalParameterValues;
import org.esa.snap.product.library.ui.v2.repository.local.MoveLocalProductsRunnable;
import org.esa.snap.product.library.ui.v2.repository.local.OpenLocalProductsRunnable;
import org.esa.snap.product.library.ui.v2.repository.local.ReadLocalProductsTimerRunnable;
import org.esa.snap.product.library.ui.v2.repository.local.ScanAllLocalRepositoryFoldersTimerRunnable;
import org.esa.snap.product.library.ui.v2.repository.local.ScanLocalRepositoryOptionsDialog;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductListModel;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductListPanel;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.repository.remote.DownloadProgressStatus;
import org.esa.snap.product.library.ui.v2.repository.remote.OpenDownloadedProductsRunnable;
import org.esa.snap.product.library.ui.v2.repository.remote.RemoteProductsRepositoryPanel;
import org.esa.snap.product.library.ui.v2.repository.remote.RemoteRepositoriesSemaphore;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadProductListTimerRunnable;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadProductListener;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadProductRunnable;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadRemoteProductsHelper;
import org.esa.snap.product.library.ui.v2.repository.remote.download.popup.DownloadingProductsPopupMenu;
import org.esa.snap.product.library.ui.v2.thread.AbstractProgressTimerRunnable;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelperImpl;
import org.esa.snap.product.library.ui.v2.thread.ThreadCallback;
import org.esa.snap.product.library.ui.v2.thread.ThreadListener;
import org.esa.snap.product.library.ui.v2.worldwind.WorldMapPanelWrapperImpl;
import org.esa.snap.worldwind.productlibrary.PolygonMouseListener;
import org.esa.snap.worldwind.productlibrary.WorldMapPanelWrapper;
import org.esa.snap.product.library.v2.database.AllLocalFolderProductsRepository;
import org.esa.snap.product.library.v2.database.AttributeFilter;
import org.esa.snap.product.library.v2.database.DataAccess;
import org.esa.snap.product.library.v2.database.SaveProductData;
import org.esa.snap.product.library.v2.database.model.LocalRepositoryFolder;
import org.esa.snap.product.library.v2.database.model.LocalRepositoryProduct;
import org.esa.snap.product.library.v2.preferences.RepositoriesCredentialsController;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.rcp.windows.ToolTopComponent;
import org.esa.snap.remote.products.repository.Attribute;
import org.esa.snap.remote.products.repository.RemoteMission;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.remote.products.repository.geometry.AbstractGeometry2D;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.help.HelpDisplayer;
import org.esa.snap.ui.loading.CustomFileChooser;
import org.esa.snap.ui.loading.CustomSplitPane;
import org.esa.snap.ui.loading.SwingUtils;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.filechooser.FileFilter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.lang.Math.max;
import static java.lang.Math.min;
/**
* The Product Library Tool view representing the main panel.
*/
@TopComponent.Description(
preferredID = "ProductLibraryTopComponentV2",
iconBase = "org/esa/snap/product/library/ui/v2/icons/search.png"
)
@TopComponent.Registration(
mode = "rightSlidingSide",
openAtStartup = true,
position = 0
)
@ActionID(category = "Window", id = "org.esa.snap.product.library.ui.v2.ProductLibraryToolViewV2")
@ActionReferences({
@ActionReference(path = "Menu/View/Tool Windows", position = 12),
@ActionReference(path = "Menu/File", position = 17)
})
@TopComponent.OpenActionRegistration(
displayName = "#CTL_ProductLibraryTopComponentV2Name",
preferredID = "ProductLibraryTopComponentV2"
)
@NbBundle.Messages({
"CTL_ProductLibraryTopComponentV2Name=Product Library",
"CTL_ProductLibraryTopComponentV2Description=Product Library",
})
public class ProductLibraryToolViewV2 extends ToolTopComponent implements ComponentDimension, DownloadProductListener {
private static final Logger logger = Logger.getLogger(ProductLibraryToolViewV2.class.getName());
private static final String HELP_ID = "productLibraryToolV2";
private static final String PREFERENCES_KEY_LAST_LOCAL_REPOSITORY_FOLDER_PATH = "last_local_repository_folder_path";
private final static String LAST_ERROR_OUTPUT_DIR_KEY = "snap.lastErrorOutputDir";
private Path lastLocalRepositoryFolderPath;
private RepositoryOutputProductListPanel repositoryOutputProductListPanel;
private RepositorySelectionPanel repositorySelectionPanel;
private CustomSplitPane horizontalSplitPane;
private DownloadingProductsPopupMenu downloadingProductsPopupMenu;
private AbstractProgressTimerRunnable<?> searchProductListThread;
private AbstractProgressTimerRunnable<?> localRepositoryProductsThread;
private DownloadRemoteProductsHelper downloadRemoteProductsHelper;
private int textFieldPreferredHeight;
private WorldMapPanelWrapper worldWindowPanel;
private boolean inputDataLoaded;
private AppContext appContext;
public ProductLibraryToolViewV2() {
super();
setDisplayName(Bundle.CTL_ProductLibraryTopComponentV2Name());
this.inputDataLoaded = false;
}
@Override
public void addNotify() {
if (this.downloadRemoteProductsHelper == null) {
initialize();
}
super.addNotify();
if (!this.inputDataLoaded) {
this.inputDataLoaded = true;
AllLocalFolderProductsRepository allLocalFolderProductsRepository = this.repositorySelectionPanel.getAllLocalProductsRepositoryPanel().getAllLocalFolderProductsRepository();
LoadInputDataRunnable thread = new LoadInputDataRunnable(allLocalFolderProductsRepository) {
@Override
protected void onSuccessfullyExecuting(LocalParameterValues parameterValues) {
onFinishLoadingInputData(parameterValues);
}
};
thread.executeAsync();
}
}
@Override
public int getGapBetweenRows() {
return 5;
}
@Override
public int getGapBetweenColumns() {
return 5;
}
@Override
public int getTextFieldPreferredHeight() {
return this.textFieldPreferredHeight;
}
@Override
public Color getTextFieldBackgroundColor() {
return Color.WHITE;
}
@Override
public void onFinishDownloadingProduct(DownloadProductRunnable downloadProductRunnable, DownloadProgressStatus downloadProgressStatus,
SaveProductData saveProductData, boolean hasProductsToDownload) {
if (this.downloadingProductsPopupMenu != null) {
this.downloadingProductsPopupMenu.onStopDownloadingProduct(downloadProductRunnable);
}
RepositoryProduct repositoryProduct = downloadProductRunnable.getProductToDownload();
if (downloadProgressStatus != null) {
this.repositorySelectionPanel.finishDownloadingProduct(repositoryProduct, downloadProgressStatus, saveProductData);
}
OutputProductListModel productListModel = this.repositoryOutputProductListPanel.getProductListPanel().getProductListModel();
productListModel.refreshProduct(repositoryProduct);
}
@Override
public void onUpdateProductDownloadProgress(RepositoryProduct repositoryProduct) {
if (this.downloadingProductsPopupMenu != null) {
this.downloadingProductsPopupMenu.onUpdateProductDownloadProgress(repositoryProduct);
}
OutputProductListModel productListModel = this.repositoryOutputProductListPanel.getProductListPanel().getProductListModel();
productListModel.refreshProduct(repositoryProduct);
}
@Override
public void onRefreshProduct(RepositoryProduct repositoryProduct) {
OutputProductListModel productListModel = this.repositoryOutputProductListPanel.getProductListPanel().getProductListModel();
productListModel.refreshProduct(repositoryProduct);
}
private void onFinishLoadingInputData(LocalParameterValues parameterValues) {
this.repositorySelectionPanel.setInputData(parameterValues);
this.repositoryOutputProductListPanel.setVisibleProductsPerPage(parameterValues.getVisibleProductsPerPage());
this.downloadRemoteProductsHelper.setUncompressedDownloadedProducts(parameterValues.isUncompressedDownloadedProducts());
}
private void refreshUserAccounts() {
RepositoriesCredentialsController controller = RepositoriesCredentialsController.getInstance();
this.repositorySelectionPanel.refreshUserAccounts(controller.getRepositoriesCredentials());
this.repositoryOutputProductListPanel.setVisibleProductsPerPage(controller.getNrRecordsOnPage());
this.downloadRemoteProductsHelper.setUncompressedDownloadedProducts(controller.isAutoUncompress());
}
public static Integer findLocalAttributeAsInt(String attributeName, RepositoryProduct repositoryProduct) {
List<Attribute> localAttributes = repositoryProduct.getLocalAttributes();
for (Attribute attribute : localAttributes) {
if (attribute.getName().equals(attributeName)) {
return Integer.parseInt(attribute.getValue());
}
}
return null;
}
private void onHideDownloadingProgressBar() {
if (this.downloadingProductsPopupMenu != null) {
this.downloadingProductsPopupMenu.setVisible(false);
this.downloadingProductsPopupMenu = null;
}
}
private void initialize() {
this.appContext = SnapApp.getDefault().getAppContext();
PropertyMap persistencePreferences = this.appContext.getPreferences();
String lastFolderPath = persistencePreferences.getPropertyString(PREFERENCES_KEY_LAST_LOCAL_REPOSITORY_FOLDER_PATH, null);
if (lastFolderPath != null) {
this.lastLocalRepositoryFolderPath = Paths.get(lastFolderPath);
}
Insets defaultTextFieldMargins = new Insets(3, 2, 3, 2);
JTextField productNameTextField = new JTextField();
productNameTextField.setMargin(defaultTextFieldMargins);
this.textFieldPreferredHeight = productNameTextField.getPreferredSize().height;
RemoteProductsRepositoryProvider[] remoteRepositoryProductProviders = RemoteProductsRepositoryProvider.getRemoteProductsRepositoryProviders();
for (RemoteProductsRepositoryProvider provider : remoteRepositoryProductProviders) {
DataAccess.saveRemoteRepositoryName(provider.getRepositoryName());
}
createWorldWindowPanel(persistencePreferences);
createRepositorySelectionPanel(remoteRepositoryProductProviders);
createProductListPanel();
this.repositorySelectionPanel.addComponents(this.repositoryOutputProductListPanel.getProductListPaginationPanel());
this.repositoryOutputProductListPanel.addPageProductsChangedListener(event -> outputProductsPageChanged());
int gapBetweenRows = getGapBetweenRows();
int gapBetweenColumns = getGapBetweenRows();
int visibleDividerSize = gapBetweenColumns - 2;
int dividerMargins = 0;
float initialDividerLocationPercent = 0.5f;
this.horizontalSplitPane = new CustomSplitPane(JSplitPane.HORIZONTAL_SPLIT, visibleDividerSize, dividerMargins, initialDividerLocationPercent, SwingUtils.TRANSPARENT_COLOR);
this.horizontalSplitPane.setLeftComponent(this.repositorySelectionPanel.getSelectedProductsRepositoryPanel());
this.horizontalSplitPane.setRightComponent(this.repositoryOutputProductListPanel);
setLayout(new BorderLayout(0, gapBetweenRows));
setBorder(new EmptyBorder(gapBetweenRows, gapBetweenColumns, gapBetweenRows, gapBetweenColumns));
add(this.repositorySelectionPanel, BorderLayout.NORTH);
add(this.horizontalSplitPane, BorderLayout.CENTER);
this.repositorySelectionPanel.getSelectedProductsRepositoryPanel().addInputParameterComponents();
RemoteRepositoriesSemaphore remoteRepositoriesSemaphore = new RemoteRepositoriesSemaphore(remoteRepositoryProductProviders);
ProgressBarHelperImpl progressBarHelper = this.repositoryOutputProductListPanel.getProgressBarHelper();
this.downloadRemoteProductsHelper = new DownloadRemoteProductsHelper(progressBarHelper, remoteRepositoriesSemaphore, this);
this.repositorySelectionPanel.setDownloadingProductProgressCallback(this.downloadRemoteProductsHelper);
this.repositoryOutputProductListPanel.getProductListPanel().getProductListModel().setDownloadingProductProgressCallback(this.downloadRemoteProductsHelper);
this.appContext.getApplicationWindow().addPropertyChangeListener(RepositoriesCredentialsControllerUI.REMOTE_PRODUCTS_REPOSITORY_CREDENTIALS,
event -> SwingUtilities.invokeLater(this::refreshUserAccounts));
progressBarHelper.addVisiblePropertyChangeListener(event -> {
if (!(Boolean) event.getNewValue()) {
onHideDownloadingProgressBar();
}
});
progressBarHelper.getProgressBar().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
showDownloadingProductsPopup((JComponent) mouseEvent.getSource());
}
});
}
private void showDownloadingProductsPopup(JComponent invoker) {
List<Pair<DownloadProductRunnable, DownloadProgressStatus>> downloadingProductRunnables = this.downloadRemoteProductsHelper.findDownloadingProducts();
if (downloadingProductRunnables.size() > 0) {
Color backgroundColor = getTextFieldBackgroundColor();
int gapBetweenRows = getGapBetweenRows() / 2;
int gapBetweenColumns = getGapBetweenColumns() / 2;
DownloadingProductsPopupMenu popupMenu = new DownloadingProductsPopupMenu(downloadingProductRunnables, gapBetweenRows, gapBetweenColumns, backgroundColor);
popupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent popupMenuEvent) {
downloadingProductsPopupMenu = (DownloadingProductsPopupMenu) popupMenuEvent.getSource();
downloadingProductsPopupMenu.refresh(); // refresh the texts in the panels after registering the listener
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {
ProductLibraryToolViewV2.this.downloadingProductsPopupMenu = null; // reset the listener
}
@Override
public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {
// do nothing
}
});
int x = invoker.getWidth() - popupMenu.getPreferredSize().width;
int y = invoker.getHeight();
popupMenu.show(invoker, x, y);
}
}
private void createProductListPanel() {
ActionListener stopDownloadingProductsButtonListener = e -> cancelDownloadingProducts();
String text = DownloadRemoteProductsHelper.buildProgressBarDownloadingText(100, 100);
JLabel label = new JLabel(text);
int progressBarWidth = (int) (1.1f * label.getPreferredSize().width);
this.repositoryOutputProductListPanel = new RepositoryOutputProductListPanel(this.repositorySelectionPanel, this, stopDownloadingProductsButtonListener, progressBarWidth, false);
this.repositoryOutputProductListPanel.setBorder(new EmptyBorder(0, 1, 0, 0));
this.repositoryOutputProductListPanel.getProductListPanel().addDataChangedListener(evt -> productListChanged());
this.repositoryOutputProductListPanel.getProductListPanel().addSelectionChangedListener(evt -> newSelectedRepositoryProducts());
addListeners();
}
private void createRepositorySelectionPanel(RemoteProductsRepositoryProvider[] remoteRepositoryProductProviders) {
ItemListener productsRepositoryListener = itemEvent -> onSelectedNewProductsRepository();
MissionParameterListener missionParameterListener = (mission, parentProductsRepositoryPanel) -> {
if (parentProductsRepositoryPanel == repositorySelectionPanel.getSelectedProductsRepositoryPanel()) {
onSelectedNewProductsRepositoryMission();
} else {
throw new IllegalStateException("The selected mission '" + mission + "' does not belong to the visible products repository.");
}
};
ActionListener searchButtonListener = e -> searchButtonPressed();
ActionListener stopDownloadingProductListButtonListener = e -> cancelSearchingProductList();
ActionListener helpButtonListener = e -> {
HelpDisplayer.show(HELP_ID);
};
String text = DownloadProductListTimerRunnable.buildProgressBarDownloadingText(1000, 1000);
JLabel label = new JLabel(text);
int progressBarWidth = (int) (1.1f * label.getPreferredSize().width);
this.repositorySelectionPanel = new RepositorySelectionPanel(remoteRepositoryProductProviders, this, missionParameterListener, this.worldWindowPanel, progressBarWidth);
this.repositorySelectionPanel.setRepositoriesItemListener(productsRepositoryListener);
this.repositorySelectionPanel.setSearchButtonListener(searchButtonListener);
this.repositorySelectionPanel.setHelpButtonListener(helpButtonListener);
this.repositorySelectionPanel.setStopButtonListener(stopDownloadingProductListButtonListener);
this.repositorySelectionPanel.setAllProductsRepositoryPanelBorder(new EmptyBorder(0, 0, 0, 1));
}
private void createWorldWindowPanel(PropertyMap persistencePreferences) {
PolygonMouseListener worldWindowMouseListener = ProductLibraryToolViewV2.this::leftMouseButtonClicked;
this.worldWindowPanel = new WorldMapPanelWrapperImpl(worldWindowMouseListener, getTextFieldBackgroundColor(), persistencePreferences);
this.worldWindowPanel.setPreferredSize(new Dimension(400, 250));
this.worldWindowPanel.addWorldMapPanelAsync(false, true);
}
private List<ProductLibraryV2Action> readLocalRepositoryActions() {
FileObject fileObj = FileUtil.getConfigFile("ProductLibraryV2LocalRepositoryActions");
List<ProductLibraryV2Action> localActions = new ArrayList<>();
if (fileObj == null) {
logger.log(Level.WARNING, "No ProductLibrary Action found.");
} else {
FileObject[] files = fileObj.getChildren();
List<FileObject> orderedFiles = FileUtil.getOrder(Arrays.asList(files), true);
for (FileObject fileObject : orderedFiles) {
Class<? extends ProductLibraryV2Action> actionExtClass = OperatorUIRegistry.getClassAttribute(fileObject, "actionClass", ProductLibraryV2Action.class, false);
try {
ProductLibraryV2Action action = Objects.requireNonNull(actionExtClass).getDeclaredConstructor().newInstance();
action.setProductLibraryToolView(this);
localActions.add(action);
} catch (ReflectiveOperationException e) {
logger.log(Level.SEVERE, "Failed to instantiate the product library action using class '" + actionExtClass + "'.", e);
}
}
}
return localActions;
}
private int showConfirmDialog(String title, String message, int buttonsOptionType) {
return JOptionPane.showConfirmDialog(this, message, title, buttonsOptionType);
}
public void showMessageDialog(String title, String message, int iconMessageType) {
JOptionPane.showMessageDialog(this, message, title, iconMessageType);
}
private void addListeners() {
List<ProductLibraryV2Action> localActions = readLocalRepositoryActions();
ProductLibraryV2Action jointSearchCriteriaListener = new ProductLibraryV2Action("Joint Search Criteria") {
@Override
public void actionPerformed(ActionEvent actionEvent) {
jointSearchCriteriaOptionClicked();
}
@Override
public boolean canAddItemToPopupMenu(AbstractProductsRepositoryPanel visibleProductsRepositoryPanel, RepositoryProduct[] selectedProducts) {
return (selectedProducts.length == 1 && selectedProducts[0].getRemoteMission() != null);
}
};
ProductLibraryV2Action openLocalProductListener = new ProductLibraryV2Action("Open") {
@Override
public void actionPerformed(ActionEvent actionEvent) {
openLocalSelectedProductsOptionClicked();
}
};
ProductLibraryV2Action deleteLocalProductListener = new ProductLibraryV2Action("Delete...") {
@Override
public void actionPerformed(ActionEvent actionEvent) {
deleteLocalSelectedProductsOptionClicked();
}
};
ProductLibraryV2Action batchProcessingListener = new ProductLibraryV2Action("Batch Processing...") {
@Override
public void actionPerformed(ActionEvent actionEvent) {
openBatchProcessingDialog();
}
};
ProductLibraryV2Action showInExplorerListener = new ProductLibraryV2Action("Show in Explorer...") {
@Override
public void actionPerformed(ActionEvent actionEvent) {
showSelectedLocalProductInExplorer();
}
@Override
public boolean canAddItemToPopupMenu(AbstractProductsRepositoryPanel visibleProductsRepositoryPanel, RepositoryProduct[] selectedProducts) {
return (selectedProducts.length == 1);
}
};
ProductLibraryV2Action selectAllListener = new ProductLibraryV2Action("Select All") {
@Override
public void actionPerformed(ActionEvent actionEvent) {
repositoryOutputProductListPanel.getProductListPanel().selectAllProducts();
}
};
ProductLibraryV2Action selectNoneListener = new ProductLibraryV2Action("Select None") {
@Override
public void actionPerformed(ActionEvent actionEvent) {
repositoryOutputProductListPanel.getProductListPanel().clearSelection();
}
};
ProductLibraryV2Action copyListener = new ProductLibraryV2Action("Copy") {
@Override
public void actionPerformed(ActionEvent actionEvent) {
copySelectedProductsOptionClicked();
}
};
ProductLibraryV2Action copyToListener = new ProductLibraryV2Action("Copy To...") {
@Override
public void actionPerformed(ActionEvent actionEvent) {
copyToSelectedProductsOptionClicked();
}
};
ProductLibraryV2Action moveToListener = new ProductLibraryV2Action("Move To...") {
@Override
public void actionPerformed(ActionEvent actionEvent) {
moveToSelectedProductsOptionClicked();
}
};
ProductLibraryV2Action exportListListener = new ProductLibraryV2Action("Export List...") {
@Override
public void actionPerformed(ActionEvent actionEvent) {
exportSelectedProductsListOptionClicked();
}
};
localActions.add(openLocalProductListener);
localActions.add(deleteLocalProductListener);
localActions.add(selectAllListener);
localActions.add(selectNoneListener);
localActions.add(copyListener);
localActions.add(copyToListener);
localActions.add(moveToListener);
localActions.add(exportListListener);
localActions.add(jointSearchCriteriaListener);
localActions.add(batchProcessingListener);
localActions.add(showInExplorerListener);
ActionListener scanLocalRepositoryFoldersListener = actionEvent -> scanAllLocalRepositoriesButtonPressed();
ActionListener addLocalRepositoryFolderListener = actionEvent -> addLocalRepositoryButtonPressed();
ActionListener deleteLocalRepositoryFolderListener = actionEvent -> deleteAllLocalRepositoriesButtonPressed();
this.repositorySelectionPanel.setLocalRepositoriesListeners(scanLocalRepositoryFoldersListener, addLocalRepositoryFolderListener,
deleteLocalRepositoryFolderListener, localActions);
ProductLibraryV2Action downloadRemoteProductListener = new ProductLibraryV2Action("Download") {
@Override
public void actionPerformed(ActionEvent e) {
downloadSelectedRemoteProductsButtonPressed();
}
@Override
public boolean canAddItemToPopupMenu(AbstractProductsRepositoryPanel visibleProductsRepositoryPanel, RepositoryProduct[] selectedProducts) {
return visibleProductsRepositoryPanel.getOutputProductResults().canDownloadProducts(selectedProducts);
}
};
ProductLibraryV2Action openDownloadedRemoteProductListener = new ProductLibraryV2Action("Open") {
@Override
public void actionPerformed(ActionEvent e) {
openDownloadedRemoteProductsButtonPressed();
}
@Override
public boolean canAddItemToPopupMenu(AbstractProductsRepositoryPanel visibleProductsRepositoryPanel, RepositoryProduct[] selectedProducts) {
return visibleProductsRepositoryPanel.getOutputProductResults().canOpenDownloadedProducts(selectedProducts);
}
};
List<ProductLibraryV2Action> remoteActions = new ArrayList<>();
remoteActions.add(openDownloadedRemoteProductListener);
remoteActions.add(downloadRemoteProductListener);
remoteActions.add(jointSearchCriteriaListener);
this.repositorySelectionPanel.setDownloadRemoteProductListener(remoteActions);
}
private void scanAllLocalRepositories(boolean scanRecursively, boolean generateQuickLookImages, boolean testZipFileForErrors) {
ProgressBarHelperImpl progressBarHelper = this.repositorySelectionPanel.getProgressBarHelper();
int threadId = progressBarHelper.incrementAndGetCurrentThreadId();
AllLocalFolderProductsRepository allLocalFolderProductsRepository = this.repositorySelectionPanel.getAllLocalProductsRepositoryPanel().getAllLocalFolderProductsRepository();
this.localRepositoryProductsThread = new ScanAllLocalRepositoryFoldersTimerRunnable(progressBarHelper, threadId, allLocalFolderProductsRepository, scanRecursively, generateQuickLookImages, testZipFileForErrors) {
@Override
protected void onFinishRunning() {
onFinishProcessingLocalRepositoryThread(this, null); // 'null' => no local repository folder to select
}
@Override
protected void onLocalRepositoryFolderDeleted(LocalRepositoryFolder localRepositoryFolder) {
ProductLibraryToolViewV2.this.deleteLocalRepositoryFolder(localRepositoryFolder);
}
@Override
protected void onFinishSavingProduct(SaveProductData saveProductData) {
ProductLibraryToolViewV2.this.repositorySelectionPanel.finishSavingLocalProduct(saveProductData);
}
@Override
protected void onSuccessfullyFinish(Map<File, String> errorFiles) {
processErrorFiles(errorFiles);
}
};
this.localRepositoryProductsThread.executeAsync(); // start the thread
}
private void scanAllLocalRepositoriesButtonPressed() {
if (this.downloadRemoteProductsHelper.isRunning() || this.localRepositoryProductsThread != null) {
showMessageDialog("Scan all local repositories",
"The local repository folders cannot be refreshed.\n\nThere is a running action.",
JOptionPane.ERROR_MESSAGE);
} else {
ScanLocalRepositoryOptionsDialog dialog = new ScanLocalRepositoryOptionsDialog(null) {
@Override
protected void okButtonPressed(boolean scanRecursively, boolean generateQuickLookImages, boolean testZipFileForErrors) {
super.okButtonPressed(scanRecursively, generateQuickLookImages, testZipFileForErrors);
scanAllLocalRepositories(scanRecursively, generateQuickLookImages, testZipFileForErrors);
}
};
dialog.show();
}
}
private void searchProductListLater() {
SwingUtilities.invokeLater(this::searchButtonPressed);
}
private void addLocalRepositoryButtonPressed() {
if (this.localRepositoryProductsThread != null) {
showMessageDialog("Add local repository folder",
"A local repository folder cannot be added./n/nThere is a running action.", JOptionPane.ERROR_MESSAGE);
} else {
Path selectedLocalRepositoryFolder = showDialogToSelectLocalFolder("Select folder to add the products", true);
if (selectedLocalRepositoryFolder != null) {
// a local folder has been selected
ScanLocalRepositoryOptionsDialog dialog = new ScanLocalRepositoryOptionsDialog(null) {
@Override
protected void okButtonPressed(boolean scanRecursively, boolean generateQuickLookImages, boolean testZipFileForErrors) {
super.okButtonPressed(scanRecursively, generateQuickLookImages, testZipFileForErrors);
addLocalRepository(selectedLocalRepositoryFolder, scanRecursively, generateQuickLookImages, testZipFileForErrors);
}
};
dialog.show();
}
}
}
private void addLocalRepository(Path selectedLocalRepositoryFolder, boolean scanRecursively, boolean generateQuickLookImages, boolean testZipFileForErrors) {
ProgressBarHelperImpl progressBarHelper = this.repositorySelectionPanel.getProgressBarHelper();
int threadId = progressBarHelper.incrementAndGetCurrentThreadId();
AllLocalFolderProductsRepository allLocalFolderProductsRepository = this.repositorySelectionPanel.getAllLocalProductsRepositoryPanel().getAllLocalFolderProductsRepository();
this.localRepositoryProductsThread = new AddLocalRepositoryFolderTimerRunnable(progressBarHelper, threadId, selectedLocalRepositoryFolder, allLocalFolderProductsRepository,
scanRecursively, generateQuickLookImages, testZipFileForErrors) {
@Override
protected void onFinishRunning() {
onFinishProcessingLocalRepositoryThread(this, getLocalRepositoryFolderPath());
}
@Override
protected void onFinishSavingProduct(SaveProductData saveProductData) {
ProductLibraryToolViewV2.this.repositorySelectionPanel.finishSavingLocalProduct(saveProductData);
}
@Override
protected void onSuccessfullyFinish(Map<File, String> errorFiles) {
processErrorFiles(errorFiles);
}
};
this.localRepositoryProductsThread.executeAsync(); // start the thread
}
private void processErrorFiles(Map<File, String> errorFiles) {
if (errorFiles != null && errorFiles.size() > 0) {
final StringBuilder str = new StringBuilder();
int cnt = 1;
for (Map.Entry<File, String> entry : errorFiles.entrySet()) {
str.append(entry.getValue()); // the message
str.append(" ");
str.append(entry.getKey().getAbsolutePath());
str.append('\n');
if (cnt >= 20) {
str.append("plus ").append(errorFiles.size() - 20).append(" other errors...\n");
break;
}
++cnt;
}
final String question = "\nWould you like to save the list to a text file?";
Dialogs.Answer answer = Dialogs.requestDecision("Product Errors",
"The follow files have errors:\n" + str + question,
false, null);
if (answer == Dialogs.Answer.YES) {
final File file = Dialogs.requestFileForSave("Save as...", false,
new SnapFileFilter("Text File", new String[]{".txt"}, "Text File"),
".txt", "ProductErrorList", null, LAST_ERROR_OUTPUT_DIR_KEY);
if (file != null) {
try {
writeErrors(errorFiles, file);
} catch (Exception e) {
Dialogs.showError("Unable to save to " + file.getAbsolutePath());
}
if (Desktop.isDesktopSupported() && file.exists()) {
try {
Desktop.getDesktop().open(file);
} catch (Exception e) {
SystemUtils.LOG.warning("Unable to open error file: " + e.getMessage());
}
}
}
}
}
}
private boolean resetLocalRepositoryProductsThread(Runnable invokerThread) {
if (invokerThread == this.localRepositoryProductsThread) {
this.localRepositoryProductsThread = null; // reset
return true;
}
return false;
}
private void deleteAllLocalRepositoriesButtonPressed() {
AllLocalProductsRepositoryPanel allLocalProductsRepositoryPanel = this.repositorySelectionPanel.getAllLocalProductsRepositoryPanel();
LocalRepositoryFolder[] folders;
final LocalRepositoryFolder selectedFolder = allLocalProductsRepositoryPanel.getSelectedFolder();
String messageToDisplay;
if (selectedFolder != null) {
folders = new LocalRepositoryFolder[]{selectedFolder};
messageToDisplay = "Selected local repository will be deleted.";
} else {
List<LocalRepositoryFolder> localRepositoryFoldersToDelete = allLocalProductsRepositoryPanel.getLocalRepositoryFolders();
folders = localRepositoryFoldersToDelete.toArray(new LocalRepositoryFolder[0]);
messageToDisplay = "All the local repositories will be deleted.";
}
if (folders.length > 0) {
// there are local repositories into the application
String dialogTitle = "Delete local repositories";
if (this.localRepositoryProductsThread != null || this.downloadRemoteProductsHelper.isRunning()) {
// there is a running action
String message = String.format("The local repositories cannot be deleted.%n%nThere is a running action.");
showMessageDialog(dialogTitle, message, JOptionPane.ERROR_MESSAGE);
} else {
// the local repository folders can be deleted
String message = String.format("%s%n%nAre you sure you want to continue?", messageToDisplay);
int answer = showConfirmDialog(dialogTitle, message, JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
allLocalProductsRepositoryPanel.clearInputParameterComponentValues();
this.repositoryOutputProductListPanel.clearOutputList(true);
ProgressBarHelperImpl progressBarHelper = this.repositorySelectionPanel.getProgressBarHelper();
int threadId = progressBarHelper.incrementAndGetCurrentThreadId();
AllLocalFolderProductsRepository allLocalFolderProductsRepository = this.repositorySelectionPanel.getAllLocalProductsRepositoryPanel().getAllLocalFolderProductsRepository();
this.localRepositoryProductsThread = new DeleteAllLocalRepositoriesTimerRunnable(progressBarHelper, threadId, allLocalFolderProductsRepository, folders) {
@Override
protected void onFinishRunning() {
onFinishRunningLocalProductsThread(this, true);
}
@Override
protected void onLocalRepositoryFolderDeleted(LocalRepositoryFolder localRepositoryFolder) {
ProductLibraryToolViewV2.this.deleteLocalRepositoryFolder(localRepositoryFolder);
}
};
this.localRepositoryProductsThread.executeAsync(); // start the thread
}
}
}
}
private void onFinishRunningLocalProductsThread(Runnable invokerThread, boolean startSearchProducts) {
if (resetLocalRepositoryProductsThread(invokerThread)) {
if (this.repositorySelectionPanel.getSelectedProductsRepositoryPanel() instanceof AllLocalProductsRepositoryPanel) {
this.repositoryOutputProductListPanel.updateProductListCountTitle();
// refresh the products in the output panel
OutputProductListPanel productListPanel = this.repositoryOutputProductListPanel.getProductListPanel();
productListPanel.getProductListModel().refreshProducts();
if (startSearchProducts) {
searchProductListLater();
}
}
}
}
private void deleteLocalRepositoryFolder(LocalRepositoryFolder localRepositoryFolderToRemove) {
AllLocalProductsRepositoryPanel allLocalProductsRepositoryPanel = this.repositorySelectionPanel.getAllLocalProductsRepositoryPanel();
allLocalProductsRepositoryPanel.deleteLocalRepositoryFolder(localRepositoryFolderToRemove);
}
private void onFinishProcessingLocalRepositoryThread(Runnable invokerThread, Path localRepositoryFolderPathToSelect) {
if (resetLocalRepositoryProductsThread(invokerThread)) {
if (this.repositorySelectionPanel.getSelectedProductsRepositoryPanel() instanceof AllLocalProductsRepositoryPanel) {
// the local repository is selected
AllLocalProductsRepositoryPanel allLocalProductsRepositoryPanel = (AllLocalProductsRepositoryPanel) this.repositorySelectionPanel.getSelectedProductsRepositoryPanel();
allLocalProductsRepositoryPanel.updateInputParameterValues(localRepositoryFolderPathToSelect, null, null, null, null);
this.repositoryOutputProductListPanel.clearOutputList(true);
searchProductListLater();
}
}
}
private void copySelectedProductsOptionClicked() {
RepositoryProduct[] selectedProducts = this.repositoryOutputProductListPanel.getProductListPanel().getSelectedProducts();
if (selectedProducts.length > 0) {
File[] fileList = new File[selectedProducts.length];
for (int i = 0; i < selectedProducts.length; i++) {
fileList[i] = new File(selectedProducts[i].getURL());
}
ClipboardUtils.copyToClipboard(fileList);
}
}
private void copyToSelectedProductsOptionClicked() {
RepositoryProduct[] selectedProducts = this.repositoryOutputProductListPanel.getProductListPanel().getSelectedProducts();
if (selectedProducts.length > 0) {
// there are selected products
if (this.localRepositoryProductsThread != null) {
String message = "The local products cannot be copied.\n\nThere is a running action.";
showMessageDialog("Copy local products", message, JOptionPane.ERROR_MESSAGE);
} else {
Path selectedLocalTargetFolder = showDialogToSelectLocalFolder("Select folder to copy the products", false);
if (selectedLocalTargetFolder != null) {
// a local folder has been selected
OutputProductListModel productListModel = this.repositoryOutputProductListPanel.getProductListPanel().getProductListModel();
List<RepositoryProduct> productsToCopy = productListModel.addPendingCopyLocalProducts(selectedProducts);
if (productsToCopy.size() > 0) {
// there are local products to copy
ProgressBarHelperImpl progressBarHelper = this.repositorySelectionPanel.getProgressBarHelper();
int threadId = progressBarHelper.incrementAndGetCurrentThreadId();
this.localRepositoryProductsThread = new CopyLocalProductsRunnable(progressBarHelper, threadId, this.repositoryOutputProductListPanel,
selectedLocalTargetFolder, productsToCopy) {
@Override
protected void onFinishRunning() {
onFinishRunningLocalProductsThread(this, false);
}
};
this.localRepositoryProductsThread.executeAsync(); // start the thread
}
}
}
}
}
private void moveToSelectedProductsOptionClicked() {
RepositoryProduct[] unopenedSelectedProducts = processUnopenedSelectedProducts();
if (unopenedSelectedProducts.length > 0) {
if (this.localRepositoryProductsThread != null) {
String message = "The local products cannot be moved.\n\nThere is a running action.";
showMessageDialog("Move local products", message, JOptionPane.ERROR_MESSAGE);
} else {
Path selectedLocalTargetFolder = showDialogToSelectLocalFolder("Select folder to move the products", false);
if (selectedLocalTargetFolder != null) {
// a local folder has been selected
OutputProductListModel productListModel = this.repositoryOutputProductListPanel.getProductListPanel().getProductListModel();
List<RepositoryProduct> productsToMove = productListModel.addPendingMoveLocalProducts(unopenedSelectedProducts);
if (productsToMove.size() > 0) {
// there are local products to move
ProgressBarHelperImpl progressBarHelper = this.repositorySelectionPanel.getProgressBarHelper();
int threadId = progressBarHelper.incrementAndGetCurrentThreadId();
AllLocalFolderProductsRepository allLocalFolderProductsRepository = this.repositorySelectionPanel.getAllLocalProductsRepositoryPanel().getAllLocalFolderProductsRepository();
this.localRepositoryProductsThread = new MoveLocalProductsRunnable(progressBarHelper, threadId, this.repositoryOutputProductListPanel, selectedLocalTargetFolder,
productsToMove, allLocalFolderProductsRepository) {
@Override
protected void onFinishRunning() {
onFinishRunningLocalProductsThread(this, true);
}
};
this.localRepositoryProductsThread.executeAsync(); // start the thread
}
}
}
}
}
private void openLocalSelectedProductsOptionClicked() {
RepositoryProduct[] unopenedSelectedProducts = processUnopenedSelectedProducts();
if (unopenedSelectedProducts.length > 0) {
// there are selected products into the output table
if (this.localRepositoryProductsThread != null) {
String message = "The local products cannot be opened.\n\nThere is a running action.";
showMessageDialog("Open local products", message, JOptionPane.ERROR_MESSAGE);
} else {
OutputProductListModel productListModel = this.repositoryOutputProductListPanel.getProductListPanel().getProductListModel();
List<RepositoryProduct> productsToOpen = productListModel.addPendingOpenLocalProducts(unopenedSelectedProducts);
if (productsToOpen.size() > 0) {
ProgressBarHelperImpl progressBarHelper = this.repositorySelectionPanel.getProgressBarHelper();
int threadId = progressBarHelper.incrementAndGetCurrentThreadId();
this.localRepositoryProductsThread = new OpenLocalProductsRunnable(progressBarHelper, threadId, this.repositoryOutputProductListPanel, this.appContext, productsToOpen) {
@Override
protected void onFinishRunning() {
onFinishRunningLocalProductsThread(this, false);
}
};
this.localRepositoryProductsThread.executeAsync(); // start the thread
}
}
}
}
private void exportSelectedProductsListOptionClicked() {
RepositoryProduct[] selectedProducts = this.repositoryOutputProductListPanel.getProductListPanel().getSelectedProducts();
if (selectedProducts.length > 0) {
// there are selected products
String extension = ".txt";
FileFilter fileFilter = CustomFileChooser.buildFileFilter(extension, "*.txt");
Path selectedFilePath = showDialogToSaveLocalFile("Export selected product list", fileFilter);
if (selectedFilePath != null) {
boolean canContinue = true;
String fileName = selectedFilePath.getFileName().toString();
if (!StringUtils.endsWithIgnoreCase(fileName, extension)) {
fileName += extension;
selectedFilePath = selectedFilePath.getParent().resolve(fileName); // add the '.txt' extension
}
if (Files.exists(selectedFilePath)) {
String message = String.format("The selected file '%s' already exists.%n%nAre you sure you want to overwrite?", selectedFilePath);
int answer = showConfirmDialog("Delete local products", message, JOptionPane.YES_NO_OPTION);
if (answer != JOptionPane.YES_OPTION) {
canContinue = false;
}
}
if (canContinue) {
Path[] localProductPaths = new Path[selectedProducts.length];
for (int i = 0; i < selectedProducts.length; i++) {
localProductPaths[i] = ((LocalRepositoryProduct) selectedProducts[i]).getPath();
}
ExportLocalProductListPathsRunnable runnable = new ExportLocalProductListPathsRunnable(this, selectedFilePath, localProductPaths);
runnable.executeAsync(); // start the thread
}
}
}
}
public void readLocalProductsAsync(RepositoryProduct[] productsToRead, ThreadCallback<Product[]> threadCallback) {
if (this.localRepositoryProductsThread == null) {
ProgressBarHelperImpl progressBarHelper = this.repositorySelectionPanel.getProgressBarHelper();
int threadId = progressBarHelper.incrementAndGetCurrentThreadId();
this.localRepositoryProductsThread = new ReadLocalProductsTimerRunnable(progressBarHelper, threadId, productsToRead, threadCallback) {
@Override
protected void onFinishRunning() {
resetLocalRepositoryProductsThread(this);
}
};
this.localRepositoryProductsThread.executeAsync(); // start the thread
} else {
String message = "The local products cannot be read.\n\nThere is a running action.";
showMessageDialog("Read local products", message, JOptionPane.ERROR_MESSAGE);
}
}
private void deleteLocalSelectedProductsOptionClicked() {
RepositoryProduct[] unopenedSelectedProducts = processUnopenedSelectedProducts();
if (unopenedSelectedProducts.length > 0) {
// there are selected products into the output table
if (this.localRepositoryProductsThread != null) {
String message = "The local products cannot be deleted.\n\nThere is a running action.";
showMessageDialog("Delete local products", message, JOptionPane.ERROR_MESSAGE);
} else {
StringBuilder message = new StringBuilder();
if (unopenedSelectedProducts.length > 1) {
message.append("The selected products");
} else {
message.append("The selected product");
}
message.append(" will be deleted.")
.append("\n\n")
.append("Are you sure you want to continue?");
int answer = showConfirmDialog("Delete local products", message.toString(), JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
OutputProductListModel productListModel = this.repositoryOutputProductListPanel.getProductListPanel().getProductListModel();
List<RepositoryProduct> productsToDelete = productListModel.addPendingDeleteLocalProducts(unopenedSelectedProducts);
if (productsToDelete.size() > 0) {
ProgressBarHelperImpl progressBarHelper = this.repositorySelectionPanel.getProgressBarHelper();
int threadId = progressBarHelper.incrementAndGetCurrentThreadId();
AllLocalFolderProductsRepository allLocalFolderProductsRepository = this.repositorySelectionPanel.getAllLocalProductsRepositoryPanel().getAllLocalFolderProductsRepository();
this.localRepositoryProductsThread = new DeleteLocalProductsRunnable(progressBarHelper, threadId, this.repositoryOutputProductListPanel,
productsToDelete, allLocalFolderProductsRepository) {
@Override
protected void onFinishRunning() {
onFinishRunningLocalProductsThread(this, true);
}
};
this.localRepositoryProductsThread.executeAsync(); // start the thread
}
}
}
}
}
private void openBatchProcessingDialog() {
RepositoryProduct[] selectedProducts = this.repositoryOutputProductListPanel.getProductListPanel().getSelectedProducts();
File[] selectedProductsFiles = new File[selectedProducts.length];
for (int i = 0; i < selectedProducts.length; i++) {
selectedProductsFiles[i] = ((LocalRepositoryProduct) selectedProducts[i]).getPath().toFile();
}
BatchGraphDialog batchDialog = new BatchGraphDialog(this.appContext, "Batch Processing", "batchProcessing", true);
batchDialog.setInputFiles(selectedProductsFiles);
batchDialog.show();
}
private RepositoryProduct[] processUnopenedSelectedProducts() {
RepositoryProduct[] selectedProducts = this.repositoryOutputProductListPanel.getProductListPanel().getSelectedProducts();
List<RepositoryProduct> availableLocalProducts = new ArrayList<>(selectedProducts.length);
for (RepositoryProduct selectedProduct : selectedProducts) {
Product product = this.appContext.getProductManager().getProduct(selectedProduct.getName());
if (product == null) {
// the local product is not opened in the application
availableLocalProducts.add(selectedProduct);
}
}
selectedProducts = new RepositoryProduct[availableLocalProducts.size()];
availableLocalProducts.toArray(selectedProducts);
return selectedProducts;
}
private void leftMouseButtonClicked(List<Path2D.Double> polygonPaths) {
this.repositoryOutputProductListPanel.getProductListPanel().selectProductsByPolygonPath(polygonPaths);
}
private void productListChanged() {
Path2D.Double[] polygonPaths = this.repositoryOutputProductListPanel.getProductListPanel().getPolygonPaths();
this.worldWindowPanel.setPolygons(polygonPaths);
}
private void showSelectedLocalProductInExplorer() {
RepositoryProduct[] selectedProducts = this.repositoryOutputProductListPanel.getProductListPanel().getSelectedProducts();
Path selectedProductPath = ((LocalRepositoryProduct) selectedProducts[0]).getPath();
String dialogTitle = "Show local product in explorer";
if (Files.exists(selectedProductPath)) {
try {
Desktop.getDesktop().open(selectedProductPath.toFile());
} catch (IOException exception) {
String message = String.format("The local product path '%s' can not be opened in the explorer.", selectedProductPath);
showMessageDialog(dialogTitle, message, JOptionPane.ERROR_MESSAGE);
}
} else {
// the product path does not exist
String message = String.format("The local product path '%s' does not exist.", selectedProductPath);
showMessageDialog(dialogTitle, message, JOptionPane.ERROR_MESSAGE);
}
}
private void cancelSearchingProductList() {
this.repositorySelectionPanel.getProgressBarHelper().hideProgressPanel();
if (this.searchProductListThread != null) {
this.searchProductListThread.cancelRunning(); // stop the thread
}
this.repositoryOutputProductListPanel.updateProductListCountTitle();
this.downloadRemoteProductsHelper.cancelDownloadingProductsQuickLookImage();
}
private void setHorizontalSplitPaneLeftComponent(AbstractProductsRepositoryPanel selectedProductsRepositoryPanel) {
int dividerLocation = this.horizontalSplitPane.getDividerLocation();
this.horizontalSplitPane.setLeftComponent(selectedProductsRepositoryPanel);
this.horizontalSplitPane.setDividerLocation(dividerLocation);
this.horizontalSplitPane.revalidate();
this.horizontalSplitPane.repaint();
}
private void onSelectedNewProductsRepository() {
cancelSearchingProductList();
AbstractProductsRepositoryPanel selectedProductsRepositoryPanel = this.repositorySelectionPanel.getSelectedProductsRepositoryPanel();
setHorizontalSplitPaneLeftComponent(selectedProductsRepositoryPanel);
selectedProductsRepositoryPanel.addInputParameterComponents();
boolean refreshed = selectedProductsRepositoryPanel.refreshInputParameterComponentValues();
if (refreshed) {
this.repositoryOutputProductListPanel.refreshOutputList();
} else {
this.repositoryOutputProductListPanel.clearOutputList(true);
}
}
private void onSelectedNewProductsRepositoryMission() {
cancelSearchingProductList();
AbstractProductsRepositoryPanel selectedProductsRepositoryPanel = this.repositorySelectionPanel.getSelectedProductsRepositoryPanel();
selectedProductsRepositoryPanel.addInputParameterComponents();
selectedProductsRepositoryPanel.resetInputParameterValues();
this.repositoryOutputProductListPanel.clearOutputList(true);
}
private void cancelDownloadingProducts() {
this.downloadRemoteProductsHelper.cancelDownloadingProducts(); // stop the thread
this.repositoryOutputProductListPanel.getProgressBarHelper().hideProgressPanel();
}
private Path showDialogToSaveLocalFile(String dialogTitle, FileFilter fileFilter) {
CustomFileChooser fileChooser = CustomFileChooser.buildFileChooser(dialogTitle, false, JFileChooser.FILES_ONLY, false);
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setFileFilter(fileFilter);
if (this.lastLocalRepositoryFolderPath != null) {
fileChooser.setCurrentDirectoryPath(this.lastLocalRepositoryFolderPath);
}
int result = fileChooser.showDialog(this, "Save");
if (result == JFileChooser.APPROVE_OPTION) {
Path selectedFilePath = fileChooser.getSelectedPath();
if (selectedFilePath == null) {
throw new NullPointerException("The selected file path is null.");
}
saveLastSelectedFolderPath(selectedFilePath.getParent());
return selectedFilePath;
}
return null;
}
private Path showDialogToSelectLocalFolder(String dialogTitle, boolean readOnly) {
CustomFileChooser fileChooser = CustomFileChooser.buildFileChooser(dialogTitle, false, JFileChooser.DIRECTORIES_ONLY, readOnly);
fileChooser.setAcceptAllFileFilterUsed(false);
if (this.lastLocalRepositoryFolderPath != null) {
fileChooser.setCurrentDirectoryPath(this.lastLocalRepositoryFolderPath);
}
int result = fileChooser.showDialog(this, "Select");
if (result == JFileChooser.APPROVE_OPTION) {
Path selectedFolderPath = fileChooser.getSelectedPath();
if (selectedFolderPath == null) {
throw new NullPointerException("The selected folder path is null.");
}
saveLastSelectedFolderPath(selectedFolderPath);
return selectedFolderPath;
}
return null;
}
private void saveLastSelectedFolderPath(Path selectedFolderPath) {
// save the folder path into the preferences
this.lastLocalRepositoryFolderPath = selectedFolderPath;
this.appContext.getPreferences().setPropertyString(PREFERENCES_KEY_LAST_LOCAL_REPOSITORY_FOLDER_PATH, this.lastLocalRepositoryFolderPath.toString());
}
private void openDownloadedRemoteProductsButtonPressed() {
RepositoryProduct[] unopenedSelectedProducts = processUnopenedSelectedProducts();
if (unopenedSelectedProducts.length > 0) {
OutputProductListModel productListModel = this.repositoryOutputProductListPanel.getProductListPanel().getProductListModel();
Map<RepositoryProduct, Path> productsToOpen = productListModel.addPendingOpenDownloadedProducts(unopenedSelectedProducts);
if (productsToOpen.size() > 0) {
OpenDownloadedProductsRunnable runnable = new OpenDownloadedProductsRunnable(this.appContext, this.repositoryOutputProductListPanel, productsToOpen);
runnable.executeAsync(); // start the thread
}
}
}
private void newSelectedRepositoryProducts() {
RepositoryProduct[] selectedProducts = this.repositoryOutputProductListPanel.getProductListPanel().getSelectedProducts();
int totalPathCount = 0;
for (RepositoryProduct selectedProduct : selectedProducts) {
if (selectedProduct.getPolygon() != null) {
totalPathCount += selectedProduct.getPolygon().getPathCount();
}
}
Path2D.Double[] polygonPaths = new Path2D.Double[totalPathCount];
for (int i = 0, index = 0; i < selectedProducts.length; i++) {
if (selectedProducts[i].getPolygon() != null) {
AbstractGeometry2D productGeometry = selectedProducts[i].getPolygon();
for (int p = 0; p < productGeometry.getPathCount(); p++) {
polygonPaths[index++] = productGeometry.getPathAt(p);
}
}
}
this.worldWindowPanel.highlightPolygons(polygonPaths);
if (polygonPaths.length == 1) {
// the repository product has only one path
this.worldWindowPanel.setEyePosition(polygonPaths[0]);
}
}
public RepositoryProduct[] getSelectedProducts() {
return this.repositoryOutputProductListPanel.getProductListPanel().getSelectedProducts();
}
private void outputProductsPageChanged() {
this.downloadRemoteProductsHelper.cancelDownloadingProductsQuickLookImage();
if (this.localRepositoryProductsThread == null) {
AbstractProductsRepositoryPanel selectedProductsRepositoryPanel = this.repositorySelectionPanel.getSelectedProductsRepositoryPanel();
if (selectedProductsRepositoryPanel instanceof RemoteProductsRepositoryPanel) {
OutputProductListModel productListModel = this.repositoryOutputProductListPanel.getProductListPanel().getProductListModel();
List<RepositoryProduct> productsWithoutQuickLookImage = productListModel.findProductsWithoutQuickLookImage();
if (productsWithoutQuickLookImage.size() > 0) {
if (logger.isLoggable(Level.FINE)) {
int currentPageNumber = selectedProductsRepositoryPanel.getOutputProductResults().getCurrentPageNumber();
String repositoryName = selectedProductsRepositoryPanel.getRepositoryName();
logger.log(Level.FINE, "Start downloading the quick look images for " + productsWithoutQuickLookImage.size() + " products from page number " + currentPageNumber + " using the '" + repositoryName + "' remote repository.");
}
RemoteProductsRepositoryPanel remoteProductsRepositoryPanel = (RemoteProductsRepositoryPanel) selectedProductsRepositoryPanel;
Credentials selectedCredentials = remoteProductsRepositoryPanel.getSelectedAccount();
RemoteProductsRepositoryProvider productsRepositoryProvider = remoteProductsRepositoryPanel.getProductsRepositoryProvider();
this.downloadRemoteProductsHelper.downloadProductsQuickLookImageAsync(productsWithoutQuickLookImage, productsRepositoryProvider, selectedCredentials, this.repositoryOutputProductListPanel);
}
}
}
}
public void findRelatedSlices() {
RepositoryProduct[] selectedProducts = getSelectedProducts();
if (selectedProducts.length > 0) {
// there are selected products into the output table
if (selectedProducts.length > 1) {
throw new IllegalStateException("Only one selected product is allowed.");
} else {
Integer dataTakeId = findLocalAttributeAsInt(AbstractMetadata.data_take_id, selectedProducts[0]);
if (dataTakeId != null && dataTakeId != AbstractMetadata.NO_METADATA) {
cancelSearchingProductList();
AbstractProductsRepositoryPanel selectedProductsRepositoryPanel = this.repositorySelectionPanel.getSelectedProductsRepositoryPanel();
if (selectedProductsRepositoryPanel instanceof AllLocalProductsRepositoryPanel) {
// the local repository is selected
AllLocalProductsRepositoryPanel allLocalProductsRepositoryPanel = (AllLocalProductsRepositoryPanel) selectedProductsRepositoryPanel;
AttributeFilter attributeFilter = new AttributeFilter(AbstractMetadata.data_take_id, dataTakeId.toString(), AttributesParameterComponent.EQUAL_VALUE_FILTER);
List<AttributeFilter> attributes = new ArrayList<>(1);
attributes.add(attributeFilter);
allLocalProductsRepositoryPanel.updateInputParameterValues(null, null, null, null, null, attributes);
this.repositoryOutputProductListPanel.clearOutputList(true);
searchProductListLater();
} else {
throw new IllegalStateException("The local products repository is not the selected repository.");
}
}
}
}
}
private void jointSearchCriteriaOptionClicked() {
OutputProductListPanel productListPanel = this.repositoryOutputProductListPanel.getProductListPanel();
RepositoryProduct[] selectedProducts = productListPanel.getSelectedProducts();
if (selectedProducts.length > 0) {
// there are selected products into the output table
try {
if (selectedProducts.length > 1) {
throw new IllegalStateException("Only one selected product is allowed.");
} else {
RemoteMission remoteMission = selectedProducts[0].getRemoteMission();
if (remoteMission == null) {
throw new NullPointerException("The remote mission is missing.");
}
LocalDateTime acquisitionDate = selectedProducts[0].getAcquisitionDate();
if (acquisitionDate == null) {
throw new NullPointerException("The product acquisition date is missing.");
}
cancelSearchingProductList();
RemoteProductsRepositoryPanel selectedProductsRepositoryPanel = this.repositorySelectionPanel.selectRemoteProductsRepositoryPanelByName(remoteMission);
if (selectedProductsRepositoryPanel == null) {
throw new IllegalStateException("The remote products repository '" + remoteMission.getRepositoryName() + "' is missing.");
} else {
// the remote products repository exists and it is selected
LocalDateTime startDate = acquisitionDate.minusDays(7); // one week ago
LocalDateTime endDate = acquisitionDate.plusDays(14);
Rectangle2D.Double areaOfInterestToSelect = null;
if (selectedProducts[0].getPolygon() != null) {
Path2D.Double productAreaPath = selectedProducts[0].getPolygon().getPathAt(0);
areaOfInterestToSelect = convertProductAreaPathToRectangle(productAreaPath);
}
setHorizontalSplitPaneLeftComponent(selectedProductsRepositoryPanel);
selectedProductsRepositoryPanel.addInputParameterComponents();
selectedProductsRepositoryPanel.updateInputParameterValues(remoteMission.getName(), startDate, endDate, areaOfInterestToSelect);
this.repositoryOutputProductListPanel.clearOutputList(true);
searchProductListLater();
}
}
} catch (NullPointerException ex) {
showMessageDialog("Joint search", "Cannot perform joint search!\nReason: " + ex.getMessage(), JOptionPane.WARNING_MESSAGE);
} catch (IllegalStateException ex) {
showMessageDialog("Joint search", "Cannot perform joint search!\nReason: " + ex.getMessage(), JOptionPane.ERROR_MESSAGE);
}
}
}
private void onFinishSearchingProducts(Runnable invokerThread) {
if (invokerThread == ProductLibraryToolViewV2.this.searchProductListThread) {
this.searchProductListThread = null; // reset
this.repositoryOutputProductListPanel.updateProductListCountTitle();
}
}
private void downloadSelectedRemoteProductsButtonPressed() {
OutputProductListPanel productListPanel = this.repositoryOutputProductListPanel.getProductListPanel();
RepositoryProduct[] selectedProducts = productListPanel.getSelectedProducts();
if (selectedProducts.length > 0) {
// there are selected products into the output table
if (this.localRepositoryProductsThread == null) {
// there is no running thread for the local repository products
Path selectedLocalRepositoryFolder = showDialogToSelectLocalFolder("Select folder to download the product", false);
if (selectedLocalRepositoryFolder != null) {
AbstractProductsRepositoryPanel selectedRepository = this.repositorySelectionPanel.getSelectedProductsRepositoryPanel();
if (selectedRepository instanceof RemoteProductsRepositoryPanel) {
RemoteProductsRepositoryPanel remoteProductsRepositoryPanel = (RemoteProductsRepositoryPanel) selectedRepository;
Credentials selectedCredentials = remoteProductsRepositoryPanel.getSelectedAccount();
RemoteProductsRepositoryProvider remoteProductsRepositoryProvider = remoteProductsRepositoryPanel.getProductsRepositoryProvider();
AllLocalFolderProductsRepository allLocalFolderProductsRepository = this.repositorySelectionPanel.getAllLocalProductsRepositoryPanel().getAllLocalFolderProductsRepository();
this.downloadRemoteProductsHelper.downloadProductsAsync(selectedProducts, remoteProductsRepositoryProvider, selectedLocalRepositoryFolder,
selectedCredentials, allLocalFolderProductsRepository);
// refresh the products in the output panel
productListPanel.getProductListModel().refreshProducts();
} else {
throw new IllegalStateException("The selected repository is not a remote repository.");
}
}
} else {
StringBuilder message = new StringBuilder();
if (selectedProducts.length > 1) {
message.append("The selected products");
} else {
message.append("The selected product");
}
message.append(" cannot be downloaded.")
.append("\n\n")
.append("There is a running action .");
showMessageDialog("Download products", message.toString(), JOptionPane.ERROR_MESSAGE);
}
}
}
private static Rectangle2D.Double convertProductAreaPathToRectangle(Path2D.Double productAreaPath) {
double[] coordinates = new double[2];
PathIterator pathIterator = productAreaPath.getPathIterator(null);
pathIterator.currentSegment(coordinates);
double x1 = coordinates[0];
double x2 = coordinates[0];
double y1 = coordinates[1];
double y2 = coordinates[1];
pathIterator.next();
while (!pathIterator.isDone()) {
pathIterator.currentSegment(coordinates);
x1 = min(x1, coordinates[0]);
x2 = max(x2, coordinates[0]);
y1 = min(y1, coordinates[1]);
y2 = max(y2, coordinates[1]);
pathIterator.next();
}
return new Rectangle2D.Double(x1, y1, x2 - x1, y2 - y1);
}
private static void writeErrors(final Map<File, String> errorFiles, final File file) throws Exception {
PrintStream p = null; // declare a print stream object
try {
final FileOutputStream out = new FileOutputStream(file.getAbsolutePath());
// Connect print stream to the output stream
p = new PrintStream(out);
for (Map.Entry<File, String> entry : errorFiles.entrySet()) {
p.println(entry.getValue() + " " + entry.getKey().getAbsolutePath());
}
} finally {
if (p != null) {
p.close();
}
}
}
private void searchButtonPressed() {
cancelSearchingProductList();
ThreadListener threadListener = this::onFinishSearchingProducts;
ProgressBarHelperImpl progressBarHelper = this.repositorySelectionPanel.getProgressBarHelper();
int threadId = progressBarHelper.incrementAndGetCurrentThreadId();
AbstractProductsRepositoryPanel selectedProductsRepositoryPanel = this.repositorySelectionPanel.getSelectedProductsRepositoryPanel();
RemoteRepositoriesSemaphore remoteRepositoriesSemaphore = this.downloadRemoteProductsHelper.getRemoteRepositoriesSemaphore();
AbstractProgressTimerRunnable<?> thread = selectedProductsRepositoryPanel.buildSearchProductListThread(progressBarHelper, threadId, threadListener,
remoteRepositoriesSemaphore, this.repositoryOutputProductListPanel);
if (thread != null) {
this.repositoryOutputProductListPanel.clearOutputList(true);
this.searchProductListThread = thread;
this.searchProductListThread.executeAsync(); // start the thread
}
}
}
| 77,030 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LoadInputDataRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/LoadInputDataRunnable.java | package org.esa.snap.product.library.ui.v2;
import org.esa.snap.product.library.v2.preferences.RepositoriesCredentialsController;
import org.esa.snap.product.library.v2.preferences.RepositoriesCredentialsPersistence;
import org.esa.snap.product.library.v2.preferences.model.RemoteRepositoryCredentials;
import org.esa.snap.product.library.ui.v2.repository.local.LocalParameterValues;
import org.esa.snap.product.library.ui.v2.thread.AbstractRunnable;
import org.esa.snap.product.library.v2.database.AllLocalFolderProductsRepository;
import org.esa.snap.product.library.v2.database.LocalRepositoryParameterValues;
import org.esa.snap.ui.loading.GenericRunnable;
import javax.swing.SwingUtilities;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread to load the initial data when showing for the first time the Product Library Tool.
*
* Created by jcoravu on 16/9/2019.
*/
public class LoadInputDataRunnable extends AbstractRunnable<LocalParameterValues> {
private static final Logger logger = Logger.getLogger(LoadInputDataRunnable.class.getName());
private final AllLocalFolderProductsRepository allLocalFolderProductsRepository;
public LoadInputDataRunnable(AllLocalFolderProductsRepository allLocalFolderProductsRepository) {
this.allLocalFolderProductsRepository = allLocalFolderProductsRepository;
}
@Override
protected LocalParameterValues execute() throws Exception {
int visibleProductsPerPage = RepositoriesCredentialsPersistence.VISIBLE_PRODUCTS_PER_PAGE;
boolean uncompressedDownloadedProducts = RepositoriesCredentialsPersistence.UNCOMPRESSED_DOWNLOADED_PRODUCTS;
List<RemoteRepositoryCredentials> repositoriesCredentials = null;
try {
RepositoriesCredentialsController controller = RepositoriesCredentialsController.getInstance();
repositoriesCredentials = controller.getRepositoriesCredentials();
visibleProductsPerPage = controller.getNrRecordsOnPage();
uncompressedDownloadedProducts = controller.isAutoUncompress();
} catch (Exception exception) {
logger.log(Level.SEVERE, "Failed to load the remote repository credentials.", exception);
}
LocalRepositoryParameterValues localRepositoryParameterValues = null;
try {
localRepositoryParameterValues = this.allLocalFolderProductsRepository.loadParameterValues();
} catch (Exception exception) {
logger.log(Level.SEVERE, "Failed to load input data from the database.", exception);
}
return new LocalParameterValues(repositoriesCredentials, visibleProductsPerPage, uncompressedDownloadedProducts, localRepositoryParameterValues);
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to read the parameters from the database.";
}
@Override
protected final void successfullyExecuting(LocalParameterValues parameterValues) {
GenericRunnable<LocalParameterValues> runnable = new GenericRunnable<LocalParameterValues>(parameterValues) {
@Override
protected void execute(LocalParameterValues item) {
onSuccessfullyExecuting(item);
}
};
SwingUtilities.invokeLater(runnable);
}
protected void onSuccessfullyExecuting(LocalParameterValues parameterValues) {
}
}
| 3,429 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ComponentDimension.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/ComponentDimension.java | package org.esa.snap.product.library.ui.v2;
import java.awt.*;
/**
* The interface containing to retrieve information about a component displayed in a panel.
*
* Created by jcoravu on 26/8/2019.
*/
public interface ComponentDimension {
public int getGapBetweenRows();
public int getGapBetweenColumns();
public int getTextFieldPreferredHeight();
public Color getTextFieldBackgroundColor();
}
| 417 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RepositoryProductPanelBackground.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/RepositoryProductPanelBackground.java | package org.esa.snap.product.library.ui.v2;
import org.esa.snap.product.library.ui.v2.repository.AbstractRepositoryProductPanel;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import java.awt.Color;
import java.util.Map;
/**
* The interface contains methods to retrieve information from the panel of a repository product.
*
* Created by jcoravu on 27/9/2019.
*/
public interface RepositoryProductPanelBackground {
public Map<String, String> getRemoteMissionVisibleAttributes(String mission);
public Color getProductPanelBackground(AbstractRepositoryProductPanel productPanel);
public RepositoryProduct getProductPanelItem(AbstractRepositoryProductPanel repositoryProductPanel);
}
| 721 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RepositorySelectionPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/RepositorySelectionPanel.java | package org.esa.snap.product.library.ui.v2.repository;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.product.library.ui.v2.MissionParameterListener;
import org.esa.snap.product.library.ui.v2.ProductLibraryV2Action;
import org.esa.snap.product.library.v2.preferences.model.RemoteRepositoryCredentials;
import org.esa.snap.product.library.ui.v2.repository.local.AllLocalProductsRepositoryPanel;
import org.esa.snap.product.library.ui.v2.repository.local.LocalParameterValues;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductListPaginationPanel;
import org.esa.snap.product.library.ui.v2.repository.remote.DownloadProgressStatus;
import org.esa.snap.product.library.ui.v2.repository.remote.RemoteProductsRepositoryPanel;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadingProductProgressCallback;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelperImpl;
import org.esa.snap.worldwind.productlibrary.WorldMapPanelWrapper;
import org.esa.snap.product.library.v2.database.SaveProductData;
import org.esa.snap.remote.products.repository.RemoteMission;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.loading.CustomComboBox;
import org.esa.snap.ui.loading.ItemRenderer;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
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.List;
import java.util.Map;
import java.util.Stack;
/**
* The class represents the top bar panel which contains the combox box with the available repositories,
* the search product list button, the progress bar panel.
*
* Created by jcoravu on 22/8/2019.
*/
public class RepositorySelectionPanel extends JPanel {
private final JButton searchButton;
private final JButton helpButton;
private final JLabel repositoryLabel;
private final ProgressBarHelperImpl progressBarHelper;
private final ComponentDimension componentDimension;
private final WorldMapPanelWrapper worldWindowPanel;
private JComboBox<AbstractProductsRepositoryPanel> repositoriesComboBox;
private JPanel topBarButtonsPanel;
private ItemListener productsRepositoryListener;
private ItemListener localRepositoryListener;
public RepositorySelectionPanel(RemoteProductsRepositoryProvider[] productsRepositoryProviders, ComponentDimension componentDimension,
MissionParameterListener missionParameterListener, WorldMapPanelWrapper worldWindowPanel,
int progressBarWidth) {
super(new GridBagLayout());
this.componentDimension = componentDimension;
this.worldWindowPanel = worldWindowPanel;
createRepositoriesComboBox(productsRepositoryProviders, missionParameterListener);
int preferredHeight = this.componentDimension.getTextFieldPreferredHeight();
Dimension buttonSize = new Dimension(preferredHeight, preferredHeight);
this.searchButton = SwingUtils.buildButton("/org/esa/snap/product/library/ui/v2/icons/search24.png", null, buttonSize, 1);
this.searchButton.setToolTipText("Search");
this.helpButton = SwingUtils.buildButton("/org/esa/snap/resources/images/icons/Help24.gif", null, buttonSize, 1);
this.helpButton.setToolTipText("Help");
this.progressBarHelper = new ProgressBarHelperImpl(progressBarWidth, buttonSize.height) {
@Override
protected void setParametersEnabledWhileDownloading(boolean enabled) {
RepositorySelectionPanel.this.setParametersEnabledWhileDownloading(enabled);
}
};
this.repositoryLabel = new JLabel("Repository");
}
public void refreshUserAccounts(List<RemoteRepositoryCredentials> repositoriesCredentials) {
int repositoryCount = this.repositoriesComboBox.getModel().getSize();
for (int i=0; i<repositoriesCredentials.size(); i++) {
RemoteRepositoryCredentials repositoryCredentials = repositoriesCredentials.get(i);
for (int k=0; k<repositoryCount; k++) {
AbstractProductsRepositoryPanel repositoryPanel = this.repositoriesComboBox.getModel().getElementAt(k);
if (repositoryPanel instanceof RemoteProductsRepositoryPanel) {
RemoteProductsRepositoryPanel remoteRepositoryPanel = (RemoteProductsRepositoryPanel)repositoryPanel;
if (remoteRepositoryPanel.getProductsRepositoryProvider().getRepositoryName().equals(repositoryCredentials.getRepositoryName())) {
remoteRepositoryPanel.setUserAccounts(repositoryCredentials.getCredentialsList());
}
}
}
}
}
public void setInputData(LocalParameterValues parameterValues) {
if (parameterValues.getRepositoriesCredentials() != null) {
refreshUserAccounts(parameterValues.getRepositoriesCredentials());
}
AllLocalProductsRepositoryPanel localProductsRepositoryPanel = getAllLocalProductsRepositoryPanel();
localProductsRepositoryPanel.setLocalParameterValues(parameterValues.getLocalRepositoryParameterValues());
}
public ProgressBarHelperImpl getProgressBarHelper() {
return progressBarHelper;
}
public void setSearchButtonListener(ActionListener searchButtonListener) {
this.searchButton.addActionListener(searchButtonListener);
}
public void setHelpButtonListener(ActionListener helpButtonListener) {
this.helpButton.addActionListener(helpButtonListener);
}
public void setStopButtonListener(ActionListener stopButtonListener) {
this.progressBarHelper.getStopButton().addActionListener(stopButtonListener);
}
public AbstractProductsRepositoryPanel getSelectedProductsRepositoryPanel() {
return (AbstractProductsRepositoryPanel)this.repositoriesComboBox.getSelectedItem();
}
public void setAllProductsRepositoryPanelBorder(Border border) {
int count = this.repositoriesComboBox.getModel().getSize();
for (int i=0; i<count; i++) {
AbstractProductsRepositoryPanel repositoryPanel = this.repositoriesComboBox.getModel().getElementAt(i);
repositoryPanel.setBorder(border);
}
}
public void finishSavingLocalProduct(SaveProductData saveProductData) {
AllLocalProductsRepositoryPanel allLocalProductsRepositoryPanel = getAllLocalProductsRepositoryPanel();
if (saveProductData.getLocalRepositoryFolder() != null) {
allLocalProductsRepositoryPanel.addLocalRepositoryFolderIfMissing(saveProductData.getLocalRepositoryFolder());
}
// a product has either a remote mission, either a metadata mission
if (saveProductData.getRemoteMission() != null) {
allLocalProductsRepositoryPanel.addMissionIfMissing(saveProductData.getRemoteMission().getName());
} else if (!StringUtils.isNullOrEmpty(saveProductData.getMetadataMission())) {
allLocalProductsRepositoryPanel.addMissionIfMissing(saveProductData.getMetadataMission());
}
}
public void finishDownloadingProduct(RepositoryProduct repositoryProduct, DownloadProgressStatus downloadProgressStatus, SaveProductData saveProductData) {
ComboBoxModel<AbstractProductsRepositoryPanel> model = this.repositoriesComboBox.getModel();
for (int i = 0; i < model.getSize(); i++) {
AbstractProductsRepositoryPanel repositoryPanel = model.getElementAt(i);
if (repositoryPanel instanceof RemoteProductsRepositoryPanel) {
if (repositoryPanel.getRepositoryName().equals(repositoryProduct.getRemoteMission().getRepositoryName())) {
((RemoteProductsRepositoryPanel) repositoryPanel).addDownloadedProductProgress(repositoryProduct, downloadProgressStatus);
}
} else if (repositoryPanel instanceof AllLocalProductsRepositoryPanel) {
if (saveProductData != null) {
AllLocalProductsRepositoryPanel allLocalProductsRepositoryPanel = (AllLocalProductsRepositoryPanel) repositoryPanel;
if (saveProductData.getLocalRepositoryFolder() != null) {
allLocalProductsRepositoryPanel.addLocalRepositoryFolderIfMissing(saveProductData.getLocalRepositoryFolder());
}
allLocalProductsRepositoryPanel.addMissionIfMissing(saveProductData.getRemoteMission().getName());
allLocalProductsRepositoryPanel.addAttributesIfMissing(repositoryProduct);
}
} else {
throw new IllegalStateException("Unknown repository panel type '" + repositoryPanel + "'.");
}
}
}
public AllLocalProductsRepositoryPanel getAllLocalProductsRepositoryPanel() {
int count = this.repositoriesComboBox.getModel().getSize();
for (int i=0; i<count; i++) {
AbstractProductsRepositoryPanel repositoryPanel = this.repositoriesComboBox.getModel().getElementAt(i);
if (repositoryPanel instanceof AllLocalProductsRepositoryPanel) {
return (AllLocalProductsRepositoryPanel)repositoryPanel;
}
}
throw new IllegalStateException("The all local products repository does not exist.");
}
public Map<String, String> getRemoteMissionVisibleAttributes(String mission) {
int count = this.repositoriesComboBox.getModel().getSize();
for (int i=0; i<count; i++) {
AbstractProductsRepositoryPanel repositoryPanel = this.repositoriesComboBox.getModel().getElementAt(i);
if (repositoryPanel instanceof RemoteProductsRepositoryPanel) {
RemoteProductsRepositoryPanel remoteProductsRepositoryPanel = (RemoteProductsRepositoryPanel)repositoryPanel;
String[] availableMissions = remoteProductsRepositoryPanel.getProductsRepositoryProvider().getAvailableMissions();
for (int k=0; k<availableMissions.length; k++) {
if (availableMissions[k].equalsIgnoreCase(mission)) {
return remoteProductsRepositoryPanel.getProductsRepositoryProvider().getDisplayedAttributes();
}
}
}
}
return null;
}
private void setParametersEnabledWhileDownloading(boolean enabled) {
this.searchButton.setEnabled(enabled);
this.repositoryLabel.setEnabled(enabled);
this.repositoriesComboBox.setEnabled(enabled);
if (this.topBarButtonsPanel != null) {
for (int i=0; i<this.topBarButtonsPanel.getComponentCount(); i++) {
this.topBarButtonsPanel.getComponent(i).setEnabled(enabled);
}
}
AbstractProductsRepositoryPanel selectedDataSource = getSelectedProductsRepositoryPanel();
Stack<JComponent> stack = new Stack<JComponent>();
stack.push(selectedDataSource);
while (!stack.isEmpty()) {
JComponent component = stack.pop();
component.setEnabled(enabled);
int childrenCount = component.getComponentCount();
for (int i=0; i<childrenCount; i++) {
Component child = component.getComponent(i);
if (child instanceof JComponent) {
JComponent childComponent = (JComponent) child;
// add the component in the stack to be enabled/disabled
stack.push(childComponent);
}
}
}
}
private void refreshRepositoryLabelWidth() {
int maximumLabelWidth = getSelectedProductsRepositoryPanel().computeLeftPanelMaximumLabelWidth();
Dimension labelSize = this.repositoryLabel.getPreferredSize();
labelSize.width = maximumLabelWidth;
this.repositoryLabel.setPreferredSize(labelSize);
this.repositoryLabel.setMinimumSize(labelSize);
Container parentContainer = this.repositoryLabel.getParent();
if (parentContainer != null) {
parentContainer.revalidate();
parentContainer.repaint();
}
}
public void setRepositoriesItemListener(ItemListener productsRepositoryListener) {
this.productsRepositoryListener = productsRepositoryListener;
}
private void createRepositoriesComboBox(RemoteProductsRepositoryProvider[] productsRepositoryProviders, MissionParameterListener missionParameterListener) {
PropertyChangeListener parameterComponentsChangedListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
refreshRepositoryLabelWidth();
}
};
ItemRenderer<AbstractProductsRepositoryPanel> itemRenderer = new ItemRenderer<AbstractProductsRepositoryPanel>() {
@Override
public String getItemDisplayText(AbstractProductsRepositoryPanel panel) {
return (panel == null) ? "" : panel.getRepositoryName();
}
};
this.repositoriesComboBox = new CustomComboBox(itemRenderer, this.componentDimension.getTextFieldPreferredHeight(), false, this.componentDimension.getTextFieldBackgroundColor());
for (int i=0; i<productsRepositoryProviders.length; i++) {
RemoteProductsRepositoryPanel remoteProductsRepositoryPanel = new RemoteProductsRepositoryPanel(productsRepositoryProviders[i], this.componentDimension, missionParameterListener, this.worldWindowPanel);
remoteProductsRepositoryPanel.addInputParameterComponentsChangedListener(parameterComponentsChangedListener);
this.repositoriesComboBox.addItem(remoteProductsRepositoryPanel);
}
this.localRepositoryListener = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent itemEvent) {
if (itemEvent.getStateChange() == ItemEvent.SELECTED) {
newSelectedRepository();
if (productsRepositoryListener != null) {
productsRepositoryListener.itemStateChanged(null);
}
}
}
};
AllLocalProductsRepositoryPanel allLocalProductsRepositoryPanel = new AllLocalProductsRepositoryPanel(this.componentDimension, this.worldWindowPanel);
allLocalProductsRepositoryPanel.addInputParameterComponentsChangedListener(parameterComponentsChangedListener);
this.repositoriesComboBox.addItem(allLocalProductsRepositoryPanel);
this.repositoriesComboBox.setMaximumRowCount(7);
this.repositoriesComboBox.setSelectedIndex(0);
this.repositoriesComboBox.addItemListener(this.localRepositoryListener);
}
public void setLocalRepositoriesListeners(ActionListener scanLocalRepositoryFoldersListener,
ActionListener addLocalRepositoryFolderListener, ActionListener deleteLocalRepositoryFolderListener, List<ProductLibraryV2Action> localActions) {
AllLocalProductsRepositoryPanel allLocalProductsRepositoryPanel = getAllLocalProductsRepositoryPanel();
allLocalProductsRepositoryPanel.setTopBarButtonListeners(scanLocalRepositoryFoldersListener, addLocalRepositoryFolderListener, deleteLocalRepositoryFolderListener);
allLocalProductsRepositoryPanel.setPopupMenuActions(localActions);
}
public RemoteProductsRepositoryPanel selectRemoteProductsRepositoryPanelByName(RemoteMission remoteMission) {
ComboBoxModel<AbstractProductsRepositoryPanel> model = this.repositoriesComboBox.getModel();
for (int i=0; i<model.getSize(); i++) {
AbstractProductsRepositoryPanel repositoryPanel = model.getElementAt(i);
if (repositoryPanel instanceof RemoteProductsRepositoryPanel) {
if (repositoryPanel.getRepositoryName().equalsIgnoreCase(remoteMission.getRepositoryName())) {
this.repositoriesComboBox.removeItemListener(this.localRepositoryListener);
try {
this.repositoriesComboBox.setSelectedIndex(i);
} finally {
this.repositoriesComboBox.addItemListener(this.localRepositoryListener);
}
RemoteProductsRepositoryPanel remoteProductsRepositoryPanel = (RemoteProductsRepositoryPanel)repositoryPanel;
return remoteProductsRepositoryPanel;
}
}
}
return null;
}
public void setDownloadRemoteProductListener(List<ProductLibraryV2Action> remoteActions) {
ComboBoxModel<AbstractProductsRepositoryPanel> model = this.repositoriesComboBox.getModel();
for (int i=0; i<model.getSize(); i++) {
AbstractProductsRepositoryPanel repositoryPanel = model.getElementAt(i);
if (repositoryPanel instanceof RemoteProductsRepositoryPanel) {
((RemoteProductsRepositoryPanel)repositoryPanel).setPopupMenuActions(remoteActions);
}
}
}
public void setDownloadingProductProgressCallback(DownloadingProductProgressCallback downloadingProductProgressCallback) {
ComboBoxModel<AbstractProductsRepositoryPanel> model = this.repositoriesComboBox.getModel();
for (int i=0; i<model.getSize(); i++) {
AbstractProductsRepositoryPanel repositoryPanel = model.getElementAt(i);
if (repositoryPanel instanceof RemoteProductsRepositoryPanel) {
((RemoteProductsRepositoryPanel)repositoryPanel).setDownloadingProductProgressCallback(downloadingProductProgressCallback);
}
}
}
private void newSelectedRepository() {
if (this.topBarButtonsPanel != null) {
remove(this.topBarButtonsPanel);
revalidate();
repaint();
}
createTopBarButtonsPanel();
if (this.topBarButtonsPanel != null) {
GridBagConstraints c = SwingUtils.buildConstraints(3, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST, 1, 1, 0, this.componentDimension.getGapBetweenColumns());
add(this.topBarButtonsPanel, c);
revalidate();
repaint();
}
}
private void createTopBarButtonsPanel() {
JButton[] topBarButtons = getSelectedProductsRepositoryPanel().getTopBarButton();
if (topBarButtons != null && topBarButtons.length > 0) {
this.topBarButtonsPanel = new JPanel(new GridLayout(1, topBarButtons.length, this.componentDimension.getGapBetweenColumns(), 0));
for (int i=0; i<topBarButtons.length; i++) {
this.topBarButtonsPanel.add(topBarButtons[i]);
}
} else {
this.topBarButtonsPanel = null;
}
}
public void addComponents(OutputProductListPaginationPanel productListPaginationPanel) {
createTopBarButtonsPanel();
int gapBetweenColumns = this.componentDimension.getGapBetweenColumns();
GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, 0, 0);
add(this.repositoryLabel, c);
c = SwingUtils.buildConstraints(1, 0, GridBagConstraints.BOTH, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns);
add(this.repositoriesComboBox, c);
c = SwingUtils.buildConstraints(2, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns);
add(this.searchButton, c);
if (this.topBarButtonsPanel != null) {
c = SwingUtils.buildConstraints(3, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns);
add(this.topBarButtonsPanel, c);
}
c = SwingUtils.buildConstraints(4, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns);
add(productListPaginationPanel, c);
c = SwingUtils.buildConstraints(5, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns);
add(this.helpButton, c);
c = SwingUtils.buildConstraints(6, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns);
add(this.progressBarHelper.getProgressBar(), c);
c = SwingUtils.buildConstraints(7, 0, GridBagConstraints.VERTICAL, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns);
add(this.progressBarHelper.getStopButton(), c);
}
}
| 20,894 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractProductsRepositoryPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/AbstractProductsRepositoryPanel.java | package org.esa.snap.product.library.ui.v2.repository;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.product.library.ui.v2.ProductLibraryV2Action;
import org.esa.snap.product.library.ui.v2.RepositoryProductPanelBackground;
import org.esa.snap.product.library.ui.v2.repository.input.AbstractParameterComponent;
import org.esa.snap.product.library.ui.v2.repository.input.ParametersPanel;
import org.esa.snap.product.library.ui.v2.repository.input.SelectionAreaParameterComponent;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductListModel;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductResults;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.repository.remote.RemoteRepositoriesSemaphore;
import org.esa.snap.product.library.ui.v2.thread.AbstractProgressTimerRunnable;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.product.library.ui.v2.thread.ThreadListener;
import org.esa.snap.worldwind.productlibrary.WorldMapPanelWrapper;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.remote.products.repository.RepositoryQueryParameter;
import org.esa.snap.ui.loading.CustomSplitPane;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.beans.PropertyChangeListener;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* The panel containing the query parameters of a repository.
*
* Created by jcoravu on 5/8/2019.
*/
public abstract class AbstractProductsRepositoryPanel extends JPanel {
private static final String INPUT_PARAMETER_COMPONENTS_CHANGED = "parameterComponentsChanged";
private final WorldMapPanelWrapper worlWindPanel;
protected final ComponentDimension componentDimension;
protected List<AbstractParameterComponent<?>> parameterComponents;
private OutputProductResults outputProductResults;
private List<ProductLibraryV2Action> popupMenuActions;
protected AbstractProductsRepositoryPanel(WorldMapPanelWrapper worlWindPanel, ComponentDimension componentDimension, LayoutManager layoutManager) {
super(layoutManager);
this.worlWindPanel = worlWindPanel;
this.componentDimension = componentDimension;
resetOutputProducts();
}
public abstract String getRepositoryName();
protected abstract ParametersPanel getInputParameterComponentsPanel();
protected abstract RepositoryQueryParameter getAreaOfInterestParameter();
public abstract boolean refreshInputParameterComponentValues();
public abstract void resetInputParameterValues();
public abstract AbstractRepositoryProductPanel buildProductProductPanel(RepositoryProductPanelBackground repositoryProductPanelBackground,
ComponentDimension componentDimension);
public abstract AbstractProgressTimerRunnable<?> buildSearchProductListThread(ProgressBarHelper progressPanel, int threadId, ThreadListener threadListener,
RemoteRepositoriesSemaphore remoteRepositoriesSemaphore, RepositoryOutputProductListPanel repositoryProductListPanel);
private void addInputParameterComponentsToPanel(){
ParametersPanel parametersPanel = getInputParameterComponentsPanel();
RepositoryQueryParameter areaOfInterestParameter = getAreaOfInterestParameter();
int gapBetweenColumns = 5;
int visibleDividerSize = gapBetweenColumns - 2;
int dividerMargins = 0;
float initialDividerLocationPercent = 0.5f;
CustomSplitPane parametersSplitPane = new CustomSplitPane(JSplitPane.VERTICAL_SPLIT, visibleDividerSize, dividerMargins, initialDividerLocationPercent, SwingUtils.TRANSPARENT_COLOR);
JScrollPane parametersScrollPanel = new JScrollPane(parametersPanel);
parametersScrollPanel.setBorder(null);
parametersScrollPanel.setMinimumSize(new Dimension(300, 200));
parametersSplitPane.setTopComponent(parametersScrollPanel);
if(areaOfInterestParameter != null) {
JPanel areaParameterComponent = getAreaParameterComponent(areaOfInterestParameter);
areaParameterComponent.setMinimumSize(new Dimension(300, 200));
parametersSplitPane.setBottomComponent(areaParameterComponent);
}
add(parametersSplitPane, BorderLayout.CENTER);
}
public JButton[] getTopBarButton() {
return null;
}
public final void resetOutputProducts() {
this.outputProductResults = new OutputProductResults();
}
public final OutputProductResults getOutputProductResults() {
return outputProductResults;
}
public void setPopupMenuActions(List<ProductLibraryV2Action> remoteActions) {
this.popupMenuActions = remoteActions;
}
public final JPopupMenu buildProductListPopupMenu(RepositoryProduct[] selectedProducts, OutputProductListModel productListModel) {
JPopupMenu popupMenu = new JPopupMenu();
for (int i = 0; i<this.popupMenuActions.size(); i++) {
ProductLibraryV2Action action = this.popupMenuActions.get(i);
if (action.canAddItemToPopupMenu(this, selectedProducts)) {
popupMenu.add(action);
}
}
return popupMenu;
}
public final void addInputParameterComponents() {
removeAll();
addInputParameterComponentsToPanel();
refreshLabelWidths();
revalidate();
repaint();
firePropertyChange(INPUT_PARAMETER_COMPONENTS_CHANGED, null, null);
}
public void addInputParameterComponentsChangedListener(PropertyChangeListener changeListener) {
addPropertyChangeListener(INPUT_PARAMETER_COMPONENTS_CHANGED, changeListener);
}
public int computeLeftPanelMaximumLabelWidth() {
int maximumLabelWidth = 0;
for (int i=0; i<this.parameterComponents.size(); i++) {
AbstractParameterComponent parameterComponent = this.parameterComponents.get(i);
int labelWidth = parameterComponent.getLabel().getPreferredSize().width;
if (maximumLabelWidth < labelWidth) {
maximumLabelWidth = labelWidth;
}
}
return maximumLabelWidth;
}
public void clearInputParameterComponentValues() {
for (int i=0; i<this.parameterComponents.size(); i++) {
AbstractParameterComponent parameterComponent = this.parameterComponents.get(i);
parameterComponent.clearParameterValue();
}
}
protected final Map<String, Object> getParameterValues() {
Map<String, Object> parameterValues = new LinkedHashMap<>();
for (int i=0; i<this.parameterComponents.size(); i++) {
AbstractParameterComponent<?> parameterComponent = this.parameterComponents.get(i);
Boolean result = parameterComponent.hasValidValue();
if (result == null) {
// the value is not specified
String errorMessage = parameterComponent.getRequiredValueErrorDialogMessage();
if (errorMessage != null) {
// the value is required and show a message dialog
showErrorMessageDialog(errorMessage, "Required parameter value");
parameterComponent.getComponent().requestFocus();
return null; // no parameters to return
}
} else if (result.booleanValue()) {
// the value is specified and it is valid
Object value = parameterComponent.getParameterValue();
if (value == null) {
throw new NullPointerException("The parameter value is null.");
} else {
parameterValues.put(parameterComponent.getParameterName(), value);
}
} else {
// the value is specified and it is invalid
String errorMessage = parameterComponent.getInvalidValueErrorDialogMessage();
if (errorMessage == null) {
throw new NullPointerException("The error message for invalid value is null.");
} else {
// the value is required and show a message dialog
showErrorMessageDialog(errorMessage, "Invalid parameter value");
parameterComponent.getComponent().requestFocus();
return null; // no parameters to return
}
}
}
return parameterValues;
}
protected final void showErrorMessageDialog(String message, String title) {
JOptionPane.showMessageDialog(getParent(), message, title, JOptionPane.ERROR_MESSAGE);
}
protected final void showInformationMessageDialog(String message, String title) {
JOptionPane.showMessageDialog(getParent(), message, title, JOptionPane.INFORMATION_MESSAGE);
}
protected final void refreshLabelWidths() {
int maximumLabelWidth = computeLeftPanelMaximumLabelWidth();
for (int i=0; i<this.parameterComponents.size(); i++) {
JLabel label = this.parameterComponents.get(i).getLabel();
Dimension labelSize = label.getPreferredSize();
labelSize.width = maximumLabelWidth;
label.setPreferredSize(labelSize);
label.setMinimumSize(labelSize);
}
}
protected final JPanel getAreaParameterComponent(RepositoryQueryParameter areaOfInterestParameter) {
this.worlWindPanel.clearSelectedArea();
SelectionAreaParameterComponent selectionAreaParameterComponent = new SelectionAreaParameterComponent(this.worlWindPanel, areaOfInterestParameter.getName(), areaOfInterestParameter.getLabel(), areaOfInterestParameter.isRequired());
this.parameterComponents.add(selectionAreaParameterComponent);
JLabel label = selectionAreaParameterComponent.getLabel();
label.setVerticalAlignment(JLabel.TOP);
int difference = this.componentDimension.getTextFieldPreferredHeight() - label.getPreferredSize().height;
label.setBorder(new EmptyBorder((difference/2), 0, 0 , 0));
JPanel centerPanel = new JPanel(new BorderLayout(this.componentDimension.getGapBetweenColumns(), 0));
centerPanel.add(label, BorderLayout.WEST);
centerPanel.add(selectionAreaParameterComponent.getComponent(), BorderLayout.CENTER);
this.worlWindPanel.refresh();
return centerPanel;
}
}
| 10,767 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RepositoryProductAttributesPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/RepositoryProductAttributesPanel.java | package org.esa.snap.product.library.ui.v2.repository;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.remote.products.repository.Attribute;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.util.*;
/**
* The class contains the repository product attributes.
*
* Created by jcoravu on 3/2/2020.
*/
public class RepositoryProductAttributesPanel extends JPanel {
private final RepositoryProduct repositoryProduct;
public RepositoryProductAttributesPanel(ComponentDimension componentDimension, RepositoryProduct repositoryProduct) {
super(new GridBagLayout());
this.repositoryProduct = repositoryProduct;
int gapBetweenRows = componentDimension.getGapBetweenRows();
int leftPanelPadding = 5 * componentDimension.getGapBetweenColumns();
String noAttributesMessage = "No attributes";
JLabel remoteAttributesTitleLabel = new JLabel("Remote Attributes");
GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, 0, 0);
add(remoteAttributesTitleLabel, c);
JComponent remoteComponent;
java.util.List<Attribute> remoteAttributes = this.repositoryProduct.getRemoteAttributes();
if (remoteAttributes != null && remoteAttributes.size() > 0) {
remoteComponent = buildPanelAttributes(remoteAttributes, componentDimension);
} else {
remoteComponent = new JLabel(noAttributesMessage);
}
c = SwingUtils.buildConstraints(0, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, leftPanelPadding);
add(remoteComponent, c);
JLabel localAttributesTitleLabel = new JLabel("Local Attributes");
c = SwingUtils.buildConstraints(0, 2, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0);
add(localAttributesTitleLabel, c);
JComponent localComponent;
java.util.List<Attribute> localAttributes = this.repositoryProduct.getLocalAttributes();
if (localAttributes != null && localAttributes.size() > 0) {
localComponent = buildPanelAttributes(localAttributes, componentDimension);
} else {
localComponent = new JLabel(noAttributesMessage);
}
c = SwingUtils.buildConstraints(0, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, leftPanelPadding);
add(localComponent, c);
}
public RepositoryProduct getRepositoryProduct() {
return repositoryProduct;
}
private static JPanel buildPanelAttributes(java.util.List<Attribute> attributes, ComponentDimension componentDimension) {
int gapBetweenRows = componentDimension.getGapBetweenRows();
int gapBetweenColumns = componentDimension.getGapBetweenColumns();
int columnCount = 3;
int rowCount = attributes.size() / columnCount;
if (attributes.size() % columnCount != 0) {
rowCount++;
}
JPanel panel = new JPanel(new GridLayout(rowCount, columnCount, gapBetweenColumns, gapBetweenRows));
panel.setOpaque(false);
for (int i=0; i<attributes.size(); i++) {
Attribute attribute = attributes.get(i);
JLabel label = new JLabel(attribute.getName() + ": " + attribute.getValue());
panel.add(label);
}
return panel;
}
}
| 3,590 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractRepositoryProductPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/AbstractRepositoryProductPanel.java | package org.esa.snap.product.library.ui.v2.repository;
import org.apache.commons.lang3.StringUtils;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.product.library.ui.v2.RepositoryProductPanelBackground;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductResults;
import org.esa.snap.remote.products.repository.Attribute;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.loading.SwingUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import javax.swing.AbstractButton;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
/**
* The base panel to show the data of a repository product.
*
* Created by jcoravu on 23/9/2019.
*/
public abstract class AbstractRepositoryProductPanel extends JPanel {
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm:ss");
private static final DecimalFormat FORMAT = new DecimalFormat("###.##");
private static ImageIcon[] ICONS;
private static ImageIcon[] ROLLOVER_ICONS;
private final JLabel nameLabel;
private final JLabel quickLookImageLabel;
private final JLabel firstAttributeLabel;
private final JLabel acquisitionDateLabel;
private final JLabel sizeLabel;
private final JLabel urlLabel;
private final JLabel secondAttributeLabel;
private final JLabel missionLabel;
private final AbstractButton expandOrCollapseButton;
private final ComponentDimension componentDimension;
private final RepositoryProductPanelBackground repositoryProductPanelBackground;
protected final JLabel statusLabel;
private RepositoryProductAttributesPanel attributesPanel;
protected AbstractRepositoryProductPanel(RepositoryProductPanelBackground repositoryProductPanelBackground,
ComponentDimension componentDimension) {
super(new BorderLayout(componentDimension.getGapBetweenColumns(), componentDimension.getGapBetweenRows()));
if (repositoryProductPanelBackground == null) {
throw new NullPointerException("The repository product panel background is null.");
}
if (ICONS == null) {
ICONS = new ImageIcon[] {
SwingUtils.loadImage(UIUtils.IMAGE_RESOURCE_PATH+"icons/PanelUp12.png"),
SwingUtils.loadImage(UIUtils.IMAGE_RESOURCE_PATH+"icons/PanelDown12.png")
};
ROLLOVER_ICONS = new ImageIcon[] {
ToolButtonFactory.createRolloverIcon(ICONS[0]),
ToolButtonFactory.createRolloverIcon(ICONS[1]),
};
}
this.repositoryProductPanelBackground = repositoryProductPanelBackground;
this.componentDimension = componentDimension;
this.nameLabel = new JLabel("");
this.quickLookImageLabel = new JLabel(OutputProductResults.EMPTY_ICON);
this.firstAttributeLabel = new JLabel("");
this.acquisitionDateLabel = new JLabel("");
this.sizeLabel = new JLabel("");
this.urlLabel = new JLabel("");
this.secondAttributeLabel = new JLabel("");
this.missionLabel = new JLabel("");
this.statusLabel = buildStatusLabel();
this.expandOrCollapseButton = ToolButtonFactory.createButton(ICONS[1], false);
this.expandOrCollapseButton.setFocusable(false);
this.expandOrCollapseButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
RepositoryProduct repositoryProduct = getRepositoryProduct();
if (attributesPanel == null) {
addAttributesPanel(repositoryProduct);
} else {
removeAttributesPanel();
}
}
});
int gapBetweenRows = componentDimension.getGapBetweenRows();
int gapBetweenColumns = componentDimension.getGapBetweenColumns();
Border outsideBorder = new MatteBorder(0, 0, 1, 0, UIManager.getColor("controlShadow"));
Border insideBorder = new EmptyBorder(gapBetweenRows, gapBetweenColumns, gapBetweenRows, gapBetweenColumns);
setBorder(new CompoundBorder(outsideBorder, insideBorder));
JPanel labelsPanel = buildLabelsPanel();
JPanel expandCollapsePanel = new JPanel(new GridBagLayout());
expandCollapsePanel.setOpaque(false);
GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.VERTICAL, GridBagConstraints.CENTER, 1, 1, 0, 0);
expandCollapsePanel.add(new JLabel(), c);
c = SwingUtils.buildConstraints(0, 1, GridBagConstraints.NONE, GridBagConstraints.SOUTH, 1, 1, 0, 0);
expandCollapsePanel.add(this.expandOrCollapseButton, c);
add(this.nameLabel, BorderLayout.NORTH);
add(this.quickLookImageLabel, BorderLayout.WEST);
add(labelsPanel, BorderLayout.CENTER);
add(expandCollapsePanel, BorderLayout.EAST);
}
@Override
public Color getBackground() {
if (this.repositoryProductPanelBackground != null) {
return this.repositoryProductPanelBackground.getProductPanelBackground(this);
}
return super.getBackground();
}
protected JLabel buildStatusLabel() {
return new JLabel("");
}
protected final Color getDefaultForegroundColor() {
return this.sizeLabel.getForeground();
}
public void refresh(OutputProductResults outputProductResults) {
RepositoryProduct repositoryProduct = getRepositoryProduct();
if (this.attributesPanel != null) {
if (this.attributesPanel.getRepositoryProduct() != repositoryProduct) {
removeAttributesPanel();
}
}
this.nameLabel.setText(repositoryProduct.getName());
this.urlLabel.setText(buildUrlLabelText(repositoryProduct.getURL()));
// if the product was downloaded and has a remote mission, display this remote mission
// otherwise, (it means it's an existing folder imported as local repository), use the metadata mission
String mission = (repositoryProduct.getRemoteMission() == null) ? repositoryProduct.getMetadataMission() : repositoryProduct.getRemoteMission().getName();
this.missionLabel.setText(buildMissionLabelText(mission));
this.acquisitionDateLabel.setText(buildAcquisitionDateLabelText(repositoryProduct.getAcquisitionDate()));
Map<String, String> visibleAttributes = this.repositoryProductPanelBackground.getRemoteMissionVisibleAttributes(mission);
updateVisibleAttributes(repositoryProduct, visibleAttributes);
ImageIcon imageIcon = outputProductResults.getProductQuickLookImage(repositoryProduct);
this.quickLookImageLabel.setIcon(imageIcon);
this.sizeLabel.setText(buildSizeLabelText(repositoryProduct.getApproximateSize()));
}
public final RepositoryProduct getRepositoryProduct() {
RepositoryProduct repositoryProduct = this.repositoryProductPanelBackground.getProductPanelItem(this);
if (repositoryProduct == null) {
throw new NullPointerException("The repository product is null.");
}
return repositoryProduct;
}
private JPanel buildColumnPanel(JLabel firstLabel, JLabel secondLabel, JLabel thirdLabel) {
int gapBetweenRows = this.componentDimension.getGapBetweenRows();
JPanel columnPanel = new JPanel();
columnPanel.setLayout(new BoxLayout(columnPanel, BoxLayout.Y_AXIS));
columnPanel.setOpaque(false);
columnPanel.add(firstLabel);
columnPanel.add(Box.createVerticalStrut(gapBetweenRows));
columnPanel.add(secondLabel);
columnPanel.add(Box.createVerticalStrut(gapBetweenRows));
columnPanel.add(thirdLabel);
return columnPanel;
}
private JPanel buildLabelsPanel() {
JPanel firstColumnPanel = buildColumnPanel(this.missionLabel, this.acquisitionDateLabel, this.sizeLabel);
JPanel secondColumnPanel = buildColumnPanel(this.firstAttributeLabel, new JLabel(" "), this.statusLabel);
JPanel thirdColumnPanel = buildColumnPanel(this.secondAttributeLabel, new JLabel(" "), new JLabel(" "));
int gapBetweenColumns = 7 * this.componentDimension.getGapBetweenColumns();
JPanel columnsPanel = new JPanel();
columnsPanel.setLayout(new BoxLayout(columnsPanel, BoxLayout.X_AXIS));
columnsPanel.setOpaque(false);
columnsPanel.add(firstColumnPanel);
columnsPanel.add(Box.createHorizontalStrut(gapBetweenColumns));
columnsPanel.add(secondColumnPanel);
columnsPanel.add(Box.createHorizontalStrut(gapBetweenColumns));
columnsPanel.add(thirdColumnPanel);
JPanel panel = new JPanel(new BorderLayout());
panel.setOpaque(false);
panel.add(this.urlLabel, BorderLayout.NORTH);
panel.add(columnsPanel, BorderLayout.WEST);
return panel;
}
private void addAttributesPanel(RepositoryProduct repositoryProduct) {
this.attributesPanel = new RepositoryProductAttributesPanel(this.componentDimension, repositoryProduct);
this.attributesPanel.setOpaque(false);
add(this.attributesPanel, BorderLayout.SOUTH);
refreshExpandOrCollapseButton(0);
}
private void removeAttributesPanel() {
remove(this.attributesPanel);
this.attributesPanel = null;
refreshExpandOrCollapseButton(1);
}
private void refreshExpandOrCollapseButton(int index) {
this.expandOrCollapseButton.setIcon(ICONS[index]);
this.expandOrCollapseButton.setRolloverIcon(ROLLOVER_ICONS[index]);
revalidate();
repaint();
}
private void updateVisibleAttributes(RepositoryProduct repositoryProduct, Map<String, String> visibleAttributes) {
String firstLabelText = " ";
String secondLabelText = " ";
List<Attribute> attributes = repositoryProduct.getRemoteAttributes();
if (visibleAttributes != null && visibleAttributes.size() > 0 && attributes != null && attributes.size() > 0) {
for (Map.Entry<String, String> entry : visibleAttributes.entrySet()) {
String attributeName = entry.getKey();
String attributeDisplayName = entry.getValue();
Attribute foundAttribute = null;
for (int i = 0; i < attributes.size() && foundAttribute == null; i++) {
Attribute attribute = attributes.get(i);
if (attributeName.equals(attribute.getName())) {
foundAttribute = attribute;
}
}
if (foundAttribute != null) {
if (firstLabelText.length() == 0) {
firstLabelText = buildAttributeLabelText(attributeDisplayName, foundAttribute.getValue());
} else if (secondLabelText.length() == 0) {
secondLabelText = buildAttributeLabelText(attributeDisplayName, foundAttribute.getValue());
break;
}
}
}
}
this.firstAttributeLabel.setText(firstLabelText);
this.secondAttributeLabel.setText(secondLabelText);
}
private static String buildUrlLabelText(String url){
return buildAttributeLabelText("URL", (url == null || StringUtils.isBlank(url) ? "N/A" : url));
}
private static String buildAttributeLabelText(String attributeDisplayName, String attributeValue) {
return attributeDisplayName + ": " + attributeValue;
}
public static String buildAcquisitionDateLabelText(LocalDateTime acquisitionDate) {
String dateAsString = "N/A";
if (acquisitionDate != null) {
dateAsString = DATE_FORMAT.format(acquisitionDate);
}
return buildAttributeLabelText("Acquisition date", dateAsString);
}
public static String buildMissionLabelText(String mission) {
return buildAttributeLabelText("Mission", (StringUtils.isBlank(mission) ? "N/A" : mission));
}
public static String buildRepositoryLabelText(String repository) {
return buildAttributeLabelText("Repository", (StringUtils.isBlank(repository) ? "N/A" : repository));
}
public static String buildSizeLabelText(long sizeInBytes) {
String sizeText = "Size: ";
if (sizeInBytes > 0) {
float oneKyloByte = 1024.0f;
double sizeInMegaBytes = sizeInBytes / (oneKyloByte * oneKyloByte);
if (sizeInMegaBytes > oneKyloByte) {
double sizeInGigaBytes = sizeInMegaBytes / oneKyloByte;
sizeText += FORMAT.format(sizeInGigaBytes) + " GB";
} else {
sizeText += FORMAT.format(sizeInMegaBytes) + " MB";
}
} else {
sizeText += "N/A";
}
return sizeText;
}
}
| 13,635 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PopupDownloadProductsListener.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/PopupDownloadProductsListener.java | package org.esa.snap.product.library.ui.v2.repository.remote;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadProductRunnable;
import org.esa.snap.remote.products.repository.RepositoryProduct;
/**
* The listener interface for receiving events about a downloading product.
*
* Created by jcoravu on 11/2/2020.
*/
public interface PopupDownloadProductsListener {
public void onUpdateProductDownloadProgress(RepositoryProduct repositoryProduct);
public void onStopDownloadingProduct(DownloadProductRunnable downloadProductRunnable);
}
| 577 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RemoteProductDownloader.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/RemoteProductDownloader.java | package org.esa.snap.product.library.ui.v2.repository.remote;
import org.apache.http.auth.Credentials;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.remote.products.repository.listener.ProgressListener;
import java.nio.file.Path;
/**
* The class stores the data about a product to be downloaded from a remote repository.
*
* Created by jcoravu on 13/9/2019.
*/
public class RemoteProductDownloader {
private final RemoteProductsRepositoryProvider remoteProductsRepositoryProvider;
private final Path localRepositoryFolderPath;
private final RepositoryProduct productToDownload;
private final Credentials credentials;
public RemoteProductDownloader(RemoteProductsRepositoryProvider remoteProductsRepositoryProvider, RepositoryProduct productToDownload,
Path localRepositoryFolderPath, Credentials credentials) {
this.remoteProductsRepositoryProvider = remoteProductsRepositoryProvider;
this.productToDownload = productToDownload;
this.localRepositoryFolderPath = localRepositoryFolderPath;
this.credentials = credentials;
}
public Path download(ProgressListener progressListener, boolean uncompressedDownloadedProduct) throws Exception {
return this.remoteProductsRepositoryProvider.downloadProduct(this.productToDownload, this.credentials, this.localRepositoryFolderPath,
progressListener, uncompressedDownloadedProduct);
}
public void cancel() {
this.remoteProductsRepositoryProvider.cancelDownloadProduct(this.productToDownload);
}
public Path getLocalRepositoryFolderPath() {
return localRepositoryFolderPath;
}
public RepositoryProduct getProductToDownload() {
return productToDownload;
}
public String getRepositoryName() {
return this.remoteProductsRepositoryProvider.getRepositoryName();
}
public Credentials getCredentials() {
return this.credentials;
}
}
| 2,157 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RemoteRepositoryProductPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/RemoteRepositoryProductPanel.java | package org.esa.snap.product.library.ui.v2.repository.remote;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.product.library.ui.v2.RepositoryProductPanelBackground;
import org.esa.snap.product.library.ui.v2.repository.AbstractRepositoryProductPanel;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductResults;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadingProductProgressCallback;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import javax.swing.*;
/**
* The panel to show the data of a remote repository product.
*
* Created by jcoravu on 27/9/2019.
*/
public class RemoteRepositoryProductPanel extends AbstractRepositoryProductPanel {
private final DownloadingProductProgressCallback downloadingProductProgressCallback;
public RemoteRepositoryProductPanel(RepositoryProductPanelBackground repositoryProductPanelBackground, DownloadingProductProgressCallback downloadingProductProgressCallback,
ComponentDimension componentDimension) {
super(repositoryProductPanelBackground, componentDimension);
if (downloadingProductProgressCallback == null) {
throw new NullPointerException("The downloading product callback is null.");
}
this.downloadingProductProgressCallback = downloadingProductProgressCallback;
}
@Override
protected JLabel buildStatusLabel() {
return new RemoteProductStatusLabel();
}
@Override
public void refresh(OutputProductResults outputProductResults) {
super.refresh(outputProductResults);
RepositoryProduct repositoryProduct = getRepositoryProduct();
DownloadProgressStatus downloadProgressStatus = this.downloadingProductProgressCallback.getDownloadingProductsProgressValue(repositoryProduct);
if (downloadProgressStatus == null) {
downloadProgressStatus = outputProductResults.getDownloadedProductProgress(repositoryProduct);
}
((RemoteProductStatusLabel)this.statusLabel).updateDownloadingPercent(downloadProgressStatus, getDefaultForegroundColor());
}
}
| 2,191 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DownloadProgressStatus.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/DownloadProgressStatus.java | package org.esa.snap.product.library.ui.v2.repository.remote;
import java.nio.file.Path;
/**
* The class stores the status of a downloading product.
*
* Created by jcoravu on 13/9/2019.
*/
public class DownloadProgressStatus {
private static final byte PENDING_DOWNLOAD = 1;
private static final byte DOWNLOADING = 2;
public static final byte CANCEL_DOWNLOADING = 3;
private static final byte DOWNLOADED = 4;
public static final byte FAILED_DOWNLOADING = 5;
public static final byte NOT_AVAILABLE = 6;
public static final byte PENDING_OPEN = 7;
public static final byte OPENING = 8;
public static final byte OPENED = 9;
public static final byte FAIL_OPENED = 10;
public static final byte FAIL_OPENED_MISSING_PRODUCT_READER = 11;
public static final byte SAVED = 12;
public static final byte QUEUED = 13;
public static final byte FAILED_DOWNLOADING_UNAUTHORIZED = 14;
private short value;
private byte status;
private Path downloadedPath;
public DownloadProgressStatus() {
this.value = 0;
this.status = PENDING_DOWNLOAD;
}
public short getValue() {
return value;
}
public void setValue(short value) {
if (value >=0 && value <= 100) {
this.value = value;
this.status = (value == 100) ? DOWNLOADED : DOWNLOADING;
} else {
throw new IllegalArgumentException("The progress percent value " + value + " is out of bounds.");
}
}
public Path getDownloadedPath() {
return downloadedPath;
}
public void setDownloadedPath(Path downloadedPath) {
this.downloadedPath = downloadedPath;
}
public void setStatus(byte status) {
this.status = status;
}
public boolean isOpened() {
return (this.status == OPENED);
}
public boolean isOpening() {
return (this.status == OPENING);
}
public boolean isPendingOpen() {
return (this.status == PENDING_OPEN);
}
public boolean isPendingDownload() {
return (this.status == PENDING_DOWNLOAD);
}
public boolean isCancelDownloading() {
return (this.status == CANCEL_DOWNLOADING);
}
public boolean isDownloading() {
return (this.status == DOWNLOADING);
}
public boolean isDownloaded() {
return (this.status == DOWNLOADED);
}
public boolean isFailedDownload() {
return (this.status == FAILED_DOWNLOADING);
}
public boolean isFailedOpen() {
return (this.status == FAIL_OPENED);
}
public boolean isFailOpenedBecauseNoProductReader() {
return (this.status == FAIL_OPENED_MISSING_PRODUCT_READER);
}
public boolean isNotAvailable() {
return (this.status == NOT_AVAILABLE);
}
public boolean isSaved() {
return (this.status == SAVED);
}
public boolean canOpen() {
return (this.value == 100 && this.downloadedPath != null);
}
public boolean isQueued() {
return (this.status == QUEUED);
}
public boolean isFailedDownloadUnauthorized() {
return (this.status == FAILED_DOWNLOADING_UNAUTHORIZED);
}
}
| 3,198 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RemoteProductsRepositoryPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/RemoteProductsRepositoryPanel.java | package org.esa.snap.product.library.ui.v2.repository.remote;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.product.library.ui.v2.MissionParameterListener;
import org.esa.snap.product.library.ui.v2.ProductLibraryV2Action;
import org.esa.snap.product.library.ui.v2.repository.input.AbstractParameterComponent;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductListModel;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.repository.AbstractRepositoryProductPanel;
import org.esa.snap.product.library.ui.v2.RepositoryProductPanelBackground;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadingProductProgressCallback;
import org.esa.snap.product.library.ui.v2.thread.ThreadListener;
import org.esa.snap.product.library.ui.v2.repository.AbstractProductsRepositoryPanel;
import org.esa.snap.product.library.ui.v2.repository.input.ParametersPanel;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadProductListTimerRunnable;
import org.esa.snap.product.library.ui.v2.thread.AbstractProgressTimerRunnable;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.worldwind.productlibrary.WorldMapPanelWrapper;
import org.esa.snap.product.library.v2.preferences.RepositoriesCredentialsController;
import org.esa.snap.remote.products.repository.RepositoryQueryParameter;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.loading.CustomComboBox;
import org.esa.snap.ui.loading.ItemRenderer;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.geom.Rectangle2D;
import java.time.LocalDateTime;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
/**
* The panel containing the query parameters of a remote repository.
*
* Created by jcoravu on 5/8/2019.
*/
public class RemoteProductsRepositoryPanel extends AbstractProductsRepositoryPanel {
private final MissionParameterListener missionParameterListener;
private final JComboBox<String> missionsComboBox;
private final RemoteProductsRepositoryProvider productsRepositoryProvider;
private final JComboBox<Credentials> userAccountsComboBox;
private ItemListener missionItemListener;
private RemoteInputParameterValues remoteInputParameterValues;
private DownloadingProductProgressCallback downloadingProductProgressCallback;
public RemoteProductsRepositoryPanel(RemoteProductsRepositoryProvider productsRepositoryProvider, ComponentDimension componentDimension,
MissionParameterListener missionParameterListener, WorldMapPanelWrapper worlWindPanel) {
super(worlWindPanel, componentDimension, new BorderLayout(0, componentDimension.getGapBetweenRows()));
if (productsRepositoryProvider == null) {
throw new NullPointerException("The remote products repository provider is null.");
}
this.productsRepositoryProvider = productsRepositoryProvider;
this.missionParameterListener = missionParameterListener;
if (this.productsRepositoryProvider.requiresAuthentication()) {
ItemRenderer<Credentials> accountsItemRenderer = new ItemRenderer<Credentials>() {
@Override
public String getItemDisplayText(Credentials item) {
return (item == null) ? " " : item.getUserPrincipal().getName();
}
};
this.userAccountsComboBox = new CustomComboBox(accountsItemRenderer, componentDimension.getTextFieldPreferredHeight(), false, componentDimension.getTextFieldBackgroundColor());
} else {
this.userAccountsComboBox = null;
}
String[] availableMissions = this.productsRepositoryProvider.getAvailableMissions();
if (availableMissions.length > 0) {
String valueToSelect = availableMissions[0];
this.missionsComboBox = SwingUtils.buildComboBox(availableMissions, valueToSelect, this.componentDimension.getTextFieldPreferredHeight(), false);
this.missionsComboBox.setBackground(this.componentDimension.getTextFieldBackgroundColor());
this.missionItemListener = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent itemEvent) {
if (itemEvent.getStateChange() == ItemEvent.SELECTED) {
newSelectedMission();
}
}
};
this.missionsComboBox.addItemListener(this.missionItemListener);
} else {
throw new IllegalStateException("At least one supported mission must be defined for '"+ getRepositoryName()+"' remote repository.");
}
this.parameterComponents = Collections.emptyList();
}
@Override
public String getRepositoryName() {
return this.productsRepositoryProvider.getRepositoryName();
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (this.userAccountsComboBox != null) {
this.userAccountsComboBox.setEnabled(enabled);
}
this.missionsComboBox.setEnabled(enabled);
for (int i=0; i<this.parameterComponents.size(); i++) {
JComponent component = this.parameterComponents.get(i).getComponent();
component.setEnabled(enabled);
}
}
@Override
public void resetInputParameterValues() {
this.remoteInputParameterValues = null;
}
@Override
public AbstractProgressTimerRunnable<?> buildSearchProductListThread(ProgressBarHelper progressPanel, int threadId, ThreadListener threadListener,
RemoteRepositoriesSemaphore remoteRepositoriesSemaphore, RepositoryOutputProductListPanel productResultsPanel) {
Credentials selectedCredentials = null;
boolean canContinue = true;
if (this.userAccountsComboBox != null) {
// the repository provider requires authentication
selectedCredentials = (Credentials) this.userAccountsComboBox.getSelectedItem();
if (selectedCredentials == null) {
// no credential account is selected
if (this.userAccountsComboBox.getModel().getSize() > 0) {
String message = "Select the account used to search the product list on the remote repository.";
showErrorMessageDialog(message, "Required credentials");
this.userAccountsComboBox.requestFocus();
} else {
StringBuilder message = new StringBuilder();
message.append("There is no account defined in the application.")
.append("\n\n")
.append("To add an account for the remote repository go to the 'Tools -> Options' menu and select the 'Product Library' tab.");
showInformationMessageDialog(message.toString(), "Add credentials");
}
canContinue = false;
}
}
if (canContinue) {
Map<String, Object> parameterValues = getParameterValues();
if (parameterValues != null) {
String selectedMission = getSelectedMission(); // the selected mission can not be null
if (selectedMission == null) {
throw new NullPointerException("The remote mission is null");
}
this.remoteInputParameterValues = new RemoteInputParameterValues(parameterValues, selectedMission);
return new DownloadProductListTimerRunnable(progressPanel, threadId, selectedCredentials, this.productsRepositoryProvider, threadListener, productResultsPanel, getRepositoryName(), selectedMission, parameterValues);
}
}
return null;
}
@Override
public AbstractRepositoryProductPanel buildProductProductPanel(RepositoryProductPanelBackground repositoryProductPanelBackground,
ComponentDimension componentDimension) {
return new RemoteRepositoryProductPanel(repositoryProductPanelBackground, this.downloadingProductProgressCallback, componentDimension);
}
@Override
protected ParametersPanel getInputParameterComponentsPanel() {
ParametersPanel panel = new ParametersPanel();
int gapBetweenColumns = this.componentDimension.getGapBetweenColumns();
int rowIndex = 0;
int gapBetweenRows = 0;
if (this.userAccountsComboBox != null) {
GridBagConstraints c = SwingUtils.buildConstraints(0, rowIndex, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0);
panel.add(new JLabel("Account"), c);
c = SwingUtils.buildConstraints(1, rowIndex, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns);
panel.add(this.userAccountsComboBox, c);
rowIndex++;
gapBetweenRows = this.componentDimension.getGapBetweenRows(); // the gap between rows for next lines
}
GridBagConstraints c = SwingUtils.buildConstraints(0, rowIndex, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0);
panel.add(new JLabel("Mission"), c);
c = SwingUtils.buildConstraints(1, rowIndex, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns);
panel.add(this.missionsComboBox, c);
rowIndex++;
gapBetweenRows = this.componentDimension.getGapBetweenRows(); // the gap between rows for next lines
Class<?> areaOfInterestClass = Rectangle2D.class;
Class<?>[] classesToIgnore = new Class<?>[] {areaOfInterestClass};
String selectedMission = getSelectedMission();
List<RepositoryQueryParameter> parameters = this.productsRepositoryProvider.getMissionParameters(selectedMission);
Credentials savedCredentials = RepositoriesCredentialsController.getInstance().getRepositoryCollectionCredential(this.productsRepositoryProvider.getRepositoryName(), selectedMission);
// filter the UI displayed parameters (those having a proper label)
List<RepositoryQueryParameter> parametersForUI = parameters.stream().filter(p -> StringUtils.isNotNullAndNotEmpty(p.getLabel())).collect(Collectors.toList());
this.parameterComponents = panel.addParameterComponents(parametersForUI, rowIndex, gapBetweenRows, this.componentDimension, classesToIgnore);
if (savedCredentials != null) {
for (AbstractParameterComponent<?> parameterComponent : this.parameterComponents) {
if (parameterComponent.getParameterName().contentEquals("username")) {
parameterComponent.setParameterValue(savedCredentials.getUserPrincipal().getName());
}
if (parameterComponent.getParameterName().contentEquals("password")) {
parameterComponent.setParameterValue(savedCredentials.getPassword());
}
}
}
return panel;
}
@Override
protected RepositoryQueryParameter getAreaOfInterestParameter(){
Class<?> areaOfInterestClass = Rectangle2D.class;
String selectedMission = getSelectedMission();
List<RepositoryQueryParameter> parameters = this.productsRepositoryProvider.getMissionParameters(selectedMission);
RepositoryQueryParameter areaOfInterestParameter = null;
for (int i=0; i<parameters.size(); i++) {
RepositoryQueryParameter param = parameters.get(i);
if (param.getType() == areaOfInterestClass) {
areaOfInterestParameter = param;
}
}
return areaOfInterestParameter;
}
@Override
public boolean refreshInputParameterComponentValues() {
if (this.remoteInputParameterValues != null) {
this.missionsComboBox.removeItemListener(this.missionItemListener);
try {
this.missionsComboBox.setSelectedItem(this.remoteInputParameterValues.getMissionName());
} finally {
this.missionsComboBox.addItemListener(this.missionItemListener);
}
for (int i=0; i<this.parameterComponents.size(); i++) {
AbstractParameterComponent<?> inputParameterComponent = this.parameterComponents.get(i);
Object parameterValue = this.remoteInputParameterValues.getParameterValue(inputParameterComponent.getParameterName());
inputParameterComponent.setParameterValue(parameterValue);
}
return true;
}
return false;
}
public void updateInputParameterValues(String missionName, LocalDateTime startDate, LocalDateTime endDate, Rectangle2D.Double areaOfInterestToSelect) {
this.missionsComboBox.setSelectedItem(missionName);
for (AbstractParameterComponent<?> inputParameterComponent : this.parameterComponents) {
switch (inputParameterComponent.getParameterName()) {
case RepositoryQueryParameter.FOOTPRINT:
inputParameterComponent.setParameterValue(areaOfInterestToSelect);
break;
case RepositoryQueryParameter.START_DATE:
inputParameterComponent.setParameterValue(startDate);
break;
case RepositoryQueryParameter.END_DATE:
inputParameterComponent.setParameterValue(endDate);
break;
}
}
}
public void addDownloadedProductProgress(RepositoryProduct repositoryProduct, DownloadProgressStatus downloadProgressStatus) {
getOutputProductResults().addDownloadedProductProgress(repositoryProduct, downloadProgressStatus);
}
public void setDownloadingProductProgressCallback(DownloadingProductProgressCallback downloadingProductProgressCallback) {
this.downloadingProductProgressCallback = downloadingProductProgressCallback;
}
private Credentials getSearchCredentials() {
String username = null;
String password = null;
for (AbstractParameterComponent<?> parameterComponent : this.parameterComponents) {
if (parameterComponent.getParameterName().contentEquals("username")) {
username = (String) parameterComponent.getParameterValue();
}
if (parameterComponent.getParameterName().contentEquals("password")) {
password = (String) parameterComponent.getParameterValue();
}
}
if (StringUtils.isNotNullAndNotEmpty(username) && StringUtils.isNotNullAndNotEmpty(password)) {
return new UsernamePasswordCredentials(username, password);
}
return null;
}
public Credentials getSelectedAccount() {
Credentials selectedCredentials = getSearchCredentials();
if (selectedCredentials != null) {
return selectedCredentials;
}
if (this.userAccountsComboBox != null) {
// the repository provider requires authentication
selectedCredentials = (Credentials) this.userAccountsComboBox.getSelectedItem();
if (selectedCredentials == null) {
// no credential account is selected
throw new NullPointerException("No credential account is selected.");
}
}
return selectedCredentials;
}
public RemoteProductsRepositoryProvider getProductsRepositoryProvider() {
return this.productsRepositoryProvider;
}
public void setUserAccounts(List<Credentials> repositoryCredentials) {
if (this.userAccountsComboBox != null && repositoryCredentials.size() > 0) {
this.userAccountsComboBox.removeAllItems();
for (int i = 0; i < repositoryCredentials.size(); i++) {
this.userAccountsComboBox.addItem(repositoryCredentials.get(i));
}
}
}
private String getSelectedMission() {
return (String) this.missionsComboBox.getSelectedItem();
}
private void newSelectedMission() {
this.missionParameterListener.newSelectedMission(getSelectedMission(), RemoteProductsRepositoryPanel.this);
}
}
| 16,881 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RemoteRepositoriesSemaphore.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/RemoteRepositoriesSemaphore.java | package org.esa.snap.product.library.ui.v2.repository.remote;
import org.apache.http.auth.Credentials;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;
/**
* A counting semaphore which allows a fixed number of connections to query a certain remote repository in the same time.
*
* Created by jcoravu on 16/10/2019.
*/
public class RemoteRepositoriesSemaphore {
private final RemoteProductsRepositoryProvider[] remoteRepositoryProductProviders;
private final Map<String, Semaphore> map;
public RemoteRepositoriesSemaphore(RemoteProductsRepositoryProvider[] remoteRepositoryProductProviders) {
this.remoteRepositoryProductProviders = remoteRepositoryProductProviders;
this.map = new HashMap<>();
}
public void acquirePermission(String remoteRepositoryName, Credentials credentials) throws InterruptedException {
Semaphore semaphore = getSemaphore(remoteRepositoryName, credentials);
if (semaphore != null) {
semaphore.acquire(1);
}
}
public void releasePermission(String remoteRepositoryName, Credentials credentials) throws InterruptedException {
Semaphore semaphore = getSemaphore(remoteRepositoryName, credentials);
if (semaphore != null) {
semaphore.release(1);
}
}
private Semaphore getSemaphore(String remoteRepositoryName, Credentials credentials) {
Semaphore semaphore;
synchronized (this.map) {
String key = buildLKey(remoteRepositoryName, credentials);
semaphore = this.map.get(key);
if (semaphore == null) {
RemoteProductsRepositoryProvider remoteRepositoryProvider = null;
for (int i=0; i<this.remoteRepositoryProductProviders.length && remoteRepositoryProvider == null; i++) {
if (this.remoteRepositoryProductProviders[i].getRepositoryName().equals(remoteRepositoryName)) {
remoteRepositoryProvider = this.remoteRepositoryProductProviders[i];
}
}
if (remoteRepositoryProvider == null) {
throw new NullPointerException("The remote repository provider with id '" + remoteRepositoryName + "' does not exist.");
}
if (remoteRepositoryProvider.getMaximumAllowedTransfersPerAccount() > 0) {
semaphore = new Semaphore(remoteRepositoryProvider.getMaximumAllowedTransfersPerAccount());
this.map.put(key, semaphore);
}
}
}
return semaphore; // the result may be null
}
private static String buildLKey(String remoteRepositoryId, Credentials credentials) {
return remoteRepositoryId + "|" + credentials.getUserPrincipal().getName();
}
}
| 2,928 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RemoteInputParameterValues.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/RemoteInputParameterValues.java | package org.esa.snap.product.library.ui.v2.repository.remote;
import java.util.Map;
/**
* The parameters data for a remote repository.
*
* Created by jcoravu on 6/2/2020.
*/
public class RemoteInputParameterValues {
private final Map<String, Object> parameterValues;
private final String missionName;
public RemoteInputParameterValues(Map<String, Object> parameterValues, String missionName) {
this.parameterValues = parameterValues;
this.missionName = missionName;
}
public String getMissionName() {
return missionName;
}
public Object getParameterValue(String parameterName) {
return this.parameterValues.get(parameterName);
}
}
| 705 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OpenDownloadedProductsRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/OpenDownloadedProductsRunnable.java | package org.esa.snap.product.library.ui.v2.repository.remote;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.dataio.ProductReader;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.product.library.ui.v2.repository.local.LocalProgressStatus;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductListModel;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.thread.AbstractRunnable;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.AppContext;
import javax.swing.SwingUtilities;
import java.io.File;
import java.nio.file.Path;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread class to open in the application a downloaded product.
*
* Created by jcoravu on 12/11/2019.
*/
public class OpenDownloadedProductsRunnable extends AbstractRunnable<Void> {
private static final Logger logger = Logger.getLogger(OpenDownloadedProductsRunnable.class.getName());
private final AppContext appContext;
private final Map<RepositoryProduct, Path> productsToOpen;
private final RepositoryOutputProductListPanel repositoryProductListPanel;
public OpenDownloadedProductsRunnable(AppContext appContext, RepositoryOutputProductListPanel repositoryProductListPanel, Map<RepositoryProduct, Path> productsToOpen) {
this.appContext = appContext;
this.repositoryProductListPanel = repositoryProductListPanel;
this.productsToOpen = productsToOpen;
}
@Override
protected Void execute() throws Exception {
for (Map.Entry<RepositoryProduct, Path> entry : this.productsToOpen.entrySet()) {
RepositoryProduct repositoryProduct = entry.getKey();
try {
updateProductProgressStatusLater(repositoryProduct, DownloadProgressStatus.OPENING);
//TODO Jean temporary method until the Landsat8 product reader will be changed to read the product from a folder
Path productPath = RemoteProductsRepositoryProvider.prepareProductPathToOpen(entry.getValue(), repositoryProduct);
File productFile = productPath.toFile();
//TODO Jean old code to get the product path to open
//File productFile = entry.getValue().toFile();
ProductReader productReader = ProductIO.getProductReaderForInput(productFile);
if (productReader == null) {
// no product reader found in the application
updateProductProgressStatusLater(repositoryProduct, DownloadProgressStatus.FAIL_OPENED_MISSING_PRODUCT_READER);
} else {
// there is a product reader in the application
Product product = productReader.readProductNodes(productFile, null);
if (product == null) {
throw new NullPointerException("The product '" + repositoryProduct.getName()+"' has not been read from '" + productFile.getAbsolutePath()+"'.");
} else {
this.appContext.getProductManager().addProduct(product);
updateProductProgressStatusLater(repositoryProduct, DownloadProgressStatus.OPENED);
}
}
} catch (Exception exception) {
updateProductProgressStatusLater(repositoryProduct, DownloadProgressStatus.FAIL_OPENED);
logger.log(Level.SEVERE, "Failed to open the downloaded product '" + repositoryProduct.getURL() + "'.", exception);
}
}
return null;
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to open the downloaded products.";
}
private void updateProductProgressStatusLater(RepositoryProduct repositoryProduct, byte openStatus) {
UpdateProgressStatusRunnable runnable = new UpdateProgressStatusRunnable(repositoryProduct, openStatus, this.repositoryProductListPanel);
SwingUtilities.invokeLater(runnable);
}
private static class UpdateProgressStatusRunnable implements Runnable {
private final RepositoryProduct productToOpen;
private final byte openStatus;
private final RepositoryOutputProductListPanel repositoryProductListPanel;
private UpdateProgressStatusRunnable(RepositoryProduct productToOpen, byte openStatus, RepositoryOutputProductListPanel repositoryProductListPanel) {
this.productToOpen = productToOpen;
this.openStatus = openStatus;
this.repositoryProductListPanel = repositoryProductListPanel;
}
@Override
public void run() {
OutputProductListModel productListModel = this.repositoryProductListPanel.getProductListPanel().getProductListModel();
productListModel.setOpenDownloadedProductStatus(this.productToOpen, this.openStatus);
}
}
}
| 5,127 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RemoteProductStatusLabel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/RemoteProductStatusLabel.java | package org.esa.snap.product.library.ui.v2.repository.remote;
import javax.swing.*;
import java.awt.*;
/**
* The status label for a repository product displayed in the output panel.
*
* Created by jcoravu on 11/2/2020.
*/
public class RemoteProductStatusLabel extends JLabel {
public RemoteProductStatusLabel() {
super("");
}
public void updateDownloadingPercent(DownloadProgressStatus downloadProgressStatus, Color defaultForegroundColor) {
Color foregroundColor = defaultForegroundColor;
String percentText = " "; // set an empty space for the default text
if (downloadProgressStatus != null) {
// the product is pending download or downloading
if (downloadProgressStatus.isDownloading()) {
percentText = "Downloading: " + Integer.toString(downloadProgressStatus.getValue()) + "%";
} else if (downloadProgressStatus.isPendingDownload()) {
percentText = "Pending download";
} else if (downloadProgressStatus.isCancelDownloading()) {
percentText = "Downloading: " + Integer.toString(downloadProgressStatus.getValue()) + "% (stopped)";
} else if (downloadProgressStatus.isDownloaded()) {
percentText = "Downloaded";
foregroundColor = Color.GREEN;
} else if (downloadProgressStatus.isSaved()) {
percentText = "Downloaded";
foregroundColor = Color.GREEN;
} else if (downloadProgressStatus.isNotAvailable()) {
percentText = "Not available to download";
foregroundColor = Color.RED;
} else if (downloadProgressStatus.isFailedDownload()) {
percentText = "Downloading: " + Integer.toString(downloadProgressStatus.getValue()) + "% (failed)";
foregroundColor = Color.RED;
} else if (downloadProgressStatus.isFailedDownloadUnauthorized()) {
percentText = "Downloading: " + Integer.toString(downloadProgressStatus.getValue()) + "% (unauthorized)";
foregroundColor = Color.RED;
} else if (downloadProgressStatus.isFailedOpen()) {
percentText = "Downloaded (failed open)";
foregroundColor = Color.GREEN;
} else if (downloadProgressStatus.isFailOpenedBecauseNoProductReader()) {
percentText = "Downloaded (failed open because no product reader found)";
foregroundColor = Color.GREEN;
} else if (downloadProgressStatus.isPendingOpen()) {
percentText = "Downloaded (pending open)";
foregroundColor = Color.GREEN;
} else if (downloadProgressStatus.isOpening()) {
percentText = "Downloaded (opening)";
foregroundColor = Color.GREEN;
} else if (downloadProgressStatus.isOpened()) {
percentText = "Downloaded (opened)";
foregroundColor = Color.GREEN;
} else if (downloadProgressStatus.isQueued()) {
percentText = "Download queued";
foregroundColor = Color.ORANGE;
}else {
throw new IllegalStateException("The percent progress status is unknown. The value is " + downloadProgressStatus.getValue()+".");
}
}
setForeground(foregroundColor);
setText(percentText);
}
}
| 3,444 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DownloadProductsQuickLookImageRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/download/DownloadProductsQuickLookImageRunnable.java | package org.esa.snap.product.library.ui.v2.repository.remote.download;
import org.apache.http.auth.Credentials;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductListModel;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.repository.remote.RemoteRepositoriesSemaphore;
import org.esa.snap.remote.products.repository.HTTPServerException;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.loading.PairRunnable;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread class to download the quick look images of the products from the search list.
*
* Created by jcoravu on 29/1/2020.
*/
public class DownloadProductsQuickLookImageRunnable extends AbstractBackgroundDownloadRunnable {
private static final Logger logger = Logger.getLogger(DownloadProductsQuickLookImageRunnable.class.getName());
private final RemoteProductsRepositoryProvider productsRepositoryProvider;
private final Credentials credentials;
private final RemoteRepositoriesSemaphore remoteRepositoriesSemaphore;
private final RepositoryOutputProductListPanel repositoryProductListPanel;
private final List<RepositoryProduct> productsWithoutQuickLookImage;
public DownloadProductsQuickLookImageRunnable(List<RepositoryProduct> productsWithoutQuickLookImage, RemoteProductsRepositoryProvider productsRepositoryProvider,
Credentials credentials, RemoteRepositoriesSemaphore remoteRepositoriesSemaphore,
RepositoryOutputProductListPanel repositoryProductListPanel) {
this.productsWithoutQuickLookImage = productsWithoutQuickLookImage;
this.productsRepositoryProvider = productsRepositoryProvider;
this.credentials = credentials;
this.remoteRepositoriesSemaphore = remoteRepositoriesSemaphore;
this.repositoryProductListPanel = repositoryProductListPanel;
}
@Override
public void run() {
try {
startRunning();
if (isFinished()) {
return; // nothing to return
}
this.remoteRepositoriesSemaphore.acquirePermission(this.productsRepositoryProvider.getRepositoryName(), this.credentials);
try {
if (isFinished()) {
return; // nothing to return
}
int maximumInternalServerErrorCount = 3;
int internalServerErrorCount = 0;
for (int i = 0; i < this.productsWithoutQuickLookImage.size() && internalServerErrorCount < maximumInternalServerErrorCount; i++) {
if (isFinished()) {
return; // nothing to return
}
RepositoryProduct repositoryProduct = this.productsWithoutQuickLookImage.get(i);
BufferedImage quickLookImage = null;
if (repositoryProduct.getDownloadQuickLookImageURL() != null) {
try {
quickLookImage = this.productsRepositoryProvider.downloadProductQuickLookImage(this.credentials, repositoryProduct.getDownloadQuickLookImageURL(), this);
} catch (java.lang.InterruptedException exception) {
logger.log(Level.WARNING, "Stop downloading the product quick look image from url '" + repositoryProduct.getDownloadQuickLookImageURL() + "'.");
return; // nothing to return
} catch (HTTPServerException exception) {
logger.log(Level.SEVERE, "Failed to download the product quick look image from url '" + repositoryProduct.getDownloadQuickLookImageURL() + "'.", exception);
if (exception.getStatusCodeResponse() >= HttpURLConnection.HTTP_INTERNAL_ERROR) {
internalServerErrorCount++;
}
} catch (java.lang.Exception exception) {
logger.log(Level.SEVERE, "Failed to download the product quick look image from url '" + repositoryProduct.getDownloadQuickLookImageURL() + "'.", exception);
}
}
setProductQuickLookImageLater(repositoryProduct, quickLookImage);
}
} finally {
this.remoteRepositoriesSemaphore.releasePermission(this.productsRepositoryProvider.getRepositoryName(), this.credentials);
}
} catch (Exception exception) {
logger.log(Level.SEVERE, "Failed to download the product quick look images.", exception);
} finally {
finishRunning();
}
}
protected void finishRunning() {
setRunning(false);
}
private void setProductQuickLookImageLater(RepositoryProduct product, BufferedImage quickLookImage) {
Runnable runnable = new PairRunnable<RepositoryProduct, BufferedImage>(product, quickLookImage) {
@Override
protected void execute(RepositoryProduct repositoryProduct, BufferedImage bufferedImage) {
onSetProductQuickLookImage(repositoryProduct, bufferedImage);
}
};
SwingUtilities.invokeLater(runnable);
}
private void onSetProductQuickLookImage(RepositoryProduct repositoryProduct, BufferedImage quickLookImage) {
repositoryProduct.setQuickLookImage(quickLookImage);
OutputProductListModel productListModel = this.repositoryProductListPanel.getProductListPanel().getProductListModel();
productListModel.refreshProduct(repositoryProduct);
}
}
| 6,008 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DownloadRemoteProductsHelper.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/download/DownloadRemoteProductsHelper.java | package org.esa.snap.product.library.ui.v2.repository.remote.download;
import org.apache.http.auth.Credentials;
import org.esa.snap.engine_utilities.util.Pair;
import org.esa.snap.engine_utilities.util.ThreadNamePoolExecutor;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.repository.remote.DownloadProgressStatus;
import org.esa.snap.product.library.ui.v2.repository.remote.RemoteProductDownloader;
import org.esa.snap.product.library.ui.v2.repository.remote.RemoteRepositoriesSemaphore;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelperImpl;
import org.esa.snap.product.library.v2.database.AllLocalFolderProductsRepository;
import org.esa.snap.product.library.v2.database.SaveProductData;
import org.esa.snap.product.library.v2.preferences.RepositoriesCredentialsPersistence;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.loading.GenericRunnable;
import org.esa.snap.ui.loading.PairRunnable;
import javax.swing.*;
import java.nio.file.Path;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The helper class to manage the downloading remote products.
*
* Created by jcoravu on 17/10/2019.
*/
public class DownloadRemoteProductsHelper implements DownloadingProductProgressCallback {
private static final Logger logger = Logger.getLogger(DownloadRemoteProductsHelper.class.getName());
private final ProgressBarHelperImpl progressPanel;
private final RemoteRepositoriesSemaphore remoteRepositoriesSemaphore;
private final DownloadProductListener downloadProductListener;
private ThreadNamePoolExecutor threadPoolExecutor;
private Map<AbstractBackgroundDownloadRunnable, Pair<DownloadProgressStatus, Boolean>> runningTasks;
private int threadId;
private boolean uncompressedDownloadedProducts;
public DownloadRemoteProductsHelper(ProgressBarHelperImpl progressPanel, RemoteRepositoriesSemaphore remoteRepositoriesSemaphore,
DownloadProductListener downloadProductListener) {
this.progressPanel = progressPanel;
this.remoteRepositoriesSemaphore = remoteRepositoriesSemaphore;
this.downloadProductListener = downloadProductListener;
this.uncompressedDownloadedProducts = RepositoriesCredentialsPersistence.UNCOMPRESSED_DOWNLOADED_PRODUCTS;
}
@Override
public DownloadProgressStatus getDownloadingProductsProgressValue(RepositoryProduct repositoryProduct) {
if (repositoryProduct == null) {
throw new NullPointerException("The repository product is null.");
}
if (this.runningTasks != null && this.runningTasks.size() > 0) {
for (Map.Entry<AbstractBackgroundDownloadRunnable, Pair<DownloadProgressStatus, Boolean>> entry : this.runningTasks.entrySet()) {
AbstractBackgroundDownloadRunnable runnable = entry.getKey();
if (runnable instanceof DownloadProductRunnable) {
DownloadProductRunnable downloadProductRunnable = (DownloadProductRunnable)runnable;
if (downloadProductRunnable.getProductToDownload() == repositoryProduct) {
Pair<DownloadProgressStatus, Boolean> value = entry.getValue();
if (value == null) {
throw new NullPointerException("The value is null.");
}
return value.getFirst();
}
}
}
}
return null;
}
public void setUncompressedDownloadedProducts(boolean uncompressedDownloadedProducts) {
this.uncompressedDownloadedProducts = uncompressedDownloadedProducts;
}
public RemoteRepositoriesSemaphore getRemoteRepositoriesSemaphore() {
return remoteRepositoriesSemaphore;
}
public void downloadProductsQuickLookImageAsync(List<RepositoryProduct> productsWithoutQuickLookImage, RemoteProductsRepositoryProvider productsRepositoryProvider,
Credentials credentials, RepositoryOutputProductListPanel repositoryProductListPanel) {
createThreadPoolExecutorIfNeeded();
DownloadProductsQuickLookImageRunnable runnable = new DownloadProductsQuickLookImageRunnable(productsWithoutQuickLookImage, productsRepositoryProvider,
credentials, this.remoteRepositoriesSemaphore, repositoryProductListPanel) {
@Override
protected void finishRunning() {
super.finishRunning();
finishRunningDownloadProductsQuickLookImageThreadLater(this);
}
};
this.runningTasks.put(runnable, null);
this.threadPoolExecutor.execute(runnable); // start the thread
}
public void downloadProductsAsync(RepositoryProduct[] productsToDownload, RemoteProductsRepositoryProvider remoteProductsRepositoryProvider,
Path localRepositoryFolderPath, Credentials credentials, AllLocalFolderProductsRepository allLocalFolderProductsRepository) {
createThreadPoolExecutorIfNeeded();
for (int i=0; i<productsToDownload.length; i++) {
DownloadProgressStatus downloadProgressStatus = getDownloadingProductsProgressValue(productsToDownload[i]);
if (downloadProgressStatus == null || downloadProgressStatus.isCancelDownloading()) {
downloadProgressStatus = new DownloadProgressStatus();
RemoteProductDownloader remoteProductDownloader = new RemoteProductDownloader(remoteProductsRepositoryProvider, productsToDownload[i], localRepositoryFolderPath, credentials);
DownloadProductRunnable runnable = new DownloadProductRunnable(remoteProductDownloader, this.remoteRepositoriesSemaphore, allLocalFolderProductsRepository, this.uncompressedDownloadedProducts) {
@Override
protected void startRunning() {
super.startRunning();
new AllLocalFolderProductsRepository().saveLocalRepositoryFolder(localRepositoryFolderPath);
startRunningDownloadProductThreadLater(this);
}
@Override
public void cancelRunning() {
super.cancelRunning();
cancelRunningDownloadProductThreadLater(this);
}
@Override
public void notifyApproximateSize(long approximateSize) {
updateApproximateSizeLater(this, approximateSize);
}
@Override
public void notifyProductStatus(String productStatusName) {
if(productStatusName.toLowerCase().contentEquals("queued")){
notifyProductStatusLater(this, DownloadProgressStatus.QUEUED);
}
}
@Override
protected void updateDownloadingProgressPercent(short progressPercent, Path downloadedPath) {
updateDownloadingProgressPercentLater(this, progressPercent, downloadedPath);
}
@Override
protected void finishRunning(SaveProductData saveProductData, byte downloadStatus, Path productPath) {
super.finishRunning(saveProductData, downloadStatus, productPath);
finishRunningDownloadProductThreadLater(this, saveProductData, downloadStatus, productPath);
}
};
this.runningTasks.put(runnable, new Pair(downloadProgressStatus, true));
this.threadPoolExecutor.execute(runnable); // start the thread
}
}
updateProgressBarDownloadedProducts();
}
public boolean isRunning() {
return (this.threadPoolExecutor != null);
}
public void cancelDownloadingProducts() {
if (this.runningTasks != null) {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "Stop downloading the products.");
}
for (AbstractBackgroundDownloadRunnable runnable : this.runningTasks.keySet()) {
if (runnable instanceof DownloadProductRunnable) {
runnable.cancelRunning();
}
}
updateProgressBarDownloadedProducts();
}
}
public void cancelDownloadingProductsQuickLookImage() {
if (this.runningTasks != null) {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "Stop downloading the products quick look image.");
}
for (AbstractBackgroundDownloadRunnable runnable : this.runningTasks.keySet()) {
if (runnable instanceof DownloadProductsQuickLookImageRunnable) {
runnable.cancelRunning();
}
}
}
}
public List<Pair<DownloadProductRunnable, DownloadProgressStatus>> findDownloadingProducts() {
List<Pair<DownloadProductRunnable, DownloadProgressStatus>> downloadingProductRunnables;
if (this.runningTasks != null && this.runningTasks.size() > 0) {
downloadingProductRunnables = new ArrayList<>(this.runningTasks.size());
for (Map.Entry<AbstractBackgroundDownloadRunnable, Pair<DownloadProgressStatus, Boolean>> entry : this.runningTasks.entrySet()) {
AbstractBackgroundDownloadRunnable runnable = entry.getKey();
if (runnable instanceof DownloadProductRunnable) {
Pair<DownloadProgressStatus, Boolean> value = entry.getValue();
Pair<DownloadProductRunnable, DownloadProgressStatus> pair = new Pair(runnable, value.getFirst());
downloadingProductRunnables.add(pair);
}
}
} else {
downloadingProductRunnables = Collections.emptyList();
}
return downloadingProductRunnables;
}
private void startRunningDownloadProductThreadLater(DownloadProductRunnable parentRunnableItem) {
GenericRunnable<DownloadProductRunnable> runnable = new GenericRunnable<DownloadProductRunnable>(parentRunnableItem) {
@Override
protected void execute(DownloadProductRunnable item) {
onStartRunningDownloadProductThread(item);
}
};
SwingUtilities.invokeLater(runnable);
}
private void cancelRunningDownloadProductThreadLater(DownloadProductRunnable parentRunnableItem) {
GenericRunnable<DownloadProductRunnable> runnable = new GenericRunnable<DownloadProductRunnable>(parentRunnableItem) {
@Override
protected void execute(DownloadProductRunnable item) {
onCancelRunningDownloadProductThread(item);
}
};
SwingUtilities.invokeLater(runnable);
}
private void updateApproximateSizeLater(DownloadProductRunnable parentRunnableItem, long approximateSize) {
Runnable runnable = new PairRunnable<DownloadProductRunnable, Long>(parentRunnableItem, approximateSize) {
@Override
protected void execute(DownloadProductRunnable downloadProductRunnable, Long productSizeInBytes) {
onUpdateApproximateSize(downloadProductRunnable, productSizeInBytes.longValue());
}
};
SwingUtilities.invokeLater(runnable);
}
private void notifyProductStatusLater(DownloadProductRunnable parentRunnable, byte downloadStatus){
Runnable notifyProductStatusRunnable= () -> onNotifyProductStatus(parentRunnable, downloadStatus);
SwingUtilities.invokeLater(notifyProductStatusRunnable);
}
private void onNotifyProductStatus(DownloadProductRunnable parentRunnable, byte downloadStatus){
Pair<DownloadProgressStatus, Boolean> value = this.runningTasks.get(parentRunnable);
if (value == null) {
throw new NullPointerException("The value is null.");
} else {
DownloadProgressStatus downloadProgressStatus = value.getFirst();
downloadProgressStatus.setStatus(downloadStatus);
this.downloadProductListener.onUpdateProductDownloadProgress(parentRunnable.getProductToDownload());
}
}
private void updateDownloadingProgressPercentLater(DownloadProductRunnable parentRunnableItem, short progressPercentValue, Path downloadedPath) {
if (logger.isLoggable(Level.FINE)) {
RepositoryProduct repositoryProduct = parentRunnableItem.getProductToDownload();
logger.log(Level.FINE, "Update the downloading progress percent " + progressPercentValue + "% of the product '" + repositoryProduct.getName()+"' using the '" + repositoryProduct.getRemoteMission().getName()+"' mission.");
}
Runnable runnable = new UpdateDownloadingProgressPercentRunnable(parentRunnableItem, progressPercentValue, downloadedPath) {
@Override
public void run() {
if (progressPanel.isCurrentThread(threadId)) {
onUpdateDownloadingProgressPercent(this.downloadProductRunnable, this.progressPercent, this.downloadedProductPath);
}
}
};
SwingUtilities.invokeLater(runnable);
}
private void finishRunningDownloadProductThreadLater(DownloadProductRunnable parentRunnableItem, SaveProductData saveProductDataItem,
byte downloadStatus, Path productPath) {
FinishDownloadingProductStatusRunnable runnable = new FinishDownloadingProductStatusRunnable(parentRunnableItem, saveProductDataItem, downloadStatus, productPath) {
@Override
public void run() {
onFinishRunningDownloadProductThread(this.downloadProductRunnable, this.saveDownloadedProductData, this.saveDownloadStatus, this.downloadedProductPath);
}
};
SwingUtilities.invokeLater(runnable);
}
private void finishRunningDownloadProductsQuickLookImageThreadLater(DownloadProductsQuickLookImageRunnable parentRunnableItem) {
GenericRunnable<DownloadProductsQuickLookImageRunnable> runnable = new GenericRunnable<DownloadProductsQuickLookImageRunnable>(parentRunnableItem) {
@Override
protected void execute(DownloadProductsQuickLookImageRunnable item) {
onFinishRunningDownloadProductQuickLookImageThread(item);
}
};
SwingUtilities.invokeLater(runnable);
}
private boolean hasDownloadingProducts() {
for (AbstractBackgroundDownloadRunnable runnable : this.runningTasks.keySet()) {
if (runnable instanceof DownloadProductRunnable && !runnable.isFinished()) {
return true;
}
}
return false;
}
private void onStartRunningDownloadProductThread(DownloadProductRunnable parentRunnableItem) {
if (this.runningTasks.containsKey(parentRunnableItem)) {
if (hasDownloadingProducts()) {
if (!this.progressPanel.isCurrentThread(this.threadId)) {
this.threadId = this.progressPanel.incrementAndGetCurrentThreadId();
}
this.progressPanel.showProgressPanel(this.threadId, null); // 'null' => do not reset the progress bar message
updateProgressBarDownloadedProducts();
}
} else {
throw new IllegalArgumentException("The parent thread parameter is wrong.");
}
}
private void onCancelRunningDownloadProductThread(DownloadProductRunnable parentRunnableItem) {
if (this.runningTasks.containsKey(parentRunnableItem)) {
DownloadProgressStatus downloadProgressStatus = getDownloadingProductsProgressValue(parentRunnableItem.getProductToDownload());
if (downloadProgressStatus != null) {
downloadProgressStatus.setStatus(DownloadProgressStatus.CANCEL_DOWNLOADING);
}
updateProgressBarDownloadedProducts();
this.downloadProductListener.onUpdateProductDownloadProgress(parentRunnableItem.getProductToDownload());
}
}
private void onFinishRunningDownloadProductThread(DownloadProductRunnable parentRunnable, SaveProductData saveProductData,
byte saveDownloadStatus, Path downloadedProductPath) {
Pair<DownloadProgressStatus, Boolean> value = this.runningTasks.get(parentRunnable);
if (value == null) {
throw new NullPointerException("The value is null.");
} else {
value.setSecond(false);
DownloadProgressStatus downloadProgressStatus = value.getFirst();
downloadProgressStatus.setStatus(saveDownloadStatus);
downloadProgressStatus.setDownloadedPath(downloadedProductPath);
updateProgressBarDownloadedProducts();
boolean hasProductsToDownload = hasDownloadingProducts();
if (saveProductData != null) {
RepositoryProduct repositoryProduct = parentRunnable.getProductToDownload();
repositoryProduct.setLocalAttributes(saveProductData.getLocalAttributes());
}
this.downloadProductListener.onFinishDownloadingProduct(parentRunnable, downloadProgressStatus, saveProductData, hasProductsToDownload);
if (!hasProductsToDownload) {
// there are no downloading products and hide the progress panel if visible
this.progressPanel.hideProgressPanel(this.threadId);
}
shutdownThreadPoolIfEmpty();
}
}
private void onFinishRunningDownloadProductQuickLookImageThread(DownloadProductsQuickLookImageRunnable parentRunnable) {
if (this.runningTasks.containsKey(parentRunnable)) {
this.runningTasks.remove(parentRunnable);
shutdownThreadPoolIfEmpty();
} else {
throw new IllegalArgumentException("The parent thread parameter is wrong.");
}
}
private void shutdownThreadPoolIfEmpty() {
boolean canCloseThreadPool = true;
for (Map.Entry<AbstractBackgroundDownloadRunnable, Pair<DownloadProgressStatus, Boolean>> entry : this.runningTasks.entrySet()) {
AbstractBackgroundDownloadRunnable runnable = entry.getKey();
if (runnable instanceof DownloadProductRunnable) {
Pair<DownloadProgressStatus, Boolean> value = entry.getValue();
if (value == null) {
throw new NullPointerException("The value is null.");
} else if (value.getSecond().booleanValue() == true) {
canCloseThreadPool = false;
}
} else {
canCloseThreadPool = false;
}
}
if (canCloseThreadPool) {
this.threadPoolExecutor.shutdown();
this.threadPoolExecutor = null; // reset the thread pool
this.runningTasks = null; // reset the running tasks
}
}
private void createThreadPoolExecutorIfNeeded() {
if (this.threadPoolExecutor == null) {
this.runningTasks = new HashMap<>();
this.threadId = this.progressPanel.incrementAndGetCurrentThreadId();
int maximumThreadCount = Math.max(3, Runtime.getRuntime().availableProcessors());
this.threadPoolExecutor = new ThreadNamePoolExecutor("product-library", maximumThreadCount);
}
}
private void updateProgressBarDownloadedProducts() {
if (this.progressPanel.isCurrentThread(this.threadId)) {
int totalProductCountToDownload = 0;
int totalDownloadedProductCount = 0;
for (AbstractBackgroundDownloadRunnable runnable : this.runningTasks.keySet()) {
if (runnable instanceof DownloadProductRunnable) {
totalProductCountToDownload++;
if (runnable.isFinished()) {
totalDownloadedProductCount++;
}
}
}
if (totalDownloadedProductCount > totalProductCountToDownload) {
throw new IllegalStateException("The downloaded product count " + totalDownloadedProductCount+" is greater than the total product count to download" + totalProductCountToDownload+".");
} else {
String text = buildProgressBarDownloadingText(totalDownloadedProductCount, totalProductCountToDownload);
this.progressPanel.updateProgressBarText(this.threadId, text);
}
}
}
private void onUpdateApproximateSize(DownloadProductRunnable parentRunnable, long approximateSize) {
Pair<DownloadProgressStatus, Boolean> value = this.runningTasks.get(parentRunnable);
if (value == null) {
throw new NullPointerException("The value is null.");
} else {
RepositoryProduct repositoryProduct = parentRunnable.getProductToDownload();
repositoryProduct.setApproximateSize(approximateSize);
this.downloadProductListener.onRefreshProduct(repositoryProduct);
}
}
private void onUpdateDownloadingProgressPercent(DownloadProductRunnable parentRunnable, short progressPercent, Path downloadedPath) {
Pair<DownloadProgressStatus, Boolean> value = this.runningTasks.get(parentRunnable);
if (value == null) {
throw new NullPointerException("The value is null.");
} else {
DownloadProgressStatus downloadProgressStatus = value.getFirst();
downloadProgressStatus.setValue(progressPercent);
downloadProgressStatus.setDownloadedPath(downloadedPath);
this.downloadProductListener.onUpdateProductDownloadProgress(parentRunnable.getProductToDownload());
}
}
private static abstract class FinishDownloadingProductStatusRunnable implements Runnable {
final DownloadProductRunnable downloadProductRunnable;
final SaveProductData saveDownloadedProductData;
final byte saveDownloadStatus;
final Path downloadedProductPath;
private FinishDownloadingProductStatusRunnable(DownloadProductRunnable parentRunnableItem, SaveProductData saveProductDataItem,
byte downloadStatus, Path productPath) {
this.downloadProductRunnable = parentRunnableItem;
this.saveDownloadedProductData = saveProductDataItem;
this.saveDownloadStatus = downloadStatus;
this.downloadedProductPath = productPath;
}
}
private static abstract class UpdateDownloadingProgressPercentRunnable implements Runnable {
final DownloadProductRunnable downloadProductRunnable;
final short progressPercent;
final Path downloadedProductPath;
private UpdateDownloadingProgressPercentRunnable(DownloadProductRunnable parentRunnableItem, short progressPercent, Path productPath) {
this.downloadProductRunnable = parentRunnableItem;
this.progressPercent = progressPercent;
this.downloadedProductPath = productPath;
}
}
public static String buildProgressBarDownloadingText(int totalDownloaded, int totalProducts) {
return "Downloading products: " + Integer.toString(totalDownloaded) + " out of " + Integer.toString(totalProducts);
}
}
| 23,964 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DownloadProductRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/download/DownloadProductRunnable.java | package org.esa.snap.product.library.ui.v2.repository.remote.download;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.product.library.ui.v2.repository.remote.DownloadProgressStatus;
import org.esa.snap.product.library.ui.v2.repository.remote.RemoteProductDownloader;
import org.esa.snap.product.library.ui.v2.repository.remote.RemoteRepositoriesSemaphore;
import org.esa.snap.product.library.v2.database.AllLocalFolderProductsRepository;
import org.esa.snap.product.library.v2.database.SaveProductData;
import org.esa.snap.remote.products.repository.RemoteMission;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.remote.products.repository.listener.ProgressListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread class to download a remote product.
* Created by jcoravu on 16/10/2019.
*/
public abstract class DownloadProductRunnable extends AbstractBackgroundDownloadRunnable implements ProgressListener {
private static final Logger logger = Logger.getLogger(DownloadProductRunnable.class.getName());
private final RemoteProductDownloader remoteProductDownloader;
private final RemoteRepositoriesSemaphore remoteRepositoriesSemaphore;
private final AllLocalFolderProductsRepository allLocalFolderProductsRepository;
private final boolean uncompressedDownloadedProducts;
public DownloadProductRunnable(RemoteProductDownloader remoteProductDownloader, RemoteRepositoriesSemaphore remoteRepositoriesSemaphore,
AllLocalFolderProductsRepository allLocalFolderProductsRepository, boolean uncompressedDownloadedProducts) {
super();
this.remoteProductDownloader = remoteProductDownloader;
this.remoteRepositoriesSemaphore = remoteRepositoriesSemaphore;
this.allLocalFolderProductsRepository = allLocalFolderProductsRepository;
this.uncompressedDownloadedProducts = uncompressedDownloadedProducts;
}
@Override
public final void run() {
SaveProductData saveProductData = null;
byte downloadStatus = DownloadProgressStatus.FAILED_DOWNLOADING;
Path productPath = null;
try {
startRunning();
if (isFinished()) {
return; // nothing to return
}
productPath = downloadProduct();
if (isFinished()) {
return; // nothing to return
}
//TODO Jean temporary method until the Landsat8 product reader will be changed to read the product from a folder
Path productPathToOpen = RemoteProductsRepositoryProvider.prepareProductPathToOpen(productPath, this.remoteProductDownloader.getProductToDownload());
File productFileToOpen = productPathToOpen.toFile();
//TODO Jean old code to get the product path to open
//File productFileToOpen = productPath.toFile();
Product product = null;
try {
product = ProductIO.readProduct(productFileToOpen);
} catch (Exception exception){
logger.log(Level.WARNING, "Failed to read the remote product '" + this.remoteProductDownloader.getProductToDownload().getName() + "'. " + exception.getMessage());
}
try {
saveProductData = this.allLocalFolderProductsRepository.saveRemoteProduct(this.remoteProductDownloader.getProductToDownload(), productPath,
this.remoteProductDownloader.getRepositoryName(),
this.remoteProductDownloader.getLocalRepositoryFolderPath(), product);
} finally {
if (product != null) {
product.dispose();
}
}
downloadStatus = DownloadProgressStatus.SAVED;
} catch (java.lang.InterruptedException exception) {
downloadStatus = DownloadProgressStatus.CANCEL_DOWNLOADING;
RepositoryProduct repositoryProduct = this.remoteProductDownloader.getProductToDownload();
RemoteMission remoteMission = repositoryProduct.getRemoteMission();
logger.log(Level.WARNING, "Stop downloading the product: name '" + repositoryProduct.getName()+"', mission '" + remoteMission.getName() + "', remote pository '" + remoteMission.getRepositoryName() + "'.");
} catch (IOException exception) {
if (org.apache.commons.lang3.StringUtils.containsIgnoreCase(exception.getMessage(), "is not online")) {
downloadStatus = DownloadProgressStatus.NOT_AVAILABLE; // the product to download is not online
}
logger.log(Level.SEVERE, "Failed to download the remote product '" + this.remoteProductDownloader.getProductToDownload().getName() + "'.", exception);
} catch (Exception exception) {
if (exception.getMessage().contains("403") || exception.getMessage().contains("401")){
downloadStatus = DownloadProgressStatus.FAILED_DOWNLOADING_UNAUTHORIZED;
}
logger.log(Level.SEVERE, "Failed to download the remote product '" + this.remoteProductDownloader.getProductToDownload().getName() + "'.", exception);
} finally {
finishRunning(saveProductData, downloadStatus, productPath);
}
}
@Override
public void cancelRunning() {
super.cancelRunning();
this.remoteProductDownloader.cancel();
}
@Override
public final void notifyProgress(short progressPercent) {
updateDownloadingProgressPercent(progressPercent, null); // 'null' => no download local path
}
protected void finishRunning(SaveProductData saveProductData, byte downloadStatus, Path productPath) {
setRunning(false);
}
protected void updateDownloadingProgressPercent(short progressPercent, Path downloadedPath) {
}
public RepositoryProduct getProductToDownload() {
return this.remoteProductDownloader.getProductToDownload();
}
private Path downloadProduct() throws Exception {
this.remoteRepositoriesSemaphore.acquirePermission(this.remoteProductDownloader.getRepositoryName(), this.remoteProductDownloader.getCredentials());
try {
if (isFinished()) {
return null;
}
updateDownloadingProgressPercent((short) 0, null); // 0%
Path productPath = this.remoteProductDownloader.download(this, this.uncompressedDownloadedProducts);
// successfully downloaded and saved the product
updateDownloadingProgressPercent((short)100, productPath); // 100%
return productPath;
} finally {
this.remoteRepositoriesSemaphore.releasePermission(this.remoteProductDownloader.getRepositoryName(), this.remoteProductDownloader.getCredentials());
}
}
}
| 7,222 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DownloadingProductProgressCallback.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/download/DownloadingProductProgressCallback.java | package org.esa.snap.product.library.ui.v2.repository.remote.download;
import org.esa.snap.product.library.ui.v2.repository.remote.DownloadProgressStatus;
import org.esa.snap.remote.products.repository.RepositoryProduct;
/**
* The callback interface to get the downloading progress of a remote repository product.
*
* Created by jcoravu on 17/2/2020.
*/
public interface DownloadingProductProgressCallback {
public DownloadProgressStatus getDownloadingProductsProgressValue(RepositoryProduct repositoryProduct);
}
| 525 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DownloadProductListTimerRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/download/DownloadProductListTimerRunnable.java | package org.esa.snap.product.library.ui.v2.repository.remote.download;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.repository.remote.RemoteRepositoriesSemaphore;
import org.esa.snap.product.library.ui.v2.thread.AbstractProgressTimerRunnable;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.product.library.ui.v2.thread.ThreadListener;
import org.esa.snap.product.library.v2.preferences.RepositoriesCredentialsController;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.remote.products.repository.listener.ProductListDownloaderListener;
import org.esa.snap.ui.loading.GenericRunnable;
import javax.swing.*;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread class to search the products on a remote repository.
*
* Created by jcoravu on 9/8/2019.
*/
public class DownloadProductListTimerRunnable extends AbstractProgressTimerRunnable<Void> {
private static final Logger logger = Logger.getLogger(DownloadProductListTimerRunnable.class.getName());
private final String mission;
private final Map<String, Object> parameterValues;
private final String remoteRepositoryName;
private final Credentials credentials;
private final RepositoryOutputProductListPanel repositoryProductListPanel;
private final RemoteProductsRepositoryProvider productsRepositoryProvider;
private final ThreadListener threadListener;
private final Object lock = new Object();
public DownloadProductListTimerRunnable(ProgressBarHelper progressPanel, int threadId, Credentials credentials,
RemoteProductsRepositoryProvider productsRepositoryProvider, ThreadListener threadListener, RepositoryOutputProductListPanel repositoryProductListPanel,
String remoteRepositoryName, String mission, Map<String, Object> parameterValues) {
super(progressPanel, threadId, 500);
this.mission = mission;
this.productsRepositoryProvider = productsRepositoryProvider;
this.parameterValues = parameterValues;
this.remoteRepositoryName = remoteRepositoryName;
this.credentials = credentials;
this.threadListener = threadListener;
this.repositoryProductListPanel = repositoryProductListPanel;
}
private boolean downloadsAllPages() {
return RepositoriesCredentialsController.getInstance().downloadsAllPages();
}
private int getPageSize() {
return RepositoriesCredentialsController.getInstance().getNrRecordsOnPage();
}
@Override
protected Void execute() throws Exception {
if (isFinished()) {
return null; // nothing to return
}
try {
ProductListDownloaderListener downloaderListener = new ProductListDownloaderListener() {
@Override
public void notifyProductCount(long totalProductCount) {
if (!isFinished()) {
updateProductListSizeLater(totalProductCount);
}
}
@Override
public void notifyPageProducts(int pageNumber, List<RepositoryProduct> pageResults, long totalProductCount, int retrievedProductCount) {
if (!isFinished()) {
updatePageProductsLater(pageResults, totalProductCount, retrievedProductCount);
if (!downloadsAllPages() && retrievedProductCount < totalProductCount) {
hideProgressPanelLater();
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
showProgressPanelLater();
}
}
}
};
this.productsRepositoryProvider.downloadProductList(this.credentials, this.mission, getPageSize(), this.parameterValues, downloaderListener, this);
if (this.parameterValues.containsKey("username") && this.parameterValues.containsKey("password")) {
String username = (String) this.parameterValues.get("username");
String password = (String) this.parameterValues.get("password");
RepositoriesCredentialsController.getInstance().saveRepositoryCollectionCredential(this.remoteRepositoryName, this.mission, new UsernamePasswordCredentials(username, password));
}
} catch (java.lang.InterruptedException exception) {
logger.log(Level.FINE, "Stop searching the product list on the '" + this.remoteRepositoryName+"' remote repository using the '" +this.mission+"' mission.");
return null; // nothing to return
}
return null; // nothing to return
}
@Override
public void cancelRunning() {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "Cancel searching the product list on the '" + this.remoteRepositoryName+"' remote repository using the '" +this.mission+"' mission.");
}
super.cancelRunning();
}
public void downloadProductListNextPage() {
if (!isFinished()) {
synchronized (lock) {
lock.notify();
}
}
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to retrieve the product list from '" + this.remoteRepositoryName + "'.";
}
@Override
protected void onFailed(Exception exception) {
onShowErrorMessageDialog(this.repositoryProductListPanel, "Failed to retrieve the product list from " + this.remoteRepositoryName + ".\nReason: " + exception.getMessage(), "Error");
}
@Override
protected void onFinishRunning() {
this.threadListener.onStopExecuting(this);
}
@Override
protected boolean onTimerWakeUp(String message) {
return super.onTimerWakeUp(getSearchingProductListMessage() + "...");
}
private void updateProductListSizeLater(long totalProductCount) {
repositoryProductListPanel.setCurrentFullResultsListCount(totalProductCount);
GenericRunnable<Long> runnable = new GenericRunnable<Long>(totalProductCount) {
@Override
protected void execute(Long totalProductCountValue) {
if (isCurrentProgressPanelThread()) {
String text = buildProgressBarDownloadingText(0, totalProductCountValue.longValue());
onUpdateProgressBarText(text);
}
}
};
SwingUtilities.invokeLater(runnable);
}
private void updatePageProductsLater(List<RepositoryProduct> pageResults, long totalProductCount, int retrievedProductCount) {
repositoryProductListPanel.setDownloadProductListTimerRunnable(this);
Runnable runnable = new ProductPageResultsRunnable(pageResults, totalProductCount, retrievedProductCount) {
@Override
protected void execute(List<RepositoryProduct> pageResultsValue, long totalProductCountValue, int retrievedProductCountValue) {
if (isCurrentProgressPanelThread()) {
repositoryProductListPanel.addProducts(pageResultsValue);
String text = buildProgressBarDownloadingText(retrievedProductCountValue, totalProductCountValue);
onUpdateProgressBarText(text);
}
}
};
SwingUtilities.invokeLater(runnable);
}
private void hideProgressPanelLater() {
SwingUtilities.invokeLater(() -> super.onHideProgressPanelLater());
}
private void showProgressPanelLater() {
SwingUtilities.invokeLater(() -> super.onTimerWakeUp("Fetching next page ..."));
}
private static abstract class ProductPageResultsRunnable implements Runnable {
private final List<RepositoryProduct> pageResults;
private final long totalProductCount;
private final int retrievedProductCount;
public ProductPageResultsRunnable(List<RepositoryProduct> pageResults, long totalProductCount, int retrievedProductCount) {
this.pageResults = pageResults;
this.totalProductCount = totalProductCount;
this.retrievedProductCount = retrievedProductCount;
}
protected abstract void execute(List<RepositoryProduct> pageResults, long totalProductCount, int retrievedProductCount);
@Override
public void run() {
execute(this.pageResults, this.totalProductCount, this.retrievedProductCount);
}
}
public static String buildProgressBarDownloadingText(long totalDownloaded, long totalProducts) {
return getSearchingProductListMessage() + ": " + Long.toString(totalDownloaded) + " out of " + Long.toString(totalProducts);
}
private static String getSearchingProductListMessage() {
return "Searching product list";
}
}
| 9,527 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractBackgroundDownloadRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/download/AbstractBackgroundDownloadRunnable.java | package org.esa.snap.product.library.ui.v2.repository.remote.download;
import org.esa.snap.remote.products.repository.ThreadStatus;
/**
* The thread class to download a remote product in the background.
*
* Created by jcoravu on 29/1/2020.
*/
public abstract class AbstractBackgroundDownloadRunnable implements Runnable, ThreadStatus {
private Boolean isRunning;
protected AbstractBackgroundDownloadRunnable() {
}
@Override
public boolean isFinished() {
synchronized (this) {
return (this.isRunning != null && !this.isRunning.booleanValue());
}
}
public void cancelRunning() {
setRunning(false);
}
protected void startRunning() {
setRunning(true);
}
protected final void setRunning(boolean running) {
synchronized (this) {
this.isRunning = running;
}
}
}
| 887 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DownloadProductListener.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/download/DownloadProductListener.java | package org.esa.snap.product.library.ui.v2.repository.remote.download;
import org.esa.snap.product.library.ui.v2.repository.remote.DownloadProgressStatus;
import org.esa.snap.product.library.v2.database.SaveProductData;
import org.esa.snap.remote.products.repository.RepositoryProduct;
/**
* The listener interface for receiving events when downloading a remote product.
*
* Created by jcoravu on 11/2/2020.
*/
public interface DownloadProductListener {
public void onFinishDownloadingProduct(DownloadProductRunnable downloadProductRunnable, DownloadProgressStatus downloadProgressStatus, SaveProductData saveProductData, boolean hasProductsToDownload);
public void onUpdateProductDownloadProgress(RepositoryProduct repositoryProduct);
public void onRefreshProduct(RepositoryProduct repositoryProduct);
}
| 826 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DownloadingProductPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/download/popup/DownloadingProductPanel.java | package org.esa.snap.product.library.ui.v2.repository.remote.download.popup;
import org.esa.snap.product.library.ui.v2.repository.remote.DownloadProgressStatus;
import org.esa.snap.product.library.ui.v2.repository.remote.RemoteProductStatusLabel;
import org.esa.snap.product.library.ui.v2.repository.remote.RemoteRepositoryProductPanel;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadProductRunnable;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* The panel to show the data of a downloading product.
*
* Created by jcoravu on 11/2/2020.
*/
public class DownloadingProductPanel extends JPanel {
private final JButton stopButton;
private final JLabel nameLabel;
private final JLabel acquisitionDateLabel;
private final JLabel sizeLabel;
private final JLabel repositoryLabel;
private final JLabel missionLabel;
private final RemoteProductStatusLabel downloadStatusLabel;
private final DownloadProductRunnable downloadProductRunnable;
private final DownloadProgressStatus downloadProgressStatus;
public DownloadingProductPanel(DownloadProductRunnable downloadProductRunnable, DownloadProgressStatus downloadProgressStatus, int gapBetweenColumns) {
super(new GridBagLayout());
if (downloadProductRunnable == null) {
throw new NullPointerException("The download runnable is null.");
}
if (downloadProgressStatus == null) {
throw new NullPointerException("The download progress status is null.");
}
this.downloadProductRunnable = downloadProductRunnable;
this.downloadProgressStatus = downloadProgressStatus;
setOpaque(false);
RepositoryProduct productToDownload = this.downloadProductRunnable.getProductToDownload();
this.nameLabel = new JLabel(productToDownload.getName());
this.acquisitionDateLabel = new JLabel(RemoteRepositoryProductPanel.buildAcquisitionDateLabelText(productToDownload.getAcquisitionDate()));
this.repositoryLabel = new JLabel(RemoteRepositoryProductPanel.buildRepositoryLabelText(productToDownload.getRemoteMission().getRepositoryName()));
this.missionLabel = new JLabel(RemoteRepositoryProductPanel.buildMissionLabelText(productToDownload.getRemoteMission().getName()));
this.sizeLabel = new JLabel(RemoteRepositoryProductPanel.buildSizeLabelText(productToDownload.getApproximateSize()));
this.downloadStatusLabel = new RemoteProductStatusLabel();
int stopButtonSize = (int)(1.5f * this.nameLabel.getPreferredSize().height);
Dimension buttonSize = new Dimension(stopButtonSize, stopButtonSize);
this.stopButton = SwingUtils.buildButton("/org/esa/snap/product/library/ui/v2/icons/stop20.gif", null, buttonSize, 1);
this.stopButton.setToolTipText("Stop downloading the product");
this.stopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
stopButtonPressed();
}
});
int gapBetweenRows = 0;
int number = 3;
GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 2, 1, 0, 0);
add(this.nameLabel, c);
c = SwingUtils.buildConstraints(2, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 4, gapBetweenRows, 30 * gapBetweenColumns);
add(this.stopButton, c);
c = SwingUtils.buildConstraints(0, 1, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0);
add(this.repositoryLabel, c);
c = SwingUtils.buildConstraints(1, 1, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, number * gapBetweenColumns);
add(this.missionLabel, c);
c = SwingUtils.buildConstraints(0, 2, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0);
add(this.acquisitionDateLabel, c);
c = SwingUtils.buildConstraints(0, 3, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0);
add(this.sizeLabel, c);
c = SwingUtils.buildConstraints(1, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 2, 1, gapBetweenRows, number * gapBetweenColumns);
add(this.downloadStatusLabel, c);
refreshDownloadStatus();
}
public void refreshDownloadStatus() {
if (this.downloadProductRunnable.isFinished()) {
disableComponents();
}
this.downloadStatusLabel.updateDownloadingPercent(this.downloadProgressStatus, this.sizeLabel.getForeground());
}
public boolean stopDownloading(DownloadProductRunnable downloadProductRunnable) {
if (this.downloadProductRunnable == downloadProductRunnable) {
disablePanel();
return true;
}
return false;
}
private void stopButtonPressed() {
this.downloadProductRunnable.cancelRunning();
disablePanel();
}
private void disablePanel() {
if (this.downloadProductRunnable.isFinished()) {
disableComponents();
} else {
throw new IllegalStateException("The thread to download the product has not finished yet.");
}
}
private void disableComponents() {
this.nameLabel.setEnabled(false);
this.stopButton.setEnabled(false);
this.repositoryLabel.setEnabled(false);
this.missionLabel.setEnabled(false);
this.acquisitionDateLabel.setEnabled(false);
this.sizeLabel.setEnabled(false);
this.downloadStatusLabel.setEnabled(false);
}
}
| 5,835 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DownloadingProductsPopupPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/download/popup/DownloadingProductsPopupPanel.java | package org.esa.snap.product.library.ui.v2.repository.remote.download.popup;
import org.esa.snap.engine_utilities.util.Pair;
import org.esa.snap.product.library.ui.v2.repository.remote.DownloadProgressStatus;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadProductRunnable;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.loading.VerticalScrollablePanel;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import java.awt.*;
import java.util.List;
/**
* The panel containing the downloading products.
*
* Created by jcoravu on 11/2/2020.
*/
public class DownloadingProductsPopupPanel extends VerticalScrollablePanel {
private int preferredScrollableHeight;
public DownloadingProductsPopupPanel(List<Pair<DownloadProductRunnable, DownloadProgressStatus>> downloadingProductRunnables,
int visibleProductCount, int gapBetweenRows, int gapBetweenColumns) {
super(null);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
Color separatorColor = UIManager.getColor("controlShadow");
this.preferredScrollableHeight = 0;
for (int i=0; i<downloadingProductRunnables.size(); i++) {
Pair<DownloadProductRunnable, DownloadProgressStatus> pair = downloadingProductRunnables.get(i);
DownloadingProductPanel downloadingProductPanel = new DownloadingProductPanel(pair.getFirst(), pair.getSecond(), gapBetweenColumns);
int topLineHeight = (i > 0) ? 1 : 0;
Border outsideBorder = new MatteBorder(topLineHeight, 0, 0, 0, separatorColor);
Border insideBorder = new EmptyBorder(gapBetweenRows, gapBetweenColumns, gapBetweenRows, gapBetweenColumns);
downloadingProductPanel.setBorder(new CompoundBorder(outsideBorder, insideBorder));
add(downloadingProductPanel);
if (i < visibleProductCount) {
this.preferredScrollableHeight += downloadingProductPanel.getPreferredSize().height;
}
}
}
@Override
public final Dimension getPreferredScrollableViewportSize() {
Dimension size = super.getPreferredScrollableViewportSize();
size.height = this.preferredScrollableHeight;
return size;
}
public void updateProductDownloadProgress(RepositoryProduct repositoryProduct) {
int productCount = getComponentCount();
for (int i=0; i<productCount; i++) {
DownloadingProductPanel downloadingProductPanel = (DownloadingProductPanel)getComponent(i);
downloadingProductPanel.refreshDownloadStatus();
}
}
public void stopDownloadingProduct(DownloadProductRunnable downloadProductRunnable) {
int productCount = getComponentCount();
for (int i=0; i<productCount; i++) {
DownloadingProductPanel downloadingProductPanel = (DownloadingProductPanel)getComponent(i);
if (downloadingProductPanel.stopDownloading(downloadProductRunnable)) {
break;
}
}
}
public void refresh() {
int productCount = getComponentCount();
for (int i=0; i<productCount; i++) {
DownloadingProductPanel downloadingProductPanel = (DownloadingProductPanel)getComponent(i);
downloadingProductPanel.refreshDownloadStatus();
}
}
}
| 3,518 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DownloadingProductsPopupMenu.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/remote/download/popup/DownloadingProductsPopupMenu.java | package org.esa.snap.product.library.ui.v2.repository.remote.download.popup;
import org.esa.snap.engine_utilities.util.Pair;
import org.esa.snap.product.library.ui.v2.repository.remote.DownloadProgressStatus;
import org.esa.snap.product.library.ui.v2.repository.remote.PopupDownloadProductsListener;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadProductRunnable;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import javax.swing.*;
import java.awt.*;
import java.util.List;
/**
* The popup menu to display the panel containing the downloading products.
*
* Created by jcoravu on 11/2/2020.
*/
public class DownloadingProductsPopupMenu extends JPopupMenu implements PopupDownloadProductsListener {
private final DownloadingProductsPopupPanel downloadingProductsPopupPanel;
public DownloadingProductsPopupMenu(List<Pair<DownloadProductRunnable, DownloadProgressStatus>> downloadingProductRunnables,
int gapBetweenRows, int gapBetweenColumns, Color backgroundColor) {
this.downloadingProductsPopupPanel = new DownloadingProductsPopupPanel(downloadingProductRunnables, 5, gapBetweenRows, gapBetweenColumns);
this.downloadingProductsPopupPanel.setOpaque(false);
JScrollPane scrollPane = new JScrollPane(this.downloadingProductsPopupPanel);
scrollPane.setBackground(backgroundColor);
scrollPane.setOpaque(true);
scrollPane.setBorder(null);
scrollPane.getViewport().setOpaque(false);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
}
@Override
public void onUpdateProductDownloadProgress(RepositoryProduct repositoryProduct) {
this.downloadingProductsPopupPanel.updateProductDownloadProgress(repositoryProduct);
}
@Override
public void onStopDownloadingProduct(DownloadProductRunnable downloadProductRunnable) {
this.downloadingProductsPopupPanel.stopDownloadingProduct(downloadProductRunnable);
}
public void refresh() {
this.downloadingProductsPopupPanel.refresh();
}
}
| 2,131 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RepositoryProductsTimelinePanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/timeline/RepositoryProductsTimelinePanel.java | package org.esa.snap.product.library.ui.v2.repository.timeline;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductResults;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemListener;
import java.time.LocalDateTime;
import java.util.ArrayList;
/**
* The panel containing the two types to compute the product count from the search list: by day, by month.
*
* Created by jcoravu on 18/3/2020.
*/
public class RepositoryProductsTimelinePanel extends JPanel {
public static final Color BAR_CHART_COLOR = new Color(7, 60, 102);
private static final byte VERTICAL_GAP = 2;
private final int preferredHeight;
private final String monthsOfYear[];
private final JRadioButton daysTimelineRadioButton;
private final JRadioButton monthsTimelineRadioButton;
private AbstractTimelineHelper timelineHelper;
public RepositoryProductsTimelinePanel() {
super(null); // 'null' => no layout manager
this.daysTimelineRadioButton = new JRadioButton("Timeline");
this.daysTimelineRadioButton.setFocusable(false);
this.monthsTimelineRadioButton = new JRadioButton("Months");
this.monthsTimelineRadioButton.setFocusable(false);
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(this.daysTimelineRadioButton);
buttonGroup.add(this.monthsTimelineRadioButton);
this.monthsTimelineRadioButton.setSelected(true);
Dimension daysSize = this.daysTimelineRadioButton.getPreferredSize();
Dimension monthsSize = this.monthsTimelineRadioButton.getPreferredSize();
this.preferredHeight = daysSize.height + monthsSize.height + (3 * VERTICAL_GAP);
this.monthsOfYear = new String[12];
this.monthsOfYear[0] = "January";
this.monthsOfYear[1] = "February";
this.monthsOfYear[2] = "March";
this.monthsOfYear[3] = "April";
this.monthsOfYear[4] = "May";
this.monthsOfYear[5] = "June";
this.monthsOfYear[6] = "July";
this.monthsOfYear[7] = "August";
this.monthsOfYear[8] = "September";
this.monthsOfYear[9] = "October";
this.monthsOfYear[10] = "November";
this.monthsOfYear[11] = "December";
setVisible(false); // hide the time line by default
}
@Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, this.preferredHeight);
}
@Override
public Dimension getPreferredSize() {
Dimension preferredSize = super.getPreferredSize();
preferredSize.height = this.preferredHeight;
return preferredSize;
}
@Override
public void doLayout() {
super.doLayout();
if (this.timelineHelper != null) {
int leftPadding = 2;
Dimension daysSize = this.daysTimelineRadioButton.getPreferredSize();
int daysY = VERTICAL_GAP;
this.daysTimelineRadioButton.setBounds(leftPadding, daysY, daysSize.width, daysSize.height);
Dimension monthsSize = this.monthsTimelineRadioButton.getPreferredSize();
int monthsY = daysY + daysSize.height + VERTICAL_GAP;
this.monthsTimelineRadioButton.setBounds(leftPadding, monthsY, monthsSize.width, monthsSize.height);
int panelX = leftPadding + Math.max(daysSize.width, monthsSize.width);
int panelY = 0;
int panelWidth = getWidth() - panelX;
int panelHeight = getHeight() - panelY;
this.timelineHelper.doLayout(panelX, panelY, panelWidth, panelHeight);
}
}
public void setItemListener(ItemListener itemListener) {
this.daysTimelineRadioButton.addItemListener(itemListener);
this.monthsTimelineRadioButton.addItemListener(itemListener);
}
public void refresh(OutputProductResults outputProductResults) {
// remove all the components
removeAll();
// add the radio buttons
add(this.daysTimelineRadioButton);
add(this.monthsTimelineRadioButton);
this.timelineHelper = null; // no products by default
if (this.daysTimelineRadioButton.isSelected()) {
java.util.List<YearLabel> dayBarsByYear = computeBarsByDaysOfYear(outputProductResults);
if (dayBarsByYear.size() > 0) {
this.timelineHelper = new MultipleYearDaysTimelineHelper(dayBarsByYear, this.monthsOfYear) {
@Override
protected void addComponentToPanel(JComponent componentToAdd) {
add(componentToAdd);
}
};
}
} else if (this.monthsTimelineRadioButton.isSelected()) {
java.util.List<YearLabel> monthBarsByYear = computeBarsByMonthsOfYear(outputProductResults);
if (monthBarsByYear.size() > 1) {
this.timelineHelper = new MultipleYearMonthsTimelineHelper(monthBarsByYear, this.monthsOfYear) {
@Override
protected void addComponentToPanel(JComponent componentToAdd) {
add(componentToAdd);
}
};
} else if (monthBarsByYear.size() == 1) {
this.timelineHelper = new SingleYearMonthsTimelineHelper(monthBarsByYear.get(0), this.monthsOfYear) {
@Override
protected void addComponentToPanel(JComponent componentToAdd) {
add(componentToAdd);
}
};
}
} else {
throw new IllegalStateException("No timeline selection type.");
}
// refresh the panel
Container parent = getParent();
if (parent != null) {
parent.revalidate();
parent.repaint();
}
// show or hide the panel
setVisible(this.timelineHelper != null);
}
private static java.util.List<YearLabel> computeBarsByMonthsOfYear(OutputProductResults outputProductResults) {
java.util.List<YearLabel> monthBarsByYear = new ArrayList<>();
for (int i=0; i<outputProductResults.getAvailableProductCount(); i++) {
LocalDateTime acquisitionDate = outputProductResults.getProductAt(i).getAcquisitionDate();
if (acquisitionDate != null) {
int year = acquisitionDate.getYear();
int month = acquisitionDate.getMonthValue() - 1;
YearLabel foundPair = null;
for (int k=0; k<monthBarsByYear.size() && foundPair == null; k++) {
YearLabel pair = monthBarsByYear.get(k);
if (pair.getYear() == year) {
foundPair = pair;
}
}
if (foundPair == null) {
foundPair = new YearLabel(year);
monthBarsByYear.add(foundPair);
}
TimelineBarComponent foundMonthBarComponent = foundPair.findBarComponentById(month);
if (foundMonthBarComponent == null) {
foundMonthBarComponent = foundPair.addBarComponent(month);
}
foundMonthBarComponent.incrementProductCount();
}
}
return monthBarsByYear;
}
private static java.util.List<YearLabel> computeBarsByDaysOfYear(OutputProductResults outputProductResults) {
java.util.List<YearLabel> dayBarsByYear = new ArrayList<>();
for (int i=0; i<outputProductResults.getAvailableProductCount(); i++) {
LocalDateTime acquisitionDate = outputProductResults.getProductAt(i).getAcquisitionDate();
if (acquisitionDate != null) {
int year = acquisitionDate.getYear();
int dayOfYear = acquisitionDate.getDayOfYear();
YearLabel foundPair = null;
for (int k=0; k<dayBarsByYear.size() && foundPair == null; k++) {
YearLabel pair = dayBarsByYear.get(k);
if (pair.getYear() == year) {
foundPair = pair;
}
}
if (foundPair == null) {
foundPair = new YearLabel(year);
dayBarsByYear.add(foundPair);
}
TimelineBarComponent foundMonthBarComponent = foundPair.findBarComponentById(dayOfYear);
if (foundMonthBarComponent == null) {
foundMonthBarComponent = foundPair.addBarComponent(dayOfYear);
}
foundMonthBarComponent.incrementProductCount();
}
}
return dayBarsByYear;
}
}
| 8,733 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TimelineBarComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/timeline/TimelineBarComponent.java | package org.esa.snap.product.library.ui.v2.repository.timeline;
import javax.swing.*;
/**
* The label to represent a bar from the timeline.
*/
public class TimelineBarComponent extends JLabel {
private final YearLabel yearLabel;
private final int id;
private int productCount;
public TimelineBarComponent(YearLabel yearLabel, int id) {
this.yearLabel = yearLabel;
this.id = id;
this.productCount = 0;
}
public void incrementProductCount() {
this.productCount++;
}
public int getId() {
return id;
}
public int getProductCount() {
return productCount;
}
public YearLabel getYearLabel() {
return yearLabel;
}
}
| 728 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractTimelineHelper.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/timeline/AbstractTimelineHelper.java | package org.esa.snap.product.library.ui.v2.repository.timeline;
import javax.swing.*;
import java.util.*;
/**
* The base class to layout the bar components of a timeline.
*/
public abstract class AbstractTimelineHelper {
protected final List<YearLabel> yearLabels;
protected AbstractTimelineHelper() {
this.yearLabels = new ArrayList<>();
}
protected abstract void addComponentToPanel(JComponent componentToAdd);
public abstract void doLayout(int panelX, int panelY, int panelWidth, int panelHeight);
protected final void doYearBarsLayout(int panelX, int panelY, int panelWidth, int panelHeight,
int yearLabelsWidth, int yearLabelsHeight, int defaultBarCountPerYear) {
int maximumProductCountPerBar = computeMaximumProductCountPerBar();
int maximumBarHeight = panelHeight - yearLabelsHeight;
int barCountPerYear = defaultBarCountPerYear;
int minimumGapBetweenBars = 2; // the gap between bars should be an even number
int barWidth = yearLabelsHeight; // the default bar width value
int maximumBarWidth = (yearLabelsWidth / barCountPerYear) - minimumGapBetweenBars;
if (maximumBarWidth < barWidth) {
// recompute the values
barCountPerYear = computeMaximumBarCountPerYear(); // recompute the bar count per year
if (barCountPerYear <= 0 || barCountPerYear > defaultBarCountPerYear) {
throw new IllegalStateException("Invalid values: barCountPerYear="+barCountPerYear+", defaultBarCountPerYear=" + defaultBarCountPerYear + ".");
}
maximumBarWidth = (yearLabelsWidth / barCountPerYear) - minimumGapBetweenBars;
if (maximumBarWidth < barWidth) {
barWidth = maximumBarWidth; // update the bar width
}
}
int monthBarSegmentWidth = yearLabelsWidth / barCountPerYear;
int monthBarSegmentRemainingWidth = yearLabelsWidth % barCountPerYear;
int barSegmentsX[] = new int[barCountPerYear];
barSegmentsX[0] = 0; // the first bar has x = 0
for (int i=1; i<barCountPerYear; i++) {
barSegmentsX[i] = barSegmentsX[i - 1] + monthBarSegmentWidth;
if (i > 0 && monthBarSegmentRemainingWidth > 0) {
monthBarSegmentRemainingWidth--;
barSegmentsX[i]++; // add one pixel from the remaining width to each bar left offset
}
}
int monthBarOffsetX = (monthBarSegmentWidth - barWidth) / 2;
// iterate the years
for (int i = 0; i < this.yearLabels.size(); i++) {
YearLabel yearLabel = this.yearLabels.get(i);
doYearBarsLayout(panelX, panelY, panelWidth, yearLabel, defaultBarCountPerYear, barCountPerYear, maximumProductCountPerBar,
maximumBarHeight, barSegmentsX, barWidth, monthBarOffsetX);
}
}
private void doYearBarsLayout(int panelX, int panelY, int panelWidth, YearLabel yearLabel,
int defaultBarCountPerYear, int barCountPerYear, int maximumProductCountPerBar,
int maximumBarHeight, int[] barSegmentsX, int barWidth, int monthBarOffsetX) {
if (yearLabel.getTimelineBarCount() > barCountPerYear) {
throw new IllegalStateException("The bar count " + yearLabel.getTimelineBarCount() + " is greater than the bar count per year " + barCountPerYear + ".");
} else {
Map<TimelineBarComponent, Integer> visibleBarIndicesMap = (yearLabel.getTimelineBarCount() > 0) ? new LinkedHashMap<>() : Collections.emptyMap();
for (int k = 0; k < yearLabel.getTimelineBarCount(); k++) {
TimelineBarComponent barComponent = yearLabel.getTimelineBarAt(k);
if (barComponent.getId() < 0) {
throw new IllegalStateException("The bar component id " + barComponent.getId() +" is negative.");
} else if (barComponent.getId() >= defaultBarCountPerYear) {
throw new IllegalStateException("The bar component id " + barComponent.getId() +" is greater or equal than " + defaultBarCountPerYear + ".");
} else {
int monthBarHeight = computeBarHeight(barComponent.getProductCount(), maximumProductCountPerBar, maximumBarHeight);
int barY = maximumBarHeight - monthBarHeight;
int barX;
int segmentBarIndex;
if (barCountPerYear == defaultBarCountPerYear) {
segmentBarIndex = barComponent.getId();
barX = yearLabel.getX() + barSegmentsX[barComponent.getId()] + monthBarOffsetX;
} else {
segmentBarIndex = (barComponent.getId() * barCountPerYear) / defaultBarCountPerYear;
barX = yearLabel.getX() + barSegmentsX[segmentBarIndex] + monthBarOffsetX;
if (k > 0) {
// recompute the bar position on the X axis
TimelineBarComponent previousBarComponent = yearLabel.getTimelineBarAt(k - 1);
while (segmentBarIndex < barCountPerYear && previousBarComponent.getX() >= barX) {
segmentBarIndex++;
if (segmentBarIndex < barCountPerYear) {
barX = yearLabel.getX() + barSegmentsX[segmentBarIndex] + monthBarOffsetX;
}
}
// check if the bar to display is the last last
if (segmentBarIndex == barCountPerYear) {
// move the bars one position to the left
for (Map.Entry<TimelineBarComponent, Integer> entry : visibleBarIndicesMap.entrySet()) {
TimelineBarComponent addedBarComponent = entry.getKey();
int fromBarSegmentIndex = entry.getValue().intValue();
if (fromBarSegmentIndex < 0) {
throw new IllegalStateException("Invalid value: fromBarSegmentIndex="+fromBarSegmentIndex+".");
} else if (fromBarSegmentIndex > 0) {
int toBarSegmentIndex = fromBarSegmentIndex - 1; // decrement by one the index
int addedBarX = yearLabel.getX() + barSegmentsX[toBarSegmentIndex] + monthBarOffsetX;
beforeMoveLayoutBarToLeft(panelX, addedBarComponent.getId(), fromBarSegmentIndex, toBarSegmentIndex, barSegmentsX);
addedBarComponent.setLocation(addedBarX, addedBarComponent.getY());
entry.setValue(toBarSegmentIndex);
}
}
segmentBarIndex = barCountPerYear - 1; // the last bar index
barX = yearLabel.getX() + barSegmentsX[segmentBarIndex] + monthBarOffsetX;
}
}
}
visibleBarIndicesMap.put(barComponent, segmentBarIndex);
beforeLayoutBar(panelX, panelY, panelWidth, maximumBarHeight, barComponent.getId(), segmentBarIndex, barSegmentsX);
barComponent.setBounds(barX, barY, barWidth, monthBarHeight);
}
}
afterLayoutBars(panelX, panelY, panelWidth, maximumBarHeight, defaultBarCountPerYear, barCountPerYear, barSegmentsX, visibleBarIndicesMap);
}
}
protected void afterLayoutBars(int panelX, int panelY, int panelWidth, int maximumBarHeight, int defaultBarCountPerYear, int barCountPerYear,
int[] barSegmentsX, Map<TimelineBarComponent, Integer> visibleBarIndicesMap) {
}
protected void beforeLayoutBar(int panelX, int panelY, int panelWidth, int maximumBarHeight, int monthBarId, int barIndex, int[] barSegmentsX) {
}
protected void beforeMoveLayoutBarToLeft(int panelX, int monthBarId, int fromBarSegmentIndex, int toBarSegmentIndex, int[] barSegmentsX) {
}
private int computeMaximumBarCountPerYear() {
int maximumBarCount = 0;
for (int i = 0; i < this.yearLabels.size(); i++) {
YearLabel yearLabel = this.yearLabels.get(i);
if (yearLabel.getTimelineBarCount() > 0 && maximumBarCount < yearLabel.getTimelineBarCount()) {
maximumBarCount = yearLabel.getTimelineBarCount();
}
}
return maximumBarCount;
}
private int computeMaximumProductCountPerBar() {
int maximumProductCountPerBar = 0;
for (int i = 0; i<this.yearLabels.size(); i++) {
int productCountPerMonth = this.yearLabels.get(i).computeMaximumProductCount();
if (maximumProductCountPerBar < productCountPerMonth) {
maximumProductCountPerBar = productCountPerMonth;
}
}
return maximumProductCountPerBar;
}
private static int computeBarHeight(int barProductCount, int maximumProductCountPerBar, int maximumMonthBarHeight) {
if (barProductCount < 0) {
throw new IllegalArgumentException("The bar product count is negative: " + barProductCount + ".");
}
if (maximumProductCountPerBar < 0) {
throw new IllegalArgumentException("The maximum product count per bar is negative: " + maximumProductCountPerBar + ".");
}
if (maximumMonthBarHeight < 0) {
throw new IllegalArgumentException("The maximum month bar height is negative: " + maximumMonthBarHeight + ".");
}
if (maximumProductCountPerBar > 0) {
float barHeightPercent = (float) barProductCount / (float) maximumProductCountPerBar;
return (int) (barHeightPercent * maximumMonthBarHeight);
}
return 0;
}
}
| 10,217 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MultipleYearMonthsTimelineHelper.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/timeline/MultipleYearMonthsTimelineHelper.java | package org.esa.snap.product.library.ui.v2.repository.timeline;
import java.util.List;
/**
* The class computes the product count by month for several years.
*/
public abstract class MultipleYearMonthsTimelineHelper extends AbstractMultipleYearsTimelineHelper {
public MultipleYearMonthsTimelineHelper(List<YearLabel> monthBarsByYear, String monthsOfYear[]) {
super(monthBarsByYear, monthsOfYear);
}
@Override
protected String buildTooltipText(String monthsOfYear[], TimelineBarComponent barComponent) {
return buildMonthBarTooltipText(monthsOfYear, barComponent);
}
@Override
protected int getDefaultBarCountPerYear() {
return 12;
}
public static String buildMonthBarTooltipText(String monthsOfYear[], TimelineBarComponent barComponent) {
return monthsOfYear[barComponent.getId()] + " " + barComponent.getYearLabel().getYear() + ": " + barComponent.getProductCount();
}
}
| 953 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
YearLabel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/timeline/YearLabel.java | package org.esa.snap.product.library.ui.v2.repository.timeline;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* The label to represent an year on the time axis.
*/
public class YearLabel extends JLabel {
private final int year;
private final List<TimelineBarComponent> timelineBars;
public YearLabel(int year) {
super(Integer.toString(year), JLabel.CENTER);
this.year = year;
this.timelineBars = new ArrayList<>();
}
public int getYear() {
return year;
}
public TimelineBarComponent findBarComponentById(int barId) {
for (int k = 0; k<this.timelineBars.size(); k++) {
TimelineBarComponent barComponent = this.timelineBars.get(k);
if (barComponent.getYearLabel().getYear() == this.year && barComponent.getId() == barId) {
return barComponent;
}
}
return null;
}
public TimelineBarComponent addBarComponent(int barId) {
TimelineBarComponent barComponent = new TimelineBarComponent(this, barId);
barComponent.setBackground(RepositoryProductsTimelinePanel.BAR_CHART_COLOR);
barComponent.setOpaque(true);
this.timelineBars.add(barComponent);
return barComponent;
}
public int getTimelineBarCount() {
return this.timelineBars.size();
}
public TimelineBarComponent getTimelineBarAt(int index) {
return this.timelineBars.get(index);
}
public int computeMaximumProductCount() {
int maximumProductCount = 0;
for (int i = 0; i < this.timelineBars.size(); i++) {
int productCount = this.timelineBars.get(i).getProductCount();
if (maximumProductCount < productCount) {
maximumProductCount = productCount;
}
}
return maximumProductCount;
}
public void sortBars(Comparator<TimelineBarComponent> barsComparator) {
Collections.sort(this.timelineBars, barsComparator);
}
}
| 2,088 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SingleYearMonthsTimelineHelper.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/timeline/SingleYearMonthsTimelineHelper.java | package org.esa.snap.product.library.ui.v2.repository.timeline;
import javax.swing.*;
import java.awt.*;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* The class computes the product count by month for an year.
*/
public abstract class SingleYearMonthsTimelineHelper extends AbstractTimelineHelper {
private final JLabel monthNameLabels[];
private final String monthsOfYear[];
private final Dimension maximumMonthLabelsSize;
public SingleYearMonthsTimelineHelper(YearLabel yearLabel, String monthsOfYear[]) {
this.yearLabels.add(yearLabel);
this.monthsOfYear = monthsOfYear;
this.monthNameLabels = new JLabel[monthsOfYear.length];
for (int i=0; i<monthsOfYear.length; i++) {
this.monthNameLabels[i] = new JLabel("", JLabel.CENTER);
addComponentToPanel(this.monthNameLabels[i]);
}
for (int i = 0; i<yearLabel.getTimelineBarCount(); i++) {
TimelineBarComponent monthBarComponent = yearLabel.getTimelineBarAt(i);
String toolTipText = MultipleYearMonthsTimelineHelper.buildMonthBarTooltipText(monthsOfYear, monthBarComponent);
monthBarComponent.setToolTipText(toolTipText);
addComponentToPanel(monthBarComponent);
}
this.maximumMonthLabelsSize = computeMaximumMonthLabelsSize(this.monthsOfYear);
}
@Override
public void doLayout(int panelX, int panelY, int panelWidth, int panelHeight) {
this.yearLabels.get(0).setLocation(panelX, panelY);
doYearBarsLayout(panelX, panelY, panelWidth, panelHeight, panelWidth, this.maximumMonthLabelsSize.height, this.monthsOfYear.length);
}
@Override
protected void beforeLayoutBar(int panelX, int panelY, int panelWidth, int maximumBarHeight, int monthBarId, int monthBarSegmentIndex, int[] barSegmentsX) {
layoutMonthLabel(panelX, panelY, panelWidth, maximumBarHeight, monthBarId, monthBarSegmentIndex, barSegmentsX);
}
@Override
protected void afterLayoutBars(int panelX, int panelY, int panelWidth, int maximumBarHeight, int defaultBarCountPerYear, int barCountPerYear,
int[] barSegmentsX, Map<TimelineBarComponent, Integer> visibleBarIndicesMap) {
for (int i=0; i<this.monthsOfYear.length; i++) {
JLabel monthNameLabel = this.monthNameLabels[i];
boolean visible = false;
if (barCountPerYear == defaultBarCountPerYear) {
visible = true;
boolean foundMonthBar = false;
for (Map.Entry<TimelineBarComponent, Integer> entry : visibleBarIndicesMap.entrySet()) {
TimelineBarComponent monthBarComponent = entry.getKey();
if (monthBarComponent.getId() == i) {
foundMonthBar = true;
break;
}
}
if (!foundMonthBar) {
layoutMonthLabel(panelX, panelY, panelWidth, maximumBarHeight, i, i, barSegmentsX);
}
}
monthNameLabel.setVisible(visible);
}
}
@Override
protected void beforeMoveLayoutBarToLeft(int panelX, int monthBarId, int fromBarSegmentIndex, int toBarSegmentIndex, int[] barSegmentsX) {
JLabel monthNameLabel = this.monthNameLabels[monthBarId];
int monthLabelX = panelX + barSegmentsX[toBarSegmentIndex];
monthNameLabel.setLocation(monthLabelX, monthNameLabel.getY());
}
private void layoutMonthLabel(int panelX, int panelY, int panelWidth, int maximumBarHeight, int monthBarId, int monthBarSegmentIndex, int[] barSegmentsX) {
int totalNeededLabelsWidth = this.maximumMonthLabelsSize.width * this.monthsOfYear.length;
JLabel monthNameLabel = this.monthNameLabels[monthBarId];
String labelText = this.monthsOfYear[monthBarId];
if (totalNeededLabelsWidth > panelWidth) {
labelText = labelText.substring(0, 3);
}
monthNameLabel.setText(labelText);
int monthLabelX = panelX + barSegmentsX[monthBarSegmentIndex];
int monthLabelY = panelY + maximumBarHeight;//(panelHeight - maximumMonthLabelsSize.height);
int monthLabelWidth = panelWidth / this.monthsOfYear.length;
monthNameLabel.setBounds(monthLabelX, monthLabelY, monthLabelWidth, this.maximumMonthLabelsSize.height);
monthNameLabel.setVisible(true);
}
private static Dimension computeMaximumMonthLabelsSize(String monthsOfYear[]) {
JLabel label = new JLabel(monthsOfYear[0]);
Dimension firstSize = label.getPreferredSize();
int maximumHeight = firstSize.height;
int maximumWidth = firstSize.width;
for (int i=1; i<monthsOfYear.length; i++) {
label.setText(monthsOfYear[i]);
Dimension size = label.getPreferredSize();
if (maximumHeight < size.height) {
maximumHeight = size.height;
}
if (maximumWidth < size.width) {
maximumWidth = size.width;
}
}
return new Dimension(maximumWidth, maximumHeight);
}
}
| 5,175 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MultipleYearDaysTimelineHelper.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/timeline/MultipleYearDaysTimelineHelper.java | package org.esa.snap.product.library.ui.v2.repository.timeline;
import java.util.Calendar;
import java.util.List;
/**
* The class computes the product count by day for several years.
*/
public abstract class MultipleYearDaysTimelineHelper extends AbstractMultipleYearsTimelineHelper {
public MultipleYearDaysTimelineHelper(List<YearLabel> monthBarsByYear, String monthsOfYear[]) {
super(monthBarsByYear, monthsOfYear);
}
@Override
protected String buildTooltipText(String monthsOfYear[], TimelineBarComponent barComponent) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, barComponent.getYearLabel().getYear());
calendar.set(Calendar.DAY_OF_YEAR, barComponent.getId());
int month = calendar.get(Calendar.MONTH);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
return dayOfMonth + " " + monthsOfYear[month] + " " + barComponent.getYearLabel().getYear() + ": " + barComponent.getProductCount();
}
@Override
protected int getDefaultBarCountPerYear() {
return 366;
}
}
| 1,099 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractMultipleYearsTimelineHelper.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/timeline/AbstractMultipleYearsTimelineHelper.java | package org.esa.snap.product.library.ui.v2.repository.timeline;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;
/**
* The class computes the product count for several years.
*/
public abstract class AbstractMultipleYearsTimelineHelper extends AbstractTimelineHelper {
protected static final String SEPARATOR_LABEL_KEY = "SeparatorLabelKey";
protected AbstractMultipleYearsTimelineHelper(List<YearLabel> monthBarsByYear, String monthsOfYear[]) {
int miminumYear = monthBarsByYear.get(0).getYear();
int maximumYear = miminumYear;
for (int i=0; i<monthBarsByYear.size(); i++) {
YearLabel yearLabel = monthBarsByYear.get(i);
this.yearLabels.add(yearLabel);
if (miminumYear > yearLabel.getYear()) {
miminumYear = yearLabel.getYear();
}
if (maximumYear < yearLabel.getYear()) {
maximumYear = yearLabel.getYear();
}
}
Comparator<TimelineBarComponent> barsComparator = new Comparator<TimelineBarComponent>() {
@Override
public int compare(TimelineBarComponent leftItem, TimelineBarComponent rightItem) {
return Integer.compare(leftItem.getId(), rightItem.getId());
}
};
for (int year = miminumYear; year<=maximumYear; year++) {
YearLabel foundYear = null;
for (int k=0; k<this.yearLabels.size() && foundYear==null; k++) {
YearLabel existingYearLabel = this.yearLabels.get(k);
if (year == existingYearLabel.getYear()) {
foundYear = existingYearLabel;
}
}
if (foundYear == null) {
foundYear = new YearLabel(year);
this.yearLabels.add(foundYear);
}
foundYear.sortBars(barsComparator);
addComponentToPanel(foundYear);
if (year > miminumYear) {
JLabel yearSeparatorLabel = new JLabel();
yearSeparatorLabel.setBackground(Color.BLACK);
yearSeparatorLabel.setOpaque(true);
foundYear.putClientProperty(SEPARATOR_LABEL_KEY, yearSeparatorLabel);
addComponentToPanel(yearSeparatorLabel);
}
for (int i = 0; i<foundYear.getTimelineBarCount(); i++) {
TimelineBarComponent barComponent = foundYear.getTimelineBarAt(i);
String toolTipText = buildTooltipText(monthsOfYear, barComponent);
barComponent.setToolTipText(toolTipText);
addComponentToPanel(barComponent);
}
}
Comparator<YearLabel> yearsComparator = new Comparator<YearLabel>() {
@Override
public int compare(YearLabel leftItem, YearLabel rightItem) {
return Integer.compare(leftItem.getYear(), rightItem.getYear());
}
};
Collections.sort(this.yearLabels, yearsComparator); // sort ascending by year
}
protected abstract String buildTooltipText(String monthsOfYear[], TimelineBarComponent barComponent);
protected abstract int getDefaultBarCountPerYear();
@Override
public final void doLayout(int panelX, int panelY, int panelWidth, int panelHeight) {
int yearLabelsHeight = computeMaximumYearLabelsHeight();
int yearCount = this.yearLabels.size();
int gapBetweenYearLabels = 1;
int yearLabelsWidth = (panelWidth - (gapBetweenYearLabels * (yearCount - 1))) / yearCount;
int separatorHeight = panelHeight - yearLabelsHeight;
int yearLabelX = panelX;
int yearLabelY = panelY + (panelHeight - yearLabelsHeight);
for (int i = 0; i < yearCount; i++) {
YearLabel yearLabel = this.yearLabels.get(i);
// update the year label location
yearLabel.setBounds(yearLabelX, yearLabelY, yearLabelsWidth, yearLabelsHeight);
yearLabelX += yearLabelsWidth + gapBetweenYearLabels;
// update the separator label location
JLabel yearSeparatorLabel = (JLabel) yearLabel.getClientProperty(SEPARATOR_LABEL_KEY);
if (yearSeparatorLabel != null) {
// there is a separator line between the years
yearSeparatorLabel.setBounds(yearLabel.getX() - 1, 0, gapBetweenYearLabels, separatorHeight);
}
}
// display rhe bars
doYearBarsLayout(panelX, panelY, panelWidth, panelHeight, yearLabelsWidth, yearLabelsHeight, getDefaultBarCountPerYear());
}
private int computeMaximumYearLabelsHeight() {
int maximumHeight = this.yearLabels.get(0).getPreferredSize().height;
for (int i = 1; i<this.yearLabels.size(); i++) {
int height = this.yearLabels.get(i).getPreferredSize().height;
if (maximumHeight < height) {
maximumHeight = height;
}
}
return maximumHeight;
}
}
| 5,024 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OutputProductListPaginationPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/output/OutputProductListPaginationPanel.java | package org.esa.snap.product.library.ui.v2.repository.output;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.product.library.v2.preferences.RepositoriesCredentialsController;
import org.esa.snap.ui.loading.CustomButton;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
/**
* The panel contains the four buttons to implement the pagination.
*
* Created by jcoravu on 29/1/2020.
*/
public class OutputProductListPaginationPanel extends JPanel {
private final JButton previousPageButton;
private final JButton nextPageButton;
private final JButton firstPageButton;
private final JButton lastPageButton;
private final JLabel totalPagesTextField;
public OutputProductListPaginationPanel(ComponentDimension componentDimension, ActionListener firstPageButtonListener, ActionListener previousPageButtonListener,
ActionListener nextPageButtonListener, ActionListener lastPageButtonListener) {
super();
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
int preferredButtonHeight = componentDimension.getTextFieldPreferredHeight();
this.firstPageButton = new CustomButton("<<", preferredButtonHeight);
this.firstPageButton.setFocusable(false);
this.firstPageButton.addActionListener(firstPageButtonListener);
this.previousPageButton = new CustomButton("<", preferredButtonHeight);
this.previousPageButton.setFocusable(false);
this.previousPageButton.addActionListener(previousPageButtonListener);
this.nextPageButton = new CustomButton(">", preferredButtonHeight);
this.nextPageButton.setFocusable(false);
this.nextPageButton.addActionListener(nextPageButtonListener);
this.lastPageButton = new CustomButton(">>", preferredButtonHeight);
this.lastPageButton.setFocusable(false);
this.lastPageButton.addActionListener(lastPageButtonListener);
this.totalPagesTextField = new JLabel(" ", JLabel.CENTER);
this.totalPagesTextField.setBorder(SwingUtils.LINE_BORDER);
this.totalPagesTextField.setBackground(componentDimension.getTextFieldBackgroundColor());
this.totalPagesTextField.setOpaque(true);
Dimension labelPreferredSize = this.totalPagesTextField.getPreferredSize();
labelPreferredSize.height = preferredButtonHeight;
setComponentSize(this.totalPagesTextField, labelPreferredSize);
add(this.firstPageButton);
add(Box.createHorizontalStrut(componentDimension.getGapBetweenColumns()));
add(this.previousPageButton);
add(Box.createHorizontalStrut(componentDimension.getGapBetweenColumns()));
add(this.totalPagesTextField);
add(Box.createHorizontalStrut(componentDimension.getGapBetweenColumns()));
add(this.nextPageButton);
add(Box.createHorizontalStrut(componentDimension.getGapBetweenColumns()));
add(this.lastPageButton);
refreshPaginationButtons(false, false, false, "");
}
public void refreshPaginationButtons(boolean previousPageEnabled, boolean nextPageEnabled, boolean lastPageEnabled, String text) {
this.firstPageButton.setEnabled(previousPageEnabled);
this.previousPageButton.setEnabled(previousPageEnabled);
this.nextPageButton.setEnabled(nextPageEnabled);
this.lastPageButton.setEnabled(lastPageEnabled);
this.totalPagesTextField.setText(text);
}
private static void setComponentSize(JComponent component, Dimension preferredSize) {
component.setPreferredSize(preferredSize);
component.setMinimumSize(preferredSize);
component.setMaximumSize(preferredSize);
}
}
| 3,819 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RepositoryOutputProductListPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/output/RepositoryOutputProductListPanel.java | package org.esa.snap.product.library.ui.v2.repository.output;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.product.library.ui.v2.repository.AbstractProductsRepositoryPanel;
import org.esa.snap.product.library.ui.v2.repository.RepositorySelectionPanel;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadProductListTimerRunnable;
import org.esa.snap.product.library.ui.v2.repository.timeline.RepositoryProductsTimelinePanel;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelperImpl;
import org.esa.snap.product.library.v2.preferences.RepositoriesCredentialsController;
import org.esa.snap.product.library.v2.preferences.RepositoriesCredentialsPersistence;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.loading.CustomComboBox;
import org.esa.snap.ui.loading.ItemRenderer;
import org.esa.snap.ui.loading.SwingUtils;
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.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* The panel class contains the product list after searching then in the repository.
*
* Created by jcoravu on 21/8/2019.
*/
public class RepositoryOutputProductListPanel extends JPanel implements OutputProductResultsCallback {
private static final String PAGE_PRODUCTS_CHANGED = "pageProductsChanged";
public static final byte ASCENDING_SORTING_TYPE = 1;
public static final byte DESCENDING_SORTING_TYPE = 2;
private final JLabel titleLabel;
private final JLabel sortByLabel;
private final ProgressBarHelperImpl progressBarHelper;
private final OutputProductListPanel productListPanel;
private final OutputProductListPaginationPanel productListPaginationPanel;
private final CustomComboBox<ComparatorItem> comparatorsComboBox;
private final CustomComboBox<Byte> sortingTypeComboBox;
private RepositoryProductsTimelinePanel productsTimelinePanel;
private int visibleProductsPerPage;
private DownloadProductListTimerRunnable downloadProductListTimerRunnable = null;
public RepositoryOutputProductListPanel(RepositorySelectionPanel repositorySelectionPanel, ComponentDimension componentDimension,
ActionListener stopButtonListener, int progressBarWidth, boolean showStopDownloadButton) {
super(new BorderLayout(0, componentDimension.getGapBetweenRows()));
this.visibleProductsPerPage = RepositoriesCredentialsPersistence.VISIBLE_PRODUCTS_PER_PAGE;
this.titleLabel = new JLabel(getTitle());
this.productListPanel = new OutputProductListPanel(repositorySelectionPanel, componentDimension, this);
this.productListPanel.addDataChangedListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateProductListCountTitle();
refreshPaginationButtons();
}
});
this.productsTimelinePanel = new RepositoryProductsTimelinePanel();
this.productsTimelinePanel.setItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
productsTimelinePanel.refresh(getOutputProductResults());
}
}
});
ItemListener sortProductsListener = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent itemEvent) {
if (itemEvent.getStateChange() == ItemEvent.SELECTED) {
productListPanel.getProductListModel().sortProducts();
}
}
};
ItemRenderer<ComparatorItem> itemRenderer = new ItemRenderer<ComparatorItem>() {
@Override
public String getItemDisplayText(ComparatorItem item) {
return (item == null) ? " " : item.getDisplayName();
}
};
this.comparatorsComboBox = new CustomComboBox<>(itemRenderer, componentDimension.getTextFieldPreferredHeight(), false, componentDimension.getTextFieldBackgroundColor());
this.comparatorsComboBox.addItem(buildProductNameComparator());
this.comparatorsComboBox.addItem(buildMissionComparator());
this.comparatorsComboBox.addItem(buildAcquisitionDateComparator());
this.comparatorsComboBox.addItem(buildFileSizeComparator());
this.comparatorsComboBox.addItemListener(sortProductsListener);
ItemRenderer<Byte> sortingTypeRenderer = new ItemRenderer<Byte>() {
@Override
public String getItemDisplayText(Byte item) {
if (item == null) {
return " ";
}
if (item.byteValue() == ASCENDING_SORTING_TYPE) {
return "Ascending";
}
if (item.byteValue() == DESCENDING_SORTING_TYPE) {
return "Descending";
}
throw new IllegalArgumentException("Unknown sorting type " + item.byteValue()+".");
}
};
this.sortingTypeComboBox = new CustomComboBox<>(sortingTypeRenderer, componentDimension.getTextFieldPreferredHeight(), false, componentDimension.getTextFieldBackgroundColor());
this.sortingTypeComboBox.addItem(ASCENDING_SORTING_TYPE);
this.sortingTypeComboBox.addItem(DESCENDING_SORTING_TYPE);
this.sortingTypeComboBox.addItemListener(sortProductsListener);
int maximumPreferredWidth = 0;
JLabel label = new JLabel();
for (int i=0; i<this.comparatorsComboBox.getItemCount(); i++) {
label.setText(itemRenderer.getItemDisplayText(this.comparatorsComboBox.getItemAt(i)));
maximumPreferredWidth = Math.max(maximumPreferredWidth, label.getPreferredSize().width);
}
Dimension comboBoxSize = new Dimension(maximumPreferredWidth + componentDimension.getTextFieldPreferredHeight(), componentDimension.getTextFieldPreferredHeight());
this.comparatorsComboBox.setPreferredSize(comboBoxSize);
this.comparatorsComboBox.setMaximumSize(comboBoxSize);
this.comparatorsComboBox.setMinimumSize(comboBoxSize);
this.sortByLabel = label;
this.sortByLabel.setText("Sort By");
ActionListener firstPageButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
displayFirstPageProducts();
}
};
ActionListener previousPageButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
displayPreviousPageProducts();
}
};
ActionListener nextPageButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
displayNextPageProducts();
}
};
ActionListener lastPageButtonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
displayLastPageProducts();
}
};
this.productListPaginationPanel = new OutputProductListPaginationPanel(componentDimension, firstPageButtonListener, previousPageButtonListener,
nextPageButtonListener, lastPageButtonListener);
this.progressBarHelper = new ProgressBarHelperImpl(progressBarWidth, componentDimension.getTextFieldPreferredHeight()) {
@Override
protected void setParametersEnabledWhileDownloading(boolean enabled) {
// do nothing
}
};
this.progressBarHelper.getStopButton().addActionListener(stopButtonListener);
addComponents(componentDimension, showStopDownloadButton);
}
public void setDownloadProductListTimerRunnable(DownloadProductListTimerRunnable downloadProductListTimerRunnable) {
this.downloadProductListTimerRunnable = downloadProductListTimerRunnable;
}
public void setCurrentFullResultsListCount(Long currentFullResultsListCount) {
getOutputProductResults().setFullResultsListCount(currentFullResultsListCount);
}
private boolean downloadsAllPages(){
return RepositoriesCredentialsController.getInstance().downloadsAllPages();
}
@Override
public Comparator<RepositoryProduct> getProductsComparator() {
ComparatorItem comparator = (ComparatorItem)this.comparatorsComboBox.getSelectedItem();
Byte sortingType = (Byte)this.sortingTypeComboBox.getSelectedItem();
boolean sortAscending;
if (sortingType.byteValue() == ASCENDING_SORTING_TYPE) {
sortAscending = true;
} else if (sortingType.byteValue() == DESCENDING_SORTING_TYPE) {
sortAscending = false;
} else {
throw new IllegalStateException("unknown sorting type " + sortingType.byteValue() + ".");
}
return new ProductsComparator(comparator, sortAscending);
}
@Override
public OutputProductResults getOutputProductResults() {
AbstractProductsRepositoryPanel selectedProductsRepositoryPanel = this.productListPanel.getRepositorySelectionPanel().getSelectedProductsRepositoryPanel();
return selectedProductsRepositoryPanel.getOutputProductResults();
}
public void setVisibleProductsPerPage(int visibleProductsPerPage) {
this.visibleProductsPerPage = visibleProductsPerPage;
}
public OutputProductListPaginationPanel getProductListPaginationPanel() {
return this.productListPaginationPanel;
}
public ProgressBarHelperImpl getProgressBarHelper() {
return progressBarHelper;
}
public OutputProductListPanel getProductListPanel() {
return productListPanel;
}
public void addPageProductsChangedListener(PropertyChangeListener changeListener) {
addPropertyChangeListener(PAGE_PRODUCTS_CHANGED, changeListener);
}
public void setProducts(List<RepositoryProduct> products) {
resetOutputProducts();
if (products.size() > 0) {
getOutputProductResults().addProducts(products);
setCurrentFullResultsListCount((long) products.size());
displayPageProducts(1); // display the first page
} else {
// no products to display
clearPageProducts();
}
this.productsTimelinePanel.refresh(getOutputProductResults());
}
public void clearOutputList(boolean canResetProductListCountTitle) {
resetOutputProducts();
clearPageProducts();
if (canResetProductListCountTitle) {
resetProductListCountTitle(); // remove the product count from the title
}
this.productsTimelinePanel.refresh(getOutputProductResults());
}
public void refreshOutputList() {
OutputProductResults outputProductResults = getOutputProductResults();
if (outputProductResults.getAvailableProductCount() > 0) {
displayPageProducts(outputProductResults.getCurrentPageNumber());
} else {
clearPageProducts();
}
this.productsTimelinePanel.refresh(outputProductResults);
}
public void addProducts(List<RepositoryProduct> products) {
if (products.size() > 0) {
OutputProductResults outputProductResults = getOutputProductResults();
if (outputProductResults.getAvailableProductCount() > 0) {
if (outputProductResults.getCurrentPageNumber() <= 0) {
throw new IllegalStateException("The current page number " + outputProductResults.getCurrentPageNumber() + " must be > 0.");
}
} else if (outputProductResults.getCurrentPageNumber() != 0) {
throw new IllegalStateException("The current page number " + outputProductResults.getCurrentPageNumber() + " must be 0.");
}
outputProductResults.addProducts(products);
if (outputProductResults.getCurrentPageNumber() == 0) {
// the first page
int productCount = this.productListPanel.getProductListModel().getProductCount();
if (productCount > 0) {
throw new IllegalStateException("The product count " + productCount + " of the first page must be 0.");
}
displayPageProducts(1); // display the first page
} else {
refreshPaginationButtons(); // refresh the pagination button after received the products
if(!downloadsAllPages() && productListPageDownloaded(outputProductResults.getCurrentPageNumber() + 1)){
displayPageProducts(outputProductResults.getCurrentPageNumber() + 1);
}
}
this.productsTimelinePanel.refresh(outputProductResults);
}
}
private boolean productListPageDownloaded(int pageNumber){
return pageNumber <= getOutputProductResults().getAvailableProductCount() / this.visibleProductsPerPage + (getOutputProductResults().getAvailableProductCount() % this.visibleProductsPerPage > 0 ? 1 : 0);
}
private void displayNextPageProducts() {
int availablePagesCount = computeAvailablePagesCount();
OutputProductResults outputProductResults = getOutputProductResults();
if (outputProductResults.getCurrentPageNumber() < availablePagesCount) {
displayPageProducts(outputProductResults.getCurrentPageNumber() + 1);
} else {
if(!downloadsAllPages() && this.downloadProductListTimerRunnable != null && !productListPageDownloaded(outputProductResults.getCurrentPageNumber() + 1)){
this.downloadProductListTimerRunnable.downloadProductListNextPage();
if(this.downloadProductListTimerRunnable.isFinished()){
refreshPaginationButtons();
}
} else {
throw new IllegalStateException("The current page number " + outputProductResults.getCurrentPageNumber() + " must be < than the total page count " + availablePagesCount + ".");
}
}
}
private void displayLastPageProducts() {
OutputProductResults outputProductResults = getOutputProductResults();
int availablePagesCount = computeAvailablePagesCount();
if (outputProductResults.getCurrentPageNumber() < availablePagesCount) {
displayPageProducts(availablePagesCount);
} else {
throw new IllegalStateException("The current page number " + outputProductResults.getCurrentPageNumber()+" must be < than the total page count " + availablePagesCount + ".");
}
}
private void displayFirstPageProducts() {
OutputProductResults outputProductResults = getOutputProductResults();
if (outputProductResults.getCurrentPageNumber() > 1) {
displayPageProducts(1);
} else {
int availablePagesCount = computeAvailablePagesCount();
throw new IllegalStateException("The current page number " + outputProductResults.getCurrentPageNumber()+" must be < than the total page count " + availablePagesCount + ".");
}
}
private void displayPreviousPageProducts() {
OutputProductResults outputProductResults = getOutputProductResults();
if (outputProductResults.getCurrentPageNumber() > 1) {
displayPageProducts(outputProductResults.getCurrentPageNumber() - 1);
} else {
int availablePagesCount = computeAvailablePagesCount();
throw new IllegalStateException("The current page number " + outputProductResults.getCurrentPageNumber()+" must be < than the total page count " + availablePagesCount + ".");
}
}
private void displayPageProducts(int newCurrentPageNumber) {
if (newCurrentPageNumber <= 0) {
throw new IllegalArgumentException("The new current page number " + newCurrentPageNumber +" must be > 0.");
}
OutputProductResults outputProductResults = getOutputProductResults();
int startIndex = (newCurrentPageNumber-1) * this.visibleProductsPerPage;
int endIndex = startIndex + this.visibleProductsPerPage;
if (endIndex >= outputProductResults.getAvailableProductCount()) {
endIndex = outputProductResults.getAvailableProductCount();
}
final int size = endIndex - startIndex;
if(size > 0){
List<RepositoryProduct> pageProducts = new ArrayList<>(size);
for (int i = startIndex; i < endIndex; i++) {
pageProducts.add(outputProductResults.getProductAt(i));
}
outputProductResults.setCurrentPageNumber(newCurrentPageNumber);
this.productListPanel.setProducts(pageProducts);
firePageProductChanged();
}
}
private void clearPageProducts() {
this.productListPanel.getProductListModel().clear();
firePageProductChanged();
}
private void firePageProductChanged() {
firePropertyChange(PAGE_PRODUCTS_CHANGED, null, null);
}
private void refreshPaginationButtons() {
int availablePagesCount = computeAvailablePagesCount();
int totalPagesCount = computeTotalPagesCount();
boolean previousPageEnabled = false;
boolean nextPageEnabled = false;
boolean lastPageEnabled = false;
String text = "";
if (availablePagesCount > 0) {
OutputProductResults outputProductResults = getOutputProductResults();
if (outputProductResults.getCurrentPageNumber() > 0) {
text = Integer.toString(outputProductResults.getCurrentPageNumber()) + " / " + Integer.toString(totalPagesCount);
if (outputProductResults.getCurrentPageNumber() > 1) {
previousPageEnabled = true;
}
if(outputProductResults.getCurrentPageNumber() < totalPagesCount) {
if (outputProductResults.getCurrentPageNumber() < availablePagesCount) {
nextPageEnabled = true;
lastPageEnabled = true;
} else {
if (!downloadsAllPages() && this.downloadProductListTimerRunnable != null && !productListPageDownloaded(outputProductResults.getCurrentPageNumber() + 1)) {
nextPageEnabled = true;
}
}
}
} else {
throw new IllegalStateException("The current page number is 0.");
}
}
this.productListPaginationPanel.refreshPaginationButtons(previousPageEnabled, nextPageEnabled, lastPageEnabled, text);
}
private int computeAvailablePagesCount() {
OutputProductResults outputProductResults = getOutputProductResults();
int count = 0;
if (outputProductResults.getAvailableProductCount() > 0) {
long totalCount = outputProductResults.getAvailableProductCount();
count = (int) (totalCount / this.visibleProductsPerPage);
if (totalCount % this.visibleProductsPerPage > 0) {
count++;
}
}
return count;
}
private int computeTotalPagesCount() {
OutputProductResults outputProductResults = getOutputProductResults();
int count = 0;
if (outputProductResults.getAvailableProductCount() > 0) {
long totalCount = outputProductResults.getFullResultsListCount();
count = (int) (totalCount / this.visibleProductsPerPage);
if (totalCount % this.visibleProductsPerPage > 0) {
count++;
}
}
return count;
}
public void resetProductListCountTitle() {
this.titleLabel.setText(getTitle());
}
public void updateProductListCountTitle() {
int pageProductCount = this.productListPanel.getProductListModel().getProductCount();
int pageNr = getOutputProductResults().getCurrentPageNumber();
pageNr = pageNr < 1 ? 0 : pageNr - 1;
int pageProductStartIndex = this.visibleProductsPerPage * pageNr;
int pageProductEndIndex = pageProductStartIndex + pageProductCount;
long totalProductCount = getOutputProductResults().getFullResultsListCount();
String intervalText = Integer.toString(pageProductEndIndex);
if(pageProductCount > 0){
intervalText = Integer.toString(pageProductStartIndex + 1) + " -> " + intervalText;
}
String text = getTitle() + ": " + intervalText;
if (totalProductCount > 0) {
text += " out of " + Long.toString(totalProductCount);
}
this.titleLabel.setText(text);
}
private String getTitle() {
return "Products";
}
private void resetOutputProducts() {
AbstractProductsRepositoryPanel selectedProductsRepositoryPanel = this.productListPanel.getRepositorySelectionPanel().getSelectedProductsRepositoryPanel();
selectedProductsRepositoryPanel.resetOutputProducts();
}
private void addComponents(ComponentDimension componentDimension, boolean showStopDownloadButton) {
int gapBetweenRows = 0;
int gapBetweenColumns = componentDimension.getGapBetweenColumns();
JPanel northPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.BOTH, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0);
northPanel.add(this.titleLabel, c);
c = SwingUtils.buildConstraints(1, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns);
northPanel.add(this.sortByLabel, c);
c = SwingUtils.buildConstraints(2, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns);
northPanel.add(this.comparatorsComboBox, c);
c = SwingUtils.buildConstraints(3, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns);
northPanel.add(this.sortingTypeComboBox, c);
c = SwingUtils.buildConstraints(4, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns);
northPanel.add(this.progressBarHelper.getProgressBar(), c);
if (showStopDownloadButton) {
c = SwingUtils.buildConstraints(5, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns);
northPanel.add(this.progressBarHelper.getStopButton(), c);
}
JScrollPane scrollPane = new JScrollPane(this.productListPanel);
scrollPane.getViewport().setOpaque(true);
scrollPane.getViewport().setBackground(this.productListPanel.getBackground());
scrollPane.setBorder(SwingUtils.LINE_BORDER);
add(northPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
add(this.productsTimelinePanel, BorderLayout.SOUTH);
}
private static ComparatorItem buildProductNameComparator() {
return new ComparatorItem("Product Name") {
@Override
public int compare(RepositoryProduct o1, RepositoryProduct o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
};
}
private static ComparatorItem buildAcquisitionDateComparator() {
return new ComparatorItem("Acquisition Date") {
@Override
public int compare(RepositoryProduct o1, RepositoryProduct o2) {
final LocalDateTime acquisitionDate1 = o1.getAcquisitionDate();
final LocalDateTime acquisitionDate2 = o2.getAcquisitionDate();
if (acquisitionDate1 == null && acquisitionDate2 == null) {
return 0; // both acquisition dates are null
}
if (acquisitionDate1 == null) {
return -1; // the first acquisition date is null
}
if (acquisitionDate2 == null) {
return 1; // the second acquisition date is null
}
return acquisitionDate1.compareTo(acquisitionDate2);
}
};
}
private static ComparatorItem buildMissionComparator() {
return new ComparatorItem("Mission") {
@Override
public int compare(RepositoryProduct leftProduct, RepositoryProduct rigtProduct) {
String leftMissionName = (leftProduct.getRemoteMission() == null) ? "" : leftProduct.getRemoteMission().getName();
String rightMissionName = (rigtProduct.getRemoteMission() == null) ? "" : rigtProduct.getRemoteMission().getName();
return leftMissionName.compareToIgnoreCase(rightMissionName);
}
};
}
private static ComparatorItem buildFileSizeComparator() {
return new ComparatorItem("File size") {
@Override
public int compare(RepositoryProduct o1, RepositoryProduct o2) {
long fileSize1 = o1.getApproximateSize();
long fileSize2 = o2.getApproximateSize();
if (fileSize1 == fileSize2) {
return 0;
}
if (fileSize1 < fileSize2) {
return -1;
}
return 1;
}
};
}
private static abstract class ComparatorItem implements Comparator<RepositoryProduct> {
private final String displayName;
private ComparatorItem(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
}
private static class ProductsComparator implements Comparator<RepositoryProduct> {
private final Comparator<RepositoryProduct> comparator;
private final boolean sortAscending;
public ProductsComparator(Comparator<RepositoryProduct> comparator, boolean sortAscending) {
this.comparator = comparator;
this.sortAscending = sortAscending;
}
@Override
public int compare(RepositoryProduct leftProduct, RepositoryProduct rightProduct) {
int result = this.comparator.compare(leftProduct, rightProduct);
return this.sortAscending ? result : -result;
}
}
}
| 26,950 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OutputProductResultsCallback.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/output/OutputProductResultsCallback.java | package org.esa.snap.product.library.ui.v2.repository.output;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import java.util.Comparator;
/**
* The callback interface to obtain the comparator to sort the products.
*
* Created by jcoravu on 30/1/2020.
*/
public interface OutputProductResultsCallback {
public Comparator<RepositoryProduct> getProductsComparator();
public OutputProductResults getOutputProductResults();
}
| 457 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OutputProductListModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/output/OutputProductListModel.java | package org.esa.snap.product.library.ui.v2.repository.output;
import org.esa.snap.product.library.ui.v2.repository.local.LocalProgressStatus;
import org.esa.snap.product.library.ui.v2.repository.remote.DownloadProgressStatus;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadingProductProgressCallback;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import java.nio.file.Path;
import java.util.*;
/**
* The model class to store the visible products of the current page.
*
* Created by jcoravu on 21/8/2019.
*/
public class OutputProductListModel {
private final OutputProductResultsCallback outputProductResultsCallback;
private List<RepositoryProduct> products;
private DownloadingProductProgressCallback downloadingProductProgressCallback;
public OutputProductListModel(OutputProductResultsCallback outputProductResultsCallback) {
super();
this.outputProductResultsCallback = outputProductResultsCallback;
this.products = new ArrayList<>();
}
protected void fireIntervalAdded(int startIndex, int endIndex) {
}
protected void fireIntervalRemoved(int startIndex, int endIndex) {
}
protected void fireIntervalChanged(int startIndex, int endIndex) {
}
public int getProductCount() {
return this.products.size();
}
public RepositoryProduct getProductAt(int index) {
return this.products.get(index);
}
public void setDownloadingProductProgressCallback(DownloadingProductProgressCallback downloadingProductProgressCallback) {
this.downloadingProductProgressCallback = downloadingProductProgressCallback;
}
public OutputProductResults getOutputProductResults() {
return this.outputProductResultsCallback.getOutputProductResults();
}
public List<RepositoryProduct> findProductsWithoutQuickLookImage() {
List<RepositoryProduct> result = new ArrayList<>();
for (int i=0; i<this.products.size(); i++) {
RepositoryProduct existingProduct = this.products.get(i);
if (existingProduct.getQuickLookImage() == null && existingProduct.getDownloadQuickLookImageURL() != null) {
result.add(existingProduct);
}
}
return result;
}
public void setProducts(List<RepositoryProduct> products) {
if (products.size() > 0) {
int oldProductCount = this.products.size();
int newProductCount = products.size();
this.products = new ArrayList<>(products);
if (this.products.size() > 1) {
Collections.sort(this.products, this.outputProductResultsCallback.getProductsComparator());
}
if (oldProductCount < newProductCount) {
if (oldProductCount > 0) {
fireIntervalChanged(0, oldProductCount - 1);
}
fireIntervalAdded(oldProductCount, newProductCount-1);
} else if (oldProductCount > newProductCount) {
fireIntervalRemoved(newProductCount, oldProductCount-1);
fireIntervalChanged(0, newProductCount - 1);
} else {
// the same count
fireIntervalChanged(0, newProductCount - 1);
}
} else {
clear();
}
}
public void sortProducts() {
if (this.products.size() > 1) {
Collections.sort(this.products, this.outputProductResultsCallback.getProductsComparator());
int startIndex = 0;
int endIndex = this.products.size() - 1;
fireIntervalChanged(startIndex, endIndex);
}
}
public Map<RepositoryProduct, Path> addPendingOpenDownloadedProducts(RepositoryProduct[] pendingOpenDownloadedProducts) {
Map<RepositoryProduct, Path> productsToOpen = new HashMap<>();
if (pendingOpenDownloadedProducts.length > 0) {
int startIndex = pendingOpenDownloadedProducts.length - 1;
int endIndex = 0;
for (int i=0; i<pendingOpenDownloadedProducts.length; i++) {
DownloadProgressStatus progressPercent = getOutputProductResults().getDownloadedProductProgress(pendingOpenDownloadedProducts[i]);
if (progressPercent != null && progressPercent.canOpen()) {
if (progressPercent.getDownloadedPath() == null) {
throw new NullPointerException("The downloaded path is null for product '" + pendingOpenDownloadedProducts[i].getName()+"'.");
}
progressPercent.setStatus(DownloadProgressStatus.PENDING_OPEN);
productsToOpen.put(pendingOpenDownloadedProducts[i], progressPercent.getDownloadedPath());
int index = findProductIndex(pendingOpenDownloadedProducts[i]);
if (index >= 0) {
if (startIndex > index) {
startIndex = index;
}
if (endIndex < index) {
endIndex = index;
}
}
}
}
if (productsToOpen.size() > 0) {
fireIntervalChanged(startIndex, endIndex);
}
}
return productsToOpen;
}
private Map<RepositoryProduct, LocalProgressStatus> getLocalProductsMap() {
return this.outputProductResultsCallback.getOutputProductResults().getLocalProductsMap();
}
public List<RepositoryProduct> addPendingOpenLocalProducts(RepositoryProduct[] pendingOpenProducts) {
return addPendingLocalProgressProducts(pendingOpenProducts, LocalProgressStatus.PENDING_OPEN);
}
public List<RepositoryProduct> addPendingCopyLocalProducts(RepositoryProduct[] pendingCopyProducts) {
return addPendingLocalProgressProducts(pendingCopyProducts, LocalProgressStatus.PENDING_COPY);
}
public List<RepositoryProduct> addPendingMoveLocalProducts(RepositoryProduct[] pendingMoveProducts) {
return addPendingLocalProgressProducts(pendingMoveProducts, LocalProgressStatus.PENDING_MOVE);
}
public List<RepositoryProduct> addPendingDeleteLocalProducts(RepositoryProduct[] pendingDeleteProducts) {
return addPendingLocalProgressProducts(pendingDeleteProducts, LocalProgressStatus.PENDING_DELETE);
}
public void setOpenDownloadedProductStatus(RepositoryProduct repositoryProduct, byte openStatus) {
DownloadProgressStatus progressPercent = getOutputProductResults().getDownloadedProductProgress(repositoryProduct);
if (progressPercent != null) {
progressPercent.setStatus(openStatus);
int index = findProductIndex(repositoryProduct);
if (index >= 0) {
fireIntervalChanged(index, index);
}
}
}
public void setLocalProductStatus(RepositoryProduct repositoryProduct, byte localStatus) {
LocalProgressStatus openProgressStatus = getLocalProductsMap().get(repositoryProduct);
if (openProgressStatus != null) {
openProgressStatus.setStatus(localStatus);
int index = findProductIndex(repositoryProduct);
if (index >= 0) {
if (localStatus == LocalProgressStatus.DELETED) {
this.products.remove(index);
fireIntervalRemoved(index, index);
} else {
fireIntervalChanged(index, index);
}
}
}
}
public void refreshProducts() {
if (this.products.size() > 0) {
fireIntervalChanged(0, this.products.size() - 1);
}
}
public void refreshProduct(RepositoryProduct repositoryProduct) {
int index = findProductIndex(repositoryProduct);
if (index >= 0) {
fireIntervalChanged(index, index); // the downloading product is visible in the current page
}
}
public void clear() {
int endIndex = this.products.size() - 1;
this.products = new ArrayList<>();
if (endIndex >= 0) {
fireIntervalRemoved(0, endIndex);
}
}
private List<RepositoryProduct> addPendingLocalProgressProducts(RepositoryProduct[] pendingLocalProducts, byte status) {
List<RepositoryProduct> productsToProcess = new ArrayList<>(pendingLocalProducts.length);
if (pendingLocalProducts.length > 0) {
int startIndex = pendingLocalProducts.length - 1;
int endIndex = 0;
for (int i=0; i<pendingLocalProducts.length; i++) {
LocalProgressStatus openProgressStatus = getLocalProductsMap().get(pendingLocalProducts[i]);
if (openProgressStatus == null ) {
getLocalProductsMap().put(pendingLocalProducts[i], new LocalProgressStatus(status));
} else {
openProgressStatus.setStatus(status);
}
productsToProcess.add(pendingLocalProducts[i]);
int index = findProductIndex(pendingLocalProducts[i]);
if (index >= 0) {
if (startIndex > index) {
startIndex = index;
}
if (endIndex < index) {
endIndex = index;
}
getLocalProductsMap().put(pendingLocalProducts[i], new LocalProgressStatus(status));
}
}
if (productsToProcess.size() > 0) {
fireIntervalChanged(startIndex, endIndex);
}
}
return productsToProcess;
}
private int findProductIndex(RepositoryProduct repositoryProductToFind) {
for (int i=0; i<this.products.size(); i++) {
if (this.products.get(i) == repositoryProductToFind) {
return i;
}
}
return -1;
}
}
| 9,998 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OutputProductResults.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/output/OutputProductResults.java | package org.esa.snap.product.library.ui.v2.repository.output;
import org.esa.snap.product.library.ui.v2.repository.local.LocalProgressStatus;
import org.esa.snap.product.library.ui.v2.repository.remote.DownloadProgressStatus;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The class contains the data about the available repository products to be displayed by pagination.
*
* Created by jcoravu on 30/1/2020.
*/
public class OutputProductResults {
public static final ImageIcon EMPTY_ICON;
static {
BufferedImage emptyImage = new BufferedImage(75, 75, BufferedImage.TYPE_INT_ARGB);
EMPTY_ICON = new ImageIcon(emptyImage);
}
private final Map<RepositoryProduct, ImageIcon> scaledQuickLookImages;
private final Map<RepositoryProduct, LocalProgressStatus> localProductsMap;
private final List<RepositoryProduct> availableProducts;
private final Map<RepositoryProduct, DownloadProgressStatus> downloadedProductsProgress;
private int currentPageNumber;
private long fullResultsListCount;
public OutputProductResults() {
this.scaledQuickLookImages = new HashMap<>();
this.localProductsMap = new HashMap<>();
this.downloadedProductsProgress = new HashMap<>();
this.availableProducts = new ArrayList<>();
this.currentPageNumber = 0;
this.fullResultsListCount = 0;
}
public boolean canDownloadProducts(RepositoryProduct[] productsToCheck){
if(!canOpenDownloadedProducts(productsToCheck)){
boolean canDownloadProducts = true;
for (int i=0; i<productsToCheck.length && canDownloadProducts; i++) {
if (productsToCheck[i].getURL() == null || productsToCheck[i].getURL().isEmpty()) {
// there is at leat one selected product which is not downloaded
canDownloadProducts = false;
}
}
return canDownloadProducts;
}
return false;
}
public boolean canOpenDownloadedProducts(RepositoryProduct[] productsToCheck) {
boolean canOpenProducts = true;
for (int i=0; i<productsToCheck.length && canOpenProducts; i++) {
DownloadProgressStatus downloadProgressStatus = getDownloadedProductProgress(productsToCheck[i]);
if (downloadProgressStatus == null || !downloadProgressStatus.canOpen()) {
// there is at leat one selected product which is not downloaded
canOpenProducts = false;
}
}
return canOpenProducts;
}
public DownloadProgressStatus getDownloadedProductProgress(RepositoryProduct repositoryProduct) {
return this.downloadedProductsProgress.get(repositoryProduct);
}
public void addDownloadedProductProgress(RepositoryProduct repositoryProduct, DownloadProgressStatus downloadProgressStatus) {
this.downloadedProductsProgress.put(repositoryProduct, downloadProgressStatus);
}
public LocalProgressStatus getOpeningProductStatus(RepositoryProduct repositoryProduct) {
return this.localProductsMap.get(repositoryProduct);
}
public Map<RepositoryProduct, LocalProgressStatus> getLocalProductsMap() {
return localProductsMap;
}
public ImageIcon getProductQuickLookImage(RepositoryProduct repositoryProduct) {
ImageIcon imageIcon = this.scaledQuickLookImages.get(repositoryProduct);
if (imageIcon == null) {
if (repositoryProduct.getQuickLookImage() == null) {
imageIcon = EMPTY_ICON;
} else {
Image scaledQuickLookImage = repositoryProduct.getQuickLookImage().getScaledInstance(EMPTY_ICON.getIconWidth(), EMPTY_ICON.getIconHeight(), BufferedImage.SCALE_FAST);
imageIcon = new ImageIcon(scaledQuickLookImage);
this.scaledQuickLookImages.put(repositoryProduct, imageIcon);
}
}
return imageIcon;
}
public void setCurrentPageNumber(int currentPageNumber) {
this.currentPageNumber = currentPageNumber;
}
public int getCurrentPageNumber() {
return this.currentPageNumber;
}
public long getFullResultsListCount() {
return fullResultsListCount;
}
public void setFullResultsListCount(long fullResultsListCount) {
this.fullResultsListCount = fullResultsListCount;
}
public int getAvailableProductCount() {
return this.availableProducts.size();
}
public void addProducts(List<RepositoryProduct> products) {
this.availableProducts.addAll(products);
}
public RepositoryProduct getProductAt(int index) {
return this.availableProducts.get(index);
}
}
| 4,924 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OutputProductListPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/output/OutputProductListPanel.java | package org.esa.snap.product.library.ui.v2.repository.output;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.product.library.ui.v2.RepositoryProductPanelBackground;
import org.esa.snap.product.library.ui.v2.repository.AbstractProductsRepositoryPanel;
import org.esa.snap.product.library.ui.v2.repository.AbstractRepositoryProductPanel;
import org.esa.snap.product.library.ui.v2.repository.RepositorySelectionPanel;
import org.esa.snap.remote.products.repository.geometry.AbstractGeometry2D;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.loading.SwingUtils;
import org.esa.snap.ui.loading.VerticalScrollablePanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Path2D;
import java.beans.PropertyChangeListener;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* The panel containing the displayed products of one page.
*
* Created by jcoravu on 23/9/2019.
*/
public class OutputProductListPanel extends VerticalScrollablePanel implements RepositoryProductPanelBackground {
private static final String LIST_SELECTION_CHANGED = "listSelectionChanged";
private static final String LIST_DATA_CHANGED = "listDataChanged";
private final ComponentDimension componentDimension;
private final Color backgroundColor;
private final Color selectionBackgroundColor;
private final MouseListener mouseListener;
private final RepositorySelectionPanel repositorySelectionPanel;
private final OutputProductListModel productListModel;
private Set<AbstractRepositoryProductPanel> selectedProductPanels;
public OutputProductListPanel(RepositorySelectionPanel repositorySelectionPanel, ComponentDimension componentDimension, OutputProductResultsCallback outputProductResultsCallback) {
super(null);
this.repositorySelectionPanel = repositorySelectionPanel;
this.componentDimension = componentDimension;
this.selectedProductPanels = new HashSet<>();
this.productListModel = new OutputProductListModel(outputProductResultsCallback) {
@Override
protected void fireIntervalAdded(int startIndex, int endIndex) {
performProductsAdded(startIndex, endIndex);
}
@Override
protected void fireIntervalRemoved(int startIndex, int endIndex) {
performProductsRemoved(startIndex, endIndex);
}
@Override
protected void fireIntervalChanged(int startIndex, int endIndex) {
performProductsChanged(startIndex, endIndex);
}
};
JList list = new JList();
this.backgroundColor = list.getBackground();
this.selectionBackgroundColor = list.getSelectionBackground();
this.mouseListener = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
if (SwingUtilities.isLeftMouseButton(mouseEvent)) {
leftMouseClicked(mouseEvent);
} else if (SwingUtilities.isRightMouseButton(mouseEvent)) {
rightMouseClicked(mouseEvent);
}
}
};
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setOpaque(true);
setBackground(this.backgroundColor);
}
@Override
public Map<String, String> getRemoteMissionVisibleAttributes(String mission) {
return this.repositorySelectionPanel.getRemoteMissionVisibleAttributes(mission);
}
@Override
public Color getProductPanelBackground(AbstractRepositoryProductPanel productPanel) {
if (this.selectedProductPanels.contains(productPanel)) {
return this.selectionBackgroundColor;
}
return this.backgroundColor;
}
@Override
public RepositoryProduct getProductPanelItem(AbstractRepositoryProductPanel repositoryProductPanelToFind) {
for (int i=0; i<getComponentCount(); i++) {
AbstractRepositoryProductPanel repositoryProductPanel = (AbstractRepositoryProductPanel) getComponent(i);
if (repositoryProductPanel == repositoryProductPanelToFind) {
return this.productListModel.getProductAt(i);
}
}
return null;
}
public RepositorySelectionPanel getRepositorySelectionPanel() {
return repositorySelectionPanel;
}
public OutputProductListModel getProductListModel() {
return productListModel;
}
public void setProducts(List<RepositoryProduct> products) {
this.selectedProductPanels = new HashSet<>();
revalidate();
repaint();
firePropertyChange(LIST_SELECTION_CHANGED, null, null);
this.productListModel.setProducts(products);
}
private void performProductsChanged(int startIndex, int endIndex) {
if (startIndex < 0) {
throw new IllegalArgumentException("The start index " + startIndex +" is negative.");
}
int productPanelCount = getComponentCount();
if (endIndex >= productPanelCount) {
throw new IllegalArgumentException("The end index " + endIndex +" cannot be >= the product panel count " + productPanelCount +".");
}
boolean fireListSelectionChanged = false;
for (int i=startIndex; i<=endIndex; i++) {
AbstractRepositoryProductPanel repositoryProductPanel = (AbstractRepositoryProductPanel) getComponent(i);
repositoryProductPanel.refresh(this.productListModel.getOutputProductResults());
if (this.selectedProductPanels.contains(repositoryProductPanel)) {
fireListSelectionChanged = true;
}
}
revalidate();
repaint();
fireBothListeners(fireListSelectionChanged);
}
private void performProductsAdded(int startIndex, int endIndex) {
AbstractProductsRepositoryPanel selectedProductsRepositoryPanel = this.repositorySelectionPanel.getSelectedProductsRepositoryPanel();
for (int i=startIndex; i<=endIndex; i++) {
AbstractRepositoryProductPanel repositoryProductPanel = selectedProductsRepositoryPanel.buildProductProductPanel(this, this.componentDimension);
repositoryProductPanel.setOpaque(true);
repositoryProductPanel.setBackground(this.backgroundColor);
repositoryProductPanel.addMouseListener(this.mouseListener);
add(repositoryProductPanel);
repositoryProductPanel.refresh(this.productListModel.getOutputProductResults());
}
revalidate();
repaint();
firePropertyChange(LIST_DATA_CHANGED, null, null);
}
private void performProductsRemoved(int startIndex, int endIndex) {
if (startIndex < 0) {
throw new IllegalArgumentException("The start index " + startIndex +" is negative.");
}
int productPanelCount = getComponentCount();
if (endIndex >= productPanelCount) {
throw new IllegalArgumentException("The end index " + endIndex +" cannot be >= the product panel count " + productPanelCount +".");
}
boolean fireListSelectionChanged = false;
for (int i=endIndex; i>=startIndex; i--) {
AbstractRepositoryProductPanel repositoryProductPanel = (AbstractRepositoryProductPanel) getComponent(i);
if (this.selectedProductPanels.remove(repositoryProductPanel)) {
fireListSelectionChanged = true;
}
remove(i);
}
revalidate();
repaint();
fireBothListeners(fireListSelectionChanged);
}
private void fireBothListeners(boolean fireListSelectionChanged) {
firePropertyChange(LIST_DATA_CHANGED, null, null);
if (fireListSelectionChanged) {
firePropertyChange(LIST_SELECTION_CHANGED, null, null);
}
}
public RepositoryProduct[] getSelectedProducts() {
RepositoryProduct[] selectedProducts = new RepositoryProduct[this.selectedProductPanels.size()];
for (int i=0, k=0; i<getComponentCount(); i++) {
AbstractRepositoryProductPanel repositoryProductPanel = (AbstractRepositoryProductPanel) getComponent(i);
if (this.selectedProductPanels.contains(repositoryProductPanel)) {
selectedProducts[k++] = repositoryProductPanel.getRepositoryProduct();
}
}
return selectedProducts;
}
public Path2D.Double[] getPolygonPaths() {
int totalPathCount = 0;
for (int i=0; i<this.productListModel.getProductCount(); i++) {
AbstractGeometry2D productGeometry = this.productListModel.getProductAt(i).getPolygon();
if (productGeometry != null) {
totalPathCount += productGeometry.getPathCount();
}
}
Path2D.Double[] polygonPaths = new Path2D.Double[totalPathCount];
for (int i=0, index=0; i<this.productListModel.getProductCount(); i++) {
AbstractGeometry2D productGeometry = this.productListModel.getProductAt(i).getPolygon();
for (int p = 0; productGeometry != null && p < productGeometry.getPathCount(); p++) {
polygonPaths[index++] = productGeometry.getPathAt(p);
}
}
return polygonPaths;
}
public void selectProductsByPolygonPath(List<Path2D.Double> polygonPaths) {
int count = 0;
int productListSize = this.productListModel.getProductCount();
for (int k=0; k<polygonPaths.size(); k++) {
AbstractRepositoryProductPanel foundRepositoryProductPanel = null;
for (int i=0; i<productListSize && foundRepositoryProductPanel == null; i++) {
AbstractGeometry2D productGeometry = this.productListModel.getProductAt(i).getPolygon();
for (int p=0; productGeometry != null && p<productGeometry.getPathCount(); p++) {
if (productGeometry.getPathAt(p) == polygonPaths.get(k)) {
foundRepositoryProductPanel = (AbstractRepositoryProductPanel) getComponent(i);
break;
}
}
}
if (foundRepositoryProductPanel != null) {
if (count == 0) {
this.selectedProductPanels.clear();
}
count++;
this.selectedProductPanels.add(foundRepositoryProductPanel);
scrollRectToVisible(foundRepositoryProductPanel.getBounds());
fireProductsSelectionChanged();
} else {
throw new IllegalArgumentException("The polygon path does not exist in the list.");
}
}
}
private void rightMouseClicked(MouseEvent mouseEvent) {
AbstractRepositoryProductPanel repositoryProductPanel = (AbstractRepositoryProductPanel) mouseEvent.getSource();
if (!this.selectedProductPanels.contains(repositoryProductPanel)) {
// clear the previous selected products
this.selectedProductPanels.clear();
//mark as selected the clicked panel product
this.selectedProductPanels.add(repositoryProductPanel);
fireProductsSelectionChanged();
}
showProductsPopupMenu(repositoryProductPanel, mouseEvent.getX(), mouseEvent.getY());
}
private void leftMouseClicked(MouseEvent mouseEvent) {
AbstractRepositoryProductPanel repositoryProductPanel = (AbstractRepositoryProductPanel) mouseEvent.getSource();
if (mouseEvent.isControlDown()) {
if (!this.selectedProductPanels.add(repositoryProductPanel)) {
// the panel is already selected
this.selectedProductPanels.remove(repositoryProductPanel);
}
} else {
// clear already selected panels
this.selectedProductPanels.clear();
// select the clicked panel
this.selectedProductPanels.add(repositoryProductPanel);
}
fireProductsSelectionChanged();
}
public void selectAllProducts() {
for (int i=0; i<getComponentCount(); i++) {
AbstractRepositoryProductPanel repositoryProductPanel = (AbstractRepositoryProductPanel) getComponent(i);
this.selectedProductPanels.add(repositoryProductPanel);
}
fireProductsSelectionChanged();
}
public void clearSelection() {
this.selectedProductPanels.clear();
fireProductsSelectionChanged();
}
private void fireProductsSelectionChanged() {
repaint();
firePropertyChange(LIST_SELECTION_CHANGED, null, null);
}
public void addDataChangedListener(PropertyChangeListener listDataChangedListener) {
addPropertyChangeListener(LIST_DATA_CHANGED, listDataChangedListener);
}
public void addSelectionChangedListener(PropertyChangeListener listSelectionChangedListener) {
addPropertyChangeListener(LIST_SELECTION_CHANGED, listSelectionChangedListener);
}
private void showProductsPopupMenu(AbstractRepositoryProductPanel repositoryProductPanel, int mouseX, int mouseY) {
JPopupMenu popup = this.repositorySelectionPanel.getSelectedProductsRepositoryPanel().buildProductListPopupMenu(getSelectedProducts(), this.productListModel);
popup.show(repositoryProductPanel, mouseX, mouseY);
}
}
| 13,608 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CustomPasswordField.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/input/CustomPasswordField.java | package org.esa.snap.product.library.ui.v2.repository.input;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.*;
import java.awt.*;
public class CustomPasswordField extends JPasswordField {
private final int preferredHeight;
CustomPasswordField(int preferredHeight, Color backgroundColor) {
super();
if (preferredHeight <= 0) {
throw new IllegalArgumentException("The preferred size " + preferredHeight + " must be > 0.");
}
if (backgroundColor == null) {
throw new NullPointerException("The background color is null.");
}
this.preferredHeight = preferredHeight;
setBackground(backgroundColor);
setBorder(SwingUtils.LINE_BORDER);
}
@Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, this.preferredHeight);
}
@Override
public Dimension getMinimumSize() {
Dimension size = super.getMinimumSize();
size.height = this.preferredHeight;
return size;
}
@Override
public Dimension getMaximumSize() {
Dimension size = super.getMaximumSize();
size.height = this.preferredHeight;
return size;
}
@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.height = this.preferredHeight;
return size;
}
}
| 1,433 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
StringComboBoxParameterComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/input/StringComboBoxParameterComponent.java | package org.esa.snap.product.library.ui.v2.repository.input;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.*;
/**
* The parameter component allows the user to select a value from a combo box for the search parameter.
*
* Created by jcoravu on 7/8/2019.
*/
public class StringComboBoxParameterComponent extends AbstractParameterComponent<String> {
private final JComboBox<String> readOnlyComboBox;
public StringComboBoxParameterComponent(String parameterName, String defaultValue, String parameterLabelText,
boolean required, String[] values, ComponentDimension componentDimension) {
super(parameterName, parameterLabelText, required);
this.readOnlyComboBox = SwingUtils.buildComboBox(values, defaultValue, componentDimension.getTextFieldPreferredHeight(), false);
this.readOnlyComboBox.setBackground(componentDimension.getTextFieldBackgroundColor());
}
@Override
public JComponent getComponent() {
return this.readOnlyComboBox;
}
@Override
public void setParameterValue(Object value) {
if (value == null) {
clearParameterValue();
} else if (value instanceof String) {
this.readOnlyComboBox.setSelectedItem(value);
} else {
throw new ClassCastException("The parameter value type '" + value + "' must be '" + String.class+"'.");
}
}
@Override
public String getParameterValue() {
return getSelectedItem();
}
@Override
public void clearParameterValue() {
this.readOnlyComboBox.setSelectedItem(null);
}
@Override
public Boolean hasValidValue() {
String value = getSelectedItem();
if (value == null) {
return null; // the value is not specified
}
return true; // the value is specified and it is valid
}
private String getSelectedItem() {
return (String)this.readOnlyComboBox.getModel().getSelectedItem();
}
}
| 2,091 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SecretStringParameterComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/input/SecretStringParameterComponent.java | package org.esa.snap.product.library.ui.v2.repository.input;
import java.awt.*;
/**
* The text field parameter component allows the user to enter a value for the search parameter.
*
* Created by jcoravu on 7/8/2019.
*/
public class SecretStringParameterComponent extends PasswordFieldParameterComponent<String> {
SecretStringParameterComponent(String parameterName, String defaultValue, String parameterLabelText, boolean required, int textFieldPreferredHeight, Color backgroundColor) {
super(parameterName, parameterLabelText, required, textFieldPreferredHeight, backgroundColor);
if (defaultValue != null) {
this.passwordField.setText(defaultValue);
}
}
@Override
public String getParameterValue() {
String value = getPassword();
return (value.length() > 0 ? value : null);
}
@Override
public void setParameterValue(Object value) {
if (value == null) {
clearParameterValue();
} else if (value instanceof String) {
this.passwordField.setText((String) value);
} else {
throw new ClassCastException("The parameter value type '" + value + "' must be '" + String.class + "'.");
}
}
@Override
public Boolean hasValidValue() {
String value = getPassword();
if (value.length() > 0) {
return true; // the value is specified and it is valid
}
return null; // the value is not specified
}
}
| 1,501 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractParameterComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/input/AbstractParameterComponent.java | package org.esa.snap.product.library.ui.v2.repository.input;
import javax.swing.*;
/**
* The base class for a search parameter component.
*
* Created by jcoravu on 7/8/2019.
*/
public abstract class AbstractParameterComponent<ValueType> {
private final String parameterName;
private final JLabel label;
private final boolean required;
protected AbstractParameterComponent(String parameterName, String parameterLabelText, boolean required) {
this.parameterName = parameterName;
this.required = required;
this.label = new JLabel(parameterLabelText);
}
public abstract JComponent getComponent();
public abstract ValueType getParameterValue();
public abstract void clearParameterValue();
public abstract void setParameterValue(Object value);
public abstract Boolean hasValidValue();
public String getParameterName() {
return parameterName;
}
public JLabel getLabel() {
return label;
}
public String getRequiredValueErrorDialogMessage() {
if (this.required) {
return "The '" + this.label.getText()+"' parameter value is required.";
}
return null;
}
public String getInvalidValueErrorDialogMessage() {
return null;
}
}
| 1,286 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ParametersPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/input/ParametersPanel.java | package org.esa.snap.product.library.ui.v2.repository.input;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.remote.products.repository.RepositoryQueryParameter;
import org.esa.snap.ui.loading.SwingUtils;
import org.esa.snap.ui.loading.VerticalScrollablePanel;
import java.awt.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* The panel contains the search parameters of a repository.
*
* Created by jcoravu on 18/9/2019.
*/
public class ParametersPanel extends VerticalScrollablePanel {
public ParametersPanel() {
super(new GridBagLayout());
}
public List<AbstractParameterComponent<?>> addParameterComponents(List<RepositoryQueryParameter> parameters, int startRowIndex, int startGapBetweenRows,
ComponentDimension componentDimension, Class<?>[] classesToIgnore) {
int gapBetweenColumns = componentDimension.getGapBetweenColumns();
int gapBetweenRows = componentDimension.getGapBetweenRows();
int textFieldPreferredHeight = componentDimension.getTextFieldPreferredHeight();
Color textFieldBackgroundColor = componentDimension.getTextFieldBackgroundColor();
List<AbstractParameterComponent<?>> parameterComponents = new ArrayList<AbstractParameterComponent<?>>();
for (int i=0; i<parameters.size(); i++) {
RepositoryQueryParameter param = parameters.get(i);
AbstractParameterComponent parameterComponent = null;
if (param.getType() == String.class) {
// the parameter type is string
String defaultValue = (param.getDefaultValue() == null) ? null : (String)param.getDefaultValue();
if (param.getValueSet() == null) {
if(param.getName().toLowerCase().contentEquals("password")){
parameterComponent = new SecretStringParameterComponent(param.getName(), defaultValue, param.getLabel(), param.isRequired(), textFieldPreferredHeight, textFieldBackgroundColor);
} else {
parameterComponent = new StringParameterComponent(param.getName(), defaultValue, param.getLabel(), param.isRequired(), textFieldPreferredHeight, textFieldBackgroundColor);
}
} else {
Object[] defaultValues = param.getValueSet();
String[] values = new String[defaultValues.length + 1];
for (int k=0; k<defaultValues.length; k++) {
values[k+1] = defaultValues[k].toString();
}
parameterComponent = new StringComboBoxParameterComponent(param.getName(), defaultValue, param.getLabel(), param.isRequired(), values, componentDimension);
}
} else if (param.getType() == Double.class || param.getType() == double.class || param.getType() == Float.class || param.getType() == float.class || param.getType() == Integer.class || param.getType() == int.class || param.getType() == Short.class || param.getType() == short.class ) {
// the parameter type is number
Number defaultValue = (param.getDefaultValue() == null) ? null : (Number)param.getDefaultValue();
parameterComponent = new NumberParameterComponent(param.getName(), param.getType(), defaultValue, param.getLabel(), param.isRequired(), textFieldPreferredHeight, textFieldBackgroundColor);
} else if (param.getType() == LocalDateTime.class || param.getType() == LocalDateTime[].class) {
parameterComponent = new DateParameterComponent(param.getName(), param.getLabel(), param.isRequired(), textFieldPreferredHeight, textFieldBackgroundColor);
} else if (param.getType() == String[].class) {
String defaultValue = (param.getDefaultValue() == null) ? null : param.getDefaultValue().toString();
if(param.getName().toLowerCase().contentEquals("password")){
parameterComponent = new SecretStringParameterComponent(param.getName(), defaultValue, param.getLabel(), param.isRequired(), textFieldPreferredHeight, textFieldBackgroundColor);
}else {
parameterComponent = new StringParameterComponent(param.getName(), defaultValue, param.getLabel(), param.isRequired(), textFieldPreferredHeight, textFieldBackgroundColor);
}
} else {
boolean found = false;
for (int k=0; k<classesToIgnore.length; k++) {
if (classesToIgnore[k] == param.getType()) {
found = true;
}
}
if (!found) {
throw new IllegalArgumentException("Unknown parameter: name: '" + param.getName() + "', type: '" + param.getType() + "', label: '" + param.getLabel() + "'.");
}
}
if (parameterComponent != null) {
int rowIndex = startRowIndex + parameterComponents.size();
parameterComponents.add(parameterComponent);
int topMargin = (rowIndex == startRowIndex) ? startGapBetweenRows : gapBetweenRows;
GridBagConstraints c = SwingUtils.buildConstraints(0, rowIndex, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, topMargin, 0);
add(parameterComponent.getLabel(), c);
c = SwingUtils.buildConstraints(1, rowIndex, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, topMargin, gapBetweenColumns);
add(parameterComponent.getComponent(), c);
rowIndex++;
}
}
return parameterComponents;
}
}
| 5,809 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SelectionAreaParameterComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/input/SelectionAreaParameterComponent.java | package org.esa.snap.product.library.ui.v2.repository.input;
import org.esa.snap.worldwind.productlibrary.WorldMapPanelWrapper;
import javax.swing.*;
import java.awt.geom.Rectangle2D;
/**
* The parameter component allows the user to select an area from the earth globe panel for the search parameter.
*
* Created by jcoravu on 7/8/2019.
*/
public class SelectionAreaParameterComponent extends AbstractParameterComponent<Rectangle2D> {
private final WorldMapPanelWrapper worldMapPanelWrapper;
public SelectionAreaParameterComponent(WorldMapPanelWrapper worlWindPanel, String parameterName, String parameterLabelText, boolean required) {
super(parameterName, parameterLabelText, required);
this.worldMapPanelWrapper = worlWindPanel;
}
@Override
public JComponent getComponent() {
return this.worldMapPanelWrapper;
}
@Override
public Rectangle2D getParameterValue() {
return this.worldMapPanelWrapper.getSelectedArea();
}
@Override
public void clearParameterValue() {
this.worldMapPanelWrapper.clearSelectedArea();
}
@Override
public void setParameterValue(Object value) {
if (value == null) {
clearParameterValue();
} else if (value instanceof Rectangle2D) {
this.worldMapPanelWrapper.setSelectedArea((Rectangle2D)value);
} else {
throw new ClassCastException("The parameter value type '" + value + "' must be '" + Rectangle2D.class+"'.");
}
}
@Override
public Boolean hasValidValue() {
Rectangle2D selectedArea = this.worldMapPanelWrapper.getSelectedArea();
if (selectedArea == null) {
return null; // the value is not specified
}
return true; // the value is specified
}
}
| 1,812 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
StringParameterComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/input/StringParameterComponent.java | package org.esa.snap.product.library.ui.v2.repository.input;
import javax.swing.*;
import java.awt.*;
/**
* The text field parameter component allows the user to enter a value for the search parameter.
*
* Created by jcoravu on 7/8/2019.
*/
public class StringParameterComponent extends TextFieldParameterComponent<String> {
public StringParameterComponent(String parameterName, String defaultValue, String parameterLabelText, boolean required, int textFieldPreferredHeight, Color backgroundColor) {
super(parameterName, parameterLabelText, required, textFieldPreferredHeight, backgroundColor);
if (defaultValue != null) {
this.textField.setText(defaultValue);
}
}
@Override
public String getParameterValue() {
String value = getText();
return (value.length() > 0 ? value : null);
}
@Override
public void setParameterValue(Object value) {
if (value == null) {
clearParameterValue();
} else if (value instanceof String) {
this.textField.setText((String) value);
} else {
throw new ClassCastException("The parameter value type '" + value + "' must be '" + String.class + "'.");
}
}
@Override
public Boolean hasValidValue() {
String value = getText();
if (value.length() > 0) {
return true; // the value is specified and it is valid
}
return null; // the value is not specified
}
}
| 1,498 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
NumberParameterComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/input/NumberParameterComponent.java | package org.esa.snap.product.library.ui.v2.repository.input;
import java.awt.*;
/**
* The text field parameter component allows the user to enter a number for the search parameter.
*
* Created by jcoravu on 17/2/2020.
*/
public class NumberParameterComponent extends TextFieldParameterComponent<Number> {
private final Class<?> parameterType;
public NumberParameterComponent(String parameterName, Class<?> parameterType, Number defaultValue, String parameterLabelText, boolean required, int textFieldPreferredHeight, Color backgroundColor) {
super(parameterName, parameterLabelText, required, textFieldPreferredHeight, backgroundColor);
this.parameterType = parameterType;
if (defaultValue != null) {
this.textField.setText(defaultValue.toString());
}
}
@Override
public Boolean hasValidValue() {
String value = getText();
if (value.length() > 0) {
// the value is specified
try {
convertValue(value);
// the value is valid
return true;
} catch (NumberFormatException exception) {
return false; // the value is invalid
}
}
// the value is not specified
return null;
}
@Override
public String getInvalidValueErrorDialogMessage() {
return "The '" + getLabel().getText()+"' parameter value '"+getText()+"' is invalid.";
}
@Override
public Number getParameterValue() {
String value = getText();
if (value.length() > 0) {
return convertValue(value);
}
return null;
}
@Override
public void setParameterValue(Object value) {
if (value == null) {
clearParameterValue();
} else if (value instanceof Number) {
this.textField.setText(value.toString());
} else {
throw new ClassCastException("The parameter value type '" + value + "' must be '" + Number.class + "'.");
}
}
private Number convertValue(String value) {
if (this.parameterType == Double.class || this.parameterType == double.class) {
return Double.parseDouble(value);
}
if (this.parameterType == Float.class || this.parameterType == float.class) {
return Float.parseFloat(value);
}
if (this.parameterType == Short.class || this.parameterType == short.class) {
return Short.parseShort(value);
}
if (this.parameterType == Integer.class || this.parameterType == int.class) {
return Integer.parseInt(value);
}
throw new IllegalStateException("Unknown parameter type '" + this.parameterType + "'.");
}
}
| 2,768 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DateParameterComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/input/DateParameterComponent.java | package org.esa.snap.product.library.ui.v2.repository.input;
import org.esa.snap.ui.components.DatePickerComboBox;
import javax.swing.*;
import java.awt.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
* The parameter component allows the user to select a date for the search parameter.
*
* Created by jcoravu on 7/8/2019.
*/
public class DateParameterComponent extends AbstractParameterComponent<LocalDateTime> {
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
private final DatePickerComboBox datePickerComboBox;
public DateParameterComponent(String parameterName, String parameterLabelText, boolean required, int textFieldPreferredHeight, Color backgroundColor) {
super(parameterName, parameterLabelText, required);
this.datePickerComboBox = new DatePickerComboBox(textFieldPreferredHeight, backgroundColor, DATE_FORMAT);
}
@Override
public JComponent getComponent() {
return this.datePickerComboBox;
}
@Override
public LocalDateTime getParameterValue() {
return this.datePickerComboBox.getDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
@Override
public void setParameterValue(Object value) {
if (value == null) {
clearParameterValue();
} else if (value instanceof LocalDateTime) {
final LocalDateTime localDateTime = (LocalDateTime) value;
this.datePickerComboBox.setDate(Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()));
} else {
throw new ClassCastException("The parameter value type '" + value + "' must be '" + LocalDateTime.class+"'.");
}
}
@Override
public void clearParameterValue() {
this.datePickerComboBox.setDate(null);
}
@Override
public Boolean hasValidValue() {
String dateAsString = this.datePickerComboBox.getEnteredDateAsString();
if (dateAsString.length() > 0) {
try {
DATE_FORMAT.parse(dateAsString);
return true;
} catch (ParseException e) {
return false;
}
}
return null; // the value is not specified
}
@Override
public String getInvalidValueErrorDialogMessage() {
return "The '" + getLabel().getText()+"' parameter value '"+this.datePickerComboBox.getEnteredDateAsString()+"' is invalid.";
}
}
| 2,583 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PasswordFieldParameterComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/input/PasswordFieldParameterComponent.java | package org.esa.snap.product.library.ui.v2.repository.input;
import javax.swing.*;
import java.awt.*;
/**
* The text field parameter component allows the user to enter a value for the search parameter.
*
* Created by jcoravu on 7/8/2019.
*/
public abstract class PasswordFieldParameterComponent<ValueType> extends AbstractParameterComponent<ValueType> {
protected final CustomPasswordField passwordField;
protected PasswordFieldParameterComponent(String parameterName, String parameterLabelText, boolean required, int textFieldPreferredHeight, Color backgroundColor) {
super(parameterName, parameterLabelText, required);
this.passwordField = new CustomPasswordField(textFieldPreferredHeight, backgroundColor);
}
@Override
public JComponent getComponent() {
return this.passwordField;
}
@Override
public void clearParameterValue() {
this.passwordField.setText("");
}
protected final String getPassword() {
return new String(this.passwordField.getPassword()).trim();
}
}
| 1,065 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TextFieldParameterComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/input/TextFieldParameterComponent.java | package org.esa.snap.product.library.ui.v2.repository.input;
import org.esa.snap.ui.components.CustomTextField;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.*;
import java.awt.*;
/**
* The text field parameter component allows the user to enter a value for the search parameter.
*
* Created by jcoravu on 7/8/2019.
*/
public abstract class TextFieldParameterComponent<ValueType> extends AbstractParameterComponent<ValueType> {
protected final CustomTextField textField;
protected TextFieldParameterComponent(String parameterName, String parameterLabelText, boolean required, int textFieldPreferredHeight, Color backgroundColor) {
super(parameterName, parameterLabelText, required);
this.textField = new CustomTextField(textFieldPreferredHeight, backgroundColor);
}
@Override
public JComponent getComponent() {
return this.textField;
}
@Override
public void clearParameterValue() {
this.textField.setText("");
}
protected final String getText() {
return this.textField.getText().trim();
}
}
| 1,104 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ReadLocalProductsTimerRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/ReadLocalProductsTimerRunnable.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.dataio.ProductReader;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.product.library.ui.v2.thread.AbstractProgressTimerRunnable;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.product.library.ui.v2.thread.ThreadCallback;
import org.esa.snap.product.library.v2.database.model.LocalRepositoryProduct;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* The thread to read a product list.
*
* Created by jcoravu on 21/7/2020.
*/
public class ReadLocalProductsTimerRunnable extends AbstractProgressTimerRunnable<Product[]> {
private final RepositoryProduct[] productsToRead;
private final ThreadCallback<Product[]> threadCallback;
public ReadLocalProductsTimerRunnable(ProgressBarHelper progressPanel, int threadId, RepositoryProduct[] productsToRead,
ThreadCallback<Product[]> threadCallback) {
super(progressPanel, threadId, 500);
this.productsToRead = productsToRead;
this.threadCallback = threadCallback;
}
@Override
protected boolean onTimerWakeUp(String message) {
return super.onTimerWakeUp("Read "+this.productsToRead.length+" local products...");
}
@Override
protected Product[] execute() throws Exception {
Product[] products = new Product[this.productsToRead.length];
for (int i=0; i<this.productsToRead.length; i++) {
LocalRepositoryProduct repositoryProduct = (LocalRepositoryProduct)this.productsToRead[i];
// check if the local product exists on the disk
if (Files.exists(repositoryProduct.getPath())) {
// the product exists on the local disk
//TODO Jean temporary method until the Landsat8 product reader will be changed to read the product from a folder
Path productPath = RemoteProductsRepositoryProvider.prepareProductPathToOpen(repositoryProduct.getPath(), repositoryProduct);
File productFile = productPath.toFile();
//TODO Jean old code to get the product path to open
//File productFile = repositoryProduct.getPath().toFile();
ProductReader productReader = ProductIO.getProductReaderForInput(productFile);
if (productReader == null) {
// no product reader found in the application
throw new IllegalStateException("No product reader found in the application for file '" + productFile.getAbsolutePath()+"'.");
} else {
// there is a product reader in the application
Product product = productReader.readProductNodes(productFile, null);
if (product == null) {
// the product has not been read
throw new NullPointerException("The product '" + repositoryProduct.getName() + "' has not been read from '" + productFile.getAbsolutePath()+"'.");
} else {
// the product has been read
products[i] = product;
}
}
} else {
// the product does not exist into the local repository folder
throw new IllegalStateException("The product '" + repositoryProduct.getPath() + "' does not exist into the local repository folder.");
}
}
return products;
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to read the local products.";
}
@Override
protected void onFailed(Exception exception) {
this.threadCallback.onFailed(exception);
}
@Override
protected void onSuccessfullyFinish(Product[] result) {
this.threadCallback.onSuccessfullyFinish(result);
}
}
| 4,154 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LocalInputParameterValues.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/LocalInputParameterValues.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.product.library.v2.database.model.LocalRepositoryFolder;
import java.util.Map;
/**
* The data of the search parameters for a local repository.
*
* Created by jcoravu on 6/2/2020.
*/
public class LocalInputParameterValues {
private final Map<String, Object> parameterValues;
private final String missionName;
private final LocalRepositoryFolder localRepositoryFolder;
public LocalInputParameterValues(Map<String, Object> parameterValues, String missionName, LocalRepositoryFolder localRepositoryFolder) {
this.parameterValues = parameterValues;
this.missionName = missionName;
this.localRepositoryFolder = localRepositoryFolder;
}
public String getMissionName() {
return missionName;
}
public Object getParameterValue(String parameterName) {
return this.parameterValues.get(parameterName);
}
public LocalRepositoryFolder getLocalRepositoryFolder() {
return localRepositoryFolder;
}
}
| 1,068 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DeleteLocalProductsRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/DeleteLocalProductsRunnable.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.product.library.v2.database.AllLocalFolderProductsRepository;
import org.esa.snap.product.library.v2.database.model.LocalRepositoryProduct;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.AppContext;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread to delete local products from the local repository.
*
* Created by jcoravu on 27/9/2019.
*/
public class DeleteLocalProductsRunnable extends AbstractProcessLocalProductsRunnable {
private static final Logger logger = Logger.getLogger(DeleteLocalProductsRunnable.class.getName());
private final AllLocalFolderProductsRepository allLocalFolderProductsRepository;
public DeleteLocalProductsRunnable(ProgressBarHelper progressPanel, int threadId, RepositoryOutputProductListPanel repositoryProductListPanel,
List<RepositoryProduct> productsToDelete, AllLocalFolderProductsRepository allLocalFolderProductsRepository) {
super(progressPanel, threadId, repositoryProductListPanel, productsToDelete);
this.allLocalFolderProductsRepository = allLocalFolderProductsRepository;
}
@Override
protected boolean onTimerWakeUp(String message) {
return super.onTimerWakeUp("Delete local products...");
}
@Override
protected Void execute() throws Exception {
for (int i = 0; i<this.productsToProcess.size(); i++) {
LocalRepositoryProduct repositoryProduct = (LocalRepositoryProduct)this.productsToProcess.get(i);
try {
updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.DELETING);
//FileIOUtils.deleteFolder(repositoryProduct.getPath());
this.allLocalFolderProductsRepository.deleteProduct(repositoryProduct);
updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.DELETED);
} catch (Exception exception) {
updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.FAIL_DELETED);
logger.log(Level.SEVERE, "Failed to delete the local product '" + repositoryProduct.getURL() + "'.", exception);
}
}
return null;
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to delete the product from the local repository folder and the database.";
}
}
| 2,696 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExportLocalProductListPathsRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/ExportLocalProductListPathsRunnable.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.product.library.ui.v2.thread.AbstractRunnable;
import javax.swing.*;
import java.awt.*;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* The thread to write in a text file the paths of the product list.
*
* Created by jcoravu on 4/3/2020.
*/
public class ExportLocalProductListPathsRunnable extends AbstractRunnable<Void> {
private final Component parentDialogComponent;
private final Path filePath;
private final Path[] localProductPaths;
public ExportLocalProductListPathsRunnable(Component parentDialogComponent, Path filePath, Path[] localProductPaths) {
if (parentDialogComponent == null) {
throw new NullPointerException("The parent component dialog is null.");
}
if (filePath == null) {
throw new NullPointerException("The file path is null.");
}
if (parentDialogComponent == null) {
throw new NullPointerException("The local product paths array is null.");
}
this.parentDialogComponent = parentDialogComponent;
this.filePath = filePath;
this.localProductPaths = localProductPaths;
}
@Override
protected Void execute() throws Exception {
try (OutputStream outputStream = Files.newOutputStream(this.filePath)) {
try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream)) {
try (BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter)) {
for (int i=0; i<this.localProductPaths.length; i++) {
bufferedWriter.write(this.localProductPaths[i].toString());
bufferedWriter.newLine();
}
}
}
}
return null;
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to export the local product list paths.";
}
@Override
protected void failedExecuting(Exception exception) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
onFailedExecuting();
}
});
}
private void onFailedExecuting() {
StringBuilder message = new StringBuilder();
message.append("The product list could not be exported to the file '")
.append(this.filePath.toString())
.append("'.");
JOptionPane.showMessageDialog(this.parentDialogComponent, message.toString(), "Failed to export the list", JOptionPane.ERROR_MESSAGE);
}
}
| 2,741 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ScanAllLocalRepositoryFoldersTimerRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/ScanAllLocalRepositoryFoldersTimerRunnable.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.product.library.ui.v2.thread.AbstractProgressTimerRunnable;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.product.library.v2.database.LocalRepositoryFolderHelper;
import org.esa.snap.product.library.v2.database.AllLocalFolderProductsRepository;
import org.esa.snap.product.library.v2.database.SaveProductData;
import org.esa.snap.product.library.v2.database.model.LocalRepositoryFolder;
import org.esa.snap.ui.loading.GenericRunnable;
import javax.swing.*;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread class to scan all the local repository folders.
*
* Created by jcoravu on 4/10/2019.
*/
public class ScanAllLocalRepositoryFoldersTimerRunnable extends AbstractProgressTimerRunnable<Map<File, String>> {
private static final Logger logger = Logger.getLogger(ScanAllLocalRepositoryFoldersTimerRunnable.class.getName());
private final AllLocalFolderProductsRepository allLocalFolderProductsRepository;
private final boolean scanRecursively;
private final boolean generateQuickLookImages;
private final boolean testZipFileForErrors;
public ScanAllLocalRepositoryFoldersTimerRunnable(ProgressBarHelper progressPanel, int threadId, AllLocalFolderProductsRepository allLocalFolderProductsRepository,
boolean scanRecursively, boolean generateQuickLookImages, boolean testZipFileForErrors) {
super(progressPanel, threadId, 500);
this.allLocalFolderProductsRepository = allLocalFolderProductsRepository;
this.scanRecursively = scanRecursively;
this.generateQuickLookImages = generateQuickLookImages;
this.testZipFileForErrors = testZipFileForErrors;
}
@Override
protected boolean onTimerWakeUp(String message) {
return super.onTimerWakeUp(null); // 'null' => do not reset the progress bar message
}
protected void onFinishSavingProduct(SaveProductData saveProductData) {
}
@Override
protected Map<File, String> execute() throws Exception {
List<LocalRepositoryFolder> localRepositoryFolders = this.allLocalFolderProductsRepository.loadRepositoryFolders();
if (!isFinished()) {
LocalRepositoryFolderHelper scanLocalProductsHelper = new LocalRepositoryFolderHelper(this.allLocalFolderProductsRepository, this.scanRecursively,
this.generateQuickLookImages, this.testZipFileForErrors){
@Override
protected void finishSavingProduct(SaveProductData saveProductData) {
updateFinishSavingProductDataLater(saveProductData);
}
};
for (int i = 0; i < localRepositoryFolders.size(); i++) {
if (isFinished()) {
break;
} else {
LocalRepositoryFolder localRepositoryFolder = localRepositoryFolders.get(i);
try {
boolean deleteLocalFolderRepository = scanLocalProductsHelper.scanRepository(localRepositoryFolder, this, this);
if (deleteLocalFolderRepository) {
// no products saved and delete the local repository folder from the application
updateLocalRepositoryFolderDeletedLater(localRepositoryFolder);
}
} catch (java.lang.InterruptedException exception) {
logger.log(Level.FINE, "Stop scanning the local repository folders.");
break;
} catch (Exception exception) {
logger.log(Level.SEVERE, "Failed to scan the local repository folder '" + localRepositoryFolder.getPath().toString() + "'.", exception);
}
}
}
return scanLocalProductsHelper.getErrorFiles();
}
return null;
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to scan the local repositories.";
}
protected void onLocalRepositoryFolderDeleted(LocalRepositoryFolder localRepositoryFolder) {
}
private void updateLocalRepositoryFolderDeletedLater(LocalRepositoryFolder localRepositoryFolder) {
Runnable runnable = new GenericRunnable<LocalRepositoryFolder>(localRepositoryFolder) {
@Override
protected void execute(LocalRepositoryFolder item) {
if (isCurrentProgressPanelThread()) {
onLocalRepositoryFolderDeleted(item);
}
}
};
SwingUtilities.invokeLater(runnable);
}
private void updateFinishSavingProductDataLater(SaveProductData saveProductData) {
GenericRunnable<SaveProductData> runnable = new GenericRunnable<SaveProductData>(saveProductData) {
@Override
protected void execute(SaveProductData item) {
onFinishSavingProduct(item);
}
};
SwingUtilities.invokeLater(runnable);
}
}
| 5,299 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MoveLocalProductsRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/MoveLocalProductsRunnable.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.engine_utilities.util.FileIOUtils;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductListModel;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.product.library.v2.database.AllLocalFolderProductsRepository;
import org.esa.snap.product.library.v2.database.model.LocalRepositoryProduct;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.loading.PairRunnable;
import javax.swing.*;
import java.nio.file.Path;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread to move local products from one local repository to other repository.
*
* Created by jcoravu on 27/9/2019.
*/
public class MoveLocalProductsRunnable extends AbstractProcessLocalProductsRunnable {
private static final Logger logger = Logger.getLogger(MoveLocalProductsRunnable.class.getName());
private final Path localTargetFolder;
private final AllLocalFolderProductsRepository allLocalFolderProductsRepository;
public MoveLocalProductsRunnable(ProgressBarHelper progressPanel, int threadId, RepositoryOutputProductListPanel repositoryProductListPanel, Path localTargetFolder,
List<RepositoryProduct> productsToMove, AllLocalFolderProductsRepository allLocalFolderProductsRepository) {
super(progressPanel, threadId, repositoryProductListPanel, productsToMove);
this.localTargetFolder = localTargetFolder;
this.allLocalFolderProductsRepository = allLocalFolderProductsRepository;
}
@Override
protected boolean onTimerWakeUp(String message) {
return super.onTimerWakeUp("Move local products...");
}
@Override
protected Void execute() throws Exception {
for (int i = 0; i<this.productsToProcess.size(); i++) {
LocalRepositoryProduct repositoryProduct = (LocalRepositoryProduct)this.productsToProcess.get(i);
try {
updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.MOVING);
Path newProductPath = FileIOUtils.moveFolderNew(repositoryProduct.getPath(), this.localTargetFolder);
this.allLocalFolderProductsRepository.updateProductPath(repositoryProduct, newProductPath, this.localTargetFolder);
Runnable runnable = new PairRunnable<LocalRepositoryProduct, Path>(repositoryProduct, newProductPath) {
@Override
protected void execute(LocalRepositoryProduct localRepositoryProduct, Path path) {
onFinishMoveLocalProduct(localRepositoryProduct, path);
}
};
SwingUtilities.invokeLater(runnable);
} catch (Exception exception) {
updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.FAIL_MOVED);
logger.log(Level.SEVERE, "Failed to move the local product '" + repositoryProduct.getPath() + "'.", exception);
}
}
return null;
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to move the local products.";
}
private void onFinishMoveLocalProduct(LocalRepositoryProduct localRepositoryProduct, Path path) {
localRepositoryProduct.setPath(path);
OutputProductListModel productListModel = this.repositoryProductListPanel.getProductListPanel().getProductListModel();
productListModel.setLocalProductStatus(localRepositoryProduct, LocalProgressStatus.MOVED);
}
}
| 3,766 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AddLocalRepositoryFolderTimerRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/AddLocalRepositoryFolderTimerRunnable.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.product.library.ui.v2.thread.AbstractProgressTimerRunnable;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.product.library.v2.database.LocalRepositoryFolderHelper;
import org.esa.snap.product.library.v2.database.AllLocalFolderProductsRepository;
import org.esa.snap.product.library.v2.database.SaveProductData;
import org.esa.snap.product.library.v2.database.model.LocalRepositoryFolder;
import org.esa.snap.ui.loading.GenericRunnable;
import javax.swing.*;
import java.io.File;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread to add a local folder as a repository.
*
* Created by jcoravu on 3/10/2019.
*/
public class AddLocalRepositoryFolderTimerRunnable extends AbstractProgressTimerRunnable<Map<File, String>> {
private static final Logger logger = Logger.getLogger(AddLocalRepositoryFolderTimerRunnable.class.getName());
private final AllLocalFolderProductsRepository allLocalFolderProductsRepository;
private final Path localRepositoryFolderPath;
private final boolean scanRecursively;
private final boolean generateQuickLookImages;
private final boolean validateZips;
public AddLocalRepositoryFolderTimerRunnable(ProgressBarHelper progressPanel, int threadId, Path localRepositoryFolderPath,
AllLocalFolderProductsRepository allLocalFolderProductsRepository, boolean scanRecursively,
boolean generateQuickLookImages, boolean validateZips) {
super(progressPanel, threadId, 500);
this.allLocalFolderProductsRepository = allLocalFolderProductsRepository;
this.localRepositoryFolderPath = localRepositoryFolderPath;
this.scanRecursively = scanRecursively;
this.generateQuickLookImages = generateQuickLookImages;
this.validateZips = validateZips;
}
@Override
protected final boolean onTimerWakeUp(String message) {
return super.onTimerWakeUp(null); // 'null' => do not reset the progress bar message
}
@Override
protected final Map<File, String> execute() throws Exception {
try {
LocalRepositoryFolderHelper saveLocalProductsHelper = new LocalRepositoryFolderHelper(this.allLocalFolderProductsRepository,
this.scanRecursively, this.generateQuickLookImages, this.validateZips) {
@Override
protected void finishSavingProduct(SaveProductData saveProductData) {
updateFinishSavingProductDataLater(saveProductData);
}
};
saveLocalProductsHelper.addRepository(this.localRepositoryFolderPath, this, this);
return saveLocalProductsHelper.getErrorFiles();
} catch (java.lang.InterruptedException exception) {
logger.log(Level.FINE, "Stop adding products from the local repository folder '" + this.localRepositoryFolderPath+"'.");
return null; // nothing to return
}
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to add the local repository folder '"+this.localRepositoryFolderPath.toString()+"'.";
}
protected void onFinishSavingProduct(SaveProductData saveProductData) {
}
public Path getLocalRepositoryFolderPath() {
return localRepositoryFolderPath;
}
private void updateFinishSavingProductDataLater(SaveProductData saveProductData) {
GenericRunnable<SaveProductData> runnable = new GenericRunnable<SaveProductData>(saveProductData) {
@Override
protected void execute(SaveProductData item) {
onFinishSavingProduct(item);
}
};
SwingUtilities.invokeLater(runnable);
}
}
| 4,026 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DeleteAllLocalRepositoriesTimerRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/DeleteAllLocalRepositoriesTimerRunnable.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.product.library.ui.v2.thread.AbstractProgressTimerRunnable;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.product.library.v2.database.AllLocalFolderProductsRepository;
import org.esa.snap.product.library.v2.database.model.LocalRepositoryFolder;
import org.esa.snap.ui.loading.GenericRunnable;
import javax.swing.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread to delete all the local repository folders.
*
* Created by jcoravu on 2/10/2019.
*/
public class DeleteAllLocalRepositoriesTimerRunnable extends AbstractProgressTimerRunnable<Void> {
private static final Logger logger = Logger.getLogger(DeleteAllLocalRepositoriesTimerRunnable.class.getName());
private final LocalRepositoryFolder[] localRepositoryFolders;
private final AllLocalFolderProductsRepository allLocalFolderProductsRepository;
public DeleteAllLocalRepositoriesTimerRunnable(ProgressBarHelper progressPanel, int threadId,
AllLocalFolderProductsRepository allLocalFolderProductsRepository,
LocalRepositoryFolder... localRepositoryFolders) {
super(progressPanel, threadId, 500);
this.localRepositoryFolders = localRepositoryFolders;
this.allLocalFolderProductsRepository = allLocalFolderProductsRepository;
}
@Override
protected final boolean onTimerWakeUp(String message) {
return super.onTimerWakeUp("Delete all local repositories...");
}
@Override
protected final Void execute() throws Exception {
if (this.localRepositoryFolders != null) {
for (LocalRepositoryFolder folder : this.localRepositoryFolders) {
if (isFinished()) {
break;
} else {
boolean folderDeletedFromDatabase = false;
try {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "Delete the local repository folder '" + folder.getPath().toString() + "'.");
}
this.allLocalFolderProductsRepository.deleteRepositoryFolder(folder);
folderDeletedFromDatabase = true;
} catch (Exception exception) {
logger.log(Level.SEVERE, "Failed to delete the local repository folder '" + folder.getPath().toString() + "'.", exception);
} finally {
if (folderDeletedFromDatabase) {
updateLocalRepositoryFolderDeletedLater(folder);
}
}
}
}
}
return null;
}
@Override
protected final String getExceptionLoggingMessage() {
return "Failed to delete the local repository folders from the disk and the product from the database.";
}
protected void onLocalRepositoryFolderDeleted(LocalRepositoryFolder localRepositoryFolder) {
}
private void updateLocalRepositoryFolderDeletedLater(LocalRepositoryFolder localRepositoryFolder) {
Runnable runnable = new GenericRunnable<LocalRepositoryFolder>(localRepositoryFolder) {
@Override
protected void execute(LocalRepositoryFolder item) {
if (isCurrentProgressPanelThread()) {
onLocalRepositoryFolderDeleted(item);
}
}
};
SwingUtilities.invokeLater(runnable);
}
}
| 3,668 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AttributesParameterComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/AttributesParameterComponent.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.apache.commons.lang3.StringUtils;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.product.library.ui.v2.repository.input.AbstractParameterComponent;
import org.esa.snap.product.library.v2.database.AttributeFilter;
import org.esa.snap.product.library.v2.database.AttributeValueFilter;
import org.esa.snap.ui.loading.CustomComboBox;
import org.esa.snap.ui.loading.ItemRenderer;
import org.esa.snap.ui.loading.LabelListCellRenderer;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
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.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* The panel shows the attributes of a local product to be selected by the user when searching the products in
* the local repositories.
* <p>
* Created by jcoravu on 18/9/2019.
*/
public class AttributesParameterComponent extends AbstractParameterComponent<List<AttributeFilter>> {
public static final AttributeValueFilter EQUAL_VALUE_FILTER = (attributeValue, valueToCheck) -> attributeValue.equalsIgnoreCase(valueToCheck);
private static final AttributeValueFilter CONTAINS_VALUE_FILTER = (attributeValue, valueToCheck) -> StringUtils.containsIgnoreCase(attributeValue, valueToCheck);
private final JComboBox<String> attributeNamesComboBox;
private final JComboBox<String> attributeValuesEditableComboBox;
private final JComboBox<AttributeValueFilter> filtersComboBox;
private final JList<AttributeFilter> attributesList;
private final JPanel component;
private final Map<AttributeValueFilter, String> atributeFiltersMap;
public AttributesParameterComponent(JComboBox<String> attributesComboBox, JComboBox<String> attributeValuesEditableComboBox, String parameterName,
String parameterLabelText, boolean required, ComponentDimension componentDimension) {
super(parameterName, parameterLabelText, required);
this.attributeNamesComboBox = attributesComboBox;
this.attributeValuesEditableComboBox = attributeValuesEditableComboBox;
this.atributeFiltersMap = new LinkedHashMap<>();
this.atributeFiltersMap.put(EQUAL_VALUE_FILTER, "Equals");
this.atributeFiltersMap.put(CONTAINS_VALUE_FILTER, "Contains");
ItemRenderer<AttributeValueFilter> filtersItemRenderer = item -> (item == null) ? " " : getFilterDisplayName(item);
this.filtersComboBox = new CustomComboBox(filtersItemRenderer, componentDimension.getTextFieldPreferredHeight(), false, componentDimension.getTextFieldBackgroundColor());
JLabel label = new JLabel();
int maximumWidth = 0;
this.filtersComboBox.addItem(null); // add no filter on the first position
for (Map.Entry<AttributeValueFilter, String> entry : this.atributeFiltersMap.entrySet()) {
this.filtersComboBox.addItem(entry.getKey());
label.setText(entry.getValue());
int preferredWidth = label.getPreferredSize().width;
if (preferredWidth > maximumWidth) {
maximumWidth = preferredWidth;
}
}
Dimension filtersComboBoxSize = this.filtersComboBox.getPreferredSize();
filtersComboBoxSize.width = (int) (1.8f * maximumWidth);
this.filtersComboBox.setPreferredSize(filtersComboBoxSize);
this.filtersComboBox.setSelectedItem(null); // no selected filter by default
Dimension buttonSize = new Dimension(componentDimension.getTextFieldPreferredHeight(), componentDimension.getTextFieldPreferredHeight());
JButton addAttributeButton = SwingUtils.buildButton("/org/esa/snap/resources/images/icons/Add16.png", null, buttonSize, 1);
addAttributeButton.addActionListener(actionEvent -> addAttributeButtonClicked());
JButton removeAttributeButton = SwingUtils.buildButton("/org/esa/snap/resources/images/icons/Remove16.png", null, buttonSize, 1);
removeAttributeButton.addActionListener(actionEvent -> remoteAttributeButtonClicked());
this.attributesList = new JList<>(new DefaultListModel<>());
this.attributesList.setBackground(componentDimension.getTextFieldBackgroundColor());
this.attributesList.setVisibleRowCount(5);
this.attributesList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
int cellItemHeight = this.attributeNamesComboBox.getPreferredSize().height;
LabelListCellRenderer<AttributeFilter> listCellRenderer = new LabelListCellRenderer<>(cellItemHeight) {
@Override
protected String getItemDisplayText(AttributeFilter attribute) {
if (attribute == null) {
return " ";
}
return attribute.getName() + " " + getFilterDisplayName(attribute.getValueFilter()) + " " + attribute.getValue();
}
};
listCellRenderer.setBorder(SwingUtils.EDIT_TEXT_BORDER);
this.attributesList.setCellRenderer(listCellRenderer);
this.attributesList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
onAttributesListMouseCicked(mouseEvent);
}
});
int gapBetweenColumns = componentDimension.getGapBetweenColumns();
int gapBetweenRows = componentDimension.getGapBetweenRows();
this.component = new JPanel(new GridBagLayout()) {
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
for (int i=0; i<getComponentCount(); i++) {
getComponent(i).setEnabled(enabled);
}
}
};
GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, 0, 0);
this.component.add(this.attributeNamesComboBox, c);
c = SwingUtils.buildConstraints(1, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns);
this.component.add(this.filtersComboBox, c);
c = SwingUtils.buildConstraints(2, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns);
this.component.add(this.attributeValuesEditableComboBox, c);
c = SwingUtils.buildConstraints(3, 0, GridBagConstraints.NONE, GridBagConstraints.NORTH, 1, 1, 0, gapBetweenColumns);
this.component.add(addAttributeButton, c);
JScrollPane scrollPane = new JScrollPane(this.attributesList);
c = SwingUtils.buildConstraints(0, 1, GridBagConstraints.BOTH, GridBagConstraints.WEST, 3, 1, gapBetweenRows, 0);
this.component.add(scrollPane, c);
c = SwingUtils.buildConstraints(3, 1, GridBagConstraints.NONE, GridBagConstraints.NORTH, 1, 1, gapBetweenRows, gapBetweenColumns);
this.component.add(removeAttributeButton, c);
}
@Override
public JComponent getComponent() {
return this.component;
}
@Override
public void clearParameterValue() {
resetFilters();
DefaultListModel<AttributeFilter> model = (DefaultListModel<AttributeFilter>)this.attributesList.getModel();
model.clear();
}
@Override
public List<AttributeFilter> getParameterValue() {
DefaultListModel<AttributeFilter> model = (DefaultListModel<AttributeFilter>)this.attributesList.getModel();
List<AttributeFilter> result = new ArrayList<>(model.getSize());
AttributeFilter attributeFilter = buildAttributeFilter();
if (attributeFilter == null) {
// the attribute filter is not specified
if (isInvalidFilter()) {
return null;
}
} else {
result.add(attributeFilter);
}
for (int i = 0; i < model.getSize(); i++) {
result.add(model.getElementAt(i));
}
return (result.size() > 0) ? result : null;
}
@Override
public void setParameterValue(Object value) {
if (value == null) {
clearParameterValue();
} else if (value instanceof List) {
List<AttributeFilter> result = (List<AttributeFilter>)value;
clearParameterValue();
if (result.size() > 0) {
AttributeFilter firstAttribute = result.get(0);
setAttributeFilterToEdit(firstAttribute);
DefaultListModel<AttributeFilter> model = (DefaultListModel<AttributeFilter>)this.attributesList.getModel();
for (int i=1; i<result.size(); i++) {
model.addElement(result.get(i));
}
}
} else {
throw new ClassCastException("The parameter value type '" + value + "' must be '" + List.class+"'.");
}
}
@Override
public Boolean hasValidValue() {
String selectedAttributeName = getSelectedAttributeName();
AttributeValueFilter selectedAttributeValueFilter = getSelectedAttributeValueFilter();
String attributeValue = getEnteredAttributeValue();
// the filter is specified
if (selectedAttributeName == null && selectedAttributeValueFilter == null && attributeValue.length() == 0) {
// no filter specified
DefaultListModel<AttributeFilter> model = (DefaultListModel<AttributeFilter>) this.attributesList.getModel();
if (model.getSize() == 0) {
// no attributes added into the list
return null;
}
// the list contains at least one attribute
return true;
} else
return selectedAttributeName != null && selectedAttributeValueFilter != null && attributeValue.length() > 0;// the value is invalid
}
@Override
public String getInvalidValueErrorDialogMessage() {
return String.format("The '%s' parameter has missing values.%n%nSpecify the missing values or remove the existing values.", getLabel().getText());
}
private void setAttributeFilterToEdit(AttributeFilter firstAttribute) {
this.attributeNamesComboBox.setSelectedItem(firstAttribute.getName());
this.filtersComboBox.setSelectedItem(firstAttribute.getValueFilter());
this.attributeValuesEditableComboBox.setSelectedItem(firstAttribute.getValue());
}
private void onAttributesListMouseCicked(MouseEvent mouseEvent) {
if (SwingUtilities.isLeftMouseButton(mouseEvent) && mouseEvent.getClickCount() >= 2) {
int clickedItemIndex = this.attributesList.locationToIndex(mouseEvent.getPoint());
if (clickedItemIndex >= 0) {
Rectangle cellBounds = this.attributesList.getCellBounds(clickedItemIndex, clickedItemIndex);
if (cellBounds != null && cellBounds.contains(mouseEvent.getPoint())) {
DefaultListModel<AttributeFilter> model = (DefaultListModel<AttributeFilter>)this.attributesList.getModel();
AttributeFilter attributeFilterToEdit = model.remove(clickedItemIndex);
setAttributeFilterToEdit(attributeFilterToEdit);
}
}
}
}
private String getFilterDisplayName(AttributeValueFilter filter) {
return this.atributeFiltersMap.get(filter);
}
private void remoteAttributeButtonClicked() {
ListSelectionModel selectionModel = this.attributesList.getSelectionModel();
DefaultListModel<AttributeFilter> model = (DefaultListModel<AttributeFilter>)this.attributesList.getModel();
for (int i=model.getSize()-1; i>=0; i--) {
if (selectionModel.isSelectedIndex(i)) {
model.remove(i);
}
}
}
private void addAttributeButtonClicked() {
AttributeFilter attributeFilter = buildAttributeFilter();
if (attributeFilter != null) {
DefaultListModel<AttributeFilter> attributesListModel = (DefaultListModel<AttributeFilter>)this.attributesList.getModel();
attributesListModel.addElement(attributeFilter);
boolean foundAttributeValue = false;
ComboBoxModel<String> attributeValuesModel = this.attributeValuesEditableComboBox.getModel();
for (int i=0; i<attributeValuesModel.getSize() && !foundAttributeValue; i++) {
if (attributeFilter.getValue().equals(attributeValuesModel.getElementAt(i))) {
foundAttributeValue = true;
}
}
if (!foundAttributeValue) {
this.attributeValuesEditableComboBox.addItem(attributeFilter.getValue());
}
resetFilters();
}
}
private void resetFilters() {
this.attributeNamesComboBox.setSelectedItem(null);
this.filtersComboBox.setSelectedItem(null);
this.attributeValuesEditableComboBox.setSelectedItem(null);
}
private String getSelectedAttributeName() {
return (String)this.attributeNamesComboBox.getSelectedItem();
}
private AttributeValueFilter getSelectedAttributeValueFilter() {
return (AttributeValueFilter)this.filtersComboBox.getSelectedItem();
}
private String getEnteredAttributeValue() {
JTextComponent textComponent = (JTextComponent)this.attributeValuesEditableComboBox.getEditor().getEditorComponent();
return textComponent.getText().trim();
}
private AttributeFilter buildAttributeFilter() {
String selectedAttributeName = getSelectedAttributeName();
AttributeValueFilter selectedAttributeValueFilter = getSelectedAttributeValueFilter();
String attributeValue = getEnteredAttributeValue();
if (selectedAttributeName != null && selectedAttributeValueFilter != null && attributeValue.length() > 0) {
return new AttributeFilter(selectedAttributeName, attributeValue, selectedAttributeValueFilter);
}
return null;
}
private boolean isInvalidFilter() {
return (getSelectedAttributeName() != null || getSelectedAttributeValueFilter() != null || getEnteredAttributeValue().length() > 0);
}
}
| 14,763 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LocalParameterValues.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/LocalParameterValues.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.product.library.v2.database.LocalRepositoryParameterValues;
import org.esa.snap.product.library.v2.preferences.model.RemoteRepositoryCredentials;
import java.util.List;
/**
* The initial data to configure the local and remote repositories when the application is started.
*
* Created by jcoravu on 18/9/2019.
*/
public class LocalParameterValues {
private final List<RemoteRepositoryCredentials> repositoriesCredentials;
private final int visibleProductsPerPage;
private final boolean uncompressedDownloadedProducts;
private final LocalRepositoryParameterValues localRepositoryParameterValues;
public LocalParameterValues(List<RemoteRepositoryCredentials> repositoriesCredentials, int visibleProductsPerPage,
boolean uncompressedDownloadedProducts, LocalRepositoryParameterValues localRepositoryParameterValues) {
this.repositoriesCredentials = repositoriesCredentials;
this.visibleProductsPerPage = visibleProductsPerPage;
this.uncompressedDownloadedProducts = uncompressedDownloadedProducts;
this.localRepositoryParameterValues = localRepositoryParameterValues;
}
public List<RemoteRepositoryCredentials> getRepositoriesCredentials() {
return repositoriesCredentials;
}
public LocalRepositoryParameterValues getLocalRepositoryParameterValues() {
return localRepositoryParameterValues;
}
public int getVisibleProductsPerPage() {
return visibleProductsPerPage;
}
public boolean isUncompressedDownloadedProducts() {
return uncompressedDownloadedProducts;
}
}
| 1,705 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LocalRepositoryProductPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/LocalRepositoryProductPanel.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductListModel;
import org.esa.snap.product.library.ui.v2.repository.AbstractRepositoryProductPanel;
import org.esa.snap.product.library.ui.v2.RepositoryProductPanelBackground;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductResults;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import javax.swing.ImageIcon;
import java.awt.Color;
/**
* The panel to show the data of a local repository product.
*
* Created by jcoravu on 27/9/2019.
*/
public class LocalRepositoryProductPanel extends AbstractRepositoryProductPanel {
public LocalRepositoryProductPanel(RepositoryProductPanelBackground repositoryProductPanelBackground,
ComponentDimension componentDimension) {
super(repositoryProductPanelBackground, componentDimension);
}
@Override
public void refresh(OutputProductResults outputProductResults) {
super.refresh(outputProductResults);
RepositoryProduct repositoryProduct = getRepositoryProduct();
LocalProgressStatus localProgressStatus = outputProductResults.getOpeningProductStatus(repositoryProduct);
updateProgressStatus(localProgressStatus);
}
private void updateProgressStatus(LocalProgressStatus localProgressStatus) {
Color foregroundColor = getDefaultForegroundColor();
String openText = " "; // set an empty space for the default text
if (localProgressStatus != null) {
if (localProgressStatus.isPendingOpen()) {
openText = "Pending open...";
} else if (localProgressStatus.isOpening()) {
openText = "Opening...";
} else if (localProgressStatus.isFailOpened()) {
openText = "Failed open";
foregroundColor = Color.RED;
} else if (localProgressStatus.isFailOpenedBecauseNoProductReader()) {
openText = "Failed open because no product reader found";
foregroundColor = Color.RED;
} else if (localProgressStatus.isOpened()) {
openText = "Opened";
foregroundColor = Color.GREEN;
} else if (localProgressStatus.isPendingDelete()) {
openText = "Pending delete...";
} else if (localProgressStatus.isFailDeleted()) {
openText = "Failed deleted";
foregroundColor = Color.RED;
} else if (localProgressStatus.isDeleting()) {
openText = "Deleting...";
} else if (localProgressStatus.isDeleted()) {
openText = "Deleted";
foregroundColor = Color.GREEN;
} else if (localProgressStatus.getStatus() == LocalProgressStatus.PENDING_COPY) {
openText = "Pending copy...";
} else if (localProgressStatus.getStatus() == LocalProgressStatus.COPYING) {
openText = "Copying...";
} else if (localProgressStatus.getStatus() == LocalProgressStatus.COPIED) {
openText = "Copied";
foregroundColor = Color.GREEN;
} else if (localProgressStatus.getStatus() == LocalProgressStatus.FAIL_COPIED) {
openText = "Failed copied";
foregroundColor = Color.RED;
} else if (localProgressStatus.getStatus() == LocalProgressStatus.PENDING_MOVE) {
openText = "Pending move...";
} else if (localProgressStatus.getStatus() == LocalProgressStatus.MOVING) {
openText = "Moving...";
} else if (localProgressStatus.getStatus() == LocalProgressStatus.MOVED) {
openText = "Moved";
foregroundColor = Color.GREEN;
} else if (localProgressStatus.getStatus() == LocalProgressStatus.FAIL_MOVED) {
openText = "Failed moved";
foregroundColor = Color.RED;
} else if (localProgressStatus.getStatus() == LocalProgressStatus.MISSING_PRODUCT_FROM_REPOSITORY) {
openText = "Missing product from repository";
foregroundColor = Color.RED;
} else {
throw new IllegalStateException("Unknown status " + localProgressStatus.getStatus() + ".");
}
}
this.statusLabel.setForeground(foregroundColor);
this.statusLabel.setText(openText);
}
}
| 4,580 | 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.