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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
L2genProductTools.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/productData/L2genProductTools.java | package gov.nasa.gsfc.seadas.processing.l2gen.productData;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.esa.snap.core.util.StringUtils;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 5/28/13
* Time: 2:34 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genProductTools {
// this method takes the l2prod list and for every product matching the dependent wavelength naming convention
// where the delimitor is "_" and an element of the product is an integer, then an "nnn" product will
// be added to the list.
// i.e. "chlor_a aot_869" will become "chlor_a aot_869 aot_nnn"
// "chlor_a my_345_string_467_product" will become "chlor_a my_345_string_467_product my_nnn_string_467_product my_345_string_nnn_product"
static public final String L2PROD_DELIMITER = " ";
static public final String L2PROD_WAVELENGTH_DELIMITER = "_";
static public final String SHORTCUT_NAMEPART_VISIBLE = "vvv";
static public final String SHORTCUT_NAMEPART_IR = "iii";
static public final String SHORTCUT_NAMEPART_ALL = "nnn";
static public final int WAVELENGTH_FOR_IFILE_INDEPENDENT_MODE = -2;
public static enum ShortcutType {
VISIBLE,
IR,
ALL
}
public static String convertShortcutType(L2genProductTools.ShortcutType shortcutType) {
if (shortcutType == L2genProductTools.ShortcutType.ALL) {
return L2genProductTools.SHORTCUT_NAMEPART_ALL;
} else if (shortcutType == L2genProductTools.ShortcutType.IR) {
return L2genProductTools.SHORTCUT_NAMEPART_IR;
} else if (shortcutType == L2genProductTools.ShortcutType.VISIBLE) {
return L2genProductTools.SHORTCUT_NAMEPART_VISIBLE;
} else {
return null;
}
}
public static String convertToNNNProductList(String productList) {
if (1 == 1) {
return productList;
}
if (productList == null) {
return productList;
}
ArrayList<String> products = new ArrayList<String>();
// account for other product delimiters
if (productList.contains(",")) {
productList = productList.replaceAll(",", L2PROD_DELIMITER);
}
for (String currentProduct : productList.split(L2PROD_DELIMITER)) {
String[] productParts = currentProduct.trim().split(L2PROD_WAVELENGTH_DELIMITER);
// always add the current product
products.add(currentProduct);
// now add any wavelength shortcut variants of the current product
StringBuilder currentUntamperedProductPrefix = new StringBuilder(productParts[0]);
for (int i = 1; i < productParts.length; i++) {
if (isInteger(productParts[i])) {
// possible wavelength found at index i
StringBuilder currentNNNProduct = new StringBuilder(currentUntamperedProductPrefix.toString());
currentNNNProduct.append(L2PROD_WAVELENGTH_DELIMITER + SHORTCUT_NAMEPART_ALL);
// loop through remaining parts to add on the suffix
for (int k = i + 1; k < productParts.length; k++) {
currentNNNProduct.append(L2PROD_WAVELENGTH_DELIMITER);
currentNNNProduct.append(productParts[k]);
}
products.add(currentNNNProduct.toString());
}
// add this part and continue on looking for wavelength in the next index
currentUntamperedProductPrefix.append(L2PROD_WAVELENGTH_DELIMITER);
currentUntamperedProductPrefix.append(productParts[i]);
}
}
return StringUtils.join(products, L2PROD_DELIMITER);
}
public static boolean isInteger(String string) {
try {
Integer.parseInt(string);
} catch (NumberFormatException e) {
return false;
}
return true;
}
}
| 4,087 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genProductCategoryInfo.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/productData/L2genProductCategoryInfo.java | package gov.nasa.gsfc.seadas.processing.l2gen.productData;
import java.util.ArrayList;
/**
* A ...
*
* @author Danny Knowles
* @since SeaDAS 7.0
*/
public class L2genProductCategoryInfo extends L2genBaseInfo {
private String name = null;
private boolean visible = false;
private boolean defaultBucket = false;
private ArrayList<String> productNames = new ArrayList<String>();
ArrayList<L2genProductInfo> productInfos = new ArrayList<L2genProductInfo>();
public L2genProductCategoryInfo(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public boolean isDefaultBucket() {
return defaultBucket;
}
public void setDefaultBucket(boolean defaultBucket) {
this.defaultBucket = defaultBucket;
}
public ArrayList<L2genProductInfo> getProductInfos() {
return productInfos;
}
public void addProductInfo(L2genProductInfo productInfo) {
productInfos.add(productInfo);
}
public void clearProductInfos() {
productInfos.clear();
}
public void addProductName(String name) {
productNames.add(name);
}
public ArrayList<String> getProductNames() {
return productNames;
}
}
| 1,485 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genParamComboBox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genParamComboBox.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import gov.nasa.gsfc.seadas.processing.core.ParamValidValueInfo;
import javax.swing.*;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/12/12
* Time: 5:39 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genParamComboBox {
private ParamInfo paramInfo;
private L2genData l2genData;
private JLabel jLabel;
private JComboBox<ParamValidValueInfo> jComboBox;
public L2genParamComboBox(L2genData l2genData, ParamInfo paramInfo) {
this.l2genData = l2genData;
this.paramInfo = paramInfo;
ArrayList<ParamValidValueInfo> jComboBoxArrayList = new ArrayList<ParamValidValueInfo>();
ArrayList<String> validValuesToolTipsArrayList = new ArrayList<String>();
for (ParamValidValueInfo paramValidValueInfo : paramInfo.getValidValueInfos()) {
if (paramValidValueInfo.getValue() != null && paramValidValueInfo.getValue().length() > 0) {
boolean addThisValidValue = true;
/*
Special hardcoded entry to override any known strange xml entries
*/
if (paramValidValueInfo.getValue().equals(">0") || paramValidValueInfo.getValue().equals("<0")) {
addThisValidValue = false;
}
if (addThisValidValue) {
jComboBoxArrayList.add(paramValidValueInfo);
if (paramValidValueInfo.getDescription().length() > 70) {
validValuesToolTipsArrayList.add(paramValidValueInfo.getDescription());
} else {
validValuesToolTipsArrayList.add(null);
}
}
}
}
final ParamValidValueInfo[] jComboBoxArray;
jComboBoxArray = new ParamValidValueInfo[jComboBoxArrayList.size()];
int i = 0;
for (ParamValidValueInfo paramValidValueInfo : jComboBoxArrayList) {
jComboBoxArray[i] = paramValidValueInfo;
i++;
}
final String[] validValuesToolTipsArray = new String[jComboBoxArrayList.size()];
int j = 0;
for (String validValuesToolTip : validValuesToolTipsArrayList) {
validValuesToolTipsArray[j] = validValuesToolTip;
j++;
}
jComboBox = new JComboBox<>(jComboBoxArray);
final MyComboBoxRenderer myComboBoxRenderer = new MyComboBoxRenderer();
myComboBoxRenderer.setTooltips(validValuesToolTipsArray);
//jComboBox.setRenderer((ListCellRenderer<ParamValidValueInfo>)myComboBoxRenderer);
jComboBox.setEditable(false);
for (ParamValidValueInfo paramValidValueInfo : jComboBoxArray) {
if (l2genData.getParamValue(paramInfo.getName()).equals(paramValidValueInfo.getValue())) {
jComboBox.setSelectedItem(paramValidValueInfo);
}
}
jLabel = new JLabel(paramInfo.getName());
jLabel.setToolTipText(paramInfo.getDescription());
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
jComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
l2genData.setParamValue(paramInfo.getName(), (ParamValidValueInfo) jComboBox.getSelectedItem());
}
});
}
private void addEventListeners() {
l2genData.addPropertyChangeListener(paramInfo.getName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
boolean found = false;
ComboBoxModel<ParamValidValueInfo> comboBoxModel = jComboBox.getModel();
for (int i = 0; i < comboBoxModel.getSize(); i++) {
ParamValidValueInfo jComboBoxItem = comboBoxModel.getElementAt(i);
if (paramInfo.getValue().equals(jComboBoxItem.getValue())) {
jComboBox.setSelectedItem(jComboBoxItem);
found = true;
}
}
if (!found) {
final ParamValidValueInfo newArray[] = new ParamValidValueInfo[comboBoxModel.getSize() + 1];
int i;
for (i = 0; i < comboBoxModel.getSize(); i++) {
newArray[i] = comboBoxModel.getElementAt(i);
}
newArray[i] = new ParamValidValueInfo(paramInfo.getValue());
newArray[i].setDescription("User defined value");
jComboBox.setModel(new DefaultComboBoxModel<>(newArray));
jComboBox.setSelectedItem(newArray[i]);
}
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JComboBox<ParamValidValueInfo> getjComboBox() {
return jComboBox;
}
class MyComboBoxRenderer<ParamValidValueInfo> extends BasicComboBoxRenderer {
private String[] tooltips;
public void MyComboBoxRenderer(String[] tooltips) {
this.tooltips = tooltips;
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
if (-1 < index && index < tooltips.length) {
list.setToolTipText(tooltips[index]);
}
} else {
setBackground(Color.white);
setForeground(Color.black);
}
setFont(list.getFont());
setText((value == null) ? "" : value.toString());
return this;
}
public void setTooltips(String[] tooltips) {
this.tooltips = tooltips;
}
}
}
| 6,491 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genAction.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genAction.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* 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 gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction;
import gov.nasa.gsfc.seadas.processing.common.CloProgramUI;
import org.esa.snap.ui.AppContext;
/**
* Geographic collocation action.
*
* @author Ralf Quast
* @version $Revision: 2535 $ $Date: 2008-07-09 14:10:01 +0200 (Mi, 09 Jul 2008) $
*/
public class L2genAction extends CallCloProgramAction {
@Override
public CloProgramUI getProgramUI(AppContext appContext) {
return new L2genForm(appContext, getXmlFileName(), ocssw);
}
}
| 1,310 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genParfileImporter.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genParfileImporter.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.common.SeadasGuiUtils;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/6/12
* Time: 4:34 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genParfileImporter {
final private JButton jButton;
private L2genData l2genData;
final JFileChooser jFileChooser;
L2genParfileImporter(L2genData l2genData) {
this.l2genData = l2genData;
String NAME = "Load";
jButton = new JButton(NAME);
jButton.setToolTipText("Loads parameters from an external parameter file into the GUI parfile textfield");
jFileChooser = new JFileChooser();
addControlListeners();
}
private void addControlListeners() {
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String contents = SeadasGuiUtils.importFile(jFileChooser);
File parFileDir;
if(contents == null) {
parFileDir = null;
} else {
parFileDir = jFileChooser.getSelectedFile().getParentFile();
}
l2genData.setParString(contents, true, l2genData.isExcludeCurrentIOfile(), false, false, parFileDir);
}
});
}
public JButton getjButton() {
return jButton;
}
}
| 1,763 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L3genAction.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L3genAction.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction;
import gov.nasa.gsfc.seadas.processing.common.CloProgramUI;
import org.esa.snap.ui.AppContext;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 10/24/12
* Time: 3:14 PM
* To change this template use File | Settings | File Templates.
*/
public class L3genAction extends CallCloProgramAction {
@Override
public CloProgramUI getProgramUI(AppContext appContext) {
return new L2genForm(appContext, getXmlFileName(), L2genData.Mode.L3GEN, ocssw);
}
} | 668 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genTristateCheckBox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genTristateCheckBox.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
/**
* Created by IntelliJ IDEA.
* User: dshea
* Date: 1/20/12
* Time: 9:54 AM
* To change this template use File | Settings | File Templates.
*/
import javax.swing.*;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.ActionMapUIResource;
import java.awt.*;
import java.awt.event.*;
/**
* Maintenance tip - There were some tricks to getting this code
* working:
* <p/>
* 1. You have to overwite addMouseListener() to do nothing
* 2. You have to add a mouse event on mousePressed by calling
* super.addMouseListener()
* 3. You have to replace the UIActionMap for the keyboard event
* "pressed" with your own one.
* 4. You have to remove the UIActionMap for the keyboard event
* "released".
* 5. You have to grab focus when the next state is entered,
* otherwise clicking on the component won't get the focus.
* 6. You have to make a TristateDecorator as a button model that
* wraps the original button model and does state management.
*/
public class L2genTristateCheckBox extends JCheckBox {
/**
* This is a type-safe enumerated type
*/
public static class State {
private State() {
}
}
public static final State NOT_SELECTED = new State();
public static final State PARTIAL = new State();
public static final State SELECTED = new State();
private final TristateDecorator model;
public L2genTristateCheckBox(String text, Icon icon, State initial) {
super(text, icon);
// Add a listener for when the mouse is pressed
super.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
grabFocus();
model.nextState();
}
});
// Reset the keyboard action map
ActionMap map = new ActionMapUIResource();
map.put("pressed", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
grabFocus();
model.nextState();
}
});
map.put("released", null);
SwingUtilities.replaceUIActionMap(this, map);
// set the model to the adapted model
model = new TristateDecorator(getModel());
setModel(model);
setState(initial);
}
public L2genTristateCheckBox(String text, State initial) {
this(text, null, initial);
}
public L2genTristateCheckBox(String text) {
this(text, PARTIAL);
}
public L2genTristateCheckBox() {
this(null);
}
/**
* No one may add mouse listeners, not even Swing!
*/
@Override
public void addMouseListener(MouseListener l) {
}
/**
* Set the new state to either SELECTED, NOT_SELECTED or
* PARTIAL. If state == null, it is treated as PARTIAL.
*/
public void setState(State state) {
model.setState(state);
}
/**
* Return the current state, which is determined by the
* selection status of the model.
*/
public State getState() {
return model.getState();
}
@Override
public void setSelected(boolean b) {
if (b) {
setState(SELECTED);
} else {
setState(NOT_SELECTED);
}
}
/**
* Exactly which Design Pattern is this? Is it an Adapter,
* a Proxy or a Decorator? In this case, my vote lies with the
* Decorator, because we are extending functionality and
* "decorating" the original model with a more powerful model.
*/
private class TristateDecorator implements ButtonModel {
private final ButtonModel other;
private State state;
private Color normalBG;
private Color partialBG = Color.black;
private TristateDecorator(ButtonModel other) {
this.other = other;
normalBG = getBackground();
}
private void setState(State state) {
this.state = state;
if (state == NOT_SELECTED) {
setBackground(normalBG);
other.setArmed(false);
setPressed(false);
setSelected(false);
} else if (state == SELECTED) {
setBackground(normalBG);
other.setArmed(true); // was false
setPressed(true); // was true
setSelected(true);
} else { // either "null" or PARTIAL
setBackground(partialBG);
other.setArmed(false); // was true
setPressed(true);// was false
setSelected(true);
}
}
/**
* The current state is embedded in the selection / armed
* state of the model.
* <p/>
* We return the SELECTED state when the checkbox is selected
* but not armed, PARTIAL state when the checkbox is
* selected and armed (grey) and NOT_SELECTED when the
* checkbox is deselected.
*/
private State getState() {
return state;
}
/**
* We rotate between NOT_SELECTED, PARTIAL, and SELECTED.
*/
private void nextState() {
State current = getState();
if (current == NOT_SELECTED) {
setState(PARTIAL);
} else if (current == PARTIAL) {
setState(SELECTED);
} else if (current == SELECTED) {
setState(NOT_SELECTED);
}
}
/**
* Filter: No one may change the armed status except us.
*/
public void setArmed(boolean b) {
}
/**
* We disable focusing on the component when it is not
* enabled.
*/
public void setEnabled(boolean b) {
setFocusable(b);
other.setEnabled(b);
}
/**
* All these methods simply delegate to the "other" model
* that is being decorated.
*/
public boolean isArmed() {
return other.isArmed();
}
public boolean isSelected() {
return other.isSelected();
}
public boolean isEnabled() {
return other.isEnabled();
}
public boolean isPressed() {
return other.isPressed();
}
public boolean isRollover() {
return other.isRollover();
}
public void setSelected(boolean b) {
other.setSelected(b);
}
public void setPressed(boolean b) {
other.setPressed(b);
}
public void setRollover(boolean b) {
other.setRollover(b);
}
public void setMnemonic(int key) {
other.setMnemonic(key);
}
public int getMnemonic() {
return other.getMnemonic();
}
public void setActionCommand(String s) {
other.setActionCommand(s);
}
public String getActionCommand() {
return other.getActionCommand();
}
public void setGroup(ButtonGroup group) {
other.setGroup(group);
}
public void addActionListener(ActionListener l) {
other.addActionListener(l);
}
public void removeActionListener(ActionListener l) {
other.removeActionListener(l);
}
public void addItemListener(ItemListener l) {
other.addItemListener(l);
}
public void removeItemListener(ItemListener l) {
other.removeItemListener(l);
}
public void addChangeListener(ChangeListener l) {
other.addChangeListener(l);
}
public void removeChangeListener(ChangeListener l) {
other.removeChangeListener(l);
}
public Object[] getSelectedObjects() {
return other.getSelectedObjects();
}
}
} | 7,963 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genParamCheckBoxKit.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genParamCheckBoxKit.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/13/12
* Time: 10:19 AM
* To change this template use File | Settings | File Templates.
*/
public class L2genParamCheckBoxKit extends AbstractComponentKit {
private L2genData l2genData;
private JCheckBox jCheckBox = new JCheckBox();
public L2genParamCheckBoxKit(L2genData l2genData, String name, String toolTip) {
super(name, toolTip);
addComponent(jCheckBox);
this.l2genData = l2genData;
addEventListeners();
}
public void controlHandler() {
if (l2genData != null) {
l2genData.setParamValue(getName(), isComponentSelected());
}
}
private void addEventListeners() {
if (l2genData != null) {
l2genData.addPropertyChangeListener(getName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
setComponentSelected(l2genData.getBooleanParamValue(getName()), false);
}
});
}
}
}
| 1,338 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genShowDefaultsSpecifier.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genShowDefaultsSpecifier.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/6/12
* Time: 4:38 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genShowDefaultsSpecifier {
private JCheckBox jCheckBox;
private L2genData l2genData;
private boolean controlHandlerEnabled = true;
L2genShowDefaultsSpecifier(L2genData l2genData) {
this.l2genData = l2genData;
createJCheckBox();
addControlListeners();
addEventListeners();
}
private void createJCheckBox() {
String NAME = "Show Defaults";
String TOOL_TIP = "Displays all the defaults with the parfile text region";
jCheckBox = new JCheckBox(NAME);
jCheckBox.setSelected(l2genData.isShowDefaultsInParString());
jCheckBox.setToolTipText(TOOL_TIP);
}
private void addControlListeners() {
jCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (isControlHandlerEnabled()) {
l2genData.setShowDefaultsInParString(jCheckBox.isSelected());
}
}
});
}
private void addEventListeners() {
l2genData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
jCheckBox.setEnabled(l2genData.isValidIfile());
}
});
l2genData.addPropertyChangeListener(l2genData.SHOW_DEFAULTS, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
disableControlHandler();
jCheckBox.setSelected(l2genData.isShowDefaultsInParString());
enableControlHandler();
}
});
}
private boolean isControlHandlerEnabled() {
return controlHandlerEnabled;
}
private void enableControlHandler() {
controlHandlerEnabled = true;
}
private void disableControlHandler() {
controlHandlerEnabled = false;
}
public JCheckBox getjCheckBox() {
return jCheckBox;
}
}
| 2,504 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genWavelengthLimiterPanel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genWavelengthLimiterPanel.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.l2gen.productData.L2genWavelengthInfo;
import gov.nasa.gsfc.seadas.processing.common.GridBagConstraintsCustom;
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.util.ArrayList;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 5/11/12
* Time: 3:42 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genWavelengthLimiterPanel extends JPanel {
private L2genData l2genData;
private JPanel waveLimiterJPanel;
private ArrayList<JCheckBox> wavelengthsJCheckboxArrayList = new ArrayList<JCheckBox>();
private boolean waveLimiterControlHandlersEnabled = false;
private JButton
uvButton,
visibleButton,
nearInfraredButton,
swirButton,
infraredButton;
private String
UV_LABEL = "UV",
VISIBLE_LABEL = "Visible",
NIR_LABEL = "NIR",
SWIR_LABEL = "SWIR",
IR_LABEL = "IR";
private String SELECT_ALL = "Select All";
private String DESELECT_ALL = "Deselect All";
private String
SELECT_ALL_UV = SELECT_ALL + " " + UV_LABEL,
DESELECT_ALL_UV = DESELECT_ALL + " " + UV_LABEL,
SELECT_ALL_VISIBLE = SELECT_ALL + " " + VISIBLE_LABEL,
DESELECT_ALL_VISIBLE = DESELECT_ALL + " " + VISIBLE_LABEL,
SELECT_ALL_NEAR_INFRARED = SELECT_ALL + " " + NIR_LABEL,
DESELECT_ALL_NEAR_INFRARED = DESELECT_ALL + " " + NIR_LABEL,
SELECT_ALL_SWIR = SELECT_ALL + " " + SWIR_LABEL,
DESELECT_ALL_SWIR = DESELECT_ALL + " " + SWIR_LABEL,
SELECT_ALL_INFRARED = SELECT_ALL + " " + IR_LABEL,
DESELECT_ALL_INFRARED = DESELECT_ALL + " " + IR_LABEL;
;
L2genWavelengthLimiterPanel(L2genData l2genData) {
this.l2genData = l2genData;
initComponents();
addComponents();
}
public void initComponents() {
waveLimiterJPanel = createWaveLimiterJPanel();
uvButton = createUVButton();
visibleButton = createVisibleButton();
nearInfraredButton = createNearInfraredButton();
swirButton = createSwirButton();
infraredButton = createInfraredButton();
}
public void addComponents() {
setLayout(new GridBagLayout());
setBorder(BorderFactory.createTitledBorder("Wavelength 3-Way Toggle Selection"));
setToolTipText("<html>The wavelengths selected here are applied <br>in one of the 3-way toggle steps<br>when you check a wavelength dependent product checkbox</html>");
JPanel innerPanel = new JPanel(new GridBagLayout());
innerPanel.add(uvButton,
new GridBagConstraintsCustom(0, 0, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE));
innerPanel.add(visibleButton,
new GridBagConstraintsCustom(0, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE));
innerPanel.add(nearInfraredButton,
new GridBagConstraintsCustom(0, 2, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE));
innerPanel.add(swirButton,
new GridBagConstraintsCustom(0, 3, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE));
innerPanel.add(infraredButton,
new GridBagConstraintsCustom(0, 4, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE));
innerPanel.add(waveLimiterJPanel,
new GridBagConstraintsCustom(0, 5, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE));
innerPanel.add(new JPanel(),
new GridBagConstraintsCustom(0, 6, 1, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH));
JScrollPane innerScroll = new JScrollPane(innerPanel);
innerScroll.setBorder(null);
add(innerScroll,
new GridBagConstraintsCustom(0, 0, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH));
}
private JButton createUVButton() {
final JButton jButton = new JButton(SELECT_ALL_UV);
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (jButton.getText().equals(SELECT_ALL_UV)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.UV, true);
} else if (jButton.getText().equals(DESELECT_ALL_UV)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.UV, false);
}
}
});
l2genData.addPropertyChangeListener(L2genData.WAVE_LIMITER, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateUVButton();
}
});
l2genData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateUVButton();
}
});
return jButton;
}
private void updateUVButton() {
// Set UV 'Select All' toggle to appropriate text and enabled
if (l2genData.hasWaveType(L2genWavelengthInfo.WaveType.UV)) {
uvButton.setEnabled(true);
uvButton.setVisible(true);
if (l2genData.isSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.UV)) {
if (!uvButton.getText().equals(DESELECT_ALL_UV)) {
uvButton.setText(DESELECT_ALL_UV);
}
} else {
if (!uvButton.getText().equals(SELECT_ALL_UV)) {
uvButton.setText(SELECT_ALL_UV);
}
}
} else {
uvButton.setEnabled(false);
uvButton.setVisible(false);
}
}
private JButton createVisibleButton() {
final JButton jButton = new JButton(SELECT_ALL_VISIBLE);
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (jButton.getText().equals(SELECT_ALL_VISIBLE)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.VISIBLE, true);
} else if (jButton.getText().equals(DESELECT_ALL_VISIBLE)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.VISIBLE, false);
}
}
});
l2genData.addPropertyChangeListener(L2genData.WAVE_LIMITER, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateVisibleButton();
}
});
l2genData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateVisibleButton();
}
});
return jButton;
}
private void updateVisibleButton() {
// Set VISIBLE 'Select All' toggle to appropriate text and enabled
if (l2genData.hasWaveType(L2genWavelengthInfo.WaveType.VISIBLE)) {
visibleButton.setEnabled(true);
visibleButton.setVisible(true);
if (l2genData.isSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.VISIBLE)) {
if (!visibleButton.getText().equals(DESELECT_ALL_VISIBLE)) {
visibleButton.setText(DESELECT_ALL_VISIBLE);
}
} else {
if (!visibleButton.getText().equals(SELECT_ALL_VISIBLE)) {
visibleButton.setText(SELECT_ALL_VISIBLE);
}
}
} else {
visibleButton.setEnabled(false);
visibleButton.setVisible(false);
}
}
private JButton createNearInfraredButton() {
final JButton jButton = new JButton(SELECT_ALL_NEAR_INFRARED);
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (jButton.getText().equals(SELECT_ALL_NEAR_INFRARED)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.NIR, true);
} else if (jButton.getText().equals(DESELECT_ALL_NEAR_INFRARED)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.NIR, false);
}
}
});
l2genData.addPropertyChangeListener(L2genData.WAVE_LIMITER, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateNearInfraredButton();
}
});
l2genData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateNearInfraredButton();
}
});
return jButton;
}
private void updateNearInfraredButton() {
// Set NEAR_INFRARED 'Select All' toggle to appropriate text and enabled
if (l2genData.hasWaveType(L2genWavelengthInfo.WaveType.NIR)) {
nearInfraredButton.setEnabled(true);
nearInfraredButton.setVisible(true);
if (l2genData.isSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.NIR)) {
if (!nearInfraredButton.getText().equals(DESELECT_ALL_NEAR_INFRARED)) {
nearInfraredButton.setText(DESELECT_ALL_NEAR_INFRARED);
}
} else {
if (!nearInfraredButton.getText().equals(SELECT_ALL_NEAR_INFRARED)) {
nearInfraredButton.setText(SELECT_ALL_NEAR_INFRARED);
}
}
} else {
nearInfraredButton.setEnabled(false);
nearInfraredButton.setVisible(false);
}
}
private JButton createSwirButton() {
final JButton jButton = new JButton(SELECT_ALL_SWIR);
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (jButton.getText().equals(SELECT_ALL_SWIR)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.SWIR, true);
} else if (jButton.getText().equals(DESELECT_ALL_SWIR)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.SWIR, false);
}
}
});
l2genData.addPropertyChangeListener(L2genData.WAVE_LIMITER, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateSwirButton();
}
});
l2genData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateSwirButton();
}
});
return jButton;
}
private void updateSwirButton() {
// Set UV 'Select All' toggle to appropriate text and enabled
if (l2genData.hasWaveType(L2genWavelengthInfo.WaveType.SWIR)) {
swirButton.setEnabled(true);
swirButton.setVisible(true);
if (l2genData.isSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.SWIR)) {
if (!swirButton.getText().equals(DESELECT_ALL_SWIR)) {
swirButton.setText(DESELECT_ALL_SWIR);
}
} else {
if (!swirButton.getText().equals(SELECT_ALL_SWIR)) {
swirButton.setText(SELECT_ALL_SWIR);
}
}
} else {
swirButton.setEnabled(false);
swirButton.setVisible(false);
}
}
private JButton createInfraredButton() {
final JButton jButton = new JButton(SELECT_ALL_INFRARED);
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (jButton.getText().equals(SELECT_ALL_INFRARED)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.IR, true);
} else if (jButton.getText().equals(DESELECT_ALL_INFRARED)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.IR, false);
}
}
});
l2genData.addPropertyChangeListener(L2genData.WAVE_LIMITER, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateInfraredButton();
}
});
l2genData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateInfraredButton();
}
});
return jButton;
}
private void updateInfraredButton() {
// Set INFRARED 'Select All' toggle to appropriate text and enabled
if (l2genData.hasWaveType(L2genWavelengthInfo.WaveType.IR)) {
infraredButton.setEnabled(true);
infraredButton.setVisible(true);
if (l2genData.isSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.IR)) {
if (!infraredButton.getText().equals(DESELECT_ALL_INFRARED)) {
infraredButton.setText(DESELECT_ALL_INFRARED);
}
} else {
if (!infraredButton.getText().equals(SELECT_ALL_INFRARED)) {
infraredButton.setText(SELECT_ALL_INFRARED);
}
}
} else {
infraredButton.setEnabled(false);
infraredButton.setVisible(false);
}
}
// private class InfraredButton {
//
//
// private static final String selectAll = SELECT_ALL_INFRARED;
// private static final String deselectAll = DESELECT_ALL_INFRARED;
//
//
// InfraredButton() {
// }
//
// private JButton createInfraredButton() {
//
// final JButton jButton = new JButton(selectAll);
//
// jButton.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// if (jButton.getText().equals(selectAll)) {
// l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.INFRARED, true);
// } else if (jButton.getText().equals(deselectAll)) {
// l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.INFRARED, false);
// }
// }
// });
//
//
// l2genData.addPropertyChangeListener(L2genData.WAVE_LIMITER, new PropertyChangeListener() {
// @Override
// public void propertyChange(PropertyChangeEvent evt) {
// updateInfraredButton();
// }
// });
//
// l2genData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
// @Override
// public void propertyChange(PropertyChangeEvent evt) {
// updateInfraredButton();
// }
// });
//
// return jButton;
// }
//
//
// private void updateInfraredButton() {
//
// // Set INFRARED 'Select All' toggle to appropriate text and enabled
// if (l2genData.hasWaveType(L2genWavelengthInfo.WaveType.INFRARED)) {
// nearInfraredButton.setEnabled(true);
// if (l2genData.isSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.INFRARED)) {
// if (!infraredButton.getText().equals(deselectAll)) {
// infraredButton.setText(deselectAll);
// }
// } else {
// if (!infraredButton.getText().equals(selectAll)) {
// infraredButton.setText(selectAll);
// }
// }
// } else {
// nearInfraredButton.setEnabled(false);
// }
// }
// }
private JPanel createWaveLimiterJPanel() {
final JPanel jPanel = new JPanel(new GridBagLayout());
l2genData.addPropertyChangeListener(L2genData.WAVE_LIMITER, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateWaveLimiterSelectionStates();
}
});
l2genData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateWavelengthLimiterPanel();
updateWaveLimiterSelectionStates();
}
});
return jPanel;
}
private void updateWavelengthLimiterPanel() {
waveLimiterJPanel.removeAll();
// clear this because we dynamically rebuild it when input file selection is made or changed
wavelengthsJCheckboxArrayList.clear();
ArrayList<JCheckBox> wavelengthGroupCheckboxes = new ArrayList<JCheckBox>();
for (L2genWavelengthInfo waveLimiterInfo : l2genData.getWaveLimiterInfos()) {
final String currWavelength = waveLimiterInfo.getWavelengthString();
final JCheckBox currJCheckBox = new JCheckBox(currWavelength);
currJCheckBox.setName(currWavelength);
// add current JCheckBox to the externally accessible arrayList
wavelengthsJCheckboxArrayList.add(currJCheckBox);
// add listener for current checkbox
currJCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (waveLimiterControlHandlersEnabled) {
l2genData.setSelectedWaveLimiter(currWavelength, currJCheckBox.isSelected());
}
}
});
wavelengthGroupCheckboxes.add(currJCheckBox);
}
if (l2genData.hasWaveType(L2genWavelengthInfo.WaveType.UV)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.UV, true);
}
if (l2genData.hasWaveType(L2genWavelengthInfo.WaveType.VISIBLE)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.VISIBLE, true);
}
if (l2genData.hasWaveType(L2genWavelengthInfo.WaveType.NIR)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.NIR, true);
}
if (l2genData.hasWaveType(L2genWavelengthInfo.WaveType.SWIR)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.SWIR, true);
}
if (l2genData.hasWaveType(L2genWavelengthInfo.WaveType.IR)) {
l2genData.setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType.IR, true);
}
// some GridBagLayout formatting variables
int gridyCnt = 0;
int gridxCnt = 0;
int NUMBER_OF_COLUMNS = 2;
for (JCheckBox wavelengthGroupCheckbox : wavelengthGroupCheckboxes) {
// add current JCheckBox to the panel
waveLimiterJPanel.add(wavelengthGroupCheckbox,
new GridBagConstraintsCustom(gridxCnt, gridyCnt, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE));
// increment GridBag coordinates
if (gridxCnt < (NUMBER_OF_COLUMNS - 1)) {
gridxCnt++;
} else {
gridxCnt = 0;
gridyCnt++;
}
}
// just in case
l2genData.fireEvent(l2genData.WAVE_LIMITER);
// updateWaveLimiterSelectionStates();
}
/**
* Set all waveLimiterInfos controls to agree with l2genData
*/
private void updateWaveLimiterSelectionStates() {
// Turn off control handlers until all controls are set
waveLimiterControlHandlersEnabled = false;
// Set all checkboxes to agree with l2genData
for (L2genWavelengthInfo waveLimiterInfo : l2genData.getWaveLimiterInfos()) {
for (JCheckBox currJCheckbox : wavelengthsJCheckboxArrayList) {
if (waveLimiterInfo.getWavelengthString().equals(currJCheckbox.getName())) {
if (waveLimiterInfo.isSelected() != currJCheckbox.isSelected()) {
currJCheckbox.setSelected(waveLimiterInfo.isSelected());
}
}
}
}
// Turn on control handlers now that all controls are set
waveLimiterControlHandlersEnabled = true;
}
}
| 21,324 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genSuiteComboBox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genSuiteComboBox.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 12/13/12
* Time: 2:45 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genSuiteComboBox {
private L2genData l2genData;
private JLabel jLabel;
private JComboBox<String> jComboBox;
private boolean controlHandlerEnabled = true;
public L2genSuiteComboBox(L2genData l2genData) {
this.l2genData = l2genData;
jComboBox = new JComboBox<>();
jLabel = new JLabel("Suite");
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
jComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (isControlHandlerEnabled()) {
l2genData.setParamValue(L2genData.SUITE, (String) jComboBox.getSelectedItem());
}
}
});
}
});
}
private void addEventListeners() {
l2genData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
disableControlHandler();
String[] suiteList = l2genData.getSuiteList();
if (suiteList != null) {
jLabel.setEnabled(true);
jComboBox.setEnabled(true);
jComboBox.setModel(new DefaultComboBoxModel<String>(l2genData.getSuiteList()));
} else {
jLabel.setEnabled(false);
jComboBox.setEnabled(false);
}
jComboBox.setSelectedItem(l2genData.getParamValue(L2genData.SUITE));
enableControlHandler();
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JComboBox getjComboBox() {
return jComboBox;
}
private boolean isControlHandlerEnabled() {
return controlHandlerEnabled;
}
private void enableControlHandler() {
controlHandlerEnabled = true;
}
private void disableControlHandler() {
controlHandlerEnabled = false;
}
}
| 2,748 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genParamCheckBox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genParamCheckBox.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/12/12
* Time: 4:14 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genParamCheckBox {
private ParamInfo paramInfo;
private L2genData l2genData;
private JLabel jLabel;
private JCheckBox jCheckBox = new JCheckBox();
public L2genParamCheckBox(L2genData l2genData, ParamInfo paramInfo) {
this.l2genData = l2genData;
this.paramInfo = paramInfo;
jLabel = new JLabel(paramInfo.getName());
jLabel.setToolTipText(paramInfo.getDescription());
jCheckBox.setName(paramInfo.getName());
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
jCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
l2genData.setParamValue(paramInfo.getName(), jCheckBox.isSelected());
}
});
}
private void addEventListeners() {
l2genData.addPropertyChangeListener(paramInfo.getName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
jCheckBox.setSelected(l2genData.getBooleanParamValue(paramInfo.getName()));
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JCheckBox getjCheckBox() {
return jCheckBox;
}
}
| 1,828 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genExcludeIOfileSpecifier.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genExcludeIOfileSpecifier.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/6/12
* Time: 4:36 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genExcludeIOfileSpecifier {
private final JCheckBox jCheckBox;
private L2genData l2genData;
private boolean controlHandlerEnabled = true;
public L2genExcludeIOfileSpecifier(L2genData l2genData) {
this.l2genData = l2genData;
String NAME = "Exclude i/o Files";
String TOOL_TIP = "<html>'Load/Save' parameters functionality will exclude primary i/o file fields<br>and scene dependent ancillary files<br>Useful when reusing parfile for different ifile scenes</html>";
jCheckBox = new JCheckBox(NAME);
jCheckBox.setSelected(l2genData.isExcludeCurrentIOfile());
jCheckBox.setToolTipText(TOOL_TIP);
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
jCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (isControlHandlerEnabled()) {
l2genData.setExcludeCurrentIOfile(jCheckBox.isSelected());
}
}
});
}
private void addEventListeners() {
l2genData.addPropertyChangeListener(l2genData.EXCLUDE_IOFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
disableControlHandler();
jCheckBox.setSelected(l2genData.isExcludeCurrentIOfile());
enableControlHandler();
}
});
}
private boolean isControlHandlerEnabled() {
return controlHandlerEnabled;
}
private void enableControlHandler() {
controlHandlerEnabled = true;
}
private void disableControlHandler() {
controlHandlerEnabled = false;
}
public JCheckBox getjCheckBox() {
return jCheckBox;
}
}
| 2,480 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genGeofileSelector.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genGeofileSelector.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.common.FileSelector;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import gov.nasa.gsfc.seadas.processing.core.SeaDASProcessorModel;
import org.esa.snap.rcp.SnapApp;
import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/6/12
* Time: 11:16 AM
* To change this template use File | Settings | File Templates.
*/
public class L2genGeofileSelector {
final private SeaDASProcessorModel seaDASProcessorModel;
final private FileSelector fileSelector;
private boolean controlHandlerEnabled = true;
public L2genGeofileSelector(SeaDASProcessorModel seaDASProcessorModel) {
this.seaDASProcessorModel = seaDASProcessorModel;
fileSelector = new FileSelector(SnapApp.getDefault().getAppContext(), ParamInfo.Type.IFILE, L2genData.GEOFILE);
fileSelector.setEnabled(false);
fileSelector.setVisible(false);
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
fileSelector.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (isControlHandlerEnabled()) {
seaDASProcessorModel.setParamValue(L2genData.GEOFILE, fileSelector.getFileName());
}
}
});
}
private void addEventListeners() {
seaDASProcessorModel.addPropertyChangeListener(L2genData.GEOFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
disableControlHandler();
fileSelector.setFilename(seaDASProcessorModel.getParamValue(L2genData.GEOFILE));
enableControlHandler();
}
});
seaDASProcessorModel.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
fileSelector.setEnabled(seaDASProcessorModel.isValidIfile() && seaDASProcessorModel.isGeofileRequired());
fileSelector.setVisible(seaDASProcessorModel.isValidIfile() && seaDASProcessorModel.isGeofileRequired());
}
});
}
private boolean isControlHandlerEnabled() {
return controlHandlerEnabled;
}
private void enableControlHandler() {
controlHandlerEnabled = true;
}
private void disableControlHandler() {
controlHandlerEnabled = false;
}
public JPanel getJPanel() {
return fileSelector.getjPanel();
}
public FileSelector getFileSelector() {
return fileSelector;
}
}
| 2,933 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genPrimaryIOFilesSelector.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genPrimaryIOFilesSelector.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.SeaDASProcessorModel;
import gov.nasa.gsfc.seadas.processing.common.GridBagConstraintsCustom;
import javax.swing.*;
import java.awt.*;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 5/14/12
* Time: 7:27 AM
* To change this template use File | Settings | File Templates.
*/
public class L2genPrimaryIOFilesSelector {
private JPanel jPanel;
private L2genIfileSelector ifileSelector;
private L2genGeofileSelector geofileSelector;
private L2genOfileSelector ofileSelector;
public L2genPrimaryIOFilesSelector(SeaDASProcessorModel seaDASProcessorModel) {
ifileSelector = new L2genIfileSelector(seaDASProcessorModel);
geofileSelector = new L2genGeofileSelector(seaDASProcessorModel);
ofileSelector = new L2genOfileSelector(seaDASProcessorModel);
createJPanel(seaDASProcessorModel);
}
public void createJPanel(SeaDASProcessorModel seaDASProcessorModel) {
jPanel = new JPanel(new GridBagLayout());
jPanel.setBorder(BorderFactory.createTitledBorder("Primary I/O Files"));
int gridy = 0;
jPanel.add(ifileSelector.getJPanel(),
new GridBagConstraintsCustom(0, gridy, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
gridy++;
jPanel.add(geofileSelector.getJPanel(),
new GridBagConstraintsCustom(0, gridy, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
gridy++;
jPanel.add(ofileSelector.getJPanel(),
new GridBagConstraintsCustom(0, gridy, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
}
public L2genIfileSelector getIfileSelector() {
return ifileSelector;
}
public L2genGeofileSelector getGeofileSelector() {
return geofileSelector;
}
public L2genOfileSelector getOfileSelector() {
return ofileSelector;
}
public JPanel getjPanel() {
return jPanel;
}
}
| 2,068 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genCategorizedParamsPanel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genCategorizedParamsPanel.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.core.L2genParamCategoryInfo;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import gov.nasa.gsfc.seadas.processing.common.GridBagConstraintsCustom;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 5/12/12
* Time: 9:38 AM
* To change this template use File | Settings | File Templates.
*/
public class L2genCategorizedParamsPanel extends JPanel {
private L2genData l2genData;
private L2genParamCategoryInfo paramCategoryInfo;
private JPanel paramsPanel;
private JButton restoreDefaultsButton;
L2genCategorizedParamsPanel(L2genData l2genData, L2genParamCategoryInfo paramCategoryInfo) {
this.l2genData = l2genData;
this.paramCategoryInfo = paramCategoryInfo;
initComponents();
addComponents();
}
public void initComponents() {
paramsPanel = new JPanel();
paramsPanel.setLayout(new GridBagLayout());
restoreDefaultsButton = new JButton("Restore Defaults ("+paramCategoryInfo.getName()+ " only)");
restoreDefaultsButton.setEnabled(!l2genData.isParamCategoryDefault(paramCategoryInfo));
restoreDefaultsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
l2genData.setToDefaults(paramCategoryInfo);
}
});
int gridy = 0;
for (ParamInfo paramInfo : paramCategoryInfo.getParamInfos()) {
JLabel jLabel;
JLabel defaultIndicator;
Component rightSideComponent;
int rightSideComponentFill;
if (paramInfo.hasValidValueInfos()) {
if (paramInfo.isBit()) {
L2genParamBitwiseCheckboxGroup paramBitwiseCheckboxGroup = new L2genParamBitwiseCheckboxGroup(l2genData, paramInfo);
jLabel = paramBitwiseCheckboxGroup.getjLabel();
rightSideComponent = paramBitwiseCheckboxGroup.getjScrollPane();
rightSideComponentFill = GridBagConstraints.NONE;
} else {
L2genParamComboBox paramComboBox = new L2genParamComboBox(l2genData, paramInfo);
jLabel = paramComboBox.getjLabel();
rightSideComponent = paramComboBox.getjComboBox();
rightSideComponentFill = GridBagConstraints.NONE;
}
} else {
if (paramInfo.getType() == ParamInfo.Type.BOOLEAN) {
L2genParamCheckBox paramCheckBox = new L2genParamCheckBox(l2genData, paramInfo);
// L2genParamCheckBoxKit paramCheckBox = new L2genParamCheckBoxKit(l2genData, paramInfo.getName(), paramInfo.getDescription());
jLabel = paramCheckBox.getjLabel();
rightSideComponent = paramCheckBox.getjCheckBox();
// rightSideComponent = paramCheckBox.getComponent();
rightSideComponentFill = GridBagConstraints.NONE;
} else if (paramInfo.getType() == ParamInfo.Type.IFILE || paramInfo.getType() == ParamInfo.Type.OFILE) {
L2genParamFileSelector paramFileSelector = new L2genParamFileSelector(l2genData, paramInfo);
jLabel = paramFileSelector.getjLabel();
rightSideComponent = paramFileSelector.getjPanel();
rightSideComponentFill = GridBagConstraints.HORIZONTAL;
} else {
L2genParamTextfield paramTextfield = new L2genParamTextfield(l2genData, paramInfo);
jLabel = paramTextfield.getjLabel();
rightSideComponent = paramTextfield.getjTextField();
rightSideComponentFill = paramTextfield.getFill();
}
}
L2genParamDefaultIndicator paramDefaultIndicator = new L2genParamDefaultIndicator(l2genData, paramInfo);
defaultIndicator = paramDefaultIndicator.getjLabel();
paramsPanel.add(jLabel,
new GridBagConstraintsCustom(0, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
paramsPanel.add(defaultIndicator,
new GridBagConstraintsCustom(1, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
paramsPanel.add(rightSideComponent,
new GridBagConstraintsCustom(2, gridy, 1, 0, GridBagConstraints.WEST, rightSideComponentFill));
gridy++;
l2genData.addPropertyChangeListener(paramInfo.getName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (l2genData.isParamCategoryDefault(paramCategoryInfo)) {
restoreDefaultsButton.setEnabled(false);
} else {
restoreDefaultsButton.setEnabled(true);
}
}
});
}
/**
* Add a blank filler panel to the bottom of paramsPanel
* This serves the purpose of expanding at the bottom of the paramsPanel in order to fill the
* space so that the rest of the param controls do not expand
*/
paramsPanel.add(new JPanel(),
new GridBagConstraintsCustom(2, gridy, 1, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH));
}
public void addComponents() {
final JScrollPane paramsScroll = new JScrollPane(paramsPanel);
paramsScroll.setBorder(null);
JPanel innerPanel = new JPanel(new GridBagLayout());
innerPanel.setBorder(BorderFactory.createTitledBorder(paramCategoryInfo.getName()));
innerPanel.add(paramsScroll,
new GridBagConstraintsCustom(0, 0, 1, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH));
innerPanel.add(restoreDefaultsButton,
new GridBagConstraintsCustom(0, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
setLayout(new GridBagLayout());
setPreferredSize(new Dimension(1000, 800));
add(innerPanel,
new GridBagConstraintsCustom(0, 0, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, 3));
}
}
| 6,573 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genParamBitwiseCheckboxGroup.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genParamBitwiseCheckboxGroup.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import gov.nasa.gsfc.seadas.processing.core.ParamValidValueInfo;
import gov.nasa.gsfc.seadas.processing.common.GridBagConstraintsCustom;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/12/12
* Time: 5:17 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genParamBitwiseCheckboxGroup {
private ParamInfo paramInfo;
private L2genData l2genData;
private JLabel jLabel;
private JScrollPane jScrollPane;
private boolean controlHandlerEnabled = true;
public L2genParamBitwiseCheckboxGroup(L2genData l2genData, ParamInfo paramInfo) {
this.l2genData = l2genData;
this.paramInfo = paramInfo;
jLabel = new JLabel(paramInfo.getName());
jLabel.setToolTipText(paramInfo.getDescription());
JPanel jPanel = new JPanel(new GridBagLayout());
int gridy = 0;
for (ParamValidValueInfo paramValidValueInfo : paramInfo.getValidValueInfos()) {
if (paramValidValueInfo.getValue() != null && paramValidValueInfo.getValue().length() > 0) {
L2genParamBitwiseCheckbox paramBitwiseCheckbox = new L2genParamBitwiseCheckbox(l2genData, paramInfo, paramValidValueInfo);
jPanel.add(paramBitwiseCheckbox.getjCheckBox(),
new GridBagConstraintsCustom(0, gridy, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
jPanel.add(paramBitwiseCheckbox.getjLabel(),
new GridBagConstraintsCustom(1, gridy, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
gridy++;
}
}
jScrollPane = new JScrollPane(jPanel);
}
public JLabel getjLabel() {
return jLabel;
}
public JScrollPane getjScrollPane() {
return jScrollPane;
}
private class L2genParamBitwiseCheckbox {
private ParamInfo paramInfo;
private L2genData l2genData;
private ParamValidValueInfo paramValidValueInfo;
private JLabel jLabel;
private JCheckBox jCheckBox;
public L2genParamBitwiseCheckbox(L2genData l2genData, ParamInfo paramInfo, ParamValidValueInfo paramValidValueInfo) {
this.l2genData = l2genData;
this.paramInfo = paramInfo;
this.paramValidValueInfo = paramValidValueInfo;
jCheckBox = new JCheckBox();
jCheckBox.setSelected(paramInfo.isBitwiseSelected(paramValidValueInfo));
jLabel = new JLabel(paramValidValueInfo.getValue() + " - " + paramValidValueInfo.getDescription());
jLabel.setToolTipText(paramValidValueInfo.getValue() + " - " + paramValidValueInfo.getDescription());
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
jCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
String currValueString = l2genData.getParamValue(paramInfo.getName());
int currValue = Integer.parseInt(currValueString);
String currValidValueString = paramValidValueInfo.getValue();
int currValidValue = Integer.parseInt(currValidValueString);
int newValue = currValue;
if (currValidValue > 0) {
if (jCheckBox.isSelected()) {
newValue = (currValue | currValidValue);
} else {
if ((currValue & currValidValue) > 0) {
newValue = currValue - currValidValue;
}
}
} else {
if (jCheckBox.isSelected()) {
newValue = 0;
} else {
if (isControlHandlerEnabled()) {
disableControlHandler();
l2genData.setParamToDefaults(paramInfo.getName());
enableControlHandler();
}
return;
}
}
String newValueString = Integer.toString(newValue);
if (isControlHandlerEnabled()) {
disableControlHandler();
l2genData.setParamValue(paramInfo.getName(), newValueString);
enableControlHandler();
}
}
});
}
private void addEventListeners() {
l2genData.addPropertyChangeListener(paramInfo.getName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
int value = Integer.parseInt(paramValidValueInfo.getValue());
if (value > 0) {
jCheckBox.setSelected(paramInfo.isBitwiseSelected(paramValidValueInfo));
} else {
if (paramValidValueInfo.getValue().equals(l2genData.getParamValue(paramInfo.getName()))) {
jCheckBox.setSelected(true);
} else {
jCheckBox.setSelected(false);
}
}
}
});
}
private boolean isControlHandlerEnabled() {
return controlHandlerEnabled;
}
private void enableControlHandler() {
controlHandlerEnabled = true;
}
private void disableControlHandler() {
controlHandlerEnabled = false;
}
public JLabel getjLabel() {
return jLabel;
}
public JCheckBox getjCheckBox() {
return jCheckBox;
}
}
}
| 6,316 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genAquariusDialog.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genAquariusDialog.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 10/24/12
* Time: 1:30 PM
* To change this template use File | Settings | File Templates.
*/
/*
* Copyright (C) 2011 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* 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/
*/
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.gpf.ui.SingleTargetProductDialog;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.DefaultAppContext;
class L2genAquariusDialog extends SingleTargetProductDialog {
private final L2genForm form;
OCSSW ocssw;
public static void main(String[] args) {
final DefaultAppContext context = new DefaultAppContext("l2gen_aquarius");
final L2genAquariusDialog dialog = new L2genAquariusDialog("L2genAquariusTestDialog", null, context);
dialog.show();
}
L2genAquariusDialog(final String title, final String helpID, AppContext appContext) {
super(appContext, title, ID_APPLY_CLOSE_HELP, helpID);
//form = new L2genAquariusForm(getTargetProductSelector(), appContext);
form = new L2genForm(appContext, "test", L2genData.Mode.L2GEN_AQUARIUS, ocssw);
}
@Override
protected boolean verifyUserInput() {
if (form.getSelectedSourceProduct() == null) {
showErrorDialog("No product to reproject selected.");
return false;
}
return true;
}
@Override
protected Product createTargetProduct() throws Exception {
return null;
}
@Override
public int show() {
form.prepareShow();
setContent(form);
return super.show();
}
@Override
public void hide() {
form.prepareHide();
super.hide();
}
}
| 2,520 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genDialog.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genDialog.java | /*
* Copyright (C) 2011 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* 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 gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.gpf.ui.SingleTargetProductDialog;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.DefaultAppContext;
class L2genDialog extends SingleTargetProductDialog {
private L2genForm form;
OCSSW ocssw;
public static void main(String[] args) {
final DefaultAppContext context = new DefaultAppContext("L2gen");
final L2genDialog dialog = new L2genDialog("L2genTestDialog", null, context);
dialog.show();
}
L2genDialog(final String title, final String helpID, AppContext appContext) {
super(appContext, title, ID_APPLY_CLOSE_HELP, helpID);
//form = new L2genForm(getTargetProductSelector(), appContext);
form = new L2genForm(appContext, "test", ocssw);
}
@Override
protected boolean verifyUserInput() {
if (form.getSelectedSourceProduct() == null) {
Dialogs.showError("No product to reproject selected.");
return false;
}
return true;
}
@Override
protected Product createTargetProduct() throws Exception {
return null;
}
@Override
public int show() {
form.prepareShow();
setContent(form);
return super.show();
}
@Override
public void hide() {
form.prepareHide();
super.hide();
}
}
| 2,252 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genParamFileSelector.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genParamFileSelector.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import gov.nasa.gsfc.seadas.processing.common.FileSelector;
import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.esa.snap.rcp.SnapApp;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/12/12
* Time: 4:40 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genParamFileSelector {
private ParamInfo paramInfo;
private L2genData l2genData;
private JLabel jLabel;
private JPanel jPanel;
private FileSelector fileSelectorPanel;
private boolean controlHandlerEnabled = true;
public L2genParamFileSelector(L2genData l2genData, ParamInfo paramInfo) {
this.l2genData = l2genData;
this.paramInfo = paramInfo;
jLabel = new JLabel(paramInfo.getName());
jLabel.setToolTipText(paramInfo.getDescription());
// FileSelector.Type type = null;
// if (paramInfo.getType() == ParamInfo.Type.IFILE) {
// type = FileSelector.Type.IFILE;
// } else if (paramInfo.getType() == ParamInfo.Type.OFILE) {
// type = FileSelector.Type.OFILE;
// }
if (paramInfo.getType() != null) {
fileSelectorPanel = new FileSelector(SnapApp.getDefault().getAppContext(), paramInfo.getType());
jPanel = fileSelectorPanel.getjPanel();
}
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
fileSelectorPanel.addPropertyChangeListener(fileSelectorPanel.getPropertyName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (isControlHandlerEnabled()) {
l2genData.setParamValue(paramInfo.getName(), fileSelectorPanel.getFileName());
}
}
});
}
private void addEventListeners() {
l2genData.addPropertyChangeListener(paramInfo.getName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
disableControlHandler();
fileSelectorPanel.setFilename(l2genData.getParamValue(paramInfo.getName()));
enableControlHandler();
}
});
}
private boolean isControlHandlerEnabled() {
return controlHandlerEnabled;
}
private void enableControlHandler() {
controlHandlerEnabled = true;
}
private void disableControlHandler() {
controlHandlerEnabled = false;
}
public JLabel getjLabel() {
return jLabel;
}
public JPanel getjPanel() {
return jPanel;
}
}
| 2,871 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genParfilePanel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genParfilePanel.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.common.GridBagConstraintsCustom;
import javax.swing.*;
import java.awt.*;
/**
* Created by IntelliJ IDEA.
* User: knowles
* @author aabduraz
* Date: 6/24/19
* To change this template use File | Settings | File Templates.
*/
public class L2genParfilePanel {
private JPanel jPanel;
private L2genData l2genData;
private int tabIndex;
private L2genParfileImporter parfileImporter;
private L2genParfileExporter parfileExporter;
private L2genExcludeIOfileSpecifier excludeIOfileSpecifier;
private L2genGetAncillaryFilesSpecifier getAncillaryFilesSpecifier;
private L2genGetAncillarySplitButton getAncillarySplitButton;
private L2genShowDefaultsSpecifier showDefaultsSpecifier;
private L2genParStringSpecifier parStringSpecifier;
private L2genSuiteComboBox suiteComboBox;
L2genParfilePanel(L2genData l2genData, int tabIndex) {
this.l2genData = l2genData;
this.tabIndex = tabIndex;
parfileImporter = new L2genParfileImporter(l2genData);
parfileExporter = new L2genParfileExporter(l2genData);
excludeIOfileSpecifier = new L2genExcludeIOfileSpecifier(l2genData);
getAncillaryFilesSpecifier = new L2genGetAncillaryFilesSpecifier(l2genData);
getAncillarySplitButton = new L2genGetAncillarySplitButton(l2genData);
showDefaultsSpecifier = new L2genShowDefaultsSpecifier(l2genData);
parStringSpecifier = new L2genParStringSpecifier(l2genData, tabIndex);
suiteComboBox = new L2genSuiteComboBox(l2genData);
if (l2genData.getMode() == L2genData.Mode.L2GEN_AQUARIUS) {
parStringSpecifier.setEditable(true);
parStringSpecifier.setToolTip("<html>This parameter text field is not editable for Aquarius.<br>" +
"If you need custom files you can use the <b>Load Parameters</b> feature.</html>");
}
createJPanel();
}
public void createJPanel() {
jPanel = new JPanel(new GridBagLayout());
jPanel.setBorder(BorderFactory.createTitledBorder("Parfile"));
final JPanel openButtonExcludePanel = new JPanel(new GridBagLayout());
openButtonExcludePanel.add(parfileImporter.getjButton(),
new GridBagConstraintsCustom(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2));
openButtonExcludePanel.add(parfileExporter.getjButton(),
new GridBagConstraintsCustom(1, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
// todo Danny
if (l2genData.getMode() != L2genData.Mode.L2GEN_AQUARIUS) {
openButtonExcludePanel.setBorder(BorderFactory.createEtchedBorder());
openButtonExcludePanel.add(excludeIOfileSpecifier.getjCheckBox(),
new GridBagConstraintsCustom(2, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2));
}
int subPanelGridx = 0;
final JPanel subPanel = new JPanel(new GridBagLayout());
subPanel.add(openButtonExcludePanel,
new GridBagConstraintsCustom(++subPanelGridx, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
// todo Danny
if (l2genData.getMode() != L2genData.Mode.L2GEN_AQUARIUS) {
final JPanel defaultsPanel = new JPanel(new GridBagLayout());
defaultsPanel.setBorder(BorderFactory.createEtchedBorder());
defaultsPanel.add(showDefaultsSpecifier.getjCheckBox(),
new GridBagConstraintsCustom(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
subPanel.add(defaultsPanel,
new GridBagConstraintsCustom(++subPanelGridx, 0, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
final JPanel suitePanel = new JPanel(new GridBagLayout());
suitePanel.setBorder(BorderFactory.createEtchedBorder());
suitePanel.add(suiteComboBox.getjLabel(),
new GridBagConstraintsCustom(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2));
suitePanel.add(suiteComboBox.getjComboBox(),
new GridBagConstraintsCustom(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2));
subPanel.add(suitePanel,
new GridBagConstraintsCustom(++subPanelGridx, 0, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
// subPanel.add(getAncillaryFilesSpecifier.getjButton(),
// new GridBagConstraintsCustom(1, 0, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
if (l2genData.getMode() != L2genData.Mode.L3GEN) {
subPanel.add(getAncillarySplitButton.getAncillarySplitButton(),
new GridBagConstraintsCustom(++subPanelGridx, 0, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
}
}
// todo Danny
if (l2genData.getMode() == L2genData.Mode.L2GEN_AQUARIUS) {
subPanel.add(new JPanel(),
new GridBagConstraintsCustom(++subPanelGridx, 0, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL));
}
jPanel.add(subPanel,
new GridBagConstraintsCustom(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
jPanel.add(new JScrollPane(parStringSpecifier.getjTextArea()),
new GridBagConstraintsCustom(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH));
}
public JPanel getjPanel() {
return jPanel;
}
}
| 5,711 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genIfileSelector.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genIfileSelector.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import com.bc.ceres.swing.selection.AbstractSelectionChangeListener;
import com.bc.ceres.swing.selection.SelectionChangeEvent;
import gov.nasa.gsfc.seadas.processing.common.SeadasFileSelector;
import gov.nasa.gsfc.seadas.processing.core.SeaDASProcessorModel;
import org.esa.snap.rcp.SnapApp;
import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/6/12
* Time: 11:22 AM
* To change this template use File | Settings | File Templates.
*/
public class L2genIfileSelector {
final private SeaDASProcessorModel seaDASProcessorModel;
private SeadasFileSelector fileSelector;
private boolean controlHandlerEnabled = true;
private boolean eventHandlerEnabled = true;
public L2genIfileSelector(SeaDASProcessorModel seaDASProcessorModel) {
this.seaDASProcessorModel = seaDASProcessorModel;
fileSelector = new SeadasFileSelector(SnapApp.getDefault().getAppContext(), seaDASProcessorModel.getPrimaryInputFileOptionName(), seaDASProcessorModel.isMultipleInputFiles());
fileSelector.initProducts();
fileSelector.setFileNameLabel(new JLabel(seaDASProcessorModel.getPrimaryInputFileOptionName()));
fileSelector.getFileNameComboBox().setPrototypeDisplayValue(
"123456789 123456789 123456789 123456789 123456789 ");
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
fileSelector.addSelectionChangeListener(new AbstractSelectionChangeListener() {
@Override
public void selectionChanged(SelectionChangeEvent event) {
File iFile = getSelectedIFile();
if (isControlHandlerEnabled() && iFile != null) {
disableEventHandler();
//disableControlHandler();
seaDASProcessorModel.setParamValue(seaDASProcessorModel.getPrimaryInputFileOptionName(), getSelectedIFileName());
enableEventHandler();
}
}
});
}
private void addEventListeners() {
seaDASProcessorModel.addPropertyChangeListener(seaDASProcessorModel.getPrimaryInputFileOptionName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
String ifileName = seaDASProcessorModel.getParamValue(seaDASProcessorModel.getPrimaryInputFileOptionName());
//System.out.println("processor model property changed! ifileName in file selector " + ifileName);
File iFile = new File(ifileName);
if (isEventHandlerEnabled() || ifileName.isEmpty()) {
//disableEventHandler();
disableControlHandler();
if (iFile.exists()) {
fileSelector.setSelectedFile(iFile);
} else {
fileSelector.setSelectedFile(null);
}
enableControlHandler();
}
}
}
);
seaDASProcessorModel.addPropertyChangeListener("cancel", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
fileSelector = null;
}
});
}
private boolean isControlHandlerEnabled() {
return controlHandlerEnabled;
}
private boolean isEventHandlerEnabled() {
return eventHandlerEnabled;
}
private void enableControlHandler() {
controlHandlerEnabled = true;
}
private void disableControlHandler() {
controlHandlerEnabled = false;
}
private void enableEventHandler() {
eventHandlerEnabled = true;
}
private void disableEventHandler() {
eventHandlerEnabled = false;
}
public File getSelectedIFile() {
if (fileSelector == null) {
return null;
}
if (fileSelector.getSelectedFile() == null) {
return null;
}
return fileSelector.getSelectedFile();
}
/**
* This method derives uncompressed file name in case the product is compressed.
*
* @return Selected product file name after uncompressed.
*/
public String getSelectedIFileName() {
if (fileSelector == null) {
return null;
}
if (fileSelector.getSelectedFile() == null) {
return null;
}
return fileSelector.getSelectedFile().toString();
}
public JPanel getJPanel() {
return fileSelector.createDefaultPanel();
}
public SeadasFileSelector getFileSelector() {
return fileSelector;
}
}
| 5,024 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genParamDefaultIndicator.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genParamDefaultIndicator.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/12/12
* Time: 4:11 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genParamDefaultIndicator {
private final String DEFAULT_INDICATOR_TOOLTIP = "* Identicates that the selection is not the default value";
private final String DEFAULT_INDICATOR_LABEL_ON = " * ";
private final String DEFAULT_INDICATOR_LABEL_OFF = " ";
private L2genData l2genData;
private ParamInfo paramInfo;
private JLabel jLabel = new JLabel();
public L2genParamDefaultIndicator(L2genData l2genData, ParamInfo paramInfo) {
this.l2genData = l2genData;
this.paramInfo = paramInfo;
addEventListeners();
}
private void addEventListeners() {
l2genData.addPropertyChangeListener(paramInfo.getName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
setDefaultIndicator();
}
});
}
private void setDefaultIndicator() {
if (l2genData.isParamDefault(paramInfo.getName())) {
jLabel.setText(DEFAULT_INDICATOR_LABEL_OFF);
jLabel.setToolTipText("");
} else {
jLabel.setText(DEFAULT_INDICATOR_LABEL_ON);
jLabel.setToolTipText(DEFAULT_INDICATOR_TOOLTIP);
}
}
public JLabel getjLabel() {
return jLabel;
}
}
| 1,726 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genGetAncillarySplitButton.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genGetAncillarySplitButton.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import javax.swing.*;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 12/14/12
* Time: 3:58 PM
* To change this template use File | Settings | File Templates.
*/
// May 22, 2023 - Knowles - Updated to remove JideSplitButton as it was breaking things with Java11 on Mac
// http://java.dzone.com/news/drop-down-buttons-swing-new-al
public class L2genGetAncillarySplitButton {
private L2genData l2genData;
private JComboBox ancillaryComboBox;
private final String GET_ANCILLARY = " Get Ancillary";
private final String REFRESH_ANCILLARY = " Refresh";
private final String NEAR_REAL_TIME_NO2_ANCILLARY = " Near Real-Time NO2";
private final String FORCE_DOWNLOAD_ANCILLARY = " Force Download";
public L2genGetAncillarySplitButton(L2genData l2genData) {
this.l2genData = l2genData;
final String[] jComboBoxArray = new String[5];
final String[] jComboBoxToolTipsArray = new String[5];
jComboBoxArray[0] = "-- Get Ancillary Options --";
jComboBoxToolTipsArray[0] = "Retrieve ancillary files with options below";
jComboBoxArray[1] = GET_ANCILLARY;
jComboBoxToolTipsArray[1] = "Run getanc";
jComboBoxArray[2] = REFRESH_ANCILLARY;
jComboBoxToolTipsArray[2] = "Run getanc with option:" + REFRESH_ANCILLARY;
jComboBoxArray[3] = NEAR_REAL_TIME_NO2_ANCILLARY;
jComboBoxToolTipsArray[3] = "Run getanc with option:" + NEAR_REAL_TIME_NO2_ANCILLARY;
jComboBoxArray[4] = FORCE_DOWNLOAD_ANCILLARY;
jComboBoxToolTipsArray[4] = "Run getanc with option:" + FORCE_DOWNLOAD_ANCILLARY;
ancillaryComboBox = new JComboBox(jComboBoxArray);
ancillaryComboBox.setEnabled(false);
final MyComboBoxRenderer myComboBoxRenderer = new MyComboBoxRenderer();
myComboBoxRenderer.setTooltipList(jComboBoxToolTipsArray);
Boolean[] jComboBoxEnabledArray = {false, true, true, true, true};
myComboBoxRenderer.setEnabledList(jComboBoxEnabledArray);
ancillaryComboBox.setRenderer(myComboBoxRenderer);
ancillaryComboBox.setEditable(false);
ancillaryComboBox.setPreferredSize(ancillaryComboBox.getPreferredSize());
ancillaryComboBox.setMaximumSize(ancillaryComboBox.getPreferredSize());
ancillaryComboBox.setMinimumSize(ancillaryComboBox.getPreferredSize());
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
ancillaryComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (GET_ANCILLARY.equals(ancillaryComboBox.getSelectedItem())) {
l2genData.setAncillaryFiles(false, false, false);
} else if (REFRESH_ANCILLARY.equals(ancillaryComboBox.getSelectedItem())) {
l2genData.setAncillaryFiles(true,false,false);
} else if (NEAR_REAL_TIME_NO2_ANCILLARY.equals(ancillaryComboBox.getSelectedItem())) {
l2genData.setAncillaryFiles(false,false,true);
} else if (FORCE_DOWNLOAD_ANCILLARY.equals(ancillaryComboBox.getSelectedItem())) {
l2genData.setAncillaryFiles(false,true,false);
} else {
}
}
});
}
private void addEventListeners() {
l2genData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
ancillaryComboBox.setEnabled(l2genData.isValidIfile());
}
});
}
public JComboBox getAncillarySplitButton() {
return ancillaryComboBox;
}
class MyComboBoxRenderer extends BasicComboBoxRenderer {
private String[] tooltips;
private Boolean[] enabledList;
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected) {
if (-1 < index && index < tooltips.length) {
list.setToolTipText(tooltips[index]);
}
if (-1 < index && index < enabledList.length) {
if (enabledList[index] == true) {
setBackground(Color.blue);
setForeground(Color.white);
} else {
setBackground(Color.blue);
setForeground(Color.gray);
}
}
} else {
if (-1 < index && index < enabledList.length) {
if (enabledList[index] == true) {
setBackground(Color.white);
setForeground(Color.black);
} else {
setBackground(Color.white);
setForeground(Color.gray);
}
}
}
setFont(list.getFont());
setText((value == null) ? "" : value.toString());
return this;
}
public void setTooltipList(String[] tooltipList) {
this.tooltips = tooltipList;
}
public void setEnabledList(Boolean[] enabledList) {
this.enabledList = enabledList;
}
}
}
| 5,806 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genForm.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genForm.java | /*
Author: Danny Knowles
Don Shea
*/
package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import gov.nasa.gsfc.seadas.processing.common.CloProgramUI;
import gov.nasa.gsfc.seadas.processing.common.GridBagConstraintsCustom;
import gov.nasa.gsfc.seadas.processing.common.SeadasFileSelector;
import gov.nasa.gsfc.seadas.processing.common.SimpleDialogMessage;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.core.L2genParamCategoryInfo;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import gov.nasa.gsfc.seadas.processing.core.ProcessorModel;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.AppContext;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
public class L2genForm extends JPanel implements CloProgramUI {
private L2genData masterData;
private L2genMainPanel l2genMainPanel;
private JCheckBox openInAppCheckBox;
private final JTabbedPane jTabbedPane = new JTabbedPane();
private int tabIndex;
private JCheckBox keepParamsCheckbox;
public L2genForm(AppContext appContext, String xmlFileName, final File iFile, boolean showIOFields, L2genData.Mode mode, boolean keepParams, boolean ifileIndependent, OCSSW ocssw) {
masterData = L2genData.getNew(mode, ocssw);
masterData.setIfileIndependentMode(ifileIndependent);
masterData.setKeepParams(keepParams);
setOpenInAppCheckBox(new JCheckBox("Open in " + appContext.getApplicationName()));
getOpenInAppCheckBox().setSelected(true);
keepParamsCheckbox = new JCheckBox("Keep params when new ifile is selected");
keepParamsCheckbox.setSelected(keepParams);
keepParamsCheckbox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
masterData.setKeepParams(keepParamsCheckbox.isSelected());
}
});
masterData.showIOFields = showIOFields;
SnapApp snapApp = SnapApp.getDefault();
snapApp.setStatusBarMessage("Initializing L2gen GUI");
ProgressMonitorSwingWorker pmSwingWorker = new ProgressMonitorSwingWorker(snapApp.getMainFrame(),
masterData.getGuiName()) {
@Override
protected Void doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception {
pm.beginTask("Initializing " + masterData.getGuiName(), 2);
try {
masterData.initXmlBasedObjects();
createMainTab();
createProductsTab();
createCategoryParamTabs();
tabIndex = jTabbedPane.getSelectedIndex();
getjTabbedPane().addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
tabChangeHandler();
}
});
setLayout(new GridBagLayout());
add(getjTabbedPane(),
new GridBagConstraintsCustom(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH));
// add(getOpenInAppCheckBox(),
// new GridBagConstraintsCustom(0, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
JPanel bottomPanel = new JPanel(new GridBagLayout());
if (masterData.getMode() == L2genData.Mode.L2GEN_AQUARIUS) {
bottomPanel.add(new JPanel(),
new GridBagConstraintsCustom(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
} else {
bottomPanel.add(keepParamsCheckbox,
new GridBagConstraintsCustom(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
}
bottomPanel.add(getOpenInAppCheckBox(),
new GridBagConstraintsCustom(1, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
add(bottomPanel,
new GridBagConstraintsCustom(0, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.BOTH));
masterData.disableEvent(L2genData.PARSTRING);
masterData.disableEvent(L2genData.L2PROD);
if (!masterData.isIfileIndependentMode()) {
if (iFile != null) {
masterData.setInitialValues(iFile);
} else {
masterData.setInitialValues(getInitialSelectedSourceFile());
}
}
//todo this crazy for multilevel processor
// if (masterData.isIfileIndependentMode()) {
// masterData.fireEvent(L2genData.IFILE);
// }
masterData.fireAllParamEvents();
masterData.enableEvent(L2genData.L2PROD);
masterData.enableEvent(L2genData.PARSTRING);
pm.worked(1);
} catch (IOException e) {
pm.done();
SimpleDialogMessage dialog = new SimpleDialogMessage(null, "ERROR: " + e.getMessage());
dialog.setVisible(true);
dialog.setEnabled(true);
} finally {
pm.done();
}
return null;
}
};
pmSwingWorker.executeWithBlocking();
masterData.setInitialized(true);
}
public L2genForm(AppContext appContext, String xmlFileName, OCSSW ocssw) {
this(appContext, xmlFileName, null, true, L2genData.Mode.L2GEN, false, false, ocssw);
}
public L2genForm(AppContext appContext, String xmlFileName, L2genData.Mode mode, OCSSW ocssw) {
this(appContext, xmlFileName, null, true, mode, false, false, ocssw);
}
private void tabChangeHandler() {
int oldTabIndex = tabIndex;
int newTabIndex = jTabbedPane.getSelectedIndex();
tabIndex = newTabIndex;
masterData.fireEvent(L2genData.TAB_CHANGE, oldTabIndex, newTabIndex);
}
private void createMainTab() {
final String TAB_NAME = "Main";
final int tabIndex = jTabbedPane.getTabCount();
l2genMainPanel = new L2genMainPanel(masterData, tabIndex);
jTabbedPane.addTab(TAB_NAME, l2genMainPanel.getjPanel());
}
private void createProductsTab() {
final String TAB_NAME = "Products";
L2genProductsPanel l2genProductsPanel = new L2genProductsPanel(masterData);
jTabbedPane.addTab(TAB_NAME, l2genProductsPanel);
final int tabIndex = jTabbedPane.getTabCount() - 1;
masterData.addPropertyChangeListener(L2genData.L2PROD, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
StringBuilder tabname = new StringBuilder(TAB_NAME);
if (masterData.isParamDefault(L2genData.L2PROD)) {
jTabbedPane.setTitleAt(tabIndex, tabname.toString());
} else {
jTabbedPane.setTitleAt(tabIndex, tabname.append("*").toString());
}
}
});
masterData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
jTabbedPane.setEnabledAt(tabIndex, masterData.isValidIfile());
}
});
}
private void createCategoryParamTabs() {
for (final L2genParamCategoryInfo paramCategoryInfo : masterData.getParamCategoryInfos()) {
if (paramCategoryInfo.isAutoTab() && (paramCategoryInfo.getParamInfos().size() > 0)) {
L2genCategorizedParamsPanel l2genCategorizedParamsPanel = new L2genCategorizedParamsPanel(masterData, paramCategoryInfo);
jTabbedPane.addTab(paramCategoryInfo.getName(), l2genCategorizedParamsPanel);
final int tabIndex = jTabbedPane.getTabCount() - 1;
/*
Add titles to each of the tabs, adding (*) where tab contains a non-default parameter
*/
for (ParamInfo paramInfo : paramCategoryInfo.getParamInfos()) {
masterData.addPropertyChangeListener(paramInfo.getName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
StringBuilder stringBuilder = new StringBuilder(paramCategoryInfo.getName());
if (masterData.isParamCategoryDefault(paramCategoryInfo)) {
jTabbedPane.setTitleAt(tabIndex, stringBuilder.toString());
} else {
jTabbedPane.setTitleAt(tabIndex, stringBuilder.append("*").toString());
}
}
});
}
// todo new
if (masterData.isIfileIndependentMode()) {
jTabbedPane.setEnabled(true);
}
masterData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
jTabbedPane.setEnabledAt(tabIndex, masterData.isValidIfile());
}
});
}
}
}
@Override
public JPanel getParamPanel() {
return this;
}
public ProcessorModel getProcessorModel() {
return masterData.getProcessorModel();
}
public String getParamString() {
return masterData.getParString();
}
public void setParamString(String paramString) {
masterData.setParString(paramString, false, false);
}
public Product getInitialSelectedSourceProduct() {
return SnapApp.getDefault().getSelectedProduct(SnapApp.SelectionSourceHint.AUTO);
}
public File getInitialSelectedSourceFile() {
if (getInitialSelectedSourceProduct() != null) {
return getInitialSelectedSourceProduct().getFileLocation();
}
return null;
}
public SeadasFileSelector getSourceProductSelector() {
return l2genMainPanel.getPrimaryIOFilesPanel().getIfileSelector().getFileSelector();
}
public File getSelectedSourceProduct() {
if (getSourceProductSelector() != null) {
return getSourceProductSelector().getSelectedFile();
}
return null;
}
public void prepareShow() {
if (getSourceProductSelector() != null) {
getSourceProductSelector().initProducts();
}
}
public void prepareHide() {
if (getSourceProductSelector() != null) {
getSourceProductSelector().releaseFiles();
}
}
public boolean isOpenOutputInApp() {
if (getOpenInAppCheckBox() != null) {
return getOpenInAppCheckBox().isSelected();
}
return true;
}
public JCheckBox getOpenInAppCheckBox() {
return openInAppCheckBox;
}
public void setOpenInAppCheckBox(JCheckBox openInAppCheckBox) {
this.openInAppCheckBox = openInAppCheckBox;
}
public JTabbedPane getjTabbedPane() {
return jTabbedPane;
}
//
// public L2genData getMasterData() {
// return masterData;
// }
} | 12,124 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genParamTextfield.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genParamTextfield.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/12/12
* Time: 4:20 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genParamTextfield {
private ParamInfo paramInfo;
private L2genData l2genData;
private JLabel jLabel;
private JTextField jTextField;
private int fill;
public L2genParamTextfield(L2genData l2genData, ParamInfo paramInfo) {
this.l2genData = l2genData;
this.paramInfo = paramInfo;
final String PROTOTYPE_70 = buildStringPrototype(70);
final String PROTOTYPE_60 = buildStringPrototype(60);
final String PROTOTYPE_15 = buildStringPrototype(15);
String textfieldPrototype;
if (paramInfo.getType() == ParamInfo.Type.STRING) {
textfieldPrototype = PROTOTYPE_60;
fill = GridBagConstraints.NONE;
} else if (paramInfo.getType() == ParamInfo.Type.INT) {
textfieldPrototype = PROTOTYPE_15;
fill = GridBagConstraints.NONE;
} else if (paramInfo.getType() == ParamInfo.Type.FLOAT) {
textfieldPrototype = buildStringPrototype(60);
fill = GridBagConstraints.NONE;
} else if (paramInfo.getType() == ParamInfo.Type.IFILE) {
textfieldPrototype = PROTOTYPE_70;
fill = GridBagConstraints.HORIZONTAL;
} else if (paramInfo.getType() == ParamInfo.Type.OFILE) {
textfieldPrototype = PROTOTYPE_70;
fill = GridBagConstraints.HORIZONTAL;
} else {
textfieldPrototype = PROTOTYPE_70;
fill = GridBagConstraints.NONE;
}
jTextField = new JTextField(textfieldPrototype);
jTextField.setPreferredSize(jTextField.getPreferredSize());
jTextField.setMaximumSize(jTextField.getPreferredSize());
jTextField.setMinimumSize(jTextField.getPreferredSize());
jTextField.setText("");
jLabel = new JLabel(paramInfo.getName());
jLabel.setToolTipText(paramInfo.getDescription());
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
jTextField.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
l2genData.setParamValue(paramInfo.getName(), jTextField.getText().toString());
}
});
jTextField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
l2genData.setParamValue(paramInfo.getName(), jTextField.getText().toString());
}
});
}
private void addEventListeners() {
l2genData.addPropertyChangeListener(paramInfo.getName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
jTextField.setText(l2genData.getParamValue(paramInfo.getName()));
}
});
}
private String buildStringPrototype(int size) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < size; i++) {
stringBuilder.append("p");
}
return stringBuilder.toString();
}
public JLabel getjLabel() {
return jLabel;
}
public JTextField getjTextField() {
return jTextField;
}
public int getFill() {
return fill;
}
}
| 3,973 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genProductTreeSelectorPanel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genProductTreeSelectorPanel.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.common.GridBagConstraintsCustom;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.l2gen.productData.L2genBaseInfo;
import gov.nasa.gsfc.seadas.processing.l2gen.productData.L2genProductCategoryInfo;
import gov.nasa.gsfc.seadas.processing.l2gen.productData.L2genWavelengthInfo;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.*;
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.util.Enumeration;
import java.util.EventObject;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 5/11/12
* Time: 2:28 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genProductTreeSelectorPanel extends JPanel {
private L2genData l2genData;
private DefaultMutableTreeNode rootNode;
private JTree productJTree;
L2genProductTreeSelectorPanel(L2genData l2genData) {
this.l2genData = l2genData;
initComponents();
addComponents();
}
public void initComponents() {
productJTree = createProductJTree();
}
public void addComponents() {
setLayout(new GridBagLayout());
setBorder(BorderFactory.createTitledBorder("Product Selector"));
JScrollPane jScrollPane = new JScrollPane(productJTree);
jScrollPane.setBorder(null);
add(jScrollPane,
new GridBagConstraintsCustom(0, 0, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH));
}
private L2genTristateCheckBox.State getCheckboxState(L2genBaseInfo.State state) {
switch (state) {
case SELECTED:
return L2genTristateCheckBox.SELECTED;
case PARTIAL:
return L2genTristateCheckBox.PARTIAL;
default:
return L2genTristateCheckBox.NOT_SELECTED;
}
}
private L2genBaseInfo.State getInfoState(L2genTristateCheckBox.State state) {
if (state == L2genTristateCheckBox.SELECTED) {
return L2genBaseInfo.State.SELECTED;
}
if (state == L2genTristateCheckBox.PARTIAL) {
return L2genBaseInfo.State.PARTIAL;
}
return L2genBaseInfo.State.NOT_SELECTED;
}
class CheckBoxNodeRenderer implements TreeCellRenderer {
private JPanel nodeRenderer = new JPanel();
private JLabel label = new JLabel();
private L2genTristateCheckBox check = new L2genTristateCheckBox();
Color selectionBorderColor, selectionForeground, selectionBackground,
textForeground, textBackground;
protected L2genTristateCheckBox getJCheckBox() {
return check;
}
public CheckBoxNodeRenderer() {
Insets inset0 = new Insets(0, 0, 0, 0);
check.setMargin(inset0);
nodeRenderer.setLayout(new BorderLayout());
nodeRenderer.add(check, BorderLayout.WEST);
nodeRenderer.add(label, BorderLayout.CENTER);
Font fontValue;
fontValue = UIManager.getFont("Tree.font");
if (fontValue != null) {
check.setFont(fontValue);
label.setFont(fontValue);
}
Boolean booleanValue = (Boolean) UIManager
.get("Tree.drawsFocusBorderAroundIcon");
check.setFocusPainted((booleanValue != null)
&& (booleanValue.booleanValue()));
selectionBorderColor = UIManager.getColor("Tree.selectionBorderColor");
selectionForeground = UIManager.getColor("Tree.selectionForeground");
selectionBackground = UIManager.getColor("Tree.selectionBackground");
textForeground = UIManager.getColor("Tree.textForeground");
textBackground = UIManager.getColor("Tree.textBackground");
}
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
String stringValue = null;
L2genBaseInfo.State state = L2genBaseInfo.State.NOT_SELECTED;
if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
if (userObject instanceof L2genBaseInfo) {
L2genBaseInfo info = (L2genBaseInfo) userObject;
state = info.getState();
stringValue = info.getFullName();
tree.setToolTipText(info.getDescription());
}
}
if (stringValue == null) {
stringValue = tree.convertValueToText(value, selected, expanded, leaf, row, false);
}
label.setText(stringValue);
check.setState(getCheckboxState(state));
check.setEnabled(tree.isEnabled());
if (selected) {
label.setForeground(selectionForeground);
check.setForeground(selectionForeground);
nodeRenderer.setForeground(selectionForeground);
label.setBackground(selectionBackground);
check.setBackground(selectionBackground);
nodeRenderer.setBackground(selectionBackground);
} else {
label.setForeground(textForeground);
check.setForeground(textForeground);
nodeRenderer.setForeground(textForeground);
label.setBackground(textBackground);
check.setBackground(textBackground);
nodeRenderer.setBackground(textBackground);
}
// if (((DefaultMutableTreeNode) value).getParent() == null) {
// check.setAutoTab(false);
// }
L2genBaseInfo baseInfo = (L2genBaseInfo) ((DefaultMutableTreeNode) value).getUserObject();
if (baseInfo instanceof L2genProductCategoryInfo) {
check.setVisible(false);
} else {
check.setVisible(true);
}
return nodeRenderer;
}
}
class CheckBoxNodeEditor extends AbstractCellEditor implements TreeCellEditor {
CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();
JTree tree;
DefaultMutableTreeNode currentNode;
public CheckBoxNodeEditor(JTree tree) {
this.tree = tree;
// add a listener fo the check box
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
L2genTristateCheckBox.State state = renderer.getJCheckBox().getState();
if (stopCellEditing()) {
fireEditingStopped();
}
}
};
//renderer.getJCheckBox().addItemListener(itemListener);
renderer.getJCheckBox().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (stopCellEditing()) {
fireEditingStopped();
}
}
});
renderer.getJCheckBox().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}
});
}
public Object getCellEditorValue() {
L2genTristateCheckBox.State state = renderer.getJCheckBox().getState();
setNodeState(currentNode, getInfoState(state));
return currentNode.getUserObject();
}
public boolean isCellEditable(EventObject event) {
return true;
}
public Component getTreeCellEditorComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row) {
if (value instanceof DefaultMutableTreeNode) {
currentNode = (DefaultMutableTreeNode) value;
}
Component editor = renderer.getTreeCellRendererComponent(tree, value,
true, expanded, leaf, row, true);
return editor;
}
}
private TreeNode createTree() {
DefaultMutableTreeNode productCategory, product, oldAlgorithm, algorithm = null, wavelength;
oldAlgorithm = new DefaultMutableTreeNode();
L2genBaseInfo oldAInfo = null;
rootNode = new DefaultMutableTreeNode(new L2genBaseInfo());
for (L2genProductCategoryInfo productCategoryInfo : l2genData.getProductCategoryInfos()) {
if (productCategoryInfo.isVisible() && productCategoryInfo.hasChildren()) {
productCategory = new DefaultMutableTreeNode(productCategoryInfo);
rootNode.add(productCategory);
for (L2genBaseInfo pInfo : productCategoryInfo.getChildren()) {
product = new DefaultMutableTreeNode(pInfo);
for (L2genBaseInfo aInfo : pInfo.getChildren()) {
algorithm = new DefaultMutableTreeNode(aInfo);
if (algorithm.toString().equals(oldAlgorithm.toString())) {
if (oldAInfo.hasChildren()) {
if (aInfo.hasChildren()) {
algorithm = oldAlgorithm;
} else {
oldAlgorithm.add(algorithm);
}
} else {
if (aInfo.hasChildren()) {
product.remove(oldAlgorithm);
algorithm.add(oldAlgorithm);
product.add(algorithm);
}
}
} else {
product.add(algorithm);
}
for (L2genBaseInfo wInfo : aInfo.getChildren()) {
wavelength = new DefaultMutableTreeNode(wInfo);
algorithm.add(wavelength);
}
oldAInfo = aInfo;
oldAlgorithm = algorithm;
}
if (pInfo.getChildren().size() == 1) {
productCategory.add(algorithm);
} else {
productCategory.add(product);
}
}
}
}
return rootNode;
}
public void checkTreeState(DefaultMutableTreeNode node) {
l2genData.disableEvent(L2genData.L2PROD);
L2genBaseInfo info = (L2genBaseInfo) node.getUserObject();
L2genBaseInfo.State newState = info.getState();
if (node.getChildCount() > 0) {
Enumeration enumeration = node.children();
DefaultMutableTreeNode kid;
boolean selectedFound = false;
boolean notSelectedFound = false;
while (enumeration.hasMoreElements()) {
kid = (DefaultMutableTreeNode)enumeration.nextElement();
checkTreeState(kid);
L2genBaseInfo childInfo = (L2genBaseInfo) kid.getUserObject();
switch (childInfo.getState()) {
case SELECTED:
selectedFound = true;
break;
case PARTIAL:
selectedFound = true;
notSelectedFound = true;
break;
case NOT_SELECTED:
notSelectedFound = true;
break;
}
}
if (selectedFound && !notSelectedFound) {
newState = L2genBaseInfo.State.SELECTED;
} else if (!selectedFound && notSelectedFound) {
newState = L2genBaseInfo.State.NOT_SELECTED;
} else if (selectedFound && notSelectedFound) {
newState = L2genBaseInfo.State.PARTIAL;
}
} else {
if (newState == L2genBaseInfo.State.PARTIAL) {
newState = L2genBaseInfo.State.SELECTED;
debug("in checkAlgorithmState converted newState to " + newState);
}
}
if (newState != info.getState()) {
l2genData.setSelectedInfo(info, newState);
}
l2genData.enableEvent(L2genData.L2PROD);
}
public void setNodeState(DefaultMutableTreeNode node, L2genBaseInfo.State state) {
debug("setNodeState called with state = " + state);
if (node == null) {
return;
}
L2genBaseInfo info = (L2genBaseInfo) node.getUserObject();
if (state == info.getState()) {
return;
}
l2genData.disableEvent(L2genData.L2PROD);
if (node.getChildCount() > 0) {
l2genData.setSelectedInfo(info, state);
Enumeration enumeration = node.children();
DefaultMutableTreeNode childNode;
L2genBaseInfo.State newState = state;
while (enumeration.hasMoreElements()) {
childNode = (DefaultMutableTreeNode)enumeration.nextElement();
L2genBaseInfo childInfo = (L2genBaseInfo) childNode.getUserObject();
if (childInfo instanceof L2genWavelengthInfo) {
if (state == L2genBaseInfo.State.PARTIAL) {
if (l2genData.compareWavelengthLimiter((L2genWavelengthInfo) childInfo)) {
newState = L2genBaseInfo.State.SELECTED;
} else {
newState = L2genBaseInfo.State.NOT_SELECTED;
}
}
}
setNodeState(childNode, newState);
}
DefaultMutableTreeNode ancestorNode;
DefaultMutableTreeNode targetNode = node;
ancestorNode = (DefaultMutableTreeNode) node.getParent();
while (ancestorNode.getParent() != null) {
targetNode = ancestorNode;
ancestorNode = (DefaultMutableTreeNode) ancestorNode.getParent();
}
checkTreeState(targetNode);
} else {
if (state == L2genBaseInfo.State.PARTIAL) {
l2genData.setSelectedInfo(info, L2genBaseInfo.State.SELECTED);
} else {
l2genData.setSelectedInfo(info, state);
}
}
l2genData.enableEvent(L2genData.L2PROD);
}
private void updateProductTreePanel() {
TreeNode rootNode = createTree();
productJTree.setModel(new DefaultTreeModel(rootNode, false));
}
private JTree createProductJTree() {
TreeNode rootNode = createTree();
productJTree = new JTree(rootNode);
productJTree.setCellRenderer(new CheckBoxNodeRenderer());
productJTree.setCellEditor(new CheckBoxNodeEditor(productJTree));
productJTree.setEditable(true);
productJTree.setShowsRootHandles(true);
productJTree.setRootVisible(false);
l2genData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateProductTreePanel();
}
});
l2genData.addPropertyChangeListener(L2genData.L2PROD, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
productChangedHandler();
}
});
return productJTree;
}
private void productChangedHandler() {
productJTree.treeDidChange();
checkTreeState(rootNode);
}
private void debug(String message) {
}
}
| 16,469 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genAquariusAction.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genAquariusAction.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction;
import gov.nasa.gsfc.seadas.processing.common.CloProgramUI;
import org.esa.snap.ui.AppContext;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 10/24/12
* Time: 3:14 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genAquariusAction extends CallCloProgramAction {
@Override
public CloProgramUI getProgramUI(AppContext appContext) {
return new L2genForm(appContext, getXmlFileName(), L2genData.Mode.L2GEN_AQUARIUS, ocssw);
}
} | 686 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genGetAncillaryFilesSpecifier.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genGetAncillaryFilesSpecifier.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/6/12
* Time: 4:37 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genGetAncillaryFilesSpecifier {
private JButton jButton;
private L2genData l2genData;
public L2genGetAncillaryFilesSpecifier(L2genData l2genData) {
this.l2genData = l2genData;
String NAME = "Get Ancillary";
jButton = new JButton(NAME);
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
l2genData.setAncillaryFiles(false,false,false);
}
});
}
private void addEventListeners() {
l2genData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
jButton.setEnabled(l2genData.isValidIfile());
}
});
}
public JButton getjButton() {
return jButton;
}
}
| 1,463 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genMainPanel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genMainPanel.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.common.GridBagConstraintsCustom;
import javax.swing.*;
import java.awt.*;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 5/14/12
* Time: 9:23 AM
* To change this template use File | Settings | File Templates.
*/
public class L2genMainPanel {
private JPanel jPanel;
private int tabIndex;
private L2genPrimaryIOFilesSelector primaryIOFilesPanel;
private L2genParfilePanel parfilePanel;
L2genMainPanel(L2genData l2genData, int tabIndex) {
this.tabIndex = tabIndex;
primaryIOFilesPanel = new L2genPrimaryIOFilesSelector(l2genData);
parfilePanel = new L2genParfilePanel(l2genData, tabIndex);
primaryIOFilesPanel.getjPanel().setVisible(l2genData.showIOFields);
createJPanel();
}
private void createJPanel() {
jPanel = new JPanel(new GridBagLayout());
jPanel.add(primaryIOFilesPanel.getjPanel(),
new GridBagConstraintsCustom(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3));
jPanel.add(parfilePanel.getjPanel(),
new GridBagConstraintsCustom(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, 3));
}
public L2genPrimaryIOFilesSelector getPrimaryIOFilesPanel() {
return primaryIOFilesPanel;
}
public L2genParfilePanel getParfilePanel() {
return parfilePanel;
}
public JPanel getjPanel() {
return jPanel;
}
public int getTabIndex() {
return tabIndex;
}
}
| 1,657 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genParfileExporter.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genParfileExporter.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.common.SeadasGuiUtils;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/6/12
* Time: 4:35 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genParfileExporter {
final private JButton jButton;
private L2genData l2genData;
final JFileChooser jFileChooser;
public L2genParfileExporter(L2genData l2genData) {
this.l2genData = l2genData;
String NAME = "Save";
jButton = new JButton(NAME);
jButton.setToolTipText("Saves parameters from the GUI parfile textfield to an external parameter file");
jFileChooser = new JFileChooser();
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String contents = l2genData.getParString(false, true);
SeadasGuiUtils.exportFile(jFileChooser, contents);
}
});
}
private void addEventListeners() {
l2genData.addPropertyChangeListener(L2genData.IFILE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
jButton.setEnabled(l2genData.isValidIfile());
}
});
}
public JButton getjButton() {
return jButton;
}
}
| 1,893 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
AbstractComponentKit.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/AbstractComponentKit.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/13/12
* Time: 11:27 AM
* To change this template use File | Settings | File Templates.
*/
public class AbstractComponentKit {
private String name;
private String toolTip;
private Component component;
private JLabel jLabel = new JLabel();
private boolean controlHandlerEnabled = true;
public AbstractComponentKit(String name, Component component) {
addComponent(component);
setName(name);
}
public AbstractComponentKit(String name, String toolTip, Component component) {
this(name, component);
setToolTip(toolTip);
}
public AbstractComponentKit(String name, String toolTip) {
setName(name);
setToolTip(toolTip);
}
public void setName(String name) {
this.name = name;
jLabel.setText(name);
}
public void setToolTip(String toolTip) {
this.toolTip = toolTip;
jLabel.setToolTipText(toolTip);
}
public JLabel getjLabel() {
return jLabel;
}
public String getName() {
return name;
}
public String getToolTip() {
return toolTip;
}
public void setEnabled(boolean enabled) {
if (component != null) {
component.setEnabled(enabled);
}
if (jLabel != null) {
jLabel.setEnabled(enabled);
}
}
private boolean isControlHandlerEnabled() {
return controlHandlerEnabled;
}
private void enableControlHandler() {
controlHandlerEnabled = true;
}
private void disableControlHandler() {
controlHandlerEnabled = false;
}
public Component getComponent() {
return component;
}
public void addComponent(Component component) {
this.component = component;
if (component != null) {
addControlListeners();
}
}
private void addControlListeners() {
if (getComponent() instanceof JCheckBox) {
((JCheckBox) getComponent()).addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (isControlHandlerEnabled()) {
controlHandler();
}
}
});
}
}
public void controlHandler() {
}
public void setComponentSelected(boolean selected, boolean allowEvent) {
if (allowEvent) {
if (getComponent() instanceof JCheckBox) {
((JCheckBox) getComponent()).setSelected(selected);
}
} else {
disableControlHandler();
if (getComponent() instanceof JCheckBox) {
((JCheckBox) getComponent()).setSelected(selected);
}
enableControlHandler();
}
}
public boolean isComponentSelected() {
if (getComponent() instanceof JCheckBox) {
return ((JCheckBox) getComponent()).isSelected();
}
return false;
}
}
| 3,248 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genProductsPanel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genProductsPanel.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.common.GridBagConstraintsCustom;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 5/14/12
* Time: 8:11 AM
* To change this template use File | Settings | File Templates.
*/
public class L2genProductsPanel extends JPanel {
private L2genData l2genData;
JPanel productSelectorJPanel;
JPanel wavelengthsLimitorJPanel;
JPanel selectedProductsJPanel;
JTextArea selectedProductsJTextArea;
JLabel selectedProductsJLabel;
private JButton restoreDefaultsButton;
private JScrollPane selectedProductsJScrollPane;
L2genProductsPanel(L2genData l2genData) {
this.l2genData = l2genData;
initComponents();
addComponents();
}
public void initComponents() {
productSelectorJPanel = new L2genProductTreeSelectorPanel(l2genData);
wavelengthsLimitorJPanel = new L2genWavelengthLimiterPanel(l2genData);
if (l2genData.isIfileIndependentMode()) {
wavelengthsLimitorJPanel.setVisible(false);
}
createSelectedProductsJTextArea();
restoreDefaultsButton = new JButton("Restore Defaults (Products only)");
restoreDefaultsButton.setEnabled(!l2genData.isParamDefault(L2genData.L2PROD));
restoreDefaultsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
l2genData.setParamToDefaults(L2genData.L2PROD);
}
});
l2genData.addPropertyChangeListener(L2genData.L2PROD, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (l2genData.isParamDefault(L2genData.L2PROD)) {
restoreDefaultsButton.setEnabled(false);
} else {
restoreDefaultsButton.setEnabled(true);
}
}
});
}
public void addComponents() {
JPanel innerPanel = new JPanel(new GridBagLayout());
innerPanel.add(productSelectorJPanel,
new GridBagConstraintsCustom(0, 0, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, 3));
if (l2genData.isWavelengthRequired()) {
innerPanel.add(wavelengthsLimitorJPanel,
new GridBagConstraintsCustom(1, 0, 1, 0.3, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, 3));
}
setLayout(new GridBagLayout());
add(innerPanel,
new GridBagConstraintsCustom(0, 0, 1, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH));
add(selectedProductsJPanel,
new GridBagConstraintsCustom(0, 1, 1, 0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, 3));
add(restoreDefaultsButton,
new GridBagConstraintsCustom(0, 2, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
}
private JPanel createSelectedProductsJPanel() {
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.setBorder(BorderFactory.createTitledBorder("Selected Products"));
selectedProductsJLabel = new JLabel("l2prod ");
selectedProductsJLabel.setVisible(true);
mainPanel.add(selectedProductsJLabel,
new GridBagConstraintsCustom(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.BOTH, 4, 1, 1));
mainPanel.add(selectedProductsJScrollPane,
new GridBagConstraintsCustom(1, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, 4, 3, 3));
return mainPanel;
}
private void createSelectedProductsJTextArea() {
selectedProductsJTextArea = new JTextArea();
selectedProductsJTextArea.setLineWrap(true);
selectedProductsJTextArea.setWrapStyleWord(false);
selectedProductsJTextArea.setRows(3);
selectedProductsJTextArea.setEditable(true);
selectedProductsJScrollPane = new JScrollPane(selectedProductsJTextArea);
selectedProductsJPanel = createSelectedProductsJPanel();
selectedProductsJScrollPane.setBorder(null);
selectedProductsJScrollPane.setPreferredSize(selectedProductsJScrollPane.getPreferredSize());
selectedProductsJScrollPane.setMinimumSize(selectedProductsJScrollPane.getPreferredSize());
selectedProductsJScrollPane.setMaximumSize(selectedProductsJScrollPane.getPreferredSize());
selectedProductsJTextArea.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
String l2prod = l2genData.sortStringList(selectedProductsJTextArea.getText());
l2genData.setParamValue(L2genData.L2PROD, l2prod);
selectedProductsJTextArea.setText(l2genData.getParamValue(L2genData.L2PROD));
}
});
l2genData.addPropertyChangeListener(L2genData.L2PROD, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
selectedProductsJTextArea.setText(l2genData.getParamValue(L2genData.L2PROD));
}
});
}
private JButton createDefaultsButton() {
final JButton jButton = new JButton("Apply Defaults");
jButton.setEnabled(false);
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
l2genData.setProdToDefault();
}
});
l2genData.addPropertyChangeListener(L2genData.L2PROD, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (l2genData.isParamDefault(L2genData.L2PROD)) {
jButton.setEnabled(false);
} else {
jButton.setEnabled(true);
}
}
});
return jButton;
}
}
| 6,434 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genParStringSpecifier.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genParStringSpecifier.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import javax.swing.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/6/12
* Time: 4:39 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genParStringSpecifier {
private final JTextArea jTextArea = new JTextArea();
private L2genData l2genData;
private int tabIndex;
L2genParStringSpecifier(L2genData l2genData, int tabIndex) {
this.l2genData = l2genData;
this.tabIndex = tabIndex;
jTextArea.setEditable(true);
jTextArea.setAutoscrolls(true);
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
jTextArea.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
controlHandler();
}
});
}
private void addEventListeners() {
for (ParamInfo paramInfo : l2genData.getParamInfos()) {
final String eventName = paramInfo.getName();
l2genData.addPropertyChangeListener(eventName, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
// relay this to PARSTRING event in case it is currently disabled
l2genData.fireEvent(L2genData.PARSTRING);
}
});
}
l2genData.addPropertyChangeListener(L2genData.SHOW_DEFAULTS, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
// relay this to PARSTRING event in case it is currently disabled
l2genData.fireEvent(L2genData.PARSTRING);
}
});
l2genData.addPropertyChangeListener(L2genData.PARSTRING, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
eventHandler();
}
});
l2genData.addPropertyChangeListener(L2genData.TAB_CHANGE, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
tabChangeEventHandler(evt);
}
});
}
private void tabChangeEventHandler(PropertyChangeEvent evt) {
if (evt.getNewValue().equals(tabIndex) && !evt.getOldValue().equals(tabIndex)) {
l2genData.enableEvent(L2genData.PARSTRING);
} else if (!evt.getNewValue().equals(tabIndex) && evt.getOldValue().equals(tabIndex)) {
l2genData.disableEvent(L2genData.PARSTRING);
}
}
private void controlHandler() {
l2genData.setParString(jTextArea.getText(), false, false);
}
private void eventHandler() {
jTextArea.setText(l2genData.getParString());
}
public JTextArea getjTextArea() {
return jTextArea;
}
public void setEditable(boolean editable) {
jTextArea.setEditable(editable);
}
public void setToolTip(String toolTipText) {
jTextArea.setToolTipText(toolTipText);
}
}
| 3,531 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genOfileSelector.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genOfileSelector.java | package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import gov.nasa.gsfc.seadas.processing.core.SeaDASProcessorModel;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import gov.nasa.gsfc.seadas.processing.common.FileSelector;
import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.esa.snap.rcp.SnapApp;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/6/12
* Time: 11:17 AM
* To change this template use File | Settings | File Templates.
*/
public class L2genOfileSelector {
public static final String DEFAULT_OUTPUT_FILE_OPTION_NAME = "ofile";
final private SeaDASProcessorModel seaDASProcessorModel;
final private FileSelector fileSelector;
private boolean controlHandlerEnabled = true;
private String outputFileOptionName;
public L2genOfileSelector(SeaDASProcessorModel seaDASProcessorModel) {
this.seaDASProcessorModel = seaDASProcessorModel;
outputFileOptionName = seaDASProcessorModel.getPrimaryOutputFileOptionName();
if(outputFileOptionName == null) {
outputFileOptionName = DEFAULT_OUTPUT_FILE_OPTION_NAME;
} else {
outputFileOptionName = outputFileOptionName.replaceAll("--", "");
}
fileSelector = new FileSelector(SnapApp.getDefault().getAppContext(), ParamInfo.Type.OFILE, outputFileOptionName);
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
fileSelector.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (isControlHandlerEnabled()) {
seaDASProcessorModel.setParamValue(seaDASProcessorModel.getPrimaryOutputFileOptionName(), fileSelector.getFileName());
}
}
});
}
private void addEventListeners() {
seaDASProcessorModel.addPropertyChangeListener(seaDASProcessorModel.getPrimaryOutputFileOptionName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
disableControlHandler();
fileSelector.setFilename(seaDASProcessorModel.getParamValue(seaDASProcessorModel.getPrimaryOutputFileOptionName()));
enableControlHandler();
}
});
seaDASProcessorModel.addPropertyChangeListener(seaDASProcessorModel.getPrimaryOutputFileOptionName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
fileSelector.setEnabled(seaDASProcessorModel.isValidIfile());
}
});
}
private boolean isControlHandlerEnabled() {
return controlHandlerEnabled;
}
private void enableControlHandler() {
controlHandlerEnabled = true;
}
private void disableControlHandler() {
controlHandlerEnabled = false;
}
public JPanel getJPanel() {
return fileSelector.getjPanel();
}
public FileSelector getFileSelector() {
return fileSelector;
}
}
| 3,194 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genReader.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/L2genReader.java | package gov.nasa.gsfc.seadas.processing.core;
import gov.nasa.gsfc.seadas.processing.common.XmlReader;
import gov.nasa.gsfc.seadas.processing.l2gen.productData.L2genAlgorithmInfo;
import gov.nasa.gsfc.seadas.processing.l2gen.productData.L2genProductCategoryInfo;
import gov.nasa.gsfc.seadas.processing.l2gen.productData.L2genProductInfo;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import static gov.nasa.gsfc.seadas.processing.core.ParamInfo.NULL_STRING;
/**
* A ...
*
* @author Danny Knowles
* @since SeaDAS 7.0
*/
public class L2genReader {
private L2genData l2genData;
private boolean enable3DProducts = false; // Currently yields an undesired extra parent directory if enabled (as of SeaDAS Toolbox 1.3.0)
public L2genReader(L2genData l2genData) {
this.l2genData = l2genData;
}
public void readProductCategoryXml(InputStream stream) {
XmlReader reader = new XmlReader();
Element rootElement = reader.parseAndGetRootElement(stream);
l2genData.clearProductCategoryInfos();
NodeList categoryNodelist = rootElement.getElementsByTagName("category");
if (categoryNodelist != null && categoryNodelist.getLength() > 0) {
for (int i = 0; i < categoryNodelist.getLength(); i++) {
Element categoryElement = (Element) categoryNodelist.item(i);
String name = categoryElement.getAttribute("name");
String visible = XmlReader.getTextValue(categoryElement, "makeVisible");
String defaultBucketString = XmlReader.getTextValue(categoryElement, "defaultBucket");
L2genProductCategoryInfo productCategoryInfo = new L2genProductCategoryInfo(name);
if (visible != null && visible.equals("1")) {
productCategoryInfo.setVisible(true);
} else {
productCategoryInfo.setVisible(false);
}
boolean defaultBucket;
if (defaultBucketString != null && defaultBucketString.equals("1")) {
defaultBucket = true;
} else {
defaultBucket = false;
}
productCategoryInfo.setDefaultBucket(defaultBucket);
NodeList productNodelist = categoryElement.getElementsByTagName("product");
if (productNodelist != null && productNodelist.getLength() > 0) {
for (int j = 0; j < productNodelist.getLength(); j++) {
Element productElement = (Element) productNodelist.item(j);
String product = productElement.getTextContent();
productCategoryInfo.addProductName(product);
}
// productCategoryInfo.sortProductNames();
}
l2genData.addProductCategoryInfo(productCategoryInfo);
}
}
// l2genData.sortProductCategoryInfos();
}
public void readParamCategoryXml(InputStream stream) {
XmlReader reader = new XmlReader();
Element rootElement = reader.parseAndGetRootElement(stream);
l2genData.clearParamCategoryInfos();
NodeList categoryNodelist = rootElement.getElementsByTagName("category");
if (categoryNodelist != null && categoryNodelist.getLength() > 0) {
for (int i = 0; i < categoryNodelist.getLength(); i++) {
Element categoryElement = (Element) categoryNodelist.item(i);
String name = categoryElement.getAttribute("name");
String autoTab = XmlReader.getTextValue(categoryElement, "autoTab");
String defaultBucketString = XmlReader.getTextValue(categoryElement, "defaultBucket");
String ignore = XmlReader.getTextValue(categoryElement, "ignore");
L2genParamCategoryInfo paramCategoryInfo = new L2genParamCategoryInfo(name);
if (autoTab != null && autoTab.equals("1")) {
paramCategoryInfo.setAutoTab(true);
} else {
paramCategoryInfo.setAutoTab(false);
}
if (ignore != null && ignore.equals("1")) {
paramCategoryInfo.setIgnore(true);
} else {
paramCategoryInfo.setIgnore(false);
}
if (defaultBucketString != null && defaultBucketString.equals("1")) {
paramCategoryInfo.setDefaultBucket(true);
} else {
paramCategoryInfo.setDefaultBucket(false);
}
NodeList paramNodelist = categoryElement.getElementsByTagName("param");
if (paramNodelist != null && paramNodelist.getLength() > 0) {
for (int j = 0; j < paramNodelist.getLength(); j++) {
Element paramElement = (Element) paramNodelist.item(j);
String param = paramElement.getTextContent();
paramCategoryInfo.addParamName(param);
}
// paramCategoryInfo.sortParamNameInfos();
}
l2genData.addParamCategoryInfo(paramCategoryInfo);
}
}
// l2genData.sortParamCategoryInfos();
}
public void updateParamInfosWithXml(InputStream stream) {
XmlReader reader = new XmlReader();
Element rootElement = reader.parseAndGetRootElement(stream);
NodeList optionNodelist = rootElement.getElementsByTagName("option");
if (optionNodelist != null && optionNodelist.getLength() > 0) {
for (int i = 0; i < optionNodelist.getLength(); i++) {
Element optionElement = (Element) optionNodelist.item(i);
String name = XmlReader.getTextValue(optionElement, "name");
if (name != null) {
name = name.toLowerCase();
String value = XmlReader.getTextValue(optionElement, "value");
if (value == null || value.length() == 0) {
value = XmlReader.getTextValue(optionElement, "default");
}
if (!name.equals(l2genData.IFILE) &&
!name.equals(l2genData.OFILE) &&
!name.equals(l2genData.GEOFILE) &&
!name.equals(l2genData.SUITE) &&
!name.equals(l2genData.PAR)) {
l2genData.setParamValueAndDefault(name, value);
}
}
}
}
}
public void readParamInfoXml(InputStream stream) throws IOException {
XmlReader reader = new XmlReader();
Element rootElement = reader.parseAndGetRootElement(stream);
l2genData.clearParamInfos();
NodeList optionNodelist = rootElement.getElementsByTagName("option");
if (optionNodelist != null && optionNodelist.getLength() > 0) {
for (int i = 0; i < optionNodelist.getLength(); i++) {
Element optionElement = (Element) optionNodelist.item(i);
String name = XmlReader.getTextValue(optionElement, "name");
if (name != null && name.length() > 0) {
name = name.toLowerCase();
String tmpType = optionElement.getAttribute("type");
// String tmpType = XmlReader.getTextValue(optionElement, "type");
ParamInfo.Type type = null;
if (tmpType != null) {
if (tmpType.toLowerCase().equals("boolean")) {
type = ParamInfo.Type.BOOLEAN;
} else if (tmpType.toLowerCase().equals("int")) {
type = ParamInfo.Type.INT;
} else if (tmpType.toLowerCase().equals("float")) {
type = ParamInfo.Type.FLOAT;
} else if (tmpType.toLowerCase().equals("string")) {
type = ParamInfo.Type.STRING;
} else if (tmpType.toLowerCase().equals("ifile")) {
type = ParamInfo.Type.IFILE;
} else if (tmpType.toLowerCase().equals("ofile")) {
type = ParamInfo.Type.OFILE;
}
}
String value = XmlReader.getTextValue(optionElement, "value");
String description = XmlReader.getTextValue(optionElement, "description");
String source = XmlReader.getTextValue(optionElement, "source");
ParamInfo paramInfo;
if (name.equals(l2genData.L2PROD)) {
paramInfo = l2genData.createL2prodParamInfo(value);
} else {
paramInfo = new ParamInfo(name, value, type);
}
if (name.equals(L2genData.IFILE) ||
name.equals(L2genData.OFILE) ||
name.equals(L2genData.GEOFILE) ||
name.equals(L2genData.PAR)) {
paramInfo.setValue(NULL_STRING);
paramInfo.setDefaultValue(NULL_STRING);
} else if (name.equals(L2genData.SUITE)) {
paramInfo.setValue(l2genData.getDefaultSuite());
paramInfo.setDefaultValue(l2genData.getDefaultSuite());
} else {
paramInfo.setDefaultValue(paramInfo.getValue());
}
paramInfo.setDescription(description);
paramInfo.setSource(source);
boolean isBit = false;
if (name != null) {
if (name.equals("gas_opt") ||
name.equals("eval")) {
isBit = true;
}
}
paramInfo.setBit(isBit);
NodeList validValueNodelist = optionElement.getElementsByTagName("validValue");
if (validValueNodelist != null && validValueNodelist.getLength() > 0) {
for (int j = 0; j < validValueNodelist.getLength(); j++) {
Element validValueElement = (Element) validValueNodelist.item(j);
String validValueValue = XmlReader.getTextValue(validValueElement, "value");
String validValueDescription = XmlReader.getTextValue(validValueElement, "description");
ParamValidValueInfo paramValidValueInfo = new ParamValidValueInfo(validValueValue);
paramValidValueInfo.setDescription(validValueDescription);
paramInfo.addValidValueInfo(paramValidValueInfo);
}
}
l2genData.addParamInfo(paramInfo);
}
}
}
// add on suite if it was missing from xml
if (!l2genData.hasParamValue(L2genData.SUITE)) {
ParamInfo suiteParamInfo = new ParamInfo(L2genData.SUITE, l2genData.getDefaultSuite(),
ParamInfo.Type.STRING, l2genData.getDefaultSuite());
l2genData.addParamInfo(suiteParamInfo);
}
l2genData.sortParamInfos();
}
private String valueOverRides(String name, String value, File iFile, File geoFile, File oFile) {
name = name.toLowerCase();
if (name.equals(L2genData.IFILE)) {
if (iFile != null) {
value = iFile.toString();
} else {
value = NULL_STRING;
}
}
if (name.equals(L2genData.GEOFILE)) {
if (geoFile != null) {
value = geoFile.toString();
} else {
value = NULL_STRING;
}
}
if (name.equals(L2genData.OFILE)) {
if (oFile != null) {
value = oFile.toString();
} else {
value = NULL_STRING;
}
}
if (name.equals(L2genData.PAR)) {
value = NULL_STRING;
}
return value;
}
public void readProductsXml(InputStream stream) {
XmlReader reader = new XmlReader();
Element rootElement = reader.parseAndGetRootElement(stream);
l2genData.clearProductInfos();
NodeList prodNodelist = rootElement.getElementsByTagName("product");
if (prodNodelist != null && prodNodelist.getLength() > 0) {
for (int i = 0; i < prodNodelist.getLength(); i++) {
Element prodElement = (Element) prodNodelist.item(i);
String prodName = prodElement.getAttribute("name");
// testing block for debug breakpoints
// if ("chlor_a".equals(prodName)) {
// int junk = 1;
// }
// if ("Rrs".equals(prodName)) {
// int junk = 1;
// }
// end debug breakpoints
L2genProductInfo productInfo = null;
L2genProductInfo integerProductInfo = null;
String dataType = XmlReader.getTextValue(prodElement, "type");
String units = XmlReader.getTextValue(prodElement, "units");
NodeList paramDesignatorNodelist = prodElement.getElementsByTagName("paramDesignator");
Boolean emissiveProd = false;
Boolean visibleProd = false;
String parameterTypeProdStr = "None";
if (paramDesignatorNodelist != null && paramDesignatorNodelist.getLength() > 0) {
for (int j = 0; j < paramDesignatorNodelist.getLength(); j++) {
if (paramDesignatorNodelist.item(j).getParentNode().equals(prodElement)) {
Element paramDesignatorElement = (Element) paramDesignatorNodelist.item(j);
if (paramDesignatorElement != null) {
String paramDesignator = paramDesignatorElement.getFirstChild().getNodeValue();
if (paramDesignator.equals("uv")) {
visibleProd = true;
}
if (paramDesignator.equals("visible")) {
visibleProd = true;
}
if (paramDesignator.equals("nir")) {
emissiveProd = true;
}
if (paramDesignator.equals("swir")) {
emissiveProd = true;
}
if (paramDesignator.equals("emissive")) {
emissiveProd = true;
}
}
}
}
if (emissiveProd && visibleProd) {
parameterTypeProdStr = "All";
} else if (emissiveProd) {
parameterTypeProdStr = "IR";
} else if (visibleProd) {
parameterTypeProdStr = "Visible";
}
}
NodeList algNodelist = prodElement.getElementsByTagName("algorithm");
if (algNodelist != null && algNodelist.getLength() > 0) {
for (int j = 0; j < algNodelist.getLength(); j++) {
boolean algEnabled = true;
Element algElement = (Element) algNodelist.item(j);
L2genAlgorithmInfo algorithmInfo = new L2genAlgorithmInfo(l2genData.waveLimiterInfos);
String suffixDefault = null;
String algorithmName = null;
if (algElement.hasAttribute("name")) {
algorithmName = algElement.getAttribute("name");
algorithmInfo.setName(algorithmName);
}
String algorithmRank = XmlReader.getTextValue(algElement, "rank");
// Disable if 3D product
if (!enable3DProducts && "3".equals(algorithmRank)) {
algEnabled = false;
}
String suffix = XmlReader.getTextValue(algElement, "suffix");
if (suffix != null) {
algorithmInfo.setSuffix(suffix);
} else {
algorithmInfo.setSuffix(algorithmName);
}
String cat_ix = XmlReader.getTextValue(algElement, "cat_ix");
String description = XmlReader.getTextValue(algElement, "description");
String description2 = description.replace("%d", cat_ix);
algorithmInfo.setDescription(description2);
String prefix = XmlReader.getTextValue(algElement, "prefix");
if (prefix != null) {
algorithmInfo.setPrefix(prefix + "_");
} else {
algorithmInfo.setPrefix(prodName + "_");
}
algorithmInfo.setUnits(units);
algorithmInfo.setDataType(dataType);
NodeList paramDesNodelist = algElement.getElementsByTagName("paramDesignator");
Boolean emissiveAlg = false;
Boolean visibleAlg = false;
Boolean parameterTypeChg = false;
String parameterTypeAlgStr = "None";
if (paramDesNodelist != null && paramDesNodelist.getLength() > 0) {
for (int k = 0; k < paramDesNodelist.getLength(); k++) {
Element paramDesElement = (Element) paramDesNodelist.item(k);
if (paramDesElement != null) {
// String paramDes = XmlReader.getTextValue(paramDesElement, "paramDesignator");
String paramDes = paramDesElement.getFirstChild().getNodeValue();
parameterTypeChg = true;
if (paramDes.equals("uv")) {
visibleAlg = true;
}
if (paramDes.equals("visible")) {
visibleAlg = true;
}
if (paramDes.equals("nir")) {
emissiveAlg = true;
}
if (paramDes.equals("swir")) {
emissiveAlg = true;
}
if (paramDes.equals("emissive")) {
emissiveAlg = true;
}
}
}
if (emissiveAlg && visibleAlg) {
parameterTypeAlgStr = "All";
} else if (emissiveAlg) {
parameterTypeAlgStr = "IR";
} else if (visibleAlg) {
parameterTypeAlgStr = "Visible";
}
}
if (parameterTypeChg){
algorithmInfo.setParameterType(parameterTypeAlgStr);
} else {
algorithmInfo.setParameterType(parameterTypeProdStr);
}
if (algEnabled) {
if (algorithmInfo.getParameterType() == L2genAlgorithmInfo.ParameterType.INT) {
if (integerProductInfo == null) {
integerProductInfo = new L2genProductInfo(prodName);
}
integerProductInfo.setName(prodName);
integerProductInfo.addChild(algorithmInfo);
algorithmInfo.setProductInfo(integerProductInfo);
} else {
if (productInfo == null) {
productInfo = new L2genProductInfo(prodName);
}
productInfo.setName(prodName);
productInfo.addChild(algorithmInfo);
if (null == algorithmName && algorithmInfo.getDescription() != null) {
productInfo.setDescription(algorithmInfo.getDescription());
}
algorithmInfo.setProductInfo(productInfo);
}
}
} // for algorithms
if (productInfo != null) {
productInfo.sortChildren();
l2genData.addProductInfo(productInfo);
}
if (integerProductInfo != null) {
l2genData.addIntegerProductInfo(integerProductInfo);
}
}
} // for products
}
l2genData.sortProductInfos(L2genProductInfo.CASE_INSENSITIVE_ORDER);
}
public String readFileIntoString(String filename) {
StringBuilder stringBuilder = new StringBuilder();
ArrayList<String> fileContentsInArrayList = readFileIntoArrayList(filename);
for (String line : fileContentsInArrayList) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
return stringBuilder.toString();
}
public ArrayList<String> readFileIntoArrayList(String filename) {
File file = null;
if (filename != null) {
file = new File(filename);
}
return readFileIntoArrayList(file);
}
public ArrayList<String> readFileIntoArrayList(File file) {
return l2genData.getOcssw().readSensorFileIntoArrayList(file);
}
}
| 23,076 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ParamUtils.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/ParamUtils.java | package gov.nasa.gsfc.seadas.processing.core;
import gov.nasa.gsfc.seadas.processing.common.XmlReader;
import gov.nasa.gsfc.seadas.processing.preferences.OCSSW_L2binController;
import gov.nasa.gsfc.seadas.processing.preferences.OCSSW_L3mapgenController;
import org.esa.snap.rcp.util.Dialogs;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 3/19/12
* Time: 8:59 AM
* To change this template use File | Settings | File Templates.
*/
public class ParamUtils {
private String OCDATAROOT = System.getenv("OCDATAROOT");
public static final String PAR = "par";
public static final String GEOFILE = "geofile";
public static final String SPIXL = "spixl";
public static final String EPIXL = "epixl";
public static final String DPIXL = "dpixl";
public static final String SLINE = "sline";
public static final String ELINE = "eline";
public static final String DLINE = "dline";
public static final String NORTH = "north";
public static final String SOUTH = "south";
public static final String WEST = "west";
public static final String EAST = "east";
public static final String IFILE = "ifile";
public static final String OFILE = "ofile";
public static final String OPTION_NAME = "name";
public static final String OPTION_TYPE = "type";
public static final String XML_ELEMENT_HAS_GEO_FILE = "hasGeoFile";
public static final String XML_ELEMENT_HAS_PAR_FILE = "hasParFile";
public static final String NO_XML_FILE_SPECIFIED = "No XML file Specified";
public final String INVALID_IFILE_EVENT = "INVALID_IFILE_EVENT";
public final String PARFILE_CHANGE_EVENT = "PARFILE_CHANGE_EVENT";
public final String WAVE_LIMITER_CHANGE_EVENT = "WAVE_LIMITER_EVENT";
public final String DEFAULTS_CHANGED_EVENT = "DEFAULTS_CHANGED_EVENT";
public final static String DEFAULT_PAR_FILE_NAME = "par";
public final static String DEFAULT_PROGRESS_REGEX = "Processing scan .+?\\((\\d+) of (\\d+)\\)";
private static int longestIFileNameLength;
public enum nullValueOverrides {
IFILE, OFILE, PAR, GEOFILE
}
public static Set<String> getPrimaryOptions(String parXMLFileName) {
Set<String> primaryOptions = new HashSet<String>();
XmlReader xmlReader = new XmlReader();
InputStream paramStream = ParamUtils.class.getResourceAsStream(parXMLFileName);
Element rootElement = xmlReader.parseAndGetRootElement(paramStream);
NodeList optionNodelist = rootElement.getElementsByTagName("primaryOption");
if (optionNodelist == null || optionNodelist.getLength() == 0) {
//SeadasLogger.getLogger().warning("primaryOptions does not exist!");
primaryOptions.add("ifile");
primaryOptions.add("ofile");
return primaryOptions;
}
for (int i = 0; i < optionNodelist.getLength(); i++) {
Element optionElement = (Element) optionNodelist.item(i);
String name = optionElement.getFirstChild().getNodeValue();
primaryOptions.add(name);
}
return primaryOptions;
}
public static String getParFileOptionName(String parXMLFileName) {
XmlReader xmlReader = new XmlReader();
InputStream paramStream = ParamUtils.class.getResourceAsStream(parXMLFileName);
Element rootElement = xmlReader.parseAndGetRootElement(paramStream);
NodeList optionNodelist = rootElement.getElementsByTagName("parFileOptionName");
if (optionNodelist == null || optionNodelist.getLength() == 0) {
//SeadasLogger.getLogger().warning("par file option name is not specified in the xml file. 'par' is used as a default name.");
return DEFAULT_PAR_FILE_NAME;
}
return optionNodelist.item(0).getFirstChild().getNodeValue();
}
public static String getProgressRegex(String parXMLFileName) {
XmlReader xmlReader = new XmlReader();
InputStream paramStream = ParamUtils.class.getResourceAsStream(parXMLFileName);
Element rootElement = xmlReader.parseAndGetRootElement(paramStream);
NodeList optionNodelist = rootElement.getElementsByTagName("progressRegex");
if (optionNodelist == null || optionNodelist.getLength() == 0) {
//SeadasLogger.getLogger().warning("progress meter regular expression is not specified in the xml file.");
return DEFAULT_PROGRESS_REGEX;
}
return optionNodelist.item(0).getFirstChild().getNodeValue();
}
public static boolean getOptionStatus(String parXMLFileName, String elementName) {
boolean optionStatus = false;
XmlReader xmlReader = new XmlReader();
InputStream paramStream = ParamUtils.class.getResourceAsStream(parXMLFileName);
Element rootElement = xmlReader.parseAndGetRootElement(paramStream);
NodeList optionNodelist = rootElement.getElementsByTagName(elementName);
if (optionNodelist == null || optionNodelist.getLength() == 0) {
//SeadasLogger.getLogger().warning(elementName + " exist: " + optionStatus);
return optionStatus;
}
Element metaDataElement = (Element) optionNodelist.item(0);
String name = metaDataElement.getTagName();
//SeadasLogger.getLogger().fine("tag name: " + name);
// if (name.equals(elementName)) {
optionStatus = Boolean.parseBoolean(metaDataElement.getFirstChild().getNodeValue());
//SeadasLogger.getLogger().fine(name + " value = " + metaDataElement.getFirstChild().getNodeValue() + " " + optionStatus);
// }
return optionStatus;
}
public static int getLongestIFileNameLength() {
return longestIFileNameLength;
}
public static ArrayList<ParamInfo> computeParamList(String paramXmlFileName) {
if (paramXmlFileName.equals(NO_XML_FILE_SPECIFIED)) {
return getDefaultParamList();
}
final ArrayList<ParamInfo> paramList = new ArrayList<ParamInfo>();
XmlReader xmlReader = new XmlReader();
InputStream paramStream = ParamUtils.class.getResourceAsStream(paramXmlFileName);
if (paramStream == null) {
Dialogs.showError("XML file " + paramXmlFileName + " not found.");
return null;
}
Element rootElement = xmlReader.parseAndGetRootElement(paramStream);
if (rootElement == null) {
Dialogs.showError("XML file " + paramXmlFileName + " root element not found.");
return null;
}
NodeList optionNodelist = rootElement.getElementsByTagName("option");
if (optionNodelist == null || optionNodelist.getLength() == 0) {
return null;
}
longestIFileNameLength = 0;
for (int i = 0; i < optionNodelist.getLength(); i++) {
Element optionElement = (Element) optionNodelist.item(i);
String name = XmlReader.getTextValue(optionElement, OPTION_NAME);
debug("option name: " + name);
String tmpType = XmlReader.getAttributeTextValue(optionElement, OPTION_TYPE);
debug("option type: " + tmpType);
ParamInfo.Type type = ParamInfo.Type.HELP;
if (tmpType != null) {
if (tmpType.toLowerCase().equals("boolean")) {
type = ParamInfo.Type.BOOLEAN;
} else if (tmpType.toLowerCase().equals("int")) {
type = ParamInfo.Type.INT;
} else if (tmpType.toLowerCase().equals("float")) {
type = ParamInfo.Type.FLOAT;
} else if (tmpType.toLowerCase().equals("string")) {
type = ParamInfo.Type.STRING;
} else if (tmpType.toLowerCase().equals("ifile")) {
type = ParamInfo.Type.IFILE;
if (name.length() > longestIFileNameLength) {
longestIFileNameLength = name.length();
}
} else if (tmpType.toLowerCase().equals("ofile")) {
type = ParamInfo.Type.OFILE;
} else if (tmpType.toLowerCase().equals("help")) {
type = ParamInfo.Type.HELP;
} else if (tmpType.toLowerCase().equals("dir")) {
type = ParamInfo.Type.DIR;
} else if (tmpType.toLowerCase().equals("flags")) {
type = ParamInfo.Type.FLAGS;
} else if (tmpType.toLowerCase().equals("button")) {
type = ParamInfo.Type.BUTTON;
}
}
String value = XmlReader.getTextValue(optionElement, "value");
if (name != null) {
String nullValueOverrides[] = {ParamUtils.IFILE, ParamUtils.OFILE, ParamUtils.PAR, ParamUtils.GEOFILE};
for (String nullValueOverride : nullValueOverrides) {
if (name.equals(nullValueOverride)) {
value = ParamInfo.NULL_STRING;
}
}
}
String description = XmlReader.getTextValue(optionElement, "description");
String colSpan = XmlReader.getTextValue(optionElement, "colSpan");
String source = XmlReader.getTextValue(optionElement, "source");
String order = XmlReader.getTextValue(optionElement, "order");
String usedAs = XmlReader.getTextValue(optionElement, "usedAs");
String defaultValue = XmlReader.getTextValue(optionElement, "default");
// set the value and the default to the current value from the XML file
//ParamInfo paramInfo = (type.equals(ParamInfo.Type.OFILE)) ? new OFileParamInfo(name, value, type, value) : new ParamInfo(name, value, type, value);
ParamInfo paramInfo = (type.equals(ParamInfo.Type.OFILE)) ? new OFileParamInfo(name, value, type, defaultValue) : new ParamInfo(name, value, type, defaultValue);
paramInfo.setDescription(description);
if (colSpan != null) {
try {
int colSpanInt = Integer.parseInt(colSpan);
if (colSpanInt > 0) {
paramInfo.setColSpan(colSpanInt);
}
} catch (Exception e) {
System.out.println("ERROR: colSpan not an integer for param: " + name + "in xml file: " + paramXmlFileName);
}
} else {
paramInfo.setColSpan(1);
}
paramInfo.setSource(source);
if (order != null) {
try {
int orderInt = Integer.parseInt(order);
if (orderInt >= 0) {
paramInfo.setOrder(orderInt);
}
} catch (Exception e) {
System.out.println("ERROR: order not an integer for param: " + name + "in xml file: " + paramXmlFileName);
}
}
if (usedAs != null) {
paramInfo.setUsedAs(usedAs);
}
NodeList validValueNodelist = optionElement.getElementsByTagName("validValue");
if (validValueNodelist != null && validValueNodelist.getLength() > 0) {
for (int j = 0; j < validValueNodelist.getLength(); j++) {
Element validValueElement = (Element) validValueNodelist.item(j);
String validValueValue = XmlReader.getTextValue(validValueElement, "value");
String validValueDescription = XmlReader.getTextValue(validValueElement, "description");
ParamValidValueInfo paramValidValueInfo = new ParamValidValueInfo(validValueValue);
paramValidValueInfo.setDescription(validValueDescription);
paramInfo.addValidValueInfo(paramValidValueInfo);
}
}
final String optionName = ParamUtils.removePreceedingDashes(paramInfo.getName());
if ("l3mapgen.xml".equals(paramXmlFileName)) {
switch (optionName) {
case "product":
paramInfo.setValue(OCSSW_L3mapgenController.getPreferenceProduct());
break;
case "projection":
paramInfo.setValue(OCSSW_L3mapgenController.getPreferenceProjection());
break;
case "resolution":
paramInfo.setValue(OCSSW_L3mapgenController.getPreferenceResolution());
break;
case "interp":
paramInfo.setValue(OCSSW_L3mapgenController.getPreferenceInterp());
break;
case "north":
paramInfo.setValue(OCSSW_L3mapgenController.getPreferenceNorth());
break;
case "south":
paramInfo.setValue(OCSSW_L3mapgenController.getPreferenceSouth());
break;
case "west":
paramInfo.setValue(OCSSW_L3mapgenController.getPreferenceWest());
break;
case "east":
paramInfo.setValue(OCSSW_L3mapgenController.getPreferenceEast());
break;
}
}
if ("l2bin.xml".equals(paramXmlFileName)) {
switch (optionName) {
case "l3bprod":
paramInfo.setValue(OCSSW_L2binController.getPreferenceL3bprod());
break;
case "prodtype":
paramInfo.setValue(OCSSW_L2binController.getPreferenceProdtype());
break;
case "resolution":
paramInfo.setValue(OCSSW_L2binController.getPreferenceResolution());
break;
case "area_weighting":
paramInfo.setValue(OCSSW_L2binController.getPreferenceAreaWeighting());
break;
case "flaguse":
paramInfo.setValue(OCSSW_L2binController.getPreferenceFlaguse());
break;
case "latnorth":
paramInfo.setValue(OCSSW_L2binController.getPreferenceLatnorth());
break;
case "latsouth":
paramInfo.setValue(OCSSW_L2binController.getPreferenceLatsouth());
break;
case "lonwest":
paramInfo.setValue(OCSSW_L2binController.getPreferenceLonwest());
break;
case "loneast":
paramInfo.setValue(OCSSW_L2binController.getPreferenceLoneast());
break;
}
}
paramList.add(paramInfo);
}
return paramList;
}
/**
* Create a default array list with ifile, ofile, spixl, epixl, sline, eline options
*
* @return
*/
public static ArrayList<ParamInfo> getDefaultParamList() {
ArrayList<ParamInfo> defaultParamList = new ArrayList<ParamInfo>();
return defaultParamList;
}
static void debug(String debugMessage) {
//System.out.println(debugMessage);
}
public static String removePreceedingDashes(String optionName) {
return optionName.replaceAll("--", "");
}
}
| 15,797 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genData.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/L2genData.java | package gov.nasa.gsfc.seadas.processing.core;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import gov.nasa.gsfc.seadas.processing.common.*;
import gov.nasa.gsfc.seadas.processing.l2gen.productData.*;
import gov.nasa.gsfc.seadas.processing.l2gen.userInterface.L2genForm;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWExecutionMonitor;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWLocal;
import org.esa.snap.core.util.ResourceInstaller;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import javax.swing.event.SwingPropertyChangeSupport;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.nio.file.Path;
import java.util.*;
/**
* A ...
*
* @author Danny Knowles
* @author Aynur Abdurazik
* @since SeaDAS 7.0
*/
public class L2genData implements SeaDASProcessorModel {
public static final String OPER_DIR = "l2gen";
public static final String SHARE_DIR = "share";
public static final String COMMON_DIR = "common";
public static final String CANCEL = "cancel";
public static enum Mode {
L2GEN,
L2GEN_AQUARIUS,
L3GEN
}
public static enum Source {
L2GEN,
RESOURCES
}
public static enum ImplicitInputFileExtensions {
L2GEN("L1B_HKM, L1B_QKM, L1B_LAC.anc"),
L3GEN("L1B_HKM, L1B_QKM, L1B_LAC.anc"),
L2GEN_AQUARIUS("L1B_HKM, L1B_QKM, L1B_LAC.anc");
String fileExtensions;
ImplicitInputFileExtensions(String fieldName) {
this.fileExtensions = fieldName;
}
public String getFileExtensions() {
return fileExtensions;
}
}
public static final String
GUI_NAME = "l2gen",
// PRODUCT_INFO_XML = "productInfo.xml",
PRODUCT_XML = "product.xml",
PARAM_INFO_XML = "paramInfo.xml",
PARAM_CATEGORY_INFO_XML = "paramCategoryInfo.xml",
PRODUCT_CATEGORY_INFO_XML = "productCategoryInfo.xml",
DEFAULTS_FILE_PREFIX = "msl12_defaults_",
GETANC = "getanc",
DEFAULT_SUITE = "OC",
DEFAULT_SUITE_PACE = "BGC";
public static final String
AQUARIUS_GUI_NAME = "l2gen_aquarius",
AQUARIUS_PRODUCT_INFO_XML = "aquariusProductInfo.xml",
AQUARIUS_PARAM_INFO_XML = "aquariusParamInfo.xml",
AQUARIUS_PARAM_CATEGORY_INFO_XML = "aquariusParamCategoryInfo.xml",
AQUARIUS_PRODUCT_CATEGORY_INFO_XML = "aquariusProductCategoryInfo.xml",
AQUARIUS_DEFAULTS_FILE_PREFIX = "l2gen_aquarius_defaults_",
AQUARIUS_GETANC = "getanc_aquarius",
AQUARIUS_DEFAULT_SUITE = "V5.0.0";
private static final String L3GEN_GUI_NAME = "l3gen",
// L3GEN_PRODUCT_INFO_XML = "productInfo.xml",
L3GEN_PRODUCT_XML = "product.xml",
L3GEN_PARAM_INFO_XML = "paramInfo.xml",
L3GEN_PARAM_CATEGORY_INFO_XML = "l3genParamCategoryInfo.xml",
L3GEN_PRODUCT_CATEGORY_INFO_XML = "l3genProductCategoryInfo.xml",
L3GEN_DEFAULTS_FILE_PREFIX = "msl12_defaults_",
L3GEN_GETANC = "getanc",
L3GEN_DEFAULT_SUITE = "OC";
public static final String ANCILLARY_FILES_CATEGORY_NAME = "Ancillary Inputs";
public static final String PAR = "par",
GEOFILE = "geofile",
SPIXL = "spixl",
EPIXL = "epixl",
SLINE = "sline",
ELINE = "eline",
NORTH = "north",
SOUTH = "south",
WEST = "west",
EAST = "east",
IFILE = "ifile",
OFILE = "ofile",
L2PROD = "l2prod",
SUITE = "suite";
public static final String INVALID_IFILE = "INVALID_IFILE_EVENT",
WAVE_LIMITER = "WAVE_LIMITER_EVENT",
EXCLUDE_IOFILE = "EXCLUDE_IOFILE_EVENT",
SHOW_DEFAULTS = "SHOW_DEFAULTS_EVENT",
PARSTRING = "PARSTRING_EVENT",
TAB_CHANGE = "TAB_CHANGE_EVENT";
public FileInfo iFileInfo = null;
private boolean initialized = false;
public boolean showIOFields = true;
private Mode mode = Mode.L2GEN;
private SeadasProcessorInfo.Id processorId = SeadasProcessorInfo.Id.L2GEN;
private boolean ifileIndependentMode = false;
private boolean paramsBeingSetViaParstring = false;
// keepParams: this boolean field denotes whether l2gen keeps the current params when a new ifile is selected.
// Params not supported by the new ifile will be deleted.
private boolean keepParams = false;
// mode dependent fields
private String paramInfoXml;
private String productInfoXml;
private String productXml;
private String paramCategoryXml;
private String productCategoryXml;
private String getanc;
private String defaultsFilePrefix;
private String guiName;
private String defaultSuite;
private boolean dirty = false;
public OCSSW ocssw;
public final ArrayList<L2genWavelengthInfo> waveLimiterInfos = new ArrayList<L2genWavelengthInfo>();
private final L2genReader l2genReader = new L2genReader(this);
private final ArrayList<ParamInfo> paramInfos = new ArrayList<ParamInfo>();
private final ArrayList<L2genParamCategoryInfo> paramCategoryInfos = new ArrayList<L2genParamCategoryInfo>();
private final SwingPropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this);
private final SeadasPrint l2genPrint = new SeadasPrint();
// useful shortcuts to popular paramInfos
private final HashMap<String, ParamInfo> paramInfoLookup = new HashMap<String, ParamInfo>();
private L2genProductsParamInfo l2prodParamInfo = null;
public boolean excludeCurrentIOfile = false;
private boolean showDefaultsInParString = false;
private ProcessorModel processorModel;
private static L2genData L2genData = null;
private static L2genData L2genAquariusData = null;
private static L2genData L3genData = null;
private boolean overwriteProductInfoXML = false;
private boolean overwriteProductXML = false;
public static L2genData getNew(Mode mode, OCSSW ocssw) {
switch (mode) {
case L2GEN_AQUARIUS:
L2genAquariusData = new L2genData(mode, ocssw);
return L2genAquariusData;
case L3GEN:
L3genData = new L2genData(mode, ocssw);
return L3genData;
default:
L2genData = new L2genData(mode, ocssw);
return L2genData;
}
}
// private L2genData() {
// this(Mode.L2GEN);
// }
private L2genData(Mode mode, OCSSW ocssw) {
this.ocssw = ocssw;
setMode(mode);
}
public OCSSW getOcssw() {
return ocssw;
}
public Mode getMode() {
return mode;
}
public void setMode(Mode mode) {
this.mode = mode;
switch (mode) {
case L2GEN_AQUARIUS:
processorId = SeadasProcessorInfo.Id.L2GEN;
setGuiName(AQUARIUS_GUI_NAME);
setParamInfoXml(AQUARIUS_PARAM_INFO_XML);
setProductInfoXml(AQUARIUS_PRODUCT_INFO_XML);
setParamCategoryXml(AQUARIUS_PARAM_CATEGORY_INFO_XML);
setProductCategoryXml(AQUARIUS_PRODUCT_CATEGORY_INFO_XML);
setGetanc(AQUARIUS_GETANC);
setDefaultsFilePrefix(AQUARIUS_DEFAULTS_FILE_PREFIX);
setDefaultSuite(AQUARIUS_DEFAULT_SUITE);
break;
case L3GEN:
processorId = SeadasProcessorInfo.Id.L3GEN;
setGuiName(L3GEN_GUI_NAME);
setParamInfoXml(L3GEN_PARAM_INFO_XML);
// setProductInfoXml(L3GEN_PRODUCT_INFO_XML);
setProductXml(L3GEN_PRODUCT_XML);
setParamCategoryXml(L3GEN_PARAM_CATEGORY_INFO_XML);
setProductCategoryXml(L3GEN_PRODUCT_CATEGORY_INFO_XML);
setGetanc(L3GEN_GETANC);
setDefaultsFilePrefix(L3GEN_DEFAULTS_FILE_PREFIX);
setDefaultSuite(L3GEN_DEFAULT_SUITE);
break;
default:
processorId = SeadasProcessorInfo.Id.L2GEN;
setGuiName(GUI_NAME);
setParamInfoXml(PARAM_INFO_XML);
// setProductInfoXml(PRODUCT_INFO_XML);
setProductXml(PRODUCT_XML);
setParamCategoryXml(PARAM_CATEGORY_INFO_XML);
setProductCategoryXml(PRODUCT_CATEGORY_INFO_XML);
setGetanc(GETANC);
setDefaultsFilePrefix(DEFAULTS_FILE_PREFIX);
setDefaultSuite(DEFAULT_SUITE);
break;
}
ocssw.setProgramName(getGuiName());
processorModel = new ProcessorModel(getGuiName(), getParamInfos(), ocssw);
processorModel.setAcceptsParFile(true);
}
public boolean isIfileIndependentMode() {
return ifileIndependentMode;
}
public void setIfileIndependentMode(boolean ifileIndependentMode) {
this.ifileIndependentMode = ifileIndependentMode;
}
public String getParamInfoXml() {
return paramInfoXml;
}
public void setParamInfoXml(String paramInfoXml) {
this.paramInfoXml = paramInfoXml;
}
public String getProductInfoXml() {
return productInfoXml;
}
public void setProductInfoXml(String productInfoXml) {
this.productInfoXml = productInfoXml;
}
public String getProductXml() {
return productXml;
}
public void setProductXml(String productXml) {
this.productXml = productXml;
}
public String getParamCategoryXml() {
return paramCategoryXml;
}
public void setParamCategoryXml(String paramCategoryXml) {
this.paramCategoryXml = paramCategoryXml;
}
public String getProductCategoryXml() {
return productCategoryXml;
}
public void setProductCategoryXml(String productCategoryXml) {
this.productCategoryXml = productCategoryXml;
}
public boolean isKeepParams() {
return keepParams;
}
public void setKeepParams(boolean keepParams) {
this.keepParams = keepParams;
}
public String getGetanc() {
return getanc;
}
public void setGetanc(String getanc) {
this.getanc = getanc;
}
public String getDefaultsFilePrefix() {
return defaultsFilePrefix;
}
public void setDefaultsFilePrefix(String defaultsFilePrefix) {
this.defaultsFilePrefix = defaultsFilePrefix;
}
public String getDefaultSuite() {
return defaultSuite;
}
public void setDefaultSuite(String defaultSuite) {
this.defaultSuite = defaultSuite;
}
public boolean isExcludeCurrentIOfile() {
return excludeCurrentIOfile;
}
public void setExcludeCurrentIOfile(boolean excludeCurrentIOfile) {
if (this.excludeCurrentIOfile != excludeCurrentIOfile) {
this.excludeCurrentIOfile = excludeCurrentIOfile;
fireEvent(EXCLUDE_IOFILE);
}
}
public boolean isMultipleInputFiles() {
return false;
}
public boolean isShowDefaultsInParString() {
return showDefaultsInParString;
}
public String getPrimaryInputFileOptionName() {
return IFILE;
}
public String getPrimaryOutputFileOptionName() {
return OFILE;
}
public void setShowDefaultsInParString(boolean showDefaultsInParString) {
if (this.showDefaultsInParString != showDefaultsInParString) {
this.showDefaultsInParString = showDefaultsInParString;
fireEvent(SHOW_DEFAULTS);
}
}
public boolean isValidIfile() {
ParamInfo paramInfo = getParamInfo(IFILE);
if (paramInfo != null) {
return paramInfo.isValid();
}
return false;
}
public boolean isGeofileRequired() {
switch (getMode()) {
case L2GEN_AQUARIUS:
return false;
case L3GEN:
return false;
default:
if (iFileInfo != null) {
return iFileInfo.isGeofileRequired();
}
return false;
}
}
@Override
public boolean isWavelengthRequired() {
switch (getMode()) {
case L2GEN_AQUARIUS:
return false;
default:
return true;
}
}
public EventInfo[] eventInfos = {
new EventInfo(L2PROD, this),
new EventInfo(PARSTRING, this)
};
private EventInfo getEventInfo(String name) {
for (EventInfo eventInfo : eventInfos) {
if (name.equals(eventInfo.getName())) {
return eventInfo;
}
}
return null;
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
EventInfo eventInfo = getEventInfo(propertyName);
if (eventInfo == null) {
propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
} else {
eventInfo.addPropertyChangeListener(listener);
}
}
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
EventInfo eventInfo = getEventInfo(propertyName);
if (eventInfo == null) {
propertyChangeSupport.removePropertyChangeListener(propertyName, listener);
} else {
eventInfo.removePropertyChangeListener(listener);
}
}
public void disableEvent(String name) {
EventInfo eventInfo = getEventInfo(name);
if (eventInfo == null) {
debug("disableEvent - eventInfo not found for " + name);
} else {
eventInfo.setEnabled(false);
}
}
public void enableEvent(String name) {
EventInfo eventInfo = getEventInfo(name);
if (eventInfo == null) {
debug("enableEvent - eventInfo not found for " + name);
} else {
eventInfo.setEnabled(true);
}
}
public void fireEvent(String name) {
fireEvent(name, null, null);
}
public void fireEvent(String name, Serializable oldValue, Serializable newValue) {
EventInfo eventInfo = getEventInfo(name);
if (eventInfo == null) {
propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(this, name, oldValue, newValue));
} else {
eventInfo.fireEvent(oldValue, newValue);
}
}
public void fireAllParamEvents() {
disableEvent(PARSTRING);
disableEvent(L2PROD);
for (ParamInfo paramInfo : paramInfos) {
if (paramInfo.getName() != null && !paramInfo.getName().equals(L2genData.IFILE)) {
fireEvent(paramInfo.getName());
}
}
fireEvent(SHOW_DEFAULTS);
fireEvent(EXCLUDE_IOFILE);
fireEvent(WAVE_LIMITER);
fireEvent(PARSTRING);
enableEvent(L2PROD);
enableEvent(PARSTRING);
}
public void setSelectedInfo(L2genBaseInfo info, L2genBaseInfo.State state) {
if (state != info.getState()) {
info.setState(state);
l2prodParamInfo.updateValue();
fireEvent(L2PROD);
}
}
/**
* Set wavelength in waveLimiterInfos based on GUI change
*
* @param selectedWavelength
* @param selected
*/
public void setSelectedWaveLimiter(String selectedWavelength, boolean selected) {
for (L2genWavelengthInfo waveLimiterInfo : waveLimiterInfos) {
if (selectedWavelength.equals(waveLimiterInfo.getWavelengthString())) {
if (selected != waveLimiterInfo.isSelected()) {
waveLimiterInfo.setSelected(selected);
fireEvent(WAVE_LIMITER);
}
}
}
}
/**
* Determine is mission has particular waveType based on what is in the
* waveLimiterInfos Array
* <p/>
* Used by the waveLimiterInfos GUI to enable/disable the appropriate
* 'Select All' toggle buttons
*
* @param waveType
* @return true if waveType in waveLimiterInfos, otherwise false
*/
public boolean hasWaveType(L2genWavelengthInfo.WaveType waveType) {
for (L2genWavelengthInfo waveLimiterInfo : waveLimiterInfos) {
if (waveLimiterInfo.isWaveType(waveType)) {
return true;
}
}
return false;
}
/**
* Determines if all wavelengths for a given wavelength type within the
* wavelength limiter array are selected
* <p/>
* This is used to determine whether the toggle button in the wavelength
* limiter GUI needs to be in: 'Select All Infrared' mode, 'Deselect All
* Infrared' mode, 'Select All Visible' mode, or 'Deselect All Visible' mode
*
* @return true if all of given wavelength type selected, otherwise false
*/
public boolean isSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType waveType) {
int selectedCount = 0;
for (L2genWavelengthInfo waveLimiterInfo : waveLimiterInfos) {
if (waveLimiterInfo.isWaveType(waveType)) {
if (waveLimiterInfo.isSelected()) {
selectedCount++;
} else {
return false;
}
}
}
if (selectedCount > 0) {
return true;
} else {
return false;
}
}
/**
* Sets all wavelengths of a given wavelength type within the wavelength
* limiter array to selected
* <p/>
* This is called by the wavelength limiter GUI toggle buttons and is also
* used for initializing defaults.
*
* @param selected
*/
public void setSelectedAllWaveLimiter(L2genWavelengthInfo.WaveType waveType, boolean selected) {
for (L2genWavelengthInfo waveLimiterInfo : waveLimiterInfos) {
if (waveLimiterInfo.isWaveType(waveType)) {
waveLimiterInfo.setSelected(selected);
}
}
fireEvent(WAVE_LIMITER);
}
public void addParamInfo(ParamInfo paramInfo) {
paramInfos.add(paramInfo);
paramInfoLookup.put(paramInfo.getName().toLowerCase(), paramInfo);
}
public ArrayList<ParamInfo> getParamInfos() {
return paramInfos;
}
public void clearParamInfos() {
paramInfos.clear();
}
public void sortParamInfos() {
Collections.sort((List<ParamInfo>) paramInfos);
}
public ArrayList<L2genWavelengthInfo> getWaveLimiterInfos() {
return waveLimiterInfos;
}
/**
* Handle cases where a change in one name should effect a change in name
* <p/>
* In this case specifically coordParams and pixelParams are mutually
* exclusive so if a name in one group is being set to a non-default value,
* then set all params in the other group to the defaults
*
* @param name
*/
private void setConflictingParams(String name) {
ParamInfo paramInfo = getParamInfo(name);
if (paramInfo == null) {
return;
}
// Only proceed if name is not equal to default
if (paramInfo.getValue() == paramInfo.getDefaultValue()) {
return;
}
// Set all params in the other group to the defaults
final HashSet<String> coords = new HashSet<String>();
coords.add(NORTH);
coords.add(SOUTH);
coords.add(EAST);
coords.add(WEST);
final HashSet<String> pixels = new HashSet<String>();
pixels.add(SPIXL);
pixels.add(EPIXL);
pixels.add(SLINE);
pixels.add(ELINE);
// Test if name is coordParam
if (coords.contains(name)) {
for (String pixelParam : pixels) {
setParamToDefaults(getParamInfo(pixelParam));
}
}
// Set all pixelParams in paramInfos to defaults
if (pixels.contains(name)) {
for (String coordParam : coords) {
setParamToDefaults(getParamInfo(coordParam));
}
}
}
public String getParString() {
return getParString(isShowDefaultsInParString());
}
public String getParString(boolean loadOrSave) {
return getParString(isShowDefaultsInParString(), loadOrSave);
}
public String getParString(boolean showDefaults, boolean loadOrSave) {
StringBuilder par = new StringBuilder("");
for (L2genParamCategoryInfo paramCategoryInfo : paramCategoryInfos) {
if (!paramCategoryInfo.isIgnore()) {
boolean alwaysDisplay = false;
StringBuilder currCategoryEntries = new StringBuilder("");
for (ParamInfo paramInfo : paramCategoryInfo.getParamInfos()) {
if (paramInfo.getName().equals(IFILE)) {
if (excludeCurrentIOfile && loadOrSave) {
continue;
} else {
alwaysDisplay = true;
currCategoryEntries.append(makeParEntry(paramInfo));
}
} else if (paramInfo.getName().equals(OFILE)) {
if (excludeCurrentIOfile && loadOrSave) {
continue;
} else {
alwaysDisplay = true;
currCategoryEntries.append(makeParEntry(paramInfo));
}
} else if (paramInfo.getName().equals(GEOFILE)) {
if (isGeofileRequired()) {
if (excludeCurrentIOfile && loadOrSave) {
continue;
} else {
currCategoryEntries.append(makeParEntry(paramInfo));
}
}
} else if (paramInfo.getName().startsWith("icefile")) {
if (excludeCurrentIOfile && loadOrSave) {
continue;
} else {
if (!paramInfo.isDefault()) {
alwaysDisplay = true;
paramInfo.validateIfileValue(null, processorId, ocssw);
currCategoryEntries.append(makeParEntry(paramInfo));
}
}
} else if (paramInfo.getName().startsWith("met")) {
if (excludeCurrentIOfile && loadOrSave) {
continue;
} else {
if (!paramInfo.isDefault()){
alwaysDisplay = true;
paramInfo.validateIfileValue(null, processorId, ocssw);
currCategoryEntries.append(makeParEntry(paramInfo));
}
}
} else if (paramInfo.getName().startsWith("ozone1")) {
if (excludeCurrentIOfile && loadOrSave) {
continue;
} else {
if (!paramInfo.isDefault()) {
alwaysDisplay = true;
paramInfo.validateIfileValue(null, processorId, ocssw);
currCategoryEntries.append(makeParEntry(paramInfo));
}
}
} else if (paramInfo.getName().startsWith("ozone2")) {
if (excludeCurrentIOfile && loadOrSave) {
continue;
} else {
if (!paramInfo.isDefault()){
alwaysDisplay = true;
paramInfo.validateIfileValue(null, processorId, ocssw);
currCategoryEntries.append(makeParEntry(paramInfo));
}
}
} else if (paramInfo.getName().startsWith("ozone3")) {
if (excludeCurrentIOfile && loadOrSave) {
continue;
} else {
if (!paramInfo.isDefault()){
alwaysDisplay = true;
paramInfo.validateIfileValue(null, processorId, ocssw);
currCategoryEntries.append(makeParEntry(paramInfo));
}
}
} else if (paramInfo.getName().startsWith("sstfile")) {
if (excludeCurrentIOfile && loadOrSave) {
continue;
} else {
if (!paramInfo.isDefault()){
alwaysDisplay = true;
paramInfo.validateIfileValue(null, processorId, ocssw);
currCategoryEntries.append(makeParEntry(paramInfo));
}
}
} else if (paramInfo.getName().equals(SUITE)) {
alwaysDisplay = true;
currCategoryEntries.append(makeParEntry(paramInfo));
} else if (paramInfo.getName().equals(PAR)) {
// right ignore and do not print todo
} else {
if (!paramInfo.getName().startsWith("-")) {
if (paramInfo.getValue().equals(paramInfo.getDefaultValue())) {
if (paramInfo.getName().equals(L2PROD) && getMode() == Mode.L3GEN) {
currCategoryEntries.append(makeParEntry(paramInfo));
} else if (showDefaults) {
currCategoryEntries.append(makeParEntry(paramInfo, true));
}
} else {
currCategoryEntries.append(makeParEntry(paramInfo));
}
}
}
}
if (ANCILLARY_FILES_CATEGORY_NAME.equals(paramCategoryInfo.getName())) {
par.append("# " + paramCategoryInfo.getName().toUpperCase() + " Default = climatology (select 'Get Ancillary' to download ancillary files)\n");
par.append(currCategoryEntries.toString());
par.append("\n");
} else if (currCategoryEntries.toString().length() > 0 && !(alwaysDisplay && !showIOFields)) {
par.append("# " + paramCategoryInfo.getName().toUpperCase() + "\n");
par.append(currCategoryEntries.toString());
par.append("\n");
}
}
}
return par.toString();
}
private String makeParEntry(ParamInfo paramInfo) {
return makeParEntry(paramInfo, false);
}
private String makeParEntry(ParamInfo paramInfo, boolean commented) {
StringBuilder line = new StringBuilder();
if (paramInfo.getValue().length() > 0 || paramInfo.getName().equals(L2PROD)) {
if (commented) {
line.append("# ");
}
line.append(paramInfo.getName() + "=" + paramInfo.getValue() + "\n");
if (paramInfo.getValidationComment() != null) {
line.append("# " + paramInfo.getValidationComment() + "\n");
}
}
return line.toString();
}
private ArrayList<ParamInfo> parseParString(String parfileContents) {
ArrayList<ParamInfo> paramInfos = new ArrayList<ParamInfo>();
if (parfileContents != null) {
String parfileLines[] = parfileContents.split("\n");
for (String parfileLine : parfileLines) {
// skip the comment lines in file
if (!parfileLine.trim().startsWith("#")) {
String splitLine[] = parfileLine.split("=");
if (splitLine.length == 1 || splitLine.length == 2) {
String name = splitLine[0].toString().trim();
String value = null;
if (splitLine.length == 2) {
value = splitLine[1].toString().trim();
} else if (splitLine.length == 1) {
value = ParamInfo.NULL_STRING;
}
ParamInfo paramInfo = new ParamInfo(name, value);
paramInfos.add(paramInfo);
}
}
}
}
return paramInfos;
}
public void setParString(String parString, boolean ignoreIfile, boolean ignoreSuite) {
setParString(parString, false, ignoreIfile, ignoreSuite, false, null);
}
public void setParString(String parString, boolean ignoreIfile, boolean ignoreSuite, boolean addParamsMode) {
setParString(parString, false, ignoreIfile, ignoreSuite, addParamsMode, null);
}
public void setParString(String parString, boolean loadOrSave, boolean ignoreIfile, boolean ignoreSuite, boolean addParamsMode, File parFileDir) {
setParamsBeingSetViaParstring(true);
// addParamsMode is a special mode.
// this enables a subset parstring to be sent in
// essentially this means that you are sending in a list of params to change but leaving anything else untouched
disableEvent(PARSTRING);
// keepParams variable is tied to selection of ifile by the selector
// this variable does not apply for this case where the params are being set be a parString
// so disable keepParams and then later put it back to the original value
boolean tmpKeepParams = isKeepParams();
setKeepParams(false);
ArrayList<ParamInfo> parfileParamInfos = parseParString(parString);
String ifile = null;
String suite = null;
/*
Handle IFILE and SUITE first
*/
if (!ignoreIfile) {
for (ParamInfo parfileParamInfo : parfileParamInfos) {
if (parfileParamInfo.getName().toLowerCase().equals(IFILE)) {
File tmpFile = SeadasFileUtils.createFile(parFileDir, parfileParamInfo.getValue());
ifile = tmpFile.getAbsolutePath();
break;
}
}
}
if (!ignoreSuite) {
for (ParamInfo parfileParamInfo : parfileParamInfos) {
if (parfileParamInfo.getName().toLowerCase().equals(SUITE)) {
suite = parfileParamInfo.getValue();
break;
}
}
}
if ((!ignoreIfile && ifile != null) || !ignoreSuite && suite != null) {
setIfileAndSuiteParamValues(ifile, suite);
}
/*
Handle L2PROD
*/
ArrayList<String> l2prods = null;
for (ParamInfo test : parfileParamInfos) {
if (test.getName().toLowerCase().startsWith(L2PROD)) {
if (l2prods == null) {
l2prods = new ArrayList<String>();
}
l2prods.add(test.getValue());
}
}
if (l2prods != null) {
StringUtils.join(l2prods, " ");
setParamValue(L2PROD, StringUtils.join(l2prods, " "));
}
/*
Set all params contained in parString
Ignore IFILE (handled earlier) and PAR (which is todo)
*/
for (ParamInfo newParamInfo : parfileParamInfos) {
if (newParamInfo.getName().toLowerCase().equals(OFILE) && ignoreIfile && loadOrSave) {
continue;
}
if (newParamInfo.getName().toLowerCase().equals(GEOFILE) && ignoreIfile && loadOrSave) {
continue;
}
if (newParamInfo.getName().toLowerCase().equals(IFILE)) {
continue;
}
if (newParamInfo.getName().toLowerCase().equals(PAR)) {
continue;
}
if (newParamInfo.getName().toLowerCase().startsWith(L2PROD)) {
continue;
}
if (newParamInfo.getName().toLowerCase().startsWith("met") && ignoreIfile && loadOrSave) {
continue;
}
if (newParamInfo.getName().toLowerCase().startsWith("ozone1") && ignoreIfile && loadOrSave) {
continue;
}
if (newParamInfo.getName().toLowerCase().startsWith("ozone2") && ignoreIfile && loadOrSave) {
continue;
}
if (newParamInfo.getName().toLowerCase().startsWith("ozone3") && ignoreIfile && loadOrSave) {
continue;
}
if (newParamInfo.getName().toLowerCase().startsWith("icefile") && ignoreIfile && loadOrSave) {
continue;
}
if (newParamInfo.getName().toLowerCase().startsWith("sstfile") && ignoreIfile && loadOrSave) {
continue;
}
setParamValue(newParamInfo.getName(), newParamInfo.getValue());
}
if (!addParamsMode) {
/*
Delete all params NOT contained in parString to defaults (basically set to default)
Except: IFILE, GEOFILE, OFILE and SUITE remain at current value
*/
for (ParamInfo paramInfo : paramInfos) {
// if (!paramInfo.getName().startsWith(L2PROD) && !paramInfo.getName().equals(IFILE) && !paramInfo.getName().equals(OFILE) && !paramInfo.getName().equals(GEOFILE) && !paramInfo.getName().equals(SUITE)) {
if (!paramInfo.getName().equals(IFILE) && !paramInfo.getName().equals(OFILE) && !paramInfo.getName().equals(GEOFILE) && !paramInfo.getName().equals(SUITE)) {
boolean paramHandled = false;
for (ParamInfo parfileParamInfo : parfileParamInfos) {
if (paramInfo.getName().toLowerCase().equals(parfileParamInfo.getName().toLowerCase())) {
paramHandled = true;
}
}
if (!paramHandled && (paramInfo.getValue() != paramInfo.getDefaultValue())) {
setParamValue(paramInfo.getName(), paramInfo.getDefaultValue());
}
}
}
}
fireEvent(PARSTRING);
enableEvent(PARSTRING);
setKeepParams(tmpKeepParams);
setParamsBeingSetViaParstring(false);
}
public boolean hasParamValue(String name) {
return paramInfoLookup.containsKey(name);
}
public ParamInfo getParamInfo(String name) {
if (name == null) {
return null;
}
name = name.trim().toLowerCase();
return paramInfoLookup.get(name);
}
private String getParamValue(ParamInfo paramInfo) {
if (paramInfo == null) {
return null;
}
return paramInfo.getValue();
}
public String getParamValue(String name) {
return getParamValue(getParamInfo(name));
}
private boolean getBooleanParamValue(ParamInfo paramInfo) {
if (paramInfo.getValue().equals(ParamInfo.BOOLEAN_TRUE)) {
return true;
} else {
return false;
}
}
public boolean getBooleanParamValue(String name) {
return getBooleanParamValue(getParamInfo(name));
}
private File getParamFile(ParamInfo paramInfo) {
if (paramInfo != null && iFileInfo != null) {
return paramInfo.getFile(iFileInfo.getFile().getParentFile());
}
return null;
}
public File getParamFile(String name) {
return getParamFile(getParamInfo(name));
}
public void setParamValueAndDefault(String name, String value) {
setParamValueAndDefault(getParamInfo(name), value);
}
public void setParamValueAndDefault(ParamInfo paramInfo, String value) {
if (paramInfo == null) {
return;
}
if (value == null) {
value = ParamInfo.NULL_STRING;
}
if (!value.equals(paramInfo.getValue()) || !value.equals(paramInfo.getDefaultValue())) {
if (paramInfo.getName().toLowerCase().equals(IFILE)) {
setIfileParamValue(paramInfo, value);
paramInfo.setDefaultValue(paramInfo.getValue());
} else {
paramInfo.setValue(value);
paramInfo.setDefaultValue(paramInfo.getValue());
setConflictingParams(paramInfo.getName());
if (paramInfo.getType() == ParamInfo.Type.IFILE) {
paramInfo.validateIfileValue(null, processorId, ocssw);
}
fireEvent(paramInfo.getName());
}
}
}
private void setParamValue(ParamInfo paramInfo, String value) {
if (paramInfo == null) {
return;
}
if (value == null) {
value = ParamInfo.NULL_STRING;
}
if (!value.equals(paramInfo.getValue())) {
if (paramInfo.getName().toLowerCase().equals(IFILE)) {
ocssw.setIfileName(value);
//todo Danny is working on this in order to maintain existing params when new ifile is selected
String tmpParString = null;
if (isKeepParams()) {
tmpParString = getParString();
}
if (getMode() == Mode.L2GEN_AQUARIUS) {
setIfileAndSuiteParamValues(value, getDefaultSuite());
} else {
setIfileParamValue(paramInfo, value);
}
if (isKeepParams()) {
setParString(tmpParString, true, false,true);
}
} else if (paramInfo.getName().toLowerCase().equals(SUITE)) {
setIfileAndSuiteParamValues(null, value);
} else {
if (value.length() > 0 || paramInfo.getName().toLowerCase().equals(L2PROD)) {
paramInfo.setValue(value);
if (paramInfo.getType() == ParamInfo.Type.IFILE && !isAncFile(paramInfo.getValue())) {
paramInfo.validateIfileValue(iFileInfo.getFile().getParent(), processorId, ocssw);
}
setConflictingParams(paramInfo.getName());
} else {
paramInfo.setValue(paramInfo.getDefaultValue());
}
fireEvent(paramInfo.getName());
}
}
}
private boolean isAncFile(String fileName) {
boolean isAncFile = fileName.contains("/var/anc/");
return isAncFile;
}
public void setParamValue(String name, String value) {
setParamValue(getParamInfo(name), value);
}
private void setIfileAndSuiteParamValues(String ifileValue, String suiteValue) {
setIfileandSuiteParamValuesWrapper(getParamInfo(IFILE), ifileValue, suiteValue);
}
private void setParamValue(ParamInfo paramInfo, boolean selected) {
if (selected) {
setParamValue(paramInfo, ParamInfo.BOOLEAN_TRUE);
} else {
setParamValue(paramInfo, ParamInfo.BOOLEAN_FALSE);
}
}
public void setParamValue(String name, boolean selected) {
setParamValue(getParamInfo(name), selected);
}
private void setParamValue(ParamInfo paramInfo, ParamValidValueInfo paramValidValueInfo) {
setParamValue(paramInfo, paramValidValueInfo.getValue());
}
public void setParamValue(String name, ParamValidValueInfo paramValidValueInfo) {
setParamValue(getParamInfo(name), paramValidValueInfo);
}
private boolean isParamDefault(ParamInfo paramInfo) {
if (paramInfo.getValue().equals(paramInfo.getDefaultValue())) {
return true;
} else {
return false;
}
}
public boolean isParamDefault(String name) {
return isParamDefault(getParamInfo(name));
}
private String getParamDefault(ParamInfo paramInfo) {
if (paramInfo != null) {
return paramInfo.getDefaultValue();
} else {
return null;
}
}
public String getParamDefault(String name) {
return getParamDefault(getParamInfo(name));
}
private void setParamToDefaults(ParamInfo paramInfo) {
if (paramInfo != null) {
setParamValue(paramInfo, paramInfo.getDefaultValue());
}
}
public void setParamToDefaults(String name) {
setParamToDefaults(getParamInfo(name));
}
public void setToDefaults(L2genParamCategoryInfo paramCategoryInfo) {
for (ParamInfo paramInfo : paramCategoryInfo.getParamInfos()) {
setParamToDefaults(paramInfo);
}
}
public boolean isParamCategoryDefault(L2genParamCategoryInfo paramCategoryInfo) {
boolean isDefault = true;
for (ParamInfo paramInfo : paramCategoryInfo.getParamInfos()) {
if (!paramInfo.isDefault()) {
isDefault = false;
}
}
return isDefault;
}
private File getSensorInfoFilename() {
if (iFileInfo != null) {
// determine the filename which contains the wavelength information
String SENSOR_INFO_FILENAME = "msl12_sensor_info.dat";
File subSensorDir = iFileInfo.getSubsensorDirectory();
if (subSensorDir != null) {
File filename = new File(subSensorDir.getAbsolutePath(), SENSOR_INFO_FILENAME);
if (filename.exists()) {
return filename;
}
}
File missionDir = iFileInfo.getMissionDirectory();
if (missionDir != null) {
File filename = new File(missionDir.getAbsolutePath(), SENSOR_INFO_FILENAME);
if (filename.exists()) {
return filename;
}
}
}
return null;
}
public String[] getSuiteList() {
return ocssw.getMissionSuites(iFileInfo.getMissionName(), getGuiName());
}
private void resetWaveLimiter() {
waveLimiterInfos.clear();
if (isIfileIndependentMode()) {
L2genWavelengthInfo wavelengthInfo = new L2genWavelengthInfo(L2genProductTools.WAVELENGTH_FOR_IFILE_INDEPENDENT_MODE);
waveLimiterInfos.add(wavelengthInfo);
return;
}
// determine the filename which contains the wavelengths
File sensorInfoFilename = getSensorInfoFilename();
if (sensorInfoFilename != null) {
// read in the mission's datafile which contains the wavelengths
// final ArrayList<String> SensorInfoArrayList = myReadDataFile(sensorInfoFilename.toString());
final ArrayList<String> SensorInfoArrayList = l2genReader.readFileIntoArrayList(sensorInfoFilename);
debug("sensorInfoFilename=" + sensorInfoFilename);
// loop through datafile
for (String myLine : SensorInfoArrayList) {
// skip the comment lines in file
if (!myLine.trim().startsWith("#")) {
// just look at value pairs of the form Lambda(#) = #
String splitLine[] = myLine.split("=");
if (splitLine.length == 2
&& splitLine[0].trim().startsWith("Lambda(")
&& splitLine[0].trim().endsWith(")")) {
// get current wavelength and add into in a JCheckBox
final String currWavelength = splitLine[1].trim();
L2genWavelengthInfo wavelengthInfo = new L2genWavelengthInfo(currWavelength);
waveLimiterInfos.add(wavelengthInfo);
debug("wavelengthLimiterArray adding wave=" + wavelengthInfo.getWavelengthString());
}
}
}
}
}
// runs this if IFILE changes
// it will reset missionString
// it will reset and make new wavelengthInfoArray
private void setIfileParamValue(ParamInfo paramInfo, String value) {
setIfileandSuiteParamValuesWrapper(paramInfo, value, null);
}
private void setIfileandSuiteParamValuesWrapper(final ParamInfo ifileParamInfo, final String ifileValue, String suiteValue) {
String currIfile = getParamValue(IFILE);
String currSuite = getParamValue(SUITE);
if (suiteValue == null) {
suiteValue = currSuite;
}
final String newSuite = suiteValue;
if (currIfile != null && currSuite != null) {
if (currIfile.equals(ifileValue) && currSuite.equals(suiteValue)) {
return;
}
}
if (isInitialized() && isParamsBeingSetViaParstring()) {
SnapApp snapApp = SnapApp.getDefault();
ProgressMonitorSwingWorker worker = new ProgressMonitorSwingWorker(snapApp.getMainFrame(),
getGuiName()) {
@Override
protected Void doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception {
pm.beginTask("Re-initializing " + getGuiName(), 2);
setIfileandSuiteParamValues(ifileParamInfo, ifileValue, newSuite);
pm.done();
return null;
}
};
worker.executeWithBlocking();
try {
worker.get();
} catch (Exception e) {
}
} else {
setIfileandSuiteParamValues(ifileParamInfo, ifileValue, newSuite);
if (getMode() == Mode.L2GEN_AQUARIUS) {
setAncillaryFiles(false,false,false);
// todo setting some defaults to blank so they get force passed in on run
getParamInfo(SUITE).setDefaultValue("");
}
}
}
private void setIfileandSuiteParamValues(ParamInfo ifileParamInfo, String ifileValue, String suiteValue) {
if (ifileParamInfo == null) {
return;
}
if (ifileValue == null) {
ifileValue = ifileParamInfo.getValue();
if (ifileValue == null) {
return;
}
}
disableEvent(PARSTRING);
disableEvent(L2PROD);
String oldIfile = getParamValue(getParamInfo(IFILE));
ifileParamInfo.setValue(ifileValue);
// ifileParamInfo.setDefaultValue(ifileValue);
iFileInfo = ifileParamInfo.validateIfileValue(null, processorId, ocssw);
processorModel.setReadyToRun(isValidIfile());
if (iFileInfo != null && isValidIfile()) {
// todo temporary more Joel updates
if (suiteValue != null) {
getParamInfo(SUITE).setValue(suiteValue);
}
if (iFileInfo.getMissionId() == MissionInfo.Id.AQUARIUS
|| iFileInfo.getMissionId() == MissionInfo.Id.VIIRSN
|| iFileInfo.getMissionId() == MissionInfo.Id.VIIRSJ1
|| iFileInfo.getMissionId() == MissionInfo.Id.VIIRSJ2) {
updateLuts(iFileInfo.getMissionName());
}
resetWaveLimiter();
l2prodParamInfo.resetProductInfos();
try {
updateXmlBasedObjects(iFileInfo.getFile(), suiteValue);
} catch (IOException e) {
SimpleDialogMessage dialog = new SimpleDialogMessage(null, "ERROR: " + e.getMessage());
dialog.setVisible(true);
dialog.setEnabled(true);
}
String progName;
if (mode == Mode.L3GEN) {
progName = "l3gen";
} else if (mode == Mode.L2GEN_AQUARIUS) {
progName = "l2gen_aquarius";
} else {
progName = "l2gen";
}
String tmpOFile = ocssw.getOfileName(iFileInfo.getFile().getAbsolutePath(), progName, suiteValue);
if (tmpOFile != null) {
File oFile = new File(iFileInfo.getFile().getParent(), tmpOFile.substring(tmpOFile.lastIndexOf(File.separator) + 1));
setParamValue(OFILE, oFile.getAbsolutePath());
}
if (mode != Mode.L3GEN) {
if (iFileInfo.isGeofileRequired()) {
FileInfo geoFileInfo = FilenamePatterns.getGeoFileInfo(iFileInfo, ocssw);
if (geoFileInfo != null) {
setParamValue(GEOFILE, geoFileInfo.getFile().getAbsolutePath());
}
} else {
setParamValueAndDefault(GEOFILE, null);
}
} else {
setParamValueAndDefault(GEOFILE, null);
}
} else {
setParamToDefaults(OFILE);
setParamValueAndDefault(GEOFILE, null);
fireEvent(INVALID_IFILE);
}
setParamValueAndDefault(PAR, ParamInfo.NULL_STRING);
fireEvent(PARSTRING);
enableEvent(L2PROD);
enableEvent(PARSTRING);
oldIfile = ""; // force receiving event listeners to treat as new ifile to account for possible SUITE change instead of IFILE change
fireEvent(IFILE, oldIfile, ifileValue);
}
public void updateLuts(String missionName) {
String UPDATE_LUTS_SCRIPT = "update_luts";
ProcessorModel processorModel = new ProcessorModel(UPDATE_LUTS_SCRIPT, ocssw);
processorModel.setAcceptsParFile(false);
processorModel.addParamInfo("mission", missionName, ParamInfo.Type.STRING, 0);
OCSSWExecutionMonitor ocsswExecutionMonitor = new OCSSWExecutionMonitor();
try {
ocsswExecutionMonitor.executeWithProgressMonitor(processorModel, ocssw, UPDATE_LUTS_SCRIPT);
Process p = ocssw.execute(processorModel.getParamList()); //processorModel.executeProcess();
} catch (Exception e) {
System.out.println("ERROR - Problem running " + UPDATE_LUTS_SCRIPT);
System.out.println(e.getMessage());
return;
}
}
public void setAncillaryFiles(boolean refreshDB, boolean forceDownload, boolean getNO2) {
// getanc --refreshDB <FILE>
if (!isValidIfile()) {
System.out.println("ERROR - Can not run getanc without a valid ifile.");
return;
}
// get the ifile
final String ifile = getParamValue(getParamInfo(IFILE));
final StringBuilder ancillaryFiles = new StringBuilder("");
final ProcessorModel processorModel = new ProcessorModel(getGetanc(), ocssw);
processorModel.setAcceptsParFile(false);
//position is changed from 1 to 0.
int position = 0;
if (refreshDB) {
processorModel.addParamInfo("refreshDB", "--refreshDB", ParamInfo.Type.STRING, position);
position++;
}
if (forceDownload) {
processorModel.addParamInfo("force-download", "--force-download", ParamInfo.Type.STRING, position);
position++;
}
if (getNO2) {
processorModel.addParamInfo("no2", "--no2", ParamInfo.Type.STRING, position);
position++;
}
processorModel.addParamInfo("ifile", ifile, ParamInfo.Type.IFILE, position);
//getanc accepts ifile as an argument, not as a key-value pair.
processorModel.getParamInfo("ifile").setUsedAs(ParamInfo.USED_IN_COMMAND_AS_ARGUMENT);
final File iFile = new File(ifile);
SnapApp snapApp = SnapApp.getDefault();
ProgressMonitorSwingWorker pmSwingWorker = new ProgressMonitorSwingWorker(snapApp.getMainFrame(),
"GetAnc") {
@Override
protected Void doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception {
pm.beginTask("Retrieving ancillary files", 2);
try {
InputStream processInputStream = ocssw.executeAndGetStdout(processorModel); //processorModel.executeProcess();
// Determine exploded filenames
File runDirectoryFiles[] = processorModel.getIFileDir().listFiles();
for (File file : runDirectoryFiles) {
if (file.getName().startsWith(iFile.getName().substring(0, 13))) {
if (file.getName().endsWith(".txt") || file.getName().endsWith(".anc")) {
file.deleteOnExit();
}
}
if (getMode() == Mode.L2GEN_AQUARIUS && file.getName().endsWith("L2_SCAT_V5.0.tar")) {
file.delete();
}
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(processInputStream));
String line = stdInput.readLine();
while (line != null) {
if (line.contains("=")) {
ancillaryFiles.append(line);
ancillaryFiles.append("\n");
// Delete all ancillary files in operational (IFILE) directory on program exit
String[] splitLine = line.split("=");
if (splitLine.length == 2) {
File currentFile = new File(splitLine[1]);
boolean delete = true;
if (getMode() == Mode.L2GEN_AQUARIUS) {
if (currentFile.getName().startsWith("y") && currentFile.getName().endsWith("h5")) {
delete = false;
}
}
if (delete) {
if (currentFile.isAbsolute()) {
if (currentFile.getParent() != null && currentFile.getParent().equals(iFile.getParent())) {
currentFile.deleteOnExit();
}
} else {
File absoluteCurrentFile = new File(processorModel.getIFileDir().getAbsolutePath(), currentFile.getName());
absoluteCurrentFile.deleteOnExit();
}
}
}
}
line = stdInput.readLine();
}
pm.worked(1);
} catch (IOException e) {
pm.done();
SimpleDialogMessage dialog = new SimpleDialogMessage(null, "ERROR - Problem running " + getGetanc() + " " + e.getMessage());
dialog.setVisible(true);
dialog.setEnabled(true);
} finally {
pm.done();
}
return null;
}
};
pmSwingWorker.executeWithBlocking();
setParString(ancillaryFiles.toString(), false, true, true, true, null);
}
private void debug(String string) {
// System.out.println(string);
}
/**
* resets paramInfos within paramCategoryInfos to link to appropriate entry
* in paramInfos
*/
public void setParamCategoryInfos() {
for (L2genParamCategoryInfo paramCategoryInfo : paramCategoryInfos) {
paramCategoryInfo.clearParamInfos();
}
for (L2genParamCategoryInfo paramCategoryInfo : paramCategoryInfos) {
for (String categorizedParamName : paramCategoryInfo.getParamNames()) {
for (ParamInfo paramInfo : paramInfos) {
if (categorizedParamName.equals(paramInfo.getName())) {
paramCategoryInfo.addParamInfos(paramInfo);
}
}
}
}
for (ParamInfo paramInfo : paramInfos) {
boolean found = false;
for (L2genParamCategoryInfo paramCategoryInfo : paramCategoryInfos) {
for (String categorizedParamName : paramCategoryInfo.getParamNames()) {
if (categorizedParamName.equals(paramInfo.getName())) {
// paramCategoryInfo.addParamInfos(paramInfo);
found = true;
}
}
}
if (!found) {
for (L2genParamCategoryInfo paramCategoryInfo : paramCategoryInfos) {
if (paramCategoryInfo.isDefaultBucket()) {
paramCategoryInfo.addParamInfos(paramInfo);
l2genPrint.adminlog("Dropping uncategorized param '" + paramInfo.getName() + "' into the defaultBucket");
}
}
}
}
}
public boolean compareWavelengthLimiter(L2genWavelengthInfo wavelengthInfo) {
for (L2genWavelengthInfo waveLimitorInfo : getWaveLimiterInfos()) {
if (waveLimitorInfo.getWavelength() == wavelengthInfo.getWavelength()) {
if (waveLimitorInfo.isSelected()) {
return true;
} else {
return false;
}
}
}
return false;
}
public ArrayList<L2genParamCategoryInfo> getParamCategoryInfos() {
return paramCategoryInfos;
}
public void addParamCategoryInfo(L2genParamCategoryInfo paramCategoryInfo) {
paramCategoryInfos.add(paramCategoryInfo);
}
public void clearParamCategoryInfos() {
paramCategoryInfos.clear();
}
private void updateXmlBasedObjects(File iFile) throws IOException {
updateXmlBasedObjects(iFile, null);
}
private void updateXmlBasedObjects(File iFile, String suite) throws IOException {
InputStream paramInfoStream = getParamInfoInputStream(iFile, suite);
// do this to create new productXml file which is only used next time SeaDAS is run
switch (getMode()) {
case L2GEN_AQUARIUS:
getProductInfoInputStream(Source.RESOURCES, false);
break;
default:
getProductInfoInputStream(Source.L2GEN, overwriteProductXML);
// getProductInfoInputStream(Source.RESOURCES, true);
break;
}
// will only update existing params; next time SeaDAS is run the new params will show up
l2genReader.updateParamInfosWithXml(paramInfoStream);
}
private InputStream getProductInfoInputStream(Source source, boolean overwrite) throws IOException {
return ocssw.getProductXMLFile(source);
}
private InputStream getParamInfoInputStream() throws IOException {
File dataDir = SystemUtils.getApplicationDataDir();
File l2genDir = new File(dataDir, OPER_DIR);
l2genDir.mkdirs();
//SeadasFileUtils.debug("l2gen xml file dir :" + l2genDir.getAbsolutePath());
//SeadasLogger.getLogger().info(this.getClass().getName() + ": l2gen xml file: " + "\n" + Arrays.toString(ocssw.getCommandArray()) + "\n" + l2genDir.getAbsolutePath());
File xmlFile = new File(l2genDir, getParamInfoXml());
//SeadasFileUtils.debug("l2gen xml file :" + xmlFile.getAbsolutePath());
//SeadasLogger.getLogger().info(this.getClass().getName() + ": l2gen xml file: " + "\n" + Arrays.toString(ocssw.getCommandArray()) + "\n" + xmlFile.getAbsolutePath());
if (!xmlFile.exists()) {
xmlFile = installResource(getParamInfoXml());
}
if (xmlFile == null || !xmlFile.exists()) {
throw new IOException("param XML file does not exist");
}
try {
return new FileInputStream(xmlFile);
} catch (IOException e) {
throw new IOException("problem creating param XML file: " + e.getMessage());
}
}
private InputStream getParamInfoInputStream(File file, String suite) throws IOException {
File dataDir = SystemUtils.getApplicationDataDir();
File l2genDir = new File(dataDir, OPER_DIR);
l2genDir.mkdirs();
File xmlFile;
xmlFile = new File(l2genDir, getParamInfoXml());
String executable = getGuiName();
// String executable = SeadasProcessorInfo.getExecutable(iFileInfo, processorId);
if (executable.equals("l3gen")) {
executable = "l2gen";
}
ProcessorModel processorModel = new ProcessorModel(executable, ocssw);
processorModel.setAcceptsParFile(true);
processorModel.addParamInfo("ifile", file.getAbsolutePath(), ParamInfo.Type.IFILE);
if (suite != null) {
processorModel.addParamInfo("suite", suite, ParamInfo.Type.STRING);
}
processorModel.addParamInfo("-dump_options_xmlfile", xmlFile.getAbsolutePath(), ParamInfo.Type.OFILE);
try {
// Aquarius will use the static xml file instead of a generated one
if (getMode() != Mode.L2GEN_AQUARIUS) {
Process p = ocssw.executeSimple(processorModel);
ocssw.waitForProcess();
if (ocssw instanceof OCSSWLocal) {
File tmpParFileToDel = new File(ParFileManager.tmpParFileToDelString);
tmpParFileToDel.delete();
}
if (ocssw.getProcessExitValue() != 0) {
throw new IOException("l2gen failed to run");
}
ocssw.getIntermediateOutputFiles(processorModel);
}
if (!xmlFile.exists()) {
//SeadasLogger.getLogger().severe("l2gen can't find paramInfo.xml file!");
Dialogs.showError("SEVERE: paramInfo.xml not found!");
return null;
}
return new FileInputStream(xmlFile);
} catch (IOException e) {
throw new IOException("problem creating Parameter XML file: " + e.getMessage());
}
}
public void setInitialValues(File iFile) {
ParamInfo ifileParamInfo = getParamInfo(IFILE);
setParamValueAndDefault(ifileParamInfo, ParamInfo.NULL_STRING);
if (iFile != null) {
setParamValue(ifileParamInfo, iFile.toString());
}
}
public StatusInfo initXmlBasedObjects() throws IOException {
StatusInfo myStatusInfo = new StatusInfo(StatusInfo.Id.SUCCEED);
InputStream paramInfoStream = getParamInfoInputStream();
if (paramInfoStream != null) {
disableEvent(PARSTRING);
disableEvent(L2PROD);
l2genReader.readParamInfoXml(paramInfoStream);
processorModel.setParamList(paramInfos);
InputStream paramCategoryInfoStream = L2genForm.class.getResourceAsStream(getParamCategoryXml());
l2genReader.readParamCategoryXml(paramCategoryInfoStream);
setParamCategoryInfos();
fireEvent(PARSTRING);
enableEvent(L2PROD);
enableEvent(PARSTRING);
return myStatusInfo;
}
myStatusInfo.setStatus(StatusInfo.Id.FAIL);
myStatusInfo.setMessage("Failed");
return myStatusInfo;
}
public void setL2prodParamInfo(L2genProductsParamInfo l2prodParamInfo) {
this.l2prodParamInfo = l2prodParamInfo;
}
public void addProductInfo(L2genProductInfo productInfo) {
l2prodParamInfo.addProductInfo(productInfo);
}
public void clearProductInfos() {
l2prodParamInfo.clearProductInfos();
}
public void addIntegerProductInfo(L2genProductInfo productInfo) {
l2prodParamInfo.addIntegerProductInfo(productInfo);
}
public void clearIntegerProductInfos() {
l2prodParamInfo.clearIntegerProductInfos();
}
public void sortProductInfos(Comparator<L2genProductInfo> comparator) {
l2prodParamInfo.sortProductInfos(comparator);
}
public void setProdToDefault() {
if (!l2prodParamInfo.isDefault()) {
l2prodParamInfo.setValue(l2prodParamInfo.getDefaultValue());
fireEvent(L2PROD);
}
}
/**
* resets productInfos within productCategoryInfos to link to appropriate
* entry in productInfos
*/
public void setProductCategoryInfos() {
l2prodParamInfo.setProductCategoryInfos();
}
public ArrayList<L2genProductCategoryInfo> getProductCategoryInfos() {
return l2prodParamInfo.getProductCategoryInfos();
}
public void addProductCategoryInfo(L2genProductCategoryInfo productCategoryInfo) {
l2prodParamInfo.addProductCategoryInfo(productCategoryInfo);
}
public void clearProductCategoryInfos() {
l2prodParamInfo.clearProductCategoryInfos();
}
public L2genProductsParamInfo createL2prodParamInfo(String value) throws IOException {
InputStream productInfoStream;
switch (getMode()) {
case L2GEN_AQUARIUS:
productInfoStream = getProductInfoInputStream(Source.RESOURCES, false);
break;
default:
productInfoStream = getProductInfoInputStream(Source.L2GEN, overwriteProductXML);
// productInfoStream = getProductInfoInputStream(Source.RESOURCES, true);
break;
}
L2genProductsParamInfo l2prodParamInfo = new L2genProductsParamInfo();
setL2prodParamInfo(l2prodParamInfo);
l2genReader.readProductsXml(productInfoStream);
l2prodParamInfo.setValue(value);
InputStream productCategoryInfoStream = L2genForm.class.getResourceAsStream(getProductCategoryXml());
l2genReader.readProductCategoryXml(productCategoryInfoStream);
setProductCategoryInfos();
return l2prodParamInfo;
}
public String sortStringList(String stringlist) {
String[] products = stringlist.split("\\s+");
ArrayList<String> productArrayList = new ArrayList<String>();
for (String product : products) {
productArrayList.add(product);
}
Collections.sort(productArrayList);
return StringUtils.join(productArrayList, " ");
}
public File installResource(final String fileName) {
final File dataDir = new File(SystemUtils.getApplicationDataDir(), OPER_DIR);
File theFile = new File(dataDir, fileName);
if (theFile.canRead()) {
return theFile;
}
final Path moduleBasePath = ResourceInstaller.findModuleCodeBasePath(this.getClass());
Path targetPath = dataDir.toPath();
Path sourcePath = moduleBasePath.resolve("gov/nasa/gsfc/seadas/processing/l2gen/userInterface").toAbsolutePath();
//SeadasLogger.getLogger().info(this.getClass().getName() + " Installing resource from " + sourcePath.toString() + " to " + targetPath.toString());
final ResourceInstaller resourceInstaller = new ResourceInstaller(sourcePath, targetPath);
try {
resourceInstaller.install(".*.xml", ProgressMonitor.NULL);
//SeadasLogger.getLogger().info(System.getProperty(this.getClass().getName() + ": resource install successful. All xml files are copied to ") + targetPath.toString());
} catch (IOException e) {
e.printStackTrace();
//SeadasLogger.getLogger().severe("Unable to install " + sourcePath + File.separator + fileName + " to " + targetPath + " " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return theFile;
}
public ProcessorModel getProcessorModel() {
processorModel.setReadyToRun(isValidIfile());
processorModel.setImplicitInputFileExtensions(getImplicitInputFileExtensions());
return processorModel;
}
public void updateParamValues(File selectedFile) {
}
@Override
public String getImplicitInputFileExtensions() {
switch (mode) {
case L2GEN_AQUARIUS:
return ImplicitInputFileExtensions.L2GEN_AQUARIUS.getFileExtensions();
case L3GEN:
return ImplicitInputFileExtensions.L3GEN.getFileExtensions();
default:
return ImplicitInputFileExtensions.L2GEN.getFileExtensions();
}
}
public boolean isInitialized() {
return initialized;
}
public void setInitialized(boolean initialized) {
this.initialized = initialized;
}
public String getGuiName() {
return guiName;
}
public void setGuiName(String guiName) {
this.guiName = guiName;
}
public boolean isParamsBeingSetViaParstring() {
return paramsBeingSetViaParstring;
}
public void setParamsBeingSetViaParstring(boolean paramsBeingSetViaParstring) {
this.paramsBeingSetViaParstring = paramsBeingSetViaParstring;
}
public boolean isDirty() {
return dirty;
}
public void setDirty(boolean dirty) {
this.dirty = dirty;
}
}
| 70,210 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ParamInfo.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/ParamInfo.java | package gov.nasa.gsfc.seadas.processing.core;
import gov.nasa.gsfc.seadas.processing.common.*;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo;
import java.io.File;
import java.util.ArrayList;
/**
* A ...
*
* @author Danny Knowles
* @author Aynur Abdurazik
* @since SeaDAS 7.0
*/
public class ParamInfo implements java.lang.Comparable<ParamInfo>, Cloneable {
public static final String PARAM_TYPE_IFILE = "ifile";
public static final String PARAM_TYPE_OFILE = "ofile";
public static final String PARAM_TYPE_HELP = "help";
public static final String PARAM_TYPE_STRING = "string";
public static final String PARAM_TYPE_FLOAT = "float";
public static final String PARAM_TYPE_INT = "int";
public static final String PARAM_TYPE_BOOLEAN = "boolean";
public static final String NULL_STRING = "";
public static final String BOOLEAN_TRUE = "1";
public static final String BOOLEAN_FALSE = "0";
public static final String USED_IN_COMMAND_AS_ARGUMENT = "argument";
public static final String USED_IN_COMMAND_AS_OPTION = "option";
public static final String USED_IN_COMMAND_AS_OPTION_MINUSMINUS = "option_minusminus";
public static final String USED_IN_COMMAND_AS_FLAG_MINUSMINUS = "flag_minusminus";
public static final String USED_IN_COMMAND_AS_FLAG = "flag";
public static final String[] FILE_COMPRESSION_SUFFIXES = {"bz2", "bzip2", "gz", "gzip", "zip", "tar", "tgz", "z"};
@Override
public int compareTo(ParamInfo o) {
return getName().compareToIgnoreCase(((ParamInfo) o).getName());
}
public static enum Type {
BOOLEAN, STRING, INT, FLOAT, IFILE, OFILE, HELP, DIR, FLAGS, BUTTON
}
private String name = NULL_STRING;
private String value = NULL_STRING;
private Type type = Type.STRING;
private String defaultValue = NULL_STRING;
private String description = NULL_STRING;
private String source = NULL_STRING;
private boolean isBit = false;
private int order = 0;
private int colSpan = 1;
private String validationComment = null;
private String usedAs = USED_IN_COMMAND_AS_OPTION;
private ArrayList<ParamValidValueInfo> validValueInfos = new ArrayList<ParamValidValueInfo>();
public ParamInfo(String name, String value, Type type, String defaultValue) {
setName(name);
//setType() should be executed before setValue()!
setType(type);
setValue(value);
setDefaultValue(defaultValue);
}
public ParamInfo(String name, String value, Type type) {
setName(name);
setValue(value);
setType(type);
}
public ParamInfo(String name, String value) {
setName(name);
setValue(value);
}
public ParamInfo(String name) {
setName(name);
}
public String getValidationComment() {
return validationComment;
}
private void setValidationComment(String validationComment) {
this.validationComment = validationComment;
}
private void clearValidationComment() {
this.validationComment = null;
}
public boolean isValid() {
return getValidationComment() == null;
}
public String getUsedAs() {
return usedAs;
}
public void setUsedAs(String usedAs) {
this.usedAs = usedAs;
}
public File getFile(File rootDir) {
if (type == Type.IFILE) {
return SeadasFileUtils.createFile(rootDir, value);
}
return null;
}
public String getName() {
return name;
}
protected void setName(String name) {
// Clean up and handle input exceptions
if (name == null) {
this.name = NULL_STRING;
return;
}
name = name.trim();
if (name.length() == 0) {
this.name = NULL_STRING;
} else {
this.name = name;
}
}
public String getValue() {
return value;
}
protected void setValue(String value) {
// Clean up and handle input exceptions
if (value == null) {
this.value = NULL_STRING;
return;
}
value = value.trim();
if (value.length() == 0) {
this.value = NULL_STRING;
} else if (getType() == Type.BOOLEAN) {
this.value = getStandardizedBooleanString(value);
} else if (getType() == Type.IFILE || getType() == Type.OFILE) {
this.value = value;
} else {
this.value = value;
}
}
public static String getStandardizedBooleanString(String booleanString) {
if (booleanString == null) {
return NULL_STRING;
}
String allowedTrueValues[] = {"1", "t", "true", "y", "yes", "on"};
String allowedFalseValue[] = {"0", "f", "false", "n", "no", "off"};
for (String trueValue : allowedTrueValues) {
if (booleanString.toLowerCase().equals(trueValue)) {
return BOOLEAN_TRUE;
}
}
for (String falseValue : allowedFalseValue) {
if (booleanString.toLowerCase().equals(falseValue)) {
return BOOLEAN_FALSE;
}
}
return NULL_STRING;
}
public Type getType() {
return type;
}
protected void setType(Type type) {
this.type = type;
}
public String getDefaultValue() {
return defaultValue;
}
public boolean isDefault() {
return getValue().equals(getDefaultValue());
}
protected void setDefaultValue(String defaultValue) {
// Clean up and handle input exceptions
if (defaultValue == null) {
this.defaultValue = NULL_STRING;
return;
}
defaultValue = defaultValue.trim();
if (defaultValue.length() == 0) {
this.defaultValue = NULL_STRING;
} else if (getType() == Type.BOOLEAN) {
this.defaultValue = getStandardizedBooleanString(defaultValue);
} else {
this.defaultValue = defaultValue;
}
}
public boolean isBitwiseSelected(ParamValidValueInfo paramValidValueInfo) {
int intParamValue = Integer.parseInt(value);
int intParamValidValue = Integer.parseInt(paramValidValueInfo.getValue());
return (intParamValue & intParamValidValue) > 0;
}
public String getDescription() {
return description;
}
protected void setDescription(String description) {
// Clean up and handle input exceptions
if (description == null) {
this.description = NULL_STRING;
return;
}
description = description.trim();
if (description.length() == 0) {
this.description = NULL_STRING;
} else {
this.description = description;
}
}
public String getSource() {
return source;
}
protected void setSource(String source) {
// Clean up and handle input exceptions
if (source == null) {
this.source = NULL_STRING;
return;
}
source = source.trim();
if (source.length() == 0) {
this.source = NULL_STRING;
} else {
this.source = source;
}
}
public ArrayList<ParamValidValueInfo> getValidValueInfos() {
return validValueInfos;
}
protected void setValidValueInfos(ArrayList<ParamValidValueInfo> validValueInfos) {
this.validValueInfos = validValueInfos;
}
protected void addValidValueInfo(ParamValidValueInfo paramValidValueInfo) {
this.validValueInfos.add(paramValidValueInfo);
}
protected void clearValidValueInfos() {
this.validValueInfos.clear();
}
public boolean hasValidValueInfos() {
return validValueInfos.size() > 0;
}
public boolean isBit() {
return isBit;
}
protected void setBit(boolean bit) {
isBit = bit;
}
public FileInfo validateIfileValue(String defaultFileParent, SeadasProcessorInfo.Id processorInfoId, OCSSW ocssw) {
clearValidationComment();
FileInfo fileInfo = null;
if (getType() == ParamInfo.Type.IFILE) {
if (getName().equals(L2genData.IFILE) || getName().equals(L2genData.GEOFILE)) {
String value = SeadasFileUtils.expandEnvironment(getValue());
fileInfo = new FileInfo(defaultFileParent, value, true, ocssw);
if (fileInfo.getFile() != null) {
if (fileInfo.getFile().exists()) {
String filename = fileInfo.getFile().getAbsolutePath();
boolean isCompressedFile = false;
for (String compressionSuffix : FILE_COMPRESSION_SUFFIXES) {
if (filename.toLowerCase().endsWith("." + compressionSuffix)) {
isCompressedFile = true;
}
}
if (isCompressedFile) {
setValidationComment("WARNING!!! File '" + filename + "' is compressed (please uncompress it)");
} else if (getName().equals(L2genData.GEOFILE)) {
if (!fileInfo.isTypeId(FileTypeInfo.Id.GEO)) {
//todo check geofile validity needs to be done on the server as well
setValidationComment("WARNING!!! File '" + filename + "' is not a GEO file");
}
} else if (getName().equals(L2genData.IFILE)) {
if (filename.contains(" ")) {
setValidationComment("# WARNING!!! File " + filename + " has a space in it" + "\n");
} else if (!SeadasProcessorInfo.isSupportedMission(fileInfo, processorInfoId)) {
setValidationComment("# WARNING!!! File " + filename + " is not a valid input mission" + ": Mission="+ fileInfo.getMissionName() + "\n");
} else if (!fileInfo.isMissionDirExist()) {
File dir = fileInfo.getSubsensorDirectory();
if(dir == null) {
dir = fileInfo.getMissionDirectory();
}
if (dir != null) {
setValidationComment("WARNING!!! Mission directory '" + dir.getAbsolutePath() + "' does not exist");
} else {
setValidationComment("WARNING!!! Mission directory does not exist");
}
} else if (!SeadasProcessorInfo.isValidFileType(fileInfo, processorInfoId)) {
setValidationComment("# WARNING!!! File " + filename + " is not a valid input file type" + "\n");
}
}
} else {
setValidationComment("WARNING!!! File'" + fileInfo.getFile().getAbsolutePath() + "' does not exist");
}
} else {
setValidationComment("WARNING!!! File'" + getValue() + "' does not exist");
}
} else {
if (!("").equals(getValue())) {
fileInfo = new FileInfo(defaultFileParent, getValue(), false, ocssw);
if (fileInfo.getFile() != null && !fileInfo.getFile().exists()) {
if ("local" == OCSSWInfo.getInstance().getOcsswLocation()) {
setValidationComment("WARNING!!! File '" + fileInfo.getFile().getAbsolutePath() + "' does not exist");
} else {
String fileName = fileInfo.getFile().toString();
if (fileName != null && fileName.contains("root")) {
String localFileName = fileName.replace("root", System.getProperty("user.home"));
if (localFileName != null && ! (new File(localFileName)).exists()) {
setValidationComment("WARNING!!! File '" + fileInfo.getFile().getAbsolutePath() + "' does not exist");
}
}
}
}
}
}
}
return fileInfo;
}
public void setOrder(int order) {
this.order = order;
}
public void setColSpan(int colSpan) {
this.colSpan = colSpan;
}
public int getColSpan() {
return colSpan;
}
public int getOrder() {
return order;
}
// protected void sortValidValueInfos() {
// // Collections.sort(validValueInfos, new ParamValidValueInfo.ValueComparator());
// Collections.sort(validValueInfos);
// }
//
// @Override
// public int compareTo(Object o) {
// return getName().compareToIgnoreCase(((ParamInfo) o).getName());
// }
@Override
public Object clone() {
ParamInfo info = new ParamInfo(name);
info.value = value;
info.type = type;
info.defaultValue = defaultValue;
info.description = description;
info.source = source;
info.isBit = isBit;
info.order = order;
info.validationComment = validationComment;
info.usedAs = usedAs;
for (ParamValidValueInfo validValueInfo : validValueInfos) {
info.validValueInfos.add((ParamValidValueInfo) validValueInfo.clone());
}
return info;
}
// get a string representation of this ParamInfo usable as a param string
public String getParamString() {
if (value.length() == 0) {
return "";
}
switch (usedAs) {
case USED_IN_COMMAND_AS_ARGUMENT:
return value;
case USED_IN_COMMAND_AS_FLAG:
if (isTrue()) {
return name;
} else {
return "";
}
case USED_IN_COMMAND_AS_OPTION:
if (value.contains(" ")) {
return name + "=\"" + value + "\"";
} else {
return name + "=" + value;
}
case USED_IN_COMMAND_AS_OPTION_MINUSMINUS:
if (value.contains(" ")) {
return "--" + name + " \"" + value + "\"";
} else {
return "--" + name + " " + value;
}
case USED_IN_COMMAND_AS_FLAG_MINUSMINUS:
if (isTrue()) {
return "--" + name;
} else {
return "";
}
default:
return "";
}
// if (usedAs.equals(USED_IN_COMMAND_AS_FLAG)) {
// if (isTrue()) {
// return name;
// } else {
// return "";
// }
// } else if (value.length() > 0){
// if (value.contains(" ")) {
// return name + "=\"" + value + "\"";
// } else {
// return name + "=" + value;
// }
}
public boolean isTrue() {
return getStandardizedBooleanString(value).equals(BOOLEAN_TRUE);
}
}
| 15,579 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ParamValidValueInfo.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/ParamValidValueInfo.java | package gov.nasa.gsfc.seadas.processing.core;
/**
* A ...
*
* @author Danny Knowles
* @since SeaDAS 7.0
*/
public class ParamValidValueInfo implements Comparable<ParamValidValueInfo>, Cloneable {
private String value = null;
private String description = null;
private boolean selected;
public ParamValidValueInfo(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDescription() {
return description;
}
public String getShortDescription(int maxLength) {
if (description != null && description.length() > maxLength) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(description.substring(0,maxLength-1)).append(" ...");
return stringBuilder.toString();
} else {
return description;
}
}
public void setDescription(String description) {
this.description = description;
}
// @Override
// public int compareTo(Object object) {
// return getValue().compareToIgnoreCase(((ParamValidValueInfo) object).getValue());
// }
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("");
if (value != null) {
stringBuilder.append(value);
if (description != null) {
stringBuilder.append(" - " + getShortDescription(70));
}
}
return stringBuilder.toString();
}
@Override
public ParamValidValueInfo clone() {
ParamValidValueInfo validValueInfo = new ParamValidValueInfo(value);
validValueInfo.description = description;
return validValueInfo;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
@Override
public int compareTo(ParamValidValueInfo o) {
return getValue().compareToIgnoreCase((o).getValue());
}
}
| 2,109 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genGlobals2.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/L2genGlobals2.java | package gov.nasa.gsfc.seadas.processing.core;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 5/31/13
* Time: 10:34 AM
* To change this template use File | Settings | File Templates.
*/
public class L2genGlobals2 {
private static L2genGlobals2 l2genGlobals2 = null;
public boolean ifileIndependentMode = false;
private static void init() {
if (l2genGlobals2 == null) {
l2genGlobals2 = new L2genGlobals2();
}
}
public static boolean isIfileIndependentMode() {
init();
return l2genGlobals2.ifileIndependentMode;
}
public static void setIfileIndependentMode(boolean ifileIndependentMode) {
init();
l2genGlobals2.ifileIndependentMode = ifileIndependentMode;
}
}
| 774 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ParamList.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/ParamList.java | package gov.nasa.gsfc.seadas.processing.core;
import javax.swing.event.SwingPropertyChangeSupport;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created with IntelliJ IDEA.
* User: dshea
* Date: 8/27/12
* Time: 1:57 PM
* To change this template use File | Settings | File Templates.
*/
public class ParamList {
private HashMap<String, ParamInfo> paramMap;
private ArrayList<ParamInfo> paramArray;
private SwingPropertyChangeSupport propertyChangeSupport;
public ParamList() {
paramMap = new HashMap<String, ParamInfo>();
paramArray = new ArrayList<ParamInfo>();
propertyChangeSupport = new SwingPropertyChangeSupport(this);
}
public void set(ParamList list) {
paramMap = list.paramMap;
paramArray = list.paramArray;
propertyChangeSupport = list.propertyChangeSupport;
}
public void addInfo(ParamInfo param) {
if (param == null) {
return;
}
paramMap.put(param.getName(), param);
paramArray.add(param);
}
public ParamInfo getInfo(String name) {
if (name == null || name.isEmpty()) {
return null;
}
return paramMap.get(name);
}
public ParamInfo removeInfo(String name) {
ParamInfo param = getInfo(name);
if (param == null) {
return null;
}
paramMap.remove(param.getName());
paramArray.remove(param);
return param;
}
public String getValue(String name) {
ParamInfo param = getInfo(name);
if (param != null) {
return param.getValue();
}
return null;
}
public boolean isValueTrue(String name) {
ParamInfo param = getInfo(name);
if (param != null) {
return param.isTrue();
}
return false;
}
public boolean setValue(String name, String value) {
ParamInfo param = getInfo(name);
if (param != null) {
String oldVal = param.getValue();
param.setValue(value);
propertyChangeSupport.firePropertyChange(param.getName(), oldVal, param.getValue());
return true;
}
return false;
}
public void addPropertyChangeListener(String name, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(name, listener);
}
public void removePropertyChangeListener(String name, PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(name, listener);
}
public PropertyChangeListener[] getPropertyChangeListener(String propertyName) {
return propertyChangeSupport.getPropertyChangeListeners(propertyName);
}
public SwingPropertyChangeSupport getPropertyChangeSupport() {
return propertyChangeSupport;
}
public void appendPropertyChangeSupport(SwingPropertyChangeSupport propertyChangeSupport) {
PropertyChangeListener[] pr = propertyChangeSupport.getPropertyChangeListeners();
for (int i = 0; i < pr.length; i++) {
this.propertyChangeSupport.addPropertyChangeListener(pr[i]);
}
}
public void clearPropertyChangeSupport() {
//propertyChangeSupport = new SwingPropertyChangeSupport(this);
PropertyChangeListener[] pr = propertyChangeSupport.getPropertyChangeListeners();
for (int i = 0; i < pr.length; i++) {
this.propertyChangeSupport.removePropertyChangeListener(pr[i]);
}
}
// this makes a deep copy of the ParamInfo objects, but a shallow copy of the propertyChangeSupport
public Object clone() {
ParamList newList = new ParamList();
for(ParamInfo param : paramArray) {
newList.addInfo((ParamInfo)param.clone());
}
newList.propertyChangeSupport = propertyChangeSupport;
return newList;
}
public String getParamString(String separator) {
StringBuffer stringBuffer = new StringBuffer();
boolean first = true;
for (ParamInfo param : paramArray) {
if(param.getType() != ParamInfo.Type.HELP && !param.isDefault()) {
if (first) {
first = false;
} else {
stringBuffer.append(separator);
}
String paramString = param.getParamString();
stringBuffer.append(paramString);
}
}
return stringBuffer.toString();
}
public String getParamString4mlp(String separator) {
StringBuffer stringBuffer = new StringBuffer();
boolean first = true;
for (ParamInfo param : paramArray) {
if(param.getType() != ParamInfo.Type.HELP && !param.isDefault()) {
if (first) {
first = false;
} else {
stringBuffer.append(separator);
}
String paramString = param.getParamString();
stringBuffer.append(paramString);
}
}
return stringBuffer.toString();
}
public String getParamString() {
return getParamString(" ");
}
public String getParamString4mlp() {
return getParamString4mlp(" ");
}
protected ArrayList<ParamInfo> makeParamInfoArray(String str) {
StringBuilder part = new StringBuilder();
ArrayList<String> parts = new ArrayList<String>();
// assemble characters into words, use quotation to include spaces in word
boolean inQuote = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (inQuote) {
if (c == '"') {
inQuote = false;
} else {
part.append(c);
}
} else {
if (c == '"') {
inQuote = true;
} else if (Character.isWhitespace(c)) {
if (part.length() > 0) {
parts.add(part.toString());
part.setLength(0);
}
} else if (c == '=') {
if (part.length() > 0) {
parts.add(part.toString());
part.setLength(0);
}
parts.add("=");
} else {
part.append(c);
}
} // not inQuote
}
if(part.length() > 0) {
parts.add(part.toString());
}
// loop through parts creating a map of new ParamInfos
ArrayList<ParamInfo> params = new ArrayList<ParamInfo>();
int pairCount = 0;
for (int i = 1; i < parts.size() - 1; i++) {
if (parts.get(i).equals("=")) {
pairCount++;
if (parts.get(i - 1).equals("=")) {
//System.out.printf("ParamList.setParamString - Key/Value pair %d missing Key\n", pairCount);
} else {
if (parts.get(i + 1).equals("=") || ((parts.size() > i+2) && parts.get(i + 2).equals("="))) {
params.add(new ParamInfo(parts.get(i - 1), ""));
} else {
params.add(new ParamInfo(parts.get(i - 1), parts.get(i + 1)));
}
}
}
}
return params;
}
public void setParamString(String str, boolean retainIFile, boolean setDefaults) {
ArrayList<ParamInfo> params = makeParamInfoArray(str);
// loop through params creating a lookup map
HashMap<String, ParamInfo> map = new HashMap<String, ParamInfo>();
for(ParamInfo param : params) {
map.put(param.getName(), param);
}
// loop through all parameters setting to default value or new value
for(ParamInfo param : paramArray) {
if(retainIFile && (param.getName().equals("ifile") || param.getName().equals("infile") || param.getName().equals("geofile"))) {
continue;
}
ParamInfo newParam = map.get(param.getName());
if(newParam == null) {
// not in map so set to default value if needed
if(setDefaults && !param.isDefault()) {
setValue(param.getName(), param.getDefaultValue());
}
} else {
// in map so set to new value
setValue(param.getName(), newParam.getValue());
}
}
}
public void setParamString(String str) {
setParamString(str, false, true);
}
public void clear() {
paramMap.clear();
paramArray.clear();
}
public ArrayList<ParamInfo> getParamArray() {
return paramArray;
}
public int getModifiedParamCount() {
int count = 0;
for(ParamInfo param : paramArray) {
if(param != null && !param.isDefault()) {
count++;
}
}
return count;
}
public boolean isDefault() {
for(ParamInfo param : paramArray) {
if(param != null && !param.isDefault()) {
return false;
}
}
return true;
}
}
| 9,364 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
SeaDASProcessorModel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/SeaDASProcessorModel.java | package gov.nasa.gsfc.seadas.processing.core;
import java.beans.PropertyChangeListener;
import java.io.File;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 6/6/12
* Time: 1:41 PM
* To change this template use File | Settings | File Templates.
*/
public interface SeaDASProcessorModel {
public String getParamValue(String name);
public void setParamValue(String name, String value);
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener);
public boolean isValidIfile();
public boolean isGeofileRequired();
public boolean isWavelengthRequired();
public String getPrimaryInputFileOptionName();
public String getPrimaryOutputFileOptionName();
public boolean isMultipleInputFiles();
public void updateParamValues(File selectedFile);
public String getImplicitInputFileExtensions();
}
| 895 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MultiParamList.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/MultiParamList.java | package gov.nasa.gsfc.seadas.processing.core;
import gov.nasa.gsfc.seadas.processing.processor.MultlevelProcessorForm;
import javax.swing.event.SwingPropertyChangeSupport;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: dshea
* Date: 9/4/12
* Time: 2:34 PM
* <p/>
* Processor model for the Seadas Processor script
*/
public class MultiParamList extends ParamList {
public static final String MAIN_KEY = MultlevelProcessorForm.Processor.MAIN.toString();
private HashMap<String, ParamList> paramLists;
public MultiParamList() {
paramLists = new LinkedHashMap<String, ParamList>();
}
public void addParamList(String listName, ParamList list) {
if(listName != null && !listName.equals(MAIN_KEY)) {
paramLists.put(listName, list);
} else {
super.set(list);
}
}
public ParamList getParamList(String listName) {
if (listName != null && listName.equals(MAIN_KEY)) {
return this;
}
return paramLists.get(listName);
}
public void addInfo(String listName, ParamInfo param) {
ParamList list = getParamList(listName);
if(list != null) {
list.addInfo(param);
}
}
public ParamInfo getInfo(String listName, String name) {
ParamList list = getParamList(listName);
if(list != null) {
return list.getInfo(name);
}
return null;
}
public ParamInfo removeInfo(String listName, String name) {
ParamList list = getParamList(listName);
if(list != null) {
return list.removeInfo(name);
}
return null;
}
public String getParamValue(String listName, String name) {
ParamList list = getParamList(listName);
if (list != null) {
return list.getValue(name);
}
return null;
}
public boolean isValueTrue(String listName, String name) {
ParamList list = getParamList(listName);
if (list != null) {
return list.isValueTrue(name);
}
return false;
}
public boolean setParamValue(String listName, String name, String value) {
ParamList list = getParamList(listName);
if (list != null) {
return list.setValue(name, value);
}
return false;
}
public void addPropertyChangeListener(String listName, String name, PropertyChangeListener listener) {
ParamList list = getParamList(listName);
if (list != null) {
list.addPropertyChangeListener(name, listener);
}
}
public void removePropertyChangeListener(String listName, String name, PropertyChangeListener listener) {
ParamList list = getParamList(listName);
if (list != null) {
list.removePropertyChangeListener(name, listener);
}
}
public SwingPropertyChangeSupport getPropertyChangeSupport(String listName) {
ParamList list = getParamList(listName);
if (list != null) {
return list.getPropertyChangeSupport();
}
return null;
}
public void appendPropertyChangeSupport(String listName, SwingPropertyChangeSupport propertyChangeSupport) {
ParamList list = getParamList(listName);
if (list != null) {
list.appendPropertyChangeSupport(propertyChangeSupport);
}
}
public void clearPropertyChangeSupport(String listName) {
ParamList list = getParamList(listName);
if (list != null) {
list.clearPropertyChangeSupport();
}
}
public Object clone() {
MultiParamList result = (MultiParamList) super.clone();
result.paramLists = new HashMap<String, ParamList>();
for(Map.Entry<String, ParamList> entry : paramLists.entrySet()) {
result.addParamList(entry.getKey(), (ParamList)entry.getValue().clone());
}
return result;
}
@Override
public String getParamString(String separator) {
StringBuilder sb = new StringBuilder();
ParamList list;
// let's put main at the top
sb.append("[").append("main").append("]");
sb.append(separator);
sb.append(super.getParamString(separator));
// loop through all the param lists
for (Map.Entry<String, ParamList> entry : paramLists.entrySet()) {
list = entry.getValue();
if (list != null && !list.isDefault()) {
sb.append(separator);
sb.append("\n[").append(entry.getKey()).append("]");
sb.append(separator);
sb.append(list.getParamString(separator));
}
}
return sb.toString();
}
@Override
public String getParamString4mlp(String separator) {
StringBuilder sb = new StringBuilder();
ParamList list;
// let's put main at the top
sb.append("[").append("main").append("]");
sb.append(separator);
sb.append(super.getParamString(separator));
// loop through all the param lists
for (Map.Entry<String, ParamList> entry : paramLists.entrySet()) {
list = entry.getValue();
if (list != null && !list.getParamArray().isEmpty()) {
sb.append(separator);
sb.append("\n[").append(entry.getKey()).append("]");
sb.append(separator);
sb.append(list.getParamString(separator));
}
}
return sb.toString();
}
}
| 5,668 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
OFileParamInfo.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/OFileParamInfo.java | package gov.nasa.gsfc.seadas.processing.core;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 12/11/12
* Time: 3:05 PM
* To change this template use File | Settings | File Templates.
*/
public class OFileParamInfo extends ParamInfo {
private boolean openInSeadas;
public OFileParamInfo(String name, String value, Type type, String defaultValue) {
super(name, value, type, defaultValue);
}
public boolean isOpenInSeadas() {
return openInSeadas;
}
public void setOpenInSeadas(boolean openInSeadas) {
this.openInSeadas = openInSeadas;
}
}
| 628 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ProcessObserver.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/ProcessObserver.java | package gov.nasa.gsfc.seadas.processing.core;
import com.bc.ceres.core.ProgressMonitor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* An observer that notifies its {@link Handler handlers} gov.nasa.gsfc.seadas.about lines of characters that have been written
* by a process to both {@code stdout} and {@code stderr} output streams.
*
* @author Norman Fomferra
* @since SeaDAS 7.0
*/
public class ProcessObserver {
protected static final String STDOUT = "stdout";
protected static final String STDERR = "stderr";
protected final Process process;
protected final String processName;
protected final com.bc.ceres.core.ProgressMonitor progressMonitor;
protected final ArrayList<Handler> handlers;
private int processExitValue;
/**
* Constructor.
*
* @param process The process to be observed
* @param processName A name that represents the process
* @param progressMonitor A progress monitor
*/
public ProcessObserver(final Process process, String processName, com.bc.ceres.core.ProgressMonitor progressMonitor) {
this.process = process;
this.processName = processName;
this.progressMonitor = progressMonitor;
this.handlers = new ArrayList<Handler>();
processExitValue = -1;
}
/**
* Adds a new handler to this observer.
*
* @param handler The new handler.
*/
public void addHandler(Handler handler) {
handlers.add(handler);
}
/**
* Starts observing the given process. The method blocks until both {@code stdout} and {@code stderr}
* streams are no longer available. If the progress monitor is cancelled, the process will be destroyed.
*/
public void startAndWait() {
processExitValue = -1;
final Thread stdoutReaderThread = new LineReaderThread(STDOUT);
final Thread stderrReaderThread = new LineReaderThread(STDERR);
stdoutReaderThread.start();
stderrReaderThread.start();
awaitTermination(stdoutReaderThread, stderrReaderThread);
}
private void awaitTermination(Thread stdoutReaderThread, Thread stderrReaderThread) {
while (stdoutReaderThread.isAlive() && stderrReaderThread.isAlive()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// todo - check what is best done now:
// * 1. just leave, and let the process be unattended (current impl.)
// 2. destroy the process
// 3. throw a checked ProgressObserverException
e.printStackTrace();
return;
}
if (progressMonitor.isCanceled()) {
// todo - check what is best done now:
// 1. just leave, and let the process be unattended
// * 2. destroy the process (current impl.)
// 3. throw a checked ProgressObserverException
process.destroy();
}
}
}
public int getProcessExitValue() {
return processExitValue;
}
public void setProcessExitValue(int processExitValue) {
this.processExitValue = processExitValue;
}
/**
* A handler that will be informed if a new line has been read from either {@code stdout} or {@code stderr}.
*/
public static interface Handler {
/**
* Handle the new line that has been read from {@code stdout}.
*
* @param line The line.
* @param process The process.
* @param progressMonitor The progress monitor, that is used to monitor the progress of the running process.
*/
void handleLineOnStdoutRead(String line, Process process, ProgressMonitor progressMonitor);
/**
* Handle the new line that has been read from {@code stderr}.
*
* @param line The line.
* @param process The process.
* @param progressMonitor The progress monitor, that is used to monitor the progress of the running process.
*/
void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor);
}
private class LineReaderThread extends Thread {
private final String type;
public LineReaderThread(String type) {
super(processName + "-" + type);
this.type = type;
}
@Override
public void run() {
try {
read();
} catch (IOException e) {
// cannot be handled
}
}
private void read() throws IOException {
final InputStream inputStream = type.equals("stdout") ? process.getInputStream() : process.getErrorStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
fireLineRead(line);
}
} finally {
reader.close();
}
try {
processExitValue = process.waitFor();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
private void fireLineRead(String line) {
for (Handler handler : handlers) {
if (type.equals("stdout")) {
handler.handleLineOnStdoutRead(line, process, progressMonitor);
} else {
handler.handleLineOnStderrRead(line, process, progressMonitor);
}
}
}
}
} | 5,859 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genParamCategoryInfo.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/L2genParamCategoryInfo.java | package gov.nasa.gsfc.seadas.processing.core;
import java.util.ArrayList;
import java.util.Collections;
/**
* A ...
*
* @author Danny Knowles
* @since SeaDAS 7.0
*/
@SuppressWarnings("unchecked")
public class L2genParamCategoryInfo implements Comparable {
private String name = null;
private boolean autoTab = false;
private boolean defaultBucket = false;
private boolean ignore = false;
private ArrayList<String> paramNames = new ArrayList<String>();
private ArrayList<ParamInfo> paramInfos = new ArrayList<ParamInfo>();
public L2genParamCategoryInfo(String name, boolean autoTab) {
this.name = name;
this.autoTab = autoTab;
}
public L2genParamCategoryInfo(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isAutoTab() {
return autoTab;
}
public void setAutoTab(boolean autoTab) {
this.autoTab = autoTab;
}
public ArrayList<String> getParamNames() {
return paramNames;
}
public void setParamNames(ArrayList<String> paramNames) {
this.paramNames = paramNames;
}
public ArrayList<ParamInfo> getParamInfos() {
return paramInfos;
}
public void addParamName(String name) {
paramNames.add(name);
}
public void clearParamNames() {
paramNames.clear();
}
public void addParamInfos(ParamInfo paramInfo) {
paramInfos.add(paramInfo);
}
public void clearParamInfos() {
paramInfos.clear();
}
public boolean isDefaultBucket() {
return defaultBucket;
}
public void setDefaultBucket(boolean defaultBucket) {
this.defaultBucket = defaultBucket;
}
public void sortParamNameInfos() {
Collections.sort(paramNames, String.CASE_INSENSITIVE_ORDER);
}
public void sortParamOptionsInfos() {
Collections.sort(paramInfos);
}
@Override
public int compareTo(Object o) {
return getName().compareToIgnoreCase(((L2genParamCategoryInfo) o).getName());
}
public boolean isIgnore() {
return ignore;
}
public void setIgnore(boolean ignore) {
this.ignore = ignore;
}
}
| 2,315 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ProcessorModel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/ProcessorModel.java | package gov.nasa.gsfc.seadas.processing.core;
import com.bc.ceres.core.runtime.Version;
import gov.nasa.gsfc.seadas.processing.common.*;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWClient;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo;
import gov.nasa.gsfc.seadas.processing.preferences.OCSSW_InstallerController;
import gov.nasa.gsfc.seadas.processing.preferences.SeadasToolboxDefaults;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.core.util.VersionChecker;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.rcp.util.Dialogs.Answer;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;
import javax.swing.event.SwingPropertyChangeSupport;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static gov.nasa.gsfc.seadas.processing.common.ExtractorUI.*;
import static gov.nasa.gsfc.seadas.processing.common.FilenamePatterns.getGeoFileInfo;
import static gov.nasa.gsfc.seadas.processing.common.OCSSWInstallerForm.VALID_TAGS_OPTION_NAME;
import static gov.nasa.gsfc.seadas.processing.core.L2genData.GEOFILE;
/**
* Created by IntelliJ IDEA. User: Aynur Abdurazik (aabduraz) Date: 3/16/12
* Time: 2:20 PM To change this template use File | Settings | File Templates.
*/
public class ProcessorModel implements SeaDASProcessorModel, Cloneable {
protected String programName;
protected ParamList paramList;
private boolean acceptsParFile;
private boolean hasGeoFile;
private Set<String> primaryOptions;
private String parFileOptionName;
private boolean readyToRun;
private final String runButtonPropertyName = "RUN_BUTTON_STATUS_CHANGED";
private final String allparamInitializedPropertyName = "ALL_PARAMS_INITIALIZED";
private final String l2prodProcessors = "l2mapgen l2brsgen l2bin l2bin_aquarius l3bin smigen";
final public String L1AEXTRACT_MODIS = "l1aextract_modis",
L1AEXTRACT_MODIS_XML_FILE = "l1aextract_modis.xml",
L1AEXTRACT_SEAWIFS = "l1aextract_seawifs",
L1AEXTRACT_SEAWIFS_XML_FILE = "l1aextract_seawifs.xml",
L1AEXTRACT_VIIRS = "l1aextract_viirs",
L1AEXTRACT_VIIRS_XML_FILE = "l1aextract_viirs.xml",
L2EXTRACT = "l2extract",
L2EXTRACT_XML_FILE = "l2extract.xml";
private ProcessorModel secondaryProcessor;
private Pattern progressPattern;
private ProcessorTypeInfo.ProcessorID processorID;
private final SwingPropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this);
private boolean multipleInputFiles;
private boolean openInSeadas;
private String prodParamName = "prod";
private static String[] cmdArrayPrefix;
private String[] cmdArraySuffix;
boolean isIfileValid = false;
private static OCSSW ocssw;
private String fileExtensions = null;
FileInfo inputFileInfo;
public ProcessorModel(String name, OCSSW ocssw) {
programName = name;
this.setOcssw(ocssw);
acceptsParFile = false;
hasGeoFile = false;
readyToRun = false;
multipleInputFiles = false;
paramList = new ParamList();
setParFileOptionName(ParamUtils.DEFAULT_PAR_FILE_NAME);
processorID = ProcessorTypeInfo.getProcessorID(programName);
primaryOptions = new HashSet<String>();
primaryOptions.add("ifile");
primaryOptions.add("ofile");
progressPattern = Pattern.compile(ParamUtils.DEFAULT_PROGRESS_REGEX);
setOpenInSeadas(false);
setCommandArrayPrefix();
setCommandArraySuffix();
}
public ProcessorModel(String name, String parXMLFileName, OCSSW ocssw) {
this(name, ocssw);
if (parXMLFileName != null && parXMLFileName.length() > 0) {
setParamList((ArrayList<ParamInfo>) ParamUtils.computeParamList(parXMLFileName));
acceptsParFile = ParamUtils.getOptionStatus(parXMLFileName, "hasParFile");
setParFileOptionName(ParamUtils.getParFileOptionName(parXMLFileName));
progressPattern = Pattern.compile(ParamUtils.getProgressRegex(parXMLFileName));
hasGeoFile = ParamUtils.getOptionStatus(parXMLFileName, "hasGeoFile");
setPrimaryOptions(ParamUtils.getPrimaryOptions(parXMLFileName));
setOpenInSeadas(false);
setCommandArrayPrefix();
setCommandArraySuffix();
}
}
public ProcessorModel(String name, ArrayList<ParamInfo> paramList, OCSSW ocssw) {
this(name, ocssw);
setParamList(paramList);
}
public static ProcessorModel valueOf(String programName, String xmlFileName, OCSSW ocssw) {
ProcessorTypeInfo.ProcessorID processorID = ProcessorTypeInfo.getProcessorID(programName);
switch (processorID) {
case EXTRACTOR:
return new Extractor_Processor(programName, xmlFileName, ocssw);
case MODIS_L1B:
return new Modis_L1B_Processor(programName, xmlFileName, ocssw);
case LONLAT2PIXLINE:
return new LonLat2Pixels_Processor(programName, xmlFileName, ocssw);
// case SMIGEN:
// return new SMIGEN_Processor(programName, xmlFileName, ocssw);
case L3MAPGEN:
return new L3MAPGEN_Processor(programName, xmlFileName, ocssw);
case MAPGEN:
return new MAPGEN_Processor(programName, xmlFileName, ocssw);
case L2BIN:
return new L2Bin_Processor(programName, xmlFileName, ocssw);
// case L2BIN_AQUARIUS:
// return new L2Bin_Processor(programName, xmlFileName, ocssw);
case L3BIN:
return new L3Bin_Processor(programName, xmlFileName, ocssw);
case L3BINDUMP:
return new L3BinDump_Processor(programName, xmlFileName, ocssw);
case OCSSW_INSTALLER:
return new OCSSWInstaller_Processor(programName, xmlFileName, ocssw);
default:
}
return new ProcessorModel(programName, xmlFileName, ocssw);
}
void setCommandArrayPrefix() {
OCSSWInfo ocsswInfo = OCSSWInfo.getInstance();
cmdArrayPrefix = new String[4];
getCmdArrayPrefix()[0] = ocsswInfo.getOcsswRunnerScriptPath();
getCmdArrayPrefix()[1] = "--ocsswroot";
getCmdArrayPrefix()[2] = ocsswInfo.getOcsswRoot();
getCmdArrayPrefix()[3] = getProgramName();
}
private void setCommandArraySuffix() {
setCmdArraySuffix(new String[0]);
}
public void addParamInfo(ParamInfo info) {
paramList.addInfo(info);
}
public void removeParamInfo(ParamInfo paramInfo) {
paramList.removeInfo(paramInfo.getName());
}
public boolean isReadyToRun() {
return readyToRun;
}
public void setReadyToRun(boolean readyToRun) {
boolean oldValue = this.readyToRun;
this.readyToRun = readyToRun;
fireEvent(getRunButtonPropertyName(), oldValue, readyToRun);
}
public String getOfileName() {
return getParamValue(getPrimaryOutputFileOptionName());
}
public boolean isMultipleInputFiles() {
return multipleInputFiles;
}
public void setMultipleInputFiles(boolean multipleInputFiles) {
this.multipleInputFiles = multipleInputFiles;
}
public void createsmitoppmProcessorModel(String ofileName) {
ProcessorModel smitoppm = new ProcessorModel("smitoppm_4_ui", getOcssw());
smitoppm.setAcceptsParFile(false);
ParamInfo pi1 = new ParamInfo("ifile", getParamValue(getPrimaryOutputFileOptionName()));
pi1.setOrder(0);
pi1.setType(ParamInfo.Type.IFILE);
ParamInfo pi2 = new ParamInfo("ofile", ofileName);
pi2.setOrder(1);
pi2.setType(ParamInfo.Type.OFILE);
smitoppm.addParamInfo(pi1);
smitoppm.addParamInfo(pi2);
setSecondaryProcessor(smitoppm);
}
public void addParamInfo(String name, String value, ParamInfo.Type type) {
ParamInfo info = new ParamInfo(name, value, type);
addParamInfo(info);
}
public void addParamInfo(String name, String value, ParamInfo.Type type, int order) {
ParamInfo info = new ParamInfo(name, value, type);
info.setOrder(order);
addParamInfo(info);
}
public String getPrimaryInputFileOptionName() {
for (String name : primaryOptions) {
ParamInfo param = paramList.getInfo(name);
if ((param != null)
&& (param.getType() == ParamInfo.Type.IFILE)
&& (!param.getName().toLowerCase().contains("geo"))) {
return name;
}
}
return null;
}
public String getPrimaryOutputFileOptionName() {
for (String name : primaryOptions) {
ParamInfo param = paramList.getInfo(name);
if ((param != null) && (param.getType() == ParamInfo.Type.OFILE)) {
return name;
}
}
return null;
}
public boolean hasGeoFile() {
return hasGeoFile;
}
public void setHasGeoFile(boolean hasGeoFile) {
boolean oldValue = this.hasGeoFile;
this.hasGeoFile = hasGeoFile;
paramList.getPropertyChangeSupport().firePropertyChange("geofile", oldValue, hasGeoFile);
}
public boolean isValidProcessor() {
//SeadasLogger.getLogger().info("program location: " + OCSSWInfo.getInstance().getOcsswRunnerScriptPath());
return OCSSWInfo.getInstance().getOcsswRunnerScriptPath() != null;
}
public String getProgramName() {
return programName;
}
public ArrayList<ParamInfo> getProgramParamList() {
return paramList.getParamArray();
}
public boolean hasPrimaryOutputFile() {
String name = getPrimaryOutputFileOptionName();
if (name == null) {
return false;
} else {
return true;
}
}
public void setAcceptsParFile(boolean acceptsParFile) {
this.acceptsParFile = acceptsParFile;
}
public boolean acceptsParFile() {
return acceptsParFile;
}
public void updateParamInfo(ParamInfo currentOption, String newValue) {
updateParamInfo(currentOption.getName(), newValue);
checkCompleteness();
}
protected void checkCompleteness() {
boolean complete = true;
for (ParamInfo param : paramList.getParamArray()) {
if (param.getValue() == null || param.getValue().trim().length() == 0) {
complete = false;
break;
}
}
if (complete) {
fireEvent(getAllparamInitializedPropertyName(), false, true);
}
}
public ParamInfo getParamInfo(String paramName) {
return paramList.getInfo(paramName);
}
public String getParamValue(String paramName) {
ParamInfo option = getParamInfo(paramName);
if (option != null) {
return option.getValue();
}
return null;
}
public void updateParamInfo(String paramName, String newValue) {
ParamInfo option = getParamInfo(paramName);
if (option != null) {
String oldValue = option.getValue();
option.setValue(newValue);
checkCompleteness();
if (!(oldValue.contains(newValue) && oldValue.trim().length() == newValue.trim().length())) {
SeadasFileUtils.debug("property changed from " + oldValue + " to " + newValue);
propertyChangeSupport.firePropertyChange(option.getName(), oldValue, newValue);
}
}
}
public boolean updateIFileInfo(String ifileName) {
if (programName != null && (programName.equals("multilevel_processor"))) {
return true;
}
File ifile = new File(ifileName);
inputFileInfo = new FileInfo(ifile.getParent(), ifile.getName(), ocssw);
if (programName != null && verifyIFilePath(ifileName)) {
//ocssw.setIfileName(ifileName);
String ofileName = getOcssw().getOfileName(ifileName, programName);
//SeadasLogger.getLogger().info("ofile name from finding next level name: " + ofileName);
if (ofileName != null) {
isIfileValid = true;
updateParamInfo(getPrimaryInputFileOptionName(), ifileName + "\n");
updateGeoFileInfo(ifileName, inputFileInfo);
updateOFileInfo(getOFileFullPath(ofileName));
updateParamValues(new File(ifileName));
}
} else {
isIfileValid = false;
updateParamInfo(getPrimaryOutputFileOptionName(), "" + "\n");
removePropertyChangeListeners(getPrimaryInputFileOptionName());
Answer answer = Dialogs.requestDecision(programName, "Cannot compute output file name. Would you like to continue anyway?", true, null);
switch (answer) {
case CANCELLED:
updateParamInfo(getPrimaryInputFileOptionName(), "" + "\n");
break;
}
}
return isIfileValid;
}
//todo: change the path to get geo filename from ifile
public boolean updateGeoFileInfo(String ifileName, FileInfo inputFileInfo) {
FileInfo geoFileInfo = getGeoFileInfo(inputFileInfo, ocssw);
if (geoFileInfo != null) {
setHasGeoFile(true);
updateParamInfo(GEOFILE, geoFileInfo.getFile().getAbsolutePath());
return true;
} else {
setHasGeoFile(false);
return false;
}
}
public boolean updateOFileInfo(String newValue) {
if (newValue != null && newValue.trim().length() > 0) {
//String ofile = getOFileFullPath(newValue);
updateParamInfo(getPrimaryOutputFileOptionName(), newValue + "\n");
setReadyToRun(newValue.trim().length() == 0 ? false : true);
return true;
}
return false;
}
public void setParamValue(String name, String value) {
SeadasFileUtils.debug("primary io file option names: " + getPrimaryInputFileOptionName() + " " + getPrimaryOutputFileOptionName());
SeadasFileUtils.debug("set param value: " + name + " " + value);
SeadasFileUtils.debug(name + " " + value);
if (name.trim().equals(getPrimaryInputFileOptionName())) {
if (value.contains(" ")) {
SimpleDialogMessage dialog = new SimpleDialogMessage(null, "<html><br> WARNING!!<br> " +
" Directory path and/or filename cannot have a space in it <br> </html>");
dialog.setVisible(true);
dialog.setEnabled(true);
} else {
updateIFileInfo(value);
}
} else if (name.trim().equals(getPrimaryOutputFileOptionName())) {
if (value.contains(" ")) {
SimpleDialogMessage dialog = new SimpleDialogMessage(null, "<html><br> WARNING!!<br> " +
" Directory path and/or filename cannot have a space in it <br> </html>");
dialog.setVisible(true);
dialog.setEnabled(true);
} else {
updateOFileInfo(getOFileFullPath(value));
}
} else {
updateParamInfo(name, value);
}
}
public String[] getCmdArrayPrefix() {
return cmdArrayPrefix;
}
public EventInfo[] eventInfos = {
new EventInfo("none", this),};
private EventInfo getEventInfo(String name) {
for (EventInfo eventInfo : eventInfos) {
if (name.equals(eventInfo.getName())) {
return eventInfo;
}
}
return null;
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
SeadasFileUtils.debug(" added property name: " + propertyName);
if (propertyName != null) {
EventInfo eventInfo = getEventInfo(propertyName);
if (eventInfo == null) {
propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
} else {
eventInfo.addPropertyChangeListener(listener);
}
}
}
public void removePropertyChangeListeners(String propertyName) {
EventInfo eventInfo = getEventInfo(propertyName);
PropertyChangeListener[] propertyListeners = propertyChangeSupport.getPropertyChangeListeners(propertyName);
for (PropertyChangeListener propertyChangeListener : propertyListeners) {
propertyChangeSupport.removePropertyChangeListener(propertyChangeListener);
if (eventInfo == null) {
propertyChangeSupport.removePropertyChangeListener(propertyChangeListener);
} else {
eventInfo.removePropertyChangeListener(propertyChangeListener);
}
}
}
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
EventInfo eventInfo = getEventInfo(propertyName);
if (eventInfo == null) {
propertyChangeSupport.removePropertyChangeListener(propertyName, listener);
} else {
eventInfo.removePropertyChangeListener(listener);
}
}
public void disableEvent(String name) {
EventInfo eventInfo = getEventInfo(name);
if (eventInfo == null) {
//SeadasLogger.getLogger().severe("disableEvent - eventInfo not found for " + name);
SeadasFileUtils.debug("severe: disableEvent - eventInfo not found for " + name);
} else {
eventInfo.setEnabled(false);
}
}
public void enableEvent(String name) {
EventInfo eventInfo = getEventInfo(name);
if (eventInfo == null) {
//SeadasLogger.getLogger().severe("enableEvent - eventInfo not found for " + name);
SeadasFileUtils.debug("severe: enableEvent - eventInfo not found for " + name);
} else {
eventInfo.setEnabled(true);
}
}
public void fireEvent(String name) {
fireEvent(name, null, null);
}
public void fireEvent(String name, Serializable oldValue, Serializable newValue) {
EventInfo eventInfo = getEventInfo(name);
if (eventInfo == null) {
propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(this, name, oldValue, newValue));
} else {
eventInfo.fireEvent(oldValue, newValue);
}
}
public void fireAllParamEvents() {
for (ParamInfo paramInfo : paramList.getParamArray()) {
if (paramInfo.getName() != null && !paramInfo.getName().toLowerCase().equals("none")) {
fireEvent(paramInfo.getName());
}
}
}
public File getRootDir() {
File rootDir = (new File(getParamValue(getPrimaryInputFileOptionName()))).getParentFile();
if (rootDir != null) {
return rootDir;
} else {
try {
rootDir = new File(OCSSWInfo.getInstance().getOcsswRoot());
} catch (Exception e) {
//SeadasLogger.getLogger().severe("error in getting ocssw root!");
SeadasFileUtils.debug("severe: error in getting ocssw root!");
}
}
return rootDir == null ? new File(".") : rootDir;
}
public ProcessorModel getSecondaryProcessor() {
return secondaryProcessor;
}
public void setSecondaryProcessor(ProcessorModel secondaryProcessor) {
this.secondaryProcessor = secondaryProcessor;
}
public boolean isValidIfile() {
return isIfileValid;
}
public boolean isGeofileRequired() {
return hasGeoFile;
}
@Override
public boolean isWavelengthRequired() {
return true;
}
boolean verifyIFilePath(String ifileName) {
File ifile = new File(ifileName);
if (ifile.exists()) {
return true;
}
return false;
}
private String getIfileDirString() {
String ifileDir;
try {
ifileDir = getParamValue(getPrimaryInputFileOptionName());
ifileDir = ifileDir.substring(0, ifileDir.lastIndexOf(File.separator));
} catch (Exception e) {
ifileDir = System.getProperty("user.dir");
}
return ifileDir;
}
public File getIFileDir() {
if (new File(getIfileDirString()).isDirectory()) {
return new File(getIfileDirString());
} else {
return null;
}
}
String getOFileFullPath(String fileName) {
if (fileName.indexOf(File.separator) != -1 && new File(fileName).getParentFile().exists()) {
return fileName;
} else {
String ofileNameWithoutPath = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
return getIfileDirString() + File.separator + ofileNameWithoutPath;
}
}
public void setProgramName(String programName) {
this.programName = programName;
}
public ParamList getParamList() {
return paramList;
}
public void setParamList(ParamList paramList) {
this.paramList = paramList;
}
public void setParamList(ArrayList<ParamInfo> paramArray) {
paramList.clear();
for (ParamInfo param : paramArray) {
paramList.addInfo(param);
}
}
public SwingPropertyChangeSupport getPropertyChangeSupport() {
return paramList.getPropertyChangeSupport();
}
public void appendPropertyChangeSupport(SwingPropertyChangeSupport propertyChangeSupport) {
paramList.appendPropertyChangeSupport(propertyChangeSupport);
}
public Set<String> getPrimaryOptions() {
return primaryOptions;
}
public void setPrimaryOptions(Set<String> primaryOptions) {
this.primaryOptions = primaryOptions;
}
public String getRunButtonPropertyName() {
return runButtonPropertyName;
}
public String getAllparamInitializedPropertyName() {
return allparamInitializedPropertyName;
}
private String executionLogMessage;
public String getExecutionLogMessage() {
return executionLogMessage;
}
public void setExecutionLogMessage(String executionLogMessage) {
this.executionLogMessage = executionLogMessage;
}
public void setProgressPattern(Pattern progressPattern) {
this.progressPattern = progressPattern;
}
public Pattern getProgressPattern() {
return progressPattern;
}
public boolean isOpenInSeadas() {
return openInSeadas;
}
public void setOpenInSeadas(boolean openInSeadas) {
this.openInSeadas = openInSeadas;
}
String getProdParamName() {
return prodParamName;
}
void setProdPramName(String prodPramName) {
this.prodParamName = prodPramName;
}
public void updateParamValues(Product selectedProduct) {
updateParamValues(selectedProduct.getFileLocation());
}
public void updateParamValues(File selectedFile) {
if (selectedFile == null || (programName != null && !l2prodProcessors.contains(programName))) {
return;
}
if (selectedFile.getName().endsWith(".txt")) {
try {
LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(selectedFile));
String sampleFileName = lineNumberReader.readLine();
if (new File(sampleFileName).exists()) {
selectedFile = new File(sampleFileName);
//System.out.println("sample file name: " + sampleFileName + System.currentTimeMillis());
} else {
return;
}
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
}
}
NetcdfFile ncFile = null;
try {
ncFile = NetcdfFile.open(selectedFile.getAbsolutePath());
} catch (IOException ioe) {
}
ArrayList<String> products = new ArrayList<String>();
if (ncFile != null) {
java.util.List<Variable> var = null;
List<ucar.nc2.Group> groups = ncFile.getRootGroup().getGroups();
for (ucar.nc2.Group g : groups) {
//retrieve geophysical data to fill in "product" value ranges
if (g.getShortName().equalsIgnoreCase("Geophysical_Data")) {
var = g.getVariables();
break;
}
}
if (var != null) {
for (Variable v : var) {
products.add(v.getShortName());
}
String[] bandNames = new String[products.size()];
products.toArray(bandNames);
ParamInfo pi = getParamInfo(getProdParamName());
if (bandNames != null && pi != null) {
String oldValue = pi.getValue();
ParamValidValueInfo paramValidValueInfo;
for (String bandName : bandNames) {
paramValidValueInfo = new ParamValidValueInfo(bandName);
paramValidValueInfo.setDescription(bandName);
pi.addValidValueInfo(paramValidValueInfo);
}
ArrayList<ParamValidValueInfo> newValidValues = pi.getValidValueInfos();
String newValue = pi.getValue() != null ? pi.getValue() : newValidValues.get(0).getValue();
paramList.getPropertyChangeSupport().firePropertyChange(getProdParamName(), oldValue, newValue);
}
}
}
}
@Override
public String getImplicitInputFileExtensions() {
return fileExtensions;
}
public void setImplicitInputFileExtensions(String fileExtensions) {
this.fileExtensions = fileExtensions;
}
public String[] getCmdArraySuffix() {
return cmdArraySuffix;
}
public void setCmdArraySuffix(String[] cmdArraySuffix) {
this.cmdArraySuffix = cmdArraySuffix;
}
public String getParFileOptionName() {
return parFileOptionName;
}
public void setParFileOptionName(String parFileOptionName) {
this.parFileOptionName = parFileOptionName;
}
public OCSSW getOcssw() {
return ocssw;
}
public void setOcssw(OCSSW ocssw) {
this.ocssw = ocssw;
}
private static class Extractor_Processor extends ProcessorModel {
Extractor_Processor(String programName, String xmlFileName, OCSSW ocssw) {
super(programName, xmlFileName, ocssw);
}
@Override
public boolean updateIFileInfo(String ifileName) {
File ifile = new File(ifileName);
inputFileInfo = new FileInfo(ifile.getParent(), ifile.getName(), ocssw);
if (inputFileInfo.getTypeId() == FileTypeInfo.Id.UNKNOWN) {
}
selectExtractorProgram();
isIfileValid = false;
if (programName != null && verifyIFilePath(ifileName)) {
//ocssw.setIfileName(ifileName);
String ofileName = new File(ifileName).getParent() + File.separator + getOcssw().getOfileName(ifileName);
//SeadasLogger.getLogger().info("ofile name from finding next level name: " + ofileName);
if (ofileName != null) {
//programName = getOcssw().getProgramName();
setParamList(ParamUtils.computeParamList(getOcssw().getXmlFileName()));
isIfileValid = true;
updateParamInfo(getPrimaryInputFileOptionName(), ifileName + "\n");
//updateGeoFileInfo(ifileName, inputFileInfo);
updateOFileInfo(getOFileFullPath(ofileName));
updateParamValues(new File(ifileName));
}
} else {
isIfileValid = false;
updateParamInfo(getPrimaryOutputFileOptionName(), "" + "\n");
removePropertyChangeListeners(getPrimaryInputFileOptionName());
Answer answer = Dialogs.requestDecision(programName, "Cannot compute output file name. Would you like to continue anyway?", true, null);
switch (answer) {
case CANCELLED:
updateParamInfo(getPrimaryInputFileOptionName(), "" + "\n");
break;
}
}
return isIfileValid;
}
void selectExtractorProgram() {
String missionName = inputFileInfo.getMissionName();
String fileType = inputFileInfo.getFileTypeName();
String xmlFileName = ocssw.getXmlFileName();
if (missionName != null && fileType != null) {
if (missionName.indexOf("MODIS") != -1 && fileType.indexOf("1A") != -1) {
programName = L1AEXTRACT_MODIS;
xmlFileName = L1AEXTRACT_MODIS_XML_FILE;
} else if (missionName.indexOf("SeaWiFS") != -1 && fileType.indexOf("1A") != -1 || missionName.indexOf("CZCS") != -1) {
programName = L1AEXTRACT_SEAWIFS;
xmlFileName = L1AEXTRACT_SEAWIFS_XML_FILE;
} else if ((missionName.indexOf("VIIRS") != -1
|| missionName.indexOf("VIIRSJ1") != -1
|| missionName.indexOf("VIIRSJ2") != -1)
&& fileType.indexOf("1A") != -1) {
programName = L1AEXTRACT_VIIRS;
xmlFileName = L1AEXTRACT_VIIRS_XML_FILE;
} else if ((fileType.indexOf("L2") != -1 || fileType.indexOf("Level 2") != -1) ||
(missionName.indexOf("OCTS") != -1 && (fileType.indexOf("L1") != -1 || fileType.indexOf("Level 1") != -1))) {
programName = L2EXTRACT;
xmlFileName = L2EXTRACT_XML_FILE;
}
}
setProgramName(programName);
ocssw.setProgramName(programName);
ocssw.setXmlFileName(xmlFileName);
setPrimaryOptions(ParamUtils.getPrimaryOptions(xmlFileName));
}
}
private static class Modis_L1B_Processor extends ProcessorModel {
Modis_L1B_Processor(String programName, String xmlFileName, OCSSW ocssw) {
super(programName, xmlFileName, ocssw);
}
public boolean updateOFileInfo(String ofileName) {
updateParamInfo("--okm", ofileName.replaceAll("LAC", "LAC"));
getParamInfo("--okm").setDefaultValue(getParamValue("--okm"));
updateParamInfo("--hkm", ofileName.replaceAll("_MODIS.", "_MODIS_HKM."));
getParamInfo("--hkm").setDefaultValue(getParamValue("--hkm"));
updateParamInfo("--qkm", ofileName.replaceAll("_MODIS.", "_MODIS_QKM."));
getParamInfo("--qkm").setDefaultValue(getParamValue("--qkm"));
updateParamInfo("--obc", ofileName.replaceAll("_MODIS.", "_MODIS_OBC."));
getParamInfo("--obc").setDefaultValue(getParamValue("--obc"));
setReadyToRun(ofileName.trim().length() == 0 ? false : true);
return true;
}
public String getOfileName() {
StringBuilder ofileNameList = new StringBuilder();
if (!(getParamInfo("--del-okm").getValue().equals("true") || getParamInfo("--del-okm").getValue().equals("1"))) {
ofileNameList.append("\n" + getParamValue("--okm"));
}
if (!(getParamInfo("--del-hkm").getValue().equals("true") || getParamInfo("--del-hkm").getValue().equals("1"))) {
ofileNameList.append("\n" + getParamValue("--hkm"));
}
if (!(getParamInfo("--del-qkm").getValue().equals("true") || getParamInfo("--del-qkm").getValue().equals("1"))) {
ofileNameList.append("\n" + getParamValue("--qkm"));
}
if (getParamInfo("--keep-obc").getValue().equals("true") || getParamInfo("--keep-obc").getValue().equals("1")) {
ofileNameList.append("\n" + getParamValue("--obc"));
}
return ofileNameList.toString();
}
}
private static class LonLat2Pixels_Processor extends ProcessorModel {
static final String _SWlon = "SWlon";
static final String _SWlat = "SWlat";
static final String _NElon = "NElon";
static final String _NElat = "NElat";
public static String LON_LAT_2_PIXEL_PROGRAM_NAME = "lonlat2pixel";
LonLat2Pixels_Processor(String programName, String xmlFileName, OCSSW ocssw) {
super(programName, xmlFileName, ocssw);
addPropertyChangeListener("ifile", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
checkCompleteness();
}
});
addPropertyChangeListener(_SWlon, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
checkCompleteness();
}
});
addPropertyChangeListener(_SWlat, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
checkCompleteness();
}
});
addPropertyChangeListener(_NElon, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
checkCompleteness();
}
});
addPropertyChangeListener(_NElat, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
checkCompleteness();
}
});
}
@Override
public void checkCompleteness() {
String valueOfSWlon = getParamList().getInfo(_SWlon).getValue();
String valueOfSWlat = getParamList().getInfo(_SWlat).getValue();
String valueOfNElon = getParamList().getInfo(_NElon).getValue();
String valueOfNElat = getParamList().getInfo(_NElat).getValue();
if ((valueOfSWlon != null && valueOfSWlon.trim().length() > 0)
&& (valueOfSWlat != null && valueOfSWlat.trim().length() > 0)
&& (valueOfNElon != null && valueOfNElon.trim().length() > 0)
&& (valueOfNElat != null && valueOfNElat.trim().length() > 0)) {
HashMap<String, String> lonlats = ocssw.computePixelsFromLonLat(this);
if (lonlats != null) {
updateParamInfo(START_PIXEL_PARAM_NAME, lonlats.get(START_PIXEL_PARAM_NAME));
updateParamInfo(END_PIXEL_PARAM_NAME, lonlats.get(END_PIXEL_PARAM_NAME));
updateParamInfo(START_LINE_PARAM_NAME, lonlats.get(START_LINE_PARAM_NAME));
updateParamInfo(END_LINE_PARAM_NAME, lonlats.get(END_LINE_PARAM_NAME));
fireEvent(getAllparamInitializedPropertyName(), false, true);
}
}
}
public void updateParamInfo(String paramName, String newValue) {
ParamInfo option = getParamInfo(paramName);
if (option != null) {
option.setValue(newValue);
}
}
public boolean updateIFileInfo(String ifileName) {
updateParamInfo(getPrimaryInputFileOptionName(), ifileName);
ocssw.setIfileName(ifileName);
return true;
}
}
private static class L2Bin_Processor extends ProcessorModel {
private static final String DEFAULT_PAR_FILE_NAME = "l2bin_defaults.par";
private static final String PAR_FILE_PREFIX = "l2bin_defaults_";
String DEFAULT_FLAGUSE;
File missionDir;
FileInfo ifileInfo;
L2Bin_Processor(String programName, String xmlFileName, OCSSW ocssw) {
super(programName, xmlFileName, ocssw);
setProdPramName("l3bprod");
setMultipleInputFiles(true);
missionDir = null;
}
@Override
public void updateParamValues(Product selectedProduct) {
if (selectedProduct != null) {
String sampleFileName = selectedProduct.getFileLocation().getAbsolutePath();
ifileInfo = new FileInfo(sampleFileName);
if (ifileInfo.getMissionId().equals(MissionInfo.Id.UNKNOWN)) {
try (BufferedReader br = new BufferedReader(new FileReader(sampleFileName))) {
String listedFileName;
while ((listedFileName = br.readLine()) != null) {
ifileInfo = new FileInfo(listedFileName);
if (!ifileInfo.getMissionId().equals(MissionInfo.Id.UNKNOWN)) {
break;
}
}
} catch (Exception e) {
}
}
missionDir = ifileInfo.getMissionDirectory();
if (missionDir == null) {
try {
LineNumberReader reader = new LineNumberReader(new FileReader(new File(selectedProduct.getFileLocation().getAbsolutePath())));
sampleFileName = reader.readLine();
missionDir = new FileInfo(sampleFileName).getMissionDirectory();
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
}
}
DEFAULT_FLAGUSE = SeadasFileUtils.getKeyValueFromParFile(new File(missionDir, DEFAULT_PAR_FILE_NAME), "flaguse");
updateSuite();
super.updateParamValues(new File(sampleFileName));
}
}
private void updateSuite() {
String[] suites;
HashMap<String, Boolean> missionSuites;
if (OCSSWInfo.getInstance().getOcsswLocation().equals(OCSSWInfo.OCSSW_LOCATION_LOCAL)) {
suites = missionDir.list(new FilenameFilter() {
@Override
public boolean accept(File file, String s) {
return s.contains("l2bin_defaults_");
}
});
} else {
OCSSWClient ocsswClient = new OCSSWClient();
WebTarget target = ocsswClient.getOcsswWebTarget();
missionSuites = target.path("ocssw").path("l2bin_suites").path(ifileInfo.getMissionName()).request(MediaType.APPLICATION_JSON)
.get(new GenericType<HashMap<String, Boolean>>() {
});
int i = 0;
suites = new String[missionSuites.size()];
for (Map.Entry<String, Boolean> entry : missionSuites.entrySet()) {
String missionName = entry.getKey();
Boolean missionStatus = entry.getValue();
if (missionStatus) {
suites[i++] = missionName;
}
}
}
String suiteName;
ArrayList<ParamValidValueInfo> suiteValidValues = new ArrayList<ParamValidValueInfo>();
for (String fileName : suites) {
suiteName = fileName.substring(fileName.indexOf("_", fileName.indexOf("_") + 1) + 1, fileName.indexOf("."));
suiteValidValues.add(new ParamValidValueInfo(suiteName));
}
ArrayList<ParamValidValueInfo> oldValidValues = (ArrayList<ParamValidValueInfo>) getParamInfo("suite").getValidValueInfos().clone();
getParamInfo("suite").setValidValueInfos(suiteValidValues);
fireEvent("suite", oldValidValues, suiteValidValues);
updateFlagUse(DEFAULT_PAR_FILE_NAME);
}
@Override
public void updateParamInfo(ParamInfo currentOption, String newValue) {
if (currentOption.getName().equals("suite")) {
updateFlagUse(PAR_FILE_PREFIX + newValue + ".par");
}
super.updateParamInfo(currentOption, newValue);
}
private void updateFlagUse(String parFileName) {
String currentFlagUse = SeadasFileUtils.getKeyValueFromParFile(new File(missionDir, parFileName), "flaguse");
if (currentFlagUse == null) {
currentFlagUse = DEFAULT_FLAGUSE;
}
if (currentFlagUse != null) {
ArrayList<ParamValidValueInfo> validValues = getParamInfo("flaguse").getValidValueInfos();
for (ParamValidValueInfo paramValidValueInfo : validValues) {
if (currentFlagUse.contains(paramValidValueInfo.getValue().trim())) {
paramValidValueInfo.setSelected(true);
} else {
paramValidValueInfo.setSelected(false);
}
}
super.updateParamInfo("flaguse", currentFlagUse);
fireEvent("flaguse", null, currentFlagUse);
}
}
}
private static class L2BinAquarius_Processor extends ProcessorModel {
L2BinAquarius_Processor(String programName, String xmlFileName, OCSSW ocssw) {
super(programName, xmlFileName, ocssw);
setMultipleInputFiles(true);
}
}
private static class L3Bin_Processor extends ProcessorModel {
L3Bin_Processor(String programName, String xmlFileName, OCSSW ocssw) {
super(programName, xmlFileName, ocssw);
setMultipleInputFiles(true);
addPropertyChangeListener("prod", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
String oldProdValue = (String) propertyChangeEvent.getOldValue();
String newProdValue = (String) propertyChangeEvent.getNewValue();
String ofileName = getParamValue(getPrimaryOutputFileOptionName());
if (oldProdValue.trim().length() > 0 && ofileName.indexOf(oldProdValue) != -1) {
ofileName = ofileName.replaceAll(oldProdValue, newProdValue);
} else {
ofileName = ofileName + "_" + newProdValue;
}
updateOFileInfo(ofileName);
}
});
}
}
private static class L3BinDump_Processor extends ProcessorModel {
L3BinDump_Processor(String programName, String xmlFileName, OCSSW ocssw) {
super(programName, xmlFileName, ocssw);
}
@Override
public boolean updateIFileInfo(String ifileName) {
File ifile = new File(ifileName);
inputFileInfo = new FileInfo(ifile.getParent(), ifile.getName(), ocssw);
if (inputFileInfo.isTypeId(FileTypeInfo.Id.L3BIN)) {
isIfileValid = true;
updateParamInfo(getPrimaryInputFileOptionName(), ifileName + "\n");
updateParamValues(new File(ifileName));
} else {
isIfileValid = false;
removePropertyChangeListeners(getPrimaryInputFileOptionName());
}
setReadyToRun(isIfileValid);
return isIfileValid;
}
}
private static class SMIGEN_Processor extends ProcessorModel {
SMIGEN_Processor(final String programName, String xmlFileName, OCSSW ocssw) {
super(programName, xmlFileName, ocssw);
setOpenInSeadas(true);
addPropertyChangeListener("prod", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
String ifileName = getParamValue(getPrimaryInputFileOptionName());
if (ifileName != null) {
String oldProdValue = (String) propertyChangeEvent.getOldValue();
String newProdValue = (String) propertyChangeEvent.getNewValue();
String[] additionalOptions = {"--suite=" + newProdValue, "--resolution=" + getParamValue("resolution")};
//String ofileName = SeadasFileUtils.findNextLevelFileName(getParamValue(getPrimaryInputFileOptionName()), programName, additionalOptions);
String ofileName = ocssw.getOfileName(ifileName, additionalOptions);
updateOFileInfo(ofileName);
}
}
});
addPropertyChangeListener("resolution", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
String ifileName = getParamValue(getPrimaryInputFileOptionName());
String oldResolutionValue = (String) propertyChangeEvent.getOldValue();
String newResolutionValue = (String) propertyChangeEvent.getNewValue();
String suite = getParamValue("prod");
if (suite == null || suite.trim().length() == 0) {
suite = "all";
}
String[] additionalOptions = {"--resolution=" + newResolutionValue, "--suite=" + suite};
//String ofileName = SeadasFileUtils.findNextLevelFileName(getParamValue(getPrimaryInputFileOptionName()), programName, additionalOptions);
String ofileName = ocssw.getOfileName(ifileName, additionalOptions);
updateOFileInfo(ofileName);
}
});
}
}
private static class L3MAPGEN_Processor extends ProcessorModel {
L3MAPGEN_Processor(final String programName, String xmlFileName, OCSSW ocssw) {
super(programName, xmlFileName, ocssw);
setOpenInSeadas(true);
addPropertyChangeListener("product", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
String ifileName = getParamValue(getPrimaryInputFileOptionName());
if (ifileName != null) {
String oldProdValue = (String) propertyChangeEvent.getOldValue();
String newProdValue = (String) propertyChangeEvent.getNewValue();
String[] additionalOptions = {"--suite=" + newProdValue, "--resolution=" + getParamValue("resolution"), "--oformat=" + getParamValue("oformat")};
String ofileName = ocssw.getOfileName(ifileName, additionalOptions);
//String ofileName = SeadasFileUtils.findNextLevelFileName(getParamValue(getPrimaryInputFileOptionName()), programName, additionalOptions);
updateOFileInfo(ofileName);
}
}
});
addPropertyChangeListener("resolution", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
String ifileName = getParamValue(getPrimaryInputFileOptionName());
String oldResolutionValue = (String) propertyChangeEvent.getOldValue();
String newResolutionValue = (String) propertyChangeEvent.getNewValue();
String suite = getParamValue("product");
if (suite == null || suite.trim().length() == 0) {
suite = "all";
}
String[] additionalOptions = {"--resolution=" + newResolutionValue, "--suite=" + suite, "--oformat=" + getParamValue("oformat")};
//String ofileName = SeadasFileUtils.findNextLevelFileName(getParamValue(getPrimaryInputFileOptionName()), programName, additionalOptions);
String ofileName = ocssw.getOfileName(ifileName, additionalOptions);
updateOFileInfo(ofileName);
}
});
addPropertyChangeListener("oformat", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
String ifileName = getParamValue(getPrimaryInputFileOptionName());
String oldFormatValue = (String) propertyChangeEvent.getOldValue();
String newFormatValue = (String) propertyChangeEvent.getNewValue();
String suite = getParamValue("product");
if (suite == null || suite.trim().length() == 0) {
suite = "all";
}
String[] additionalOptions = {"--resolution=" + getParamValue("resolution"), "--suite=" + suite, "--oformat=" + newFormatValue};
//String ofileName = SeadasFileUtils.findNextLevelFileName(getParamValue(getPrimaryInputFileOptionName()), programName, additionalOptions);
String ofileName = ocssw.getOfileName(ifileName, additionalOptions);
updateOFileInfo(ofileName);
}
});
}
}
private static class MAPGEN_Processor extends ProcessorModel {
MAPGEN_Processor(final String programName, String xmlFileName, OCSSW ocssw) {
super(programName, xmlFileName, ocssw);
setOpenInSeadas(false);
addPropertyChangeListener("product", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
String ifileName = getParamValue(getPrimaryInputFileOptionName());
if (ifileName != null) {
String oldProdValue = (String) propertyChangeEvent.getOldValue();
String newProdValue = (String) propertyChangeEvent.getNewValue();
String[] additionalOptions = {"--suite=" + newProdValue, "--resolution=" + getParamValue("resolution"), "--oformat=" + getParamValue("oformat")};
String ofileName = ocssw.getOfileName(ifileName, additionalOptions);
//String ofileName = SeadasFileUtils.findNextLevelFileName(getParamValue(getPrimaryInputFileOptionName()), programName, additionalOptions);
updateOFileInfo(ofileName);
}
}
});
addPropertyChangeListener("resolution", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
String ifileName = getParamValue(getPrimaryInputFileOptionName());
String oldResolutionValue = (String) propertyChangeEvent.getOldValue();
String newResolutionValue = (String) propertyChangeEvent.getNewValue();
String suite = getParamValue("product");
if (suite == null || suite.trim().length() == 0) {
suite = "all";
}
String[] additionalOptions = {"--resolution=" + newResolutionValue, "--suite=" + suite, "--oformat=" + getParamValue("oformat")};
//String ofileName = SeadasFileUtils.findNextLevelFileName(getParamValue(getPrimaryInputFileOptionName()), programName, additionalOptions);
String ofileName = ocssw.getOfileName(ifileName, additionalOptions);
updateOFileInfo(ofileName);
}
});
addPropertyChangeListener("oformat", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
String ifileName = getParamValue(getPrimaryInputFileOptionName());
String oldFormatValue = (String) propertyChangeEvent.getOldValue();
String newFormatValue = (String) propertyChangeEvent.getNewValue();
String suite = getParamValue("product");
if (suite == null || suite.trim().length() == 0) {
suite = "all";
}
String[] additionalOptions = {"--resolution=" + getParamValue("resolution"), "--suite=" + suite, "--oformat=" + newFormatValue};
//String ofileName = SeadasFileUtils.findNextLevelFileName(getParamValue(getPrimaryInputFileOptionName()), programName, additionalOptions);
String ofileName = ocssw.getOfileName(ifileName, additionalOptions);
updateOFileInfo(ofileName);
}
});
}
}
private static class OCSSWInstaller_Processor extends ProcessorModel {
ArrayList<String> validOcsswTags = new ArrayList<>();
OCSSWInstaller_Processor(String programName, String xmlFileName, OCSSW ocssw) {
super(programName, xmlFileName, ocssw);
updateTags();
getValidOCSSWTags4SeaDASVersion();
}
@Override
void setCommandArrayPrefix() {
cmdArrayPrefix = new String[2];
cmdArrayPrefix[0] = ocssw.TMP_OCSSW_BOOTSTRAP;
getCmdArrayPrefix()[1] = ocssw.TMP_OCSSW_INSTALLER;
}
private void updateTags() {
validOcsswTags = ocssw.getOcsswTags();
ListIterator<String> listIterator = validOcsswTags.listIterator();
ParamValidValueInfo paramValidValueInfo;
ArrayList<ParamValidValueInfo> tagValidValues = new ArrayList<>();
String vTagPatternString = "^V\\d\\d\\d\\d.\\d+$";
Pattern vTagPattern = Pattern.compile(vTagPatternString);
String rTagPatternString = "^R\\d\\d\\d\\d.\\d+$";
Pattern rTagPattern = Pattern.compile(rTagPatternString);
String tTagPatternString = "^T\\d\\d\\d\\d.\\d+$";
Pattern tTagPattern = Pattern.compile(tTagPatternString);
while (listIterator.hasNext()) {
paramValidValueInfo = new ParamValidValueInfo(listIterator.next());
boolean addTag = false;
// Special case where unexpected low number of tags so likely hard-coded defaults have been used so show all regardless if T-tag or R-Tag
if (tagValidValues.size() <= 3) {
addTag = true;
}
if (paramValidValueInfo != null && paramValidValueInfo.getValue() != null) {
String currTag = paramValidValueInfo.getValue().trim();
if (!includeOfficialReleaseTagsOnly()) {
addTag = true;
}
if (!addTag) {
Matcher vMatcher = vTagPattern.matcher(currTag);
if (vMatcher != null && vMatcher.find()) {
addTag = true;
}
}
if (!addTag) {
Matcher rMatcher = rTagPattern.matcher(currTag);
if (rMatcher != null && rMatcher.find()) {
addTag = true;
}
}
if (addTag) {
tagValidValues.add(paramValidValueInfo);
}
}
}
paramList.getInfo(VALID_TAGS_OPTION_NAME).setValidValueInfos(tagValidValues);
//System.out.println(paramList.getInfo(TAG_OPTION_NAME).getName());
}
private boolean includeOfficialReleaseTagsOnly() {
return OCSSW_InstallerController.getPreferenceUseReleaseTagsOnly();
}
/**
* This method scans for valid OCSSW tags at https://oceandata.sci.gsfc.nasa.gov/manifest/tags, returns a list of tags that start with capital letter "V"
*
* @return List of valid OCSSW tags for SeaDAS
*/
public ArrayList<String> getValidOcsswTagsFromURL() {
ArrayList<String> validOcsswTags = new ArrayList<>();
try {
URL tagsURL = new URL("https://oceandata.sci.gsfc.nasa.gov/manifest/tags/");
URLConnection tagsConnection = tagsURL.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(tagsConnection.getInputStream()));
String inputLine, tagName;
String tokenString = "href=";
int sp, ep;
while ((inputLine = in.readLine()) != null) {
if (inputLine.indexOf(tokenString) != -1) {
sp = inputLine.indexOf(">");
ep = inputLine.lastIndexOf("<");
tagName = inputLine.substring(sp + 1, ep - 1);
//System.out.println("tag: " + tagName);
if (tagName.startsWith("V") ||
tagName.startsWith("R") ||
tagName.startsWith("T")) {
validOcsswTags.add(tagName);
}
}
}
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return validOcsswTags;
}
public void getValidOCSSWTags4SeaDASVersion() {
//JSON parser object to parse read file
JSONParser jsonParser = new JSONParser();
try {
URL tagsURL = new URL("https://oceandata.sci.gsfc.nasa.gov/manifest/seadasVersions.json");
URLConnection tagsConnection = tagsURL.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(tagsConnection.getInputStream()));
//Read JSON file
Object obj = jsonParser.parse(in);
JSONArray validSeaDASTags = (JSONArray) obj;
//System.out.println(validSeaDASTags);
//Iterate over seadas tag array
validSeaDASTags.forEach(tagObject -> parseValidSeaDASTagObject((JSONObject) tagObject));
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
private static void parseValidSeaDASTagObject(JSONObject tagObject) {
Version currentVersion = VersionChecker.getInstance().getLocalVersion();
String seadasVersionString = currentVersion.toString();
//Get seadas version
String seadasVersion = (String) tagObject.get("seadas");
//Get corresponding ocssw tags for seadas
JSONArray ocsswTags = (JSONArray) tagObject.get("ocssw");
//System.out.println(ocsswTags);
}
/**
* /tmp/install_ocssw --tag $TAGNAME -i ocssw-new --seadas --modist $MISSIONNAME
*
* @return
*/
@Override
public String[] getCmdArraySuffix() {
String[] cmdArraySuffix = new String[2];
cmdArraySuffix[0] = "--tag=" + paramList.getInfo(VALID_TAGS_OPTION_NAME).getValue();
cmdArraySuffix[1] = "--seadas";
return cmdArraySuffix;
}
@Override
public ParamList getParamList() {
ParamInfo paramInfo;
paramInfo = new ParamInfo(("--tag"), paramList.getInfo(VALID_TAGS_OPTION_NAME).getValue(), ParamInfo.Type.STRING);
paramInfo.setUsedAs(ParamInfo.USED_IN_COMMAND_AS_OPTION);
paramList.addInfo(paramInfo);
paramInfo = new ParamInfo(("--seadas"), "true", ParamInfo.Type.FLAGS);
paramInfo.setUsedAs(ParamInfo.USED_IN_COMMAND_AS_FLAG);
paramList.addInfo(paramInfo);
return paramList;
}
}
}
| 61,356 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
RemoteProcessObserver.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/RemoteProcessObserver.java | package gov.nasa.gsfc.seadas.processing.core;
import com.bc.ceres.core.ProgressMonitor;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWClient;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo;
import javax.ws.rs.client.WebTarget;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWRemote.PROCESS_STATUS_NONEXIST;
/**
* Created by aabduraz on 9/12/17.
*/
public class RemoteProcessObserver extends ProcessObserver {
OCSSWInfo ocsswInfo;
WebTarget target;
private String jobId;
private boolean serverProcessCompleted;
/**
* Constructor.
*
* @param process The process to be observed
* @param processName A name that represents the process
* @param progressMonitor A progress monitor
*/
public RemoteProcessObserver(Process process, String processName, ProgressMonitor progressMonitor) {
super(process, processName, progressMonitor);
this.ocsswInfo = OCSSWInfo.getInstance();
OCSSWClient ocsswClient = new OCSSWClient(ocsswInfo.getResourceBaseUri());
target = ocsswClient.getOcsswWebTarget();
setProcessExitValue(-1);
serverProcessCompleted = false;
}
/**
* Starts observing the given process. The method blocks until both {@code stdout} and {@code stderr}
* streams are no longer available. If the progress monitor is cancelled, the process will be destroyed.
*/
@Override
public final void startAndWait() {
final Thread stdoutReaderThread = new RemoteProcessObserver.LineReaderThread(STDOUT);
final Thread stderrReaderThread = new RemoteProcessObserver.LineReaderThread(STDERR);
stdoutReaderThread.start();
stderrReaderThread.start();
awaitTermination(stdoutReaderThread, stderrReaderThread);
}
private void awaitTermination(Thread stdoutReaderThread, Thread stderrReaderThread) {
while (stdoutReaderThread.isAlive() && stderrReaderThread.isAlive()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// todo - check what is best done now:
// * 1. just leave, and let the process be unattended (current impl.)
// 2. destroy the process
// 3. throw a checked ProgressObserverException
e.printStackTrace();
return;
}
if (progressMonitor.isCanceled()) {
// todo - check what is best done now:
// 1. just leave, and let the process be unattended
// * 2. destroy the process (current impl.)
// 3. throw a checked ProgressObserverException
process.destroy();
}
}
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public boolean isServerProcessCompleted() {
return serverProcessCompleted;
}
public void setServerProcessCompleted(boolean serverProcessCompleted) {
this.serverProcessCompleted = serverProcessCompleted;
}
/**
* A handler that will be informed if a new line has been read from either {@code stdout} or {@code stderr}.
*/
public static interface Handler {
/**
* Handle the new line that has been read from {@code stdout}.
*
* @param line The line.
* @param process The process.
* @param progressMonitor The progress monitor, that is used to monitor the progress of the running process.
*/
void handleLineOnStdoutRead(String line, Process process, ProgressMonitor progressMonitor);
/**
* Handle the new line that has been read from {@code stderr}.
*
* @param line The line.
* @param process The process.
* @param progressMonitor The progress monitor, that is used to monitor the progress of the running process.
*/
void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor);
}
private class LineReaderThread extends Thread {
private final String type;
public LineReaderThread(String type) {
super(processName + "-" + type);
this.type = type;
}
@Override
public void run() {
try {
read();
} catch (IOException e) {
// cannot be handled
}
}
private void read() throws IOException {
final InputStream inputStream = type.equals("stdout") ? readProcessStream(ocsswInfo.getProcessInputStreamPort()) : readProcessStream(ocsswInfo.getProcessErrorStreamPort());
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
fireLineRead(line);
}
} finally {
reader.close();
}
String processStatus = target.path("ocssw").path("processStatus").path(jobId).request().get(String.class);
setProcessExitValue(new Integer(processStatus).intValue());
}
private InputStream readProcessStream(int portNumber) {
String hostName = "127.0.0.1";
InputStream inputStream = null;
boolean serverProcessStarted = false;
try {
String processStatus = "-100";
while (!serverProcessStarted) {
processStatus = target.path("ocssw").path("processStatus").path(jobId).request().get(String.class);
if ( ! processStatus.equals(PROCESS_STATUS_NONEXIST ) ) {
serverProcessStarted = true;
}
}
Socket echoSocket = new Socket(hostName, portNumber);
inputStream = echoSocket.getInputStream();
} catch (UnknownHostException e) {
System.err.println("Unknown host " + hostName);
e.printStackTrace();
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName + " at port number " + portNumber);
e.printStackTrace();
}
return inputStream;
}
protected void fireLineRead(String line) {
for (ProcessObserver.Handler handler : handlers) {
if (type.equals("stdout")) {
handler.handleLineOnStdoutRead(line, process, progressMonitor);
} else {
handler.handleLineOnStderrRead(line, process, progressMonitor);
}
}
}
}
}
| 7,105 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
L2genProductsParamInfo.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/L2genProductsParamInfo.java | package gov.nasa.gsfc.seadas.processing.core;
import gov.nasa.gsfc.seadas.processing.l2gen.productData.L2genAlgorithmInfo;
import gov.nasa.gsfc.seadas.processing.l2gen.productData.L2genProductCategoryInfo;
import gov.nasa.gsfc.seadas.processing.l2gen.productData.L2genBaseInfo;
import gov.nasa.gsfc.seadas.processing.l2gen.productData.L2genProductInfo;
import java.util.*;
import java.util.HashSet;
import org.esa.snap.core.util.StringUtils;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 4/26/12
* Time: 2:49 PM
* To change this template use File | Settings | File Templates.
*/
public class L2genProductsParamInfo extends ParamInfo {
private ArrayList<L2genProductInfo> productInfos = new ArrayList<L2genProductInfo>();
private ArrayList<L2genProductCategoryInfo> productCategoryInfos = new ArrayList<L2genProductCategoryInfo>();
private ArrayList<L2genProductInfo> integerProductInfos = new ArrayList<L2genProductInfo>();
private HashSet<String> userRemnants = new HashSet<>();
ArrayList<String> integerL2prodList = new ArrayList<String>();
public L2genProductsParamInfo() {
super(L2genData.L2PROD);
setType(Type.STRING);
}
protected void setValue(String value) {
putValueIntoProductInfos(value);
updateValue();
}
protected void updateValue() {
super.setValue(getValueFromProductInfos());
}
private String getValueFromProductInfos() {
ArrayList<String> l2prod = new ArrayList<String>();
for (L2genProductInfo productInfo : productInfos) {
for (L2genBaseInfo aInfo : productInfo.getChildren()) {
L2genAlgorithmInfo algorithmInfo = (L2genAlgorithmInfo) aInfo;
ArrayList<String> l2prodsThisAlgorithm = algorithmInfo.getL2prod();
for (String l2prodThisAlgorithm : l2prodsThisAlgorithm) {
l2prod.add(l2prodThisAlgorithm);
}
}
}
for (String integerL2prod : integerL2prodList) {
l2prod.add(integerL2prod);
}
Collections.sort(l2prod);
for (String remnant: userRemnants) {
l2prod.add(remnant);
}
return StringUtils.join(l2prod, " ");
}
private void putValueIntoProductInfos(String value) {
userRemnants.clear();
if (value == null) {
value = "";
}
// if product changed
if (!value.equals(getValue())) {
HashSet<String> inProducts = new HashSet<String>();
// todo this is the l2prod separators adjustment
if (value.contains(",")) {
value = value.replaceAll(",", " ");
}
// if (value.contains(";")) {
// value = value.replaceAll(";", " ");
// }
//
//
// if (value.contains(":")) {
// value = value.replaceAll(":", " ");
// }
for (String prodEntry : value.split(" ")) {
prodEntry.trim();
inProducts.add(prodEntry);
}
//----------------------------------------------------------------------------------------------------
// For every product in ProductInfoArray set selected to agree with inProducts
//----------------------------------------------------------------------------------------------------
for (L2genProductInfo productInfo : productInfos) {
for (L2genBaseInfo aInfo : productInfo.getChildren()) {
L2genAlgorithmInfo algorithmInfo = (L2genAlgorithmInfo) aInfo;
algorithmInfo.setL2prod(inProducts);
}
}
//todo DAN was here
//----------------------------------------------------------------------------------------------------
// Throw anything valid remaining in the custom integer products
//----------------------------------------------------------------------------------------------------
integerL2prodList.clear();
for (L2genProductInfo productInfo : integerProductInfos) {
for (L2genBaseInfo aInfo : productInfo.getChildren()) {
L2genAlgorithmInfo algorithmInfo = (L2genAlgorithmInfo) aInfo;
String prefix = algorithmInfo.getPrefix();
String suffix = algorithmInfo.getSuffix();
for (String inProduct : inProducts) {
String remnants = inProduct;
if (inProduct.startsWith(prefix)) {
// Strip off prefix
remnants = inProduct.replaceFirst(prefix, "");
if (suffix != null) {
if (inProduct.endsWith(suffix)) {
// Strip off suffix
remnants = remnants.substring(0, (remnants.length() - suffix.length()));
if (isInteger(remnants)) {
integerL2prodList.add(inProduct);
}
}
} else {
if (isInteger(remnants)) {
integerL2prodList.add(inProduct);
}
}
}
}
}
}
userRemnants = inProducts;
}
}
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
protected void addProductInfo(L2genProductInfo productInfo) {
productInfos.add(productInfo);
}
protected void clearProductInfos() {
productInfos.clear();
}
protected void addIntegerProductInfo(L2genProductInfo integerProductInfo) {
integerProductInfos.add(integerProductInfo);
}
protected void clearIntegerProductInfos() {
integerProductInfos.clear();
}
protected void sortProductInfos(Comparator<L2genProductInfo> comparator) {
Collections.sort(productInfos, comparator);
}
protected void resetProductInfos() {
for (L2genProductInfo productInfo : productInfos) {
productInfo.setSelected(false);
for (L2genBaseInfo aInfo : productInfo.getChildren()) {
L2genAlgorithmInfo algorithmInfo = (L2genAlgorithmInfo) aInfo;
algorithmInfo.reset();
}
}
}
protected void setProductCategoryInfos() {
for (L2genProductCategoryInfo productCategoryInfo : productCategoryInfos) {
productCategoryInfo.clearChildren();
}
for (L2genProductCategoryInfo productCategoryInfo : productCategoryInfos) {
for (String categorizedProductName : productCategoryInfo.getProductNames()) {
for (L2genProductInfo productInfo : productInfos) {
if (categorizedProductName.equals(productInfo.getName())) {
productCategoryInfo.addChild(productInfo);
}
}
}
}
for (L2genProductInfo productInfo : productInfos) {
boolean found = false;
for (L2genProductCategoryInfo productCategoryInfo : productCategoryInfos) {
for (String categorizedProductName : productCategoryInfo.getProductNames()) {
if (categorizedProductName.equals(productInfo.getName())) {
found = true;
}
}
}
if (!found) {
for (L2genProductCategoryInfo productCategoryInfo : productCategoryInfos) {
if (productCategoryInfo.isDefaultBucket()) {
productCategoryInfo.addChild(productInfo);
}
}
}
}
}
public ArrayList<L2genProductCategoryInfo> getProductCategoryInfos() {
return productCategoryInfos;
}
protected void addProductCategoryInfo(L2genProductCategoryInfo productCategoryInfo) {
productCategoryInfos.add(productCategoryInfo);
}
protected void clearProductCategoryInfos() {
productCategoryInfos.clear();
}
}
| 8,588 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ProcessorTypeInfo.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/core/ProcessorTypeInfo.java | package gov.nasa.gsfc.seadas.processing.core;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 6/20/12
* Time: 3:13 PM
* To change this template use File | Settings | File Templates.
*/
public class ProcessorTypeInfo {
public static enum ProcessorID {
EXTRACTOR,
MODIS_L1A,
MODIS_GEO,
MIXED_GEO,
GEOLOCATE_VIIRS,
GEOLOCATE_HAWKEYE,
L1BGEN_GENERIC,
MODIS_L1B,
MIXED_L1B,
CALIBRATE_VIIRS,
L1BRSGEN,
L2BRSGEN,
// L1MAPGEN,
// L2MAPGEN,
L2BIN,
L2MERGE,
L3BINMERGE,
GEOREGION_GEN,
// L2BIN_AQUARIUS,
L3BIN,
L3MAPGEN,
MAPGEN,
// SMIGEN,
SMITOPPM,
LONLAT2PIXLINE,
// MULTILEVEL_PROCESSOR_PY,
MULTILEVEL_PROCESSOR,
OCSSW_INSTALLER,
L2GEN,
L3GEN,
// L2GEN_AQUARIUS,
L3BINDUMP,
// OBPG_FILE_TYPE_PY,
OBPG_FILE_TYPE,
GET_OUTPUT_NAME,
// NEXT_LEVEL_NAME_PY,
UPDATE_LUTS,
NOID
}
private static final Map<String, ProcessorID> processorHashMap = new HashMap<String, ProcessorID>() {{
put("l1aextract_modis", ProcessorID.EXTRACTOR);
put("l1aextract_seawifs", ProcessorID.EXTRACTOR);
put("l1aextract_viirs", ProcessorID.EXTRACTOR);
put("l1aextract", ProcessorID.EXTRACTOR);
put("l2extract", ProcessorID.EXTRACTOR);
put("extractor", ProcessorID.EXTRACTOR);
put("modis_L1A", ProcessorID.MODIS_L1A);
put("modis_GEO", ProcessorID.MODIS_GEO);
put("mixed_GEO", ProcessorID.MIXED_GEO);
put("geolocate_viirs", ProcessorID.GEOLOCATE_VIIRS);
put("geolocate_hawkeye", ProcessorID.GEOLOCATE_HAWKEYE);
put("l1bgen_generic", ProcessorID.L1BGEN_GENERIC);
put("modis_L1B", ProcessorID.MODIS_L1B);
put("mixed_L1B", ProcessorID.MIXED_L1B);
put("calibrate_viirs", ProcessorID.CALIBRATE_VIIRS);
put("l1brsgen", ProcessorID.L1BRSGEN);
put("l2brsgen", ProcessorID.L2BRSGEN);
// put("l1mapgen", ProcessorID.L1MAPGEN);
// put("l2mapgen", ProcessorID.L2MAPGEN);
put("l2bin", ProcessorID.L2BIN);
put("l2merge", ProcessorID.L2MERGE);
put("l3binmerge", ProcessorID.L3BINMERGE);
put("georegion_gen", ProcessorID.GEOREGION_GEN);
// put("l2bin_aquarius", ProcessorID.L2BIN_AQUARIUS);
put("l2gen", ProcessorID.L2GEN);
put("l3gen", ProcessorID.L3GEN);
// put("l2gen_aquarius", ProcessorID.L2GEN_AQUARIUS);
put("l3bin", ProcessorID.L3BIN);
put("l3mapgen", ProcessorID.L3MAPGEN);
put("mapgen", ProcessorID.MAPGEN);
// put("smigen", ProcessorID.SMIGEN);
put("smitoppm", ProcessorID.SMITOPPM);
put("lonlat2pixline", ProcessorID.LONLAT2PIXLINE);
// put("multilevel_processor", ProcessorID.MULTILEVEL_PROCESSOR_PY);
put("multilevel_processor", ProcessorID.MULTILEVEL_PROCESSOR);
put("install_ocssw", ProcessorID.OCSSW_INSTALLER);
put("l3bindump", ProcessorID.L3BINDUMP);
put("obpg_file_type", ProcessorID.OBPG_FILE_TYPE);
// put("obpg_file_type", ProcessorID.OBPG_FILE_TYPE_PY);
// put("next_level_name", ProcessorID.NEXT_LEVEL_NAME_PY);
put("get_output_name", ProcessorID.GET_OUTPUT_NAME);
put("update_luts", ProcessorID.UPDATE_LUTS);
}};
public static String getExcludedProcessorNames() {
return "multilevel_processor" +
"smitoppm" +
"l1aextract_modis" +
"l1aextract_seawifs" +
"l2extract" +
"get_output_name" +
"next_level_name" +
"obpg_file_type"+
"lonlat2pixline";
}
public static Set<String> getProcessorNames() {
return processorHashMap.keySet();
}
public static ProcessorID getProcessorID(String processorName) {
return processorHashMap.get(processorName);
}
}
| 4,145 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MultlevelProcessorForm.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/processor/MultlevelProcessorForm.java | /*
Author: Danny Knowles
Don Shea
*/
package gov.nasa.gsfc.seadas.processing.processor;
import com.bc.ceres.swing.selection.SelectionChangeEvent;
import com.bc.ceres.swing.selection.SelectionChangeListener;
import gov.nasa.gsfc.seadas.processing.common.*;
import gov.nasa.gsfc.seadas.processing.core.MultiParamList;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import gov.nasa.gsfc.seadas.processing.core.ParamList;
import gov.nasa.gsfc.seadas.processing.core.ProcessorModel;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.AppContext;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import static gov.nasa.gsfc.seadas.processing.common.FileSelector.PROPERTY_KEY_APP_LAST_OPEN_DIR;
public class MultlevelProcessorForm extends JPanel implements CloProgramUI {
public enum Processor {
MAIN("main"),
MODIS_L1A("modis_L1A"),
// L1AEXTRACT_MODIS("l1aextract_modis"),
// L1AEXTRACT_SEAWIFS("l1aextract_seawifs"),
// L1AEXTRACT_VIIRS("l1aextract_viirs"),
EXTRACTOR("l1aextract"),
// L1MAPGEN("l1mapgen"),
// GEO("geo"),
GEOLOCATE_HAWKEYE("geolocate_hawkeye"),
GEOLOCATE_VIIRS("geolocate_viirs"),
MODIS_GEO("modis_GEO"),
MIXED_GEO("mixed_GEO"),
MODIS_L1B("modis_L1B"),
MIXED_L1B("mixed_L1B"),
CALIBRATE_VIIRS("calibrate_viirs"),
// LEVEL_1B("level 1b"),
L1BGEN("l1bgen_generic"),
L1BRSGEN("l1brsgen"),
L2GEN("l2gen"),
L2EXTRACT("l2extract"),
L2BRSGEN("l2brsgen"),
// L2MAPGEN("l2mapgen"),
L2BIN("l2bin"),
// L3BIN("l3bin"),
// SMIGEN("smigen"),
L3MAPGEN("l3mapgen");
private Processor(String name) {
this.name = name;
}
private final String name;
public String toString() {
return name;
}
}
/*
MultlevelProcessorForm
tabbedPane
mainPanel
primaryIOPanel
sourceProductFileSelector (ifile)
parfilePanel
importPanel
importParfileButton
retainParfileCheckbox
exportParfileButton
parfileScrollPane
parfileTextArea
chainScrollPane
chainPanel
nameLabel
keepLabel
paramsLabel
configLabel
progRowPanel
*/
private AppContext appContext;
private JFileChooser jFileChooser;
private final JTabbedPane tabbedPane;
private JPanel mainPanel;
private JPanel primaryPanel;
private JPanel primaryIOPanel;
private JPanel primaryOptionPanel;
private SeadasFileSelector sourceProductFileSelector;
private JScrollPane parfileScrollPane;
private JPanel parfilePanel;
private JPanel importPanel;
private JButton importParfileButton;
private JCheckBox retainIFileCheckbox;
private JCheckBox overwriteCheckBox;
private JCheckBox use_existingCheckBox;
private JCheckBox deletefilesCheckBox;
private JCheckBox use_ancillaryCheckBox;
private JCheckBox combine_filesCheckBox;
private JButton exportParfileButton;
private JTextArea parfileTextArea;
private FileSelector odirSelectorOld;
private ActiveFileSelector odirSelector;
private JScrollPane chainScrollPane;
private JPanel chainPanel;
private JLabel nameLabel;
private JLabel plusLabel;
private JLabel paramsLabel;
private JLabel odirLabel;
private JPanel spacer;
public String MAIN_PARSTRING_EVENT = "MAIN_PARSTRING_EVENT";
static public String ODIR_EVENT = "ODIR";
static public final String IFILE = "ifile";
public String missionName;
public FileInfoFinder fileInfoFinder;
private ArrayList<MultilevelProcessorRow> rows;
String xmlFileName;
ProcessorModel processorModel;
private SwingPropertyChangeSupport propertyChangeSupport;
private boolean checkboxControlHandlerEnabled = true;
boolean displayDisabledProcessors = true; // todo maybe add as a preferences
OCSSW ocssw;
MultlevelProcessorForm(AppContext appContext, String xmlFileName, OCSSW ocssw) {
this.appContext = appContext;
this.xmlFileName = xmlFileName;
this.ocssw = ocssw;
propertyChangeSupport = new SwingPropertyChangeSupport(this);
jFileChooser = new JFileChooser();
// create main panel
sourceProductFileSelector = new SeadasFileSelector(SnapApp.getDefault().getAppContext(), IFILE, true);
sourceProductFileSelector.getFileNameLabel().setToolTipText("Selects the input file");
sourceProductFileSelector.initProducts();
//sourceProductFileSelector.setProductNameLabel(new JLabel(IFILE));
sourceProductFileSelector.getFileNameComboBox().setPrototypeDisplayValue(
"123456789 123456789 123456789 123456789 123456789 ");
sourceProductFileSelector.addSelectionChangeListener(new SelectionChangeListener() {
@Override
public void selectionChanged(SelectionChangeEvent selectionChangeEvent) {
handleIFileChanged();
}
@Override
public void selectionContextChanged(SelectionChangeEvent selectionChangeEvent) {
//To change body of implemented methods use File | Settings | File Templates.
}
});
odirSelector = new ActiveFileSelector(propertyChangeSupport, ODIR_EVENT, "odir", ParamInfo.Type.DIR);
odirSelector.getFileSelector().getNameLabel().setToolTipText("Selects the output directory");
// odirSelector = new FileSelector(VisatApp.getApp(), ParamInfo.Type.DIR, "odir");
//
// odirSelector.addPropertyChangeListener(new PropertyChangeListener() {
// @Override
// public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
// handleOdirChanged();
// }
// });
odirSelector.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
handleOdirChanged();
}
});
overwriteCheckBox = new JCheckBox("overwrite");
overwriteCheckBox.setToolTipText("Overwrite existing intermediate and output files");
overwriteCheckBox.setSelected(false);
overwriteCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (checkboxControlHandlerEnabled) {
setCheckboxControlHandlerEnabled(false);
handleOverwriteCheckBox();
setCheckboxControlHandlerEnabled(true);
}
}
});
use_existingCheckBox = new JCheckBox("use_existing");
use_existingCheckBox.setToolTipText("Do not re-create intermediate files if they already exist");
use_existingCheckBox.setSelected(false);
use_existingCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (checkboxControlHandlerEnabled) {
setCheckboxControlHandlerEnabled(false);
handleUse_existingCheckBox();
setCheckboxControlHandlerEnabled(true);
}
}
});
deletefilesCheckBox = new JCheckBox("deletefiles");
deletefilesCheckBox.setToolTipText("Delete intermediate files");
deletefilesCheckBox.setSelected(false);
deletefilesCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (checkboxControlHandlerEnabled) {
setCheckboxControlHandlerEnabled(false);
handleDeletefilesCheckBox();
setCheckboxControlHandlerEnabled(true);
}
}
});
use_ancillaryCheckBox = new JCheckBox("use_ancillary");
use_ancillaryCheckBox.setToolTipText("Get the ancillary data for l2gen processing");
use_ancillaryCheckBox.setSelected(false);
use_ancillaryCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (checkboxControlHandlerEnabled) {
setCheckboxControlHandlerEnabled(false);
handleUse_ancillaryCheckBox();
setCheckboxControlHandlerEnabled(true);
}
}
});
combine_filesCheckBox = new JCheckBox("combine_files");
combine_filesCheckBox.setToolTipText("Combine files for l2bin");
combine_filesCheckBox.setSelected(true);
combine_filesCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (checkboxControlHandlerEnabled) {
setCheckboxControlHandlerEnabled(false);
handleCombine_filesCheckBox();
setCheckboxControlHandlerEnabled(true);
}
}
});
primaryIOPanel = new JPanel(new GridBagLayout());
primaryIOPanel.setBorder(BorderFactory.createTitledBorder("Primary I/O Files"));
primaryIOPanel.add(sourceProductFileSelector.createDefaultPanel(),
new GridBagConstraintsCustom(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
primaryIOPanel.add(odirSelector.getJPanel(),
new GridBagConstraintsCustom(0, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
primaryOptionPanel = new JPanel(new GridBagLayout());
primaryOptionPanel.setBorder(BorderFactory.createTitledBorder("Main Options"));
primaryOptionPanel.add(overwriteCheckBox,
new GridBagConstraintsCustom(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
primaryOptionPanel.add(use_existingCheckBox,
new GridBagConstraintsCustom(1, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
primaryOptionPanel.add(deletefilesCheckBox,
new GridBagConstraintsCustom(2, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
primaryOptionPanel.add(use_ancillaryCheckBox,
new GridBagConstraintsCustom(3, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
primaryOptionPanel.add(combine_filesCheckBox,
new GridBagConstraintsCustom(4, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
primaryPanel = new JPanel(new GridBagLayout());
primaryPanel.add(primaryIOPanel,
new GridBagConstraintsCustom(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
primaryPanel.add(primaryOptionPanel,
new GridBagConstraintsCustom(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
retainIFileCheckbox = new JCheckBox("Retain Selected IFILE");
retainIFileCheckbox.setToolTipText("When loading a parfile, use the selected ifile instead of the ifile in the parfile");
importParfileButton = new JButton("Load Parameters");
importParfileButton.setToolTipText("Selects a parfile to load");
importParfileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String contents = SeadasGuiUtils.importFile(jFileChooser);
if (contents != null) {
File defaultIFileDirectory = null;
if (jFileChooser.getSelectedFile() != null) {
defaultIFileDirectory = jFileChooser.getSelectedFile().getParentFile();
}
for (MultilevelProcessorRow row2 : rows) { //clear out the paramList
if (!row2.getName().equals(Processor.MAIN.toString())) {
if (!row2.getParamList().getParamArray().isEmpty()) {
row2.setParamString("plusToChain=0", retainIFileCheckbox.isSelected());
row2.getParamList().clear();
// row2.setParamValue(MultilevelProcessorRow.PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
};
}
}
setParamString(contents, retainIFileCheckbox.isSelected(), defaultIFileDirectory);
}
}
});
importPanel = new JPanel(new GridBagLayout());
importPanel.setBorder(BorderFactory.createEtchedBorder());
importPanel.add(importParfileButton,
new GridBagConstraintsCustom(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
importPanel.add(retainIFileCheckbox,
new GridBagConstraintsCustom(1, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
exportParfileButton = new JButton("Save Parameters");
exportParfileButton.setToolTipText("Write the current parfile to a file");
exportParfileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String contents = getParamString();
SeadasGuiUtils.exportFile(jFileChooser, contents + "\n");
}
});
parfileTextArea = new JTextArea();
parfileTextArea.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void focusLost(FocusEvent e) {
handleParamStringChange();
}
});
parfileScrollPane = new JScrollPane(parfileTextArea);
parfileScrollPane.setBorder(null);
parfilePanel = new JPanel(new GridBagLayout());
parfilePanel.setBorder(BorderFactory.createTitledBorder("Parfile"));
parfilePanel.add(importPanel,
new GridBagConstraintsCustom(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
parfilePanel.add(exportParfileButton,
new GridBagConstraintsCustom(1, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
parfilePanel.add(parfileScrollPane,
new GridBagConstraintsCustom(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, 0, 2));
mainPanel = new JPanel(new GridBagLayout());
mainPanel.add(primaryPanel,
new GridBagConstraintsCustom(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
mainPanel.add(parfilePanel,
new GridBagConstraintsCustom(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH));
// create chain panel
nameLabel = new JLabel("Processor");
Font font = nameLabel.getFont().deriveFont(Font.BOLD);
nameLabel.setFont(font);
plusLabel = new JLabel("+");
plusLabel.setToolTipText("Add the processor to the chain");
plusLabel.setFont(font);
paramsLabel = new JLabel("Parameters");
paramsLabel.setFont(font);
paramsLabel.setToolTipText("Parameters for the processor");
odirLabel = new JLabel("Odir");
odirLabel.setFont(font);
spacer = new JPanel();
chainPanel = new JPanel(new GridBagLayout());
chainPanel.add(nameLabel,
new GridBagConstraintsCustom(0, 0, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 2, 2, -8)));
chainPanel.add(plusLabel,
new GridBagConstraintsCustom(1, 0, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, -8, 2, -8)));
chainPanel.add(paramsLabel,
new GridBagConstraintsCustom(2, 0, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, -8, 2, 2)));
chainPanel.add(odirLabel,
new GridBagConstraintsCustom(3, 0, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, -8, 2, 2)));
createRows();
int rowNum = 1;
for (MultilevelProcessorRow row : rows) {
if (!row.getName().equals(Processor.MAIN.toString())) {
row.attachComponents(chainPanel, rowNum);
rowNum++;
}
}
setRowVisible(Processor.MODIS_L1A.toString(), false);
setRowVisible(Processor.GEOLOCATE_VIIRS.toString(), false);
setRowVisible(Processor.GEOLOCATE_HAWKEYE.toString(), false);
setRowVisible(Processor.MODIS_GEO.toString(), false);
setRowVisible(Processor.MIXED_GEO.toString(), false);
setRowVisible(Processor.CALIBRATE_VIIRS.toString(), false);
setRowVisible(Processor.MODIS_L1B.toString(), false);
setRowVisible(Processor.MIXED_L1B.toString(), false);
setRowVisible(Processor.L1BGEN.toString(), false);
chainPanel.add(spacer,
new GridBagConstraintsCustom(0, rowNum, 0, 1, GridBagConstraints.WEST, GridBagConstraints.VERTICAL));
chainScrollPane = new JScrollPane(chainPanel);
chainScrollPane.setBorder(null);
tabbedPane = new JTabbedPane();
tabbedPane.add("Main", mainPanel);
tabbedPane.add("Processor Chain", chainScrollPane);
// add the tabbed pane
setLayout(new GridBagLayout());
add(tabbedPane, new GridBagConstraintsCustom(0, 0, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH));
// setMinimumSize(getPreferredSize());
// setMaximumSize(new Dimension(2000,2000));
}
void createRows() {
Processor[] rowNames = {
Processor.MAIN,
Processor.MODIS_L1A,
// Processor.GEO,
Processor.MODIS_GEO,
Processor.GEOLOCATE_HAWKEYE,
Processor.GEOLOCATE_VIIRS,
Processor.MIXED_GEO,
Processor.EXTRACTOR,
// Processor.L1AEXTRACT_MODIS,
// Processor.L1AEXTRACT_SEAWIFS,
// Processor.L1AEXTRACT_VIIRS,
// Processor.L1MAPGEN,
// Processor.LEVEL_1B,
Processor.MODIS_L1B,
Processor.CALIBRATE_VIIRS,
Processor.L1BGEN,
Processor.MIXED_L1B,
Processor.L1BRSGEN,
Processor.L2GEN,
Processor.L2EXTRACT,
Processor.L2BRSGEN,
// Processor.L2MAPGEN,
Processor.L2BIN,
// Processor.L3BIN,
// Processor.SMIGEN,
Processor.L3MAPGEN
};
rows = new ArrayList<MultilevelProcessorRow>();
for (Processor processor : rowNames) {
MultilevelProcessorRow row = new MultilevelProcessorRow(processor.toString(), this, ocssw);
row.addPropertyChangeListener(MultilevelProcessorRow.PARAM_STRING_EVENT, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateParamString();
}
});
rows.add(row);
}
}
public AppContext getAppContext() {
return appContext;
}
@Override
public JPanel getParamPanel() {
return this;
}
public ParamList getFinalParamList() {
MultiParamList paramList = new MultiParamList();
for (MultilevelProcessorRow row : rows) {
String name = row.getName();
ParamList list = (ParamList) row.getParamList().clone();
list.removeInfo(MultilevelProcessorRow.PLUS_PARAM);
if ((name.equals(Processor.MODIS_L1B.toString()) ||
name.equals(Processor.CALIBRATE_VIIRS.toString()) ||
name.equals(Processor.L1BGEN.toString()) ||
name.equals(Processor.MIXED_L1B.toString())) &&
!list.getParamArray().isEmpty()) {
name = "level 1b";
}
if ((name.equals(Processor.MODIS_GEO.toString()) ||
name.equals(Processor.GEOLOCATE_HAWKEYE.toString()) ||
name.equals(Processor.MIXED_GEO.toString()) ||
name.equals(Processor.GEOLOCATE_VIIRS.toString())) &&
!list.getParamArray().isEmpty()) {
name = "geo";
}
paramList.addParamList(name, list);
// paramList.addParamList(name, row.getParamList());
}
return paramList;
}
public ParamList getParamList() {
MultiParamList paramList = new MultiParamList();
for (MultilevelProcessorRow row : rows) {
String name = row.getName();
if (!row.getParamList().getParamArray().isEmpty()){
if (name.equals(Processor.MODIS_L1B.toString()) && missionName != null) {
if (missionName.contains("MODIS")) {
name = "level 1b";
}
} else if (name.equals(Processor.MIXED_L1B.toString())) {
if (missionName.contains("mixed") && missionName != null) {
name = "level 1b";
}
} else if (name.equals(Processor.CALIBRATE_VIIRS.toString()) && missionName != null) {
if (missionName.contains("VIIRS")) {
name = "level 1b";
}
} else if (name.equals(Processor.L1BGEN.toString()) && missionName != null) {
if (!missionName.contains("MODIS") && !missionName.contains("VIIRS")) {
name = "level 1b";
}
} else if (name.equals(Processor.MODIS_GEO.toString()) && missionName != null) {
if (missionName.contains("MODIS")) {
name = "geo";
}
} else if (name.equals(Processor.MIXED_GEO.toString()) && missionName != null) {
if (missionName.contains("mixed")) {
name = "geo";
}
} else if (name.equals(Processor.GEOLOCATE_HAWKEYE.toString()) && missionName != null) {
if (missionName.contains("HAWKEYE")) {
name = "geo";
}
} else if (name.equals(Processor.GEOLOCATE_VIIRS.toString()) && missionName != null) {
if (missionName.contains("VIIRS")) {
name = "geo";
}
}
}
paramList.addParamList(name, row.getParamList());
}
return paramList;
}
@Override
public ProcessorModel getProcessorModel() {
if (processorModel == null) {
processorModel = new MultilevelProcessorModel("multilevel_processor", xmlFileName, ocssw);
processorModel.setReadyToRun(true);
}
processorModel.setParamList(getFinalParamList());
return processorModel;
}
@Override
public File getSelectedSourceProduct() {
if (getSourceProductFileSelector() != null) {
return getSourceProductFileSelector().getSelectedFile();
}
return null;
}
@Override
public boolean isOpenOutputInApp() {
return false;
}
public SeadasFileSelector getSourceProductFileSelector() {
return sourceProductFileSelector;
}
public void prepareShow() {
if (getSourceProductFileSelector() != null) {
getSourceProductFileSelector().initProducts();
}
}
public void prepareHide() {
if (getSourceProductFileSelector() != null) {
getSourceProductFileSelector().releaseFiles();
}
}
private MultilevelProcessorRow getRow(String name) {
for (MultilevelProcessorRow row : rows) {
if (row.getName().equals(name)) {
return row;
} else {
if (name.equals("level 1b")) {
if (row.getName().equals(Processor.MODIS_L1B.toString())) {
if (missionName != null && missionName.contains("MODIS")) {
return row;
}
}
if (row.getName().equals(Processor.MIXED_L1B.toString())) {
if (missionName != null && missionName.contains("mixed")) {
return row;
}
}
if (row.getName().equals(Processor.CALIBRATE_VIIRS.toString())) {
if (missionName != null && missionName.contains("VIIRS")) {
return row;
}
}
if (row.getName().equals(Processor.L1BGEN.toString())) {
if (missionName != null &&
!missionName.contains("MODIS") &&
!missionName.contains("mixed") &&
!missionName.contains("VIIRS") &&
!missionName.contains("unknown")) {
return row;
}
}
}
if (name.equals("geo")) {
if (row.getName().equals(Processor.MODIS_GEO.toString())) {
if (missionName != null && missionName.contains("MODIS")) {
return row;
}
}
if (row.getName().equals(Processor.MIXED_GEO.toString())) {
if (missionName != null && missionName.contains("mixed")) {
return row;
}
}
if (row.getName().equals(Processor.GEOLOCATE_HAWKEYE.toString())) {
if (missionName != null && missionName.contains("HAWKEYE")) {
return row;
}
}
if (row.getName().equals(Processor.GEOLOCATE_VIIRS.toString())) {
if (missionName != null && missionName.contains("VIIRS")) {
return row;
}
}
}
}
}
return null;
}
public String getParamString() {
String paramString = getParamList().getParamString("\n");
// This rigged up thingy adds in some comments
String[] lines = paramString.split("\n");
StringBuilder stringBuilder = new StringBuilder();
for (String line : lines) {
line = line.trim();
if (!line.contains(MultilevelProcessorRow.PLUS_PARAM)) {
stringBuilder.append(line).append("\n");
}
if (line.toLowerCase().startsWith(IFILE)) {
String iFilename = line.substring(IFILE.length() + 1, line.length()).trim();
File iFile = new File(iFilename);
if (!iFile.exists()) {
stringBuilder.append("## WARNING: ifile '").append(iFilename).append("' does not exist").append("\n");
}
}
}
return stringBuilder.toString();
}
public void setParamString(String str) {
setParamString(str, false, null);
}
public void setParamString(String str, boolean retainIFile, File defaultIFileDirectory) {
String oldODir = getRow(Processor.MAIN.toString()).getParamList().getValue(MultilevelProcessorRow.ODIR_PARAM);
String[] lines = str.split("\n");
String section = Processor.MAIN.toString();
StringBuilder stringBuilder = new StringBuilder();
for (String line : lines) {
line = line.trim();
// get rid of comment lines
if (line.length() > 0 && line.charAt(0) != '#') {
// locate new section line
if (line.charAt(0) == '[' && line.contains("]")) {
// determine next section
int endIndex = line.indexOf(']');
String nextSection = line.substring(1, endIndex).trim();
if (nextSection.length() > 0) {
// set the params for this section
MultilevelProcessorRow row = getRow(section);
if (stringBuilder.length() > 0) {
if (row != null) {
if (!row.getName().equals(Processor.MAIN.toString())) {
row.setParamString("plusToChain=1", retainIFile);
}
row.setParamString(stringBuilder.toString(), retainIFile);
}
if (row.getName().equals(Processor.MAIN.toString())) {
if (row.getParamList().getValue("overwrite").equals(ParamInfo.BOOLEAN_TRUE)) {
overwriteCheckBox.setSelected(true);
} else {
overwriteCheckBox.setSelected(false);
}
if (row.getParamList().getValue("use_existing").equals(ParamInfo.BOOLEAN_TRUE)) {
use_existingCheckBox.setSelected(true);
} else {
use_existingCheckBox.setSelected(false);
}
if (row.getParamList().getValue("deletefiles").equals(ParamInfo.BOOLEAN_TRUE)) {
deletefilesCheckBox.setSelected(true);
} else {
deletefilesCheckBox.setSelected(false);
}
if (row.getParamList().getValue("use_ancillary").equals(ParamInfo.BOOLEAN_TRUE)) {
use_ancillaryCheckBox.setSelected(true);
} else {
use_ancillaryCheckBox.setSelected(false);
}
if (row.getParamList().getValue("combine_files").equals(ParamInfo.BOOLEAN_TRUE)) {
combine_filesCheckBox.setSelected(true);
} else {
combine_filesCheckBox.setSelected(false);
}
}
stringBuilder.setLength(0);
} else if (!nextSection.equals(Processor.MAIN.toString())){
if (row != null) {
row.setParamString("plusToChain=1", retainIFile);
}
}
section = nextSection;
}
// line = line.substring(1).trim();
// String[] words = line.split("\\s+", 2);
// section = words[0];
// int i = section.indexOf(']');
// if (i != -1) {
// section = section.substring(0, i).trim();
// }
} else {
if (line.toLowerCase().startsWith(IFILE)) {
String originalIFilename = line.substring(IFILE.length() + 1, line.length()).trim();
File originalIFile = new File(originalIFilename);
String absoluteIFilename;
if (originalIFile.isAbsolute()) {
absoluteIFilename = originalIFilename;
} else {
File absoluteFile = new File(defaultIFileDirectory, originalIFilename);
absoluteIFilename = absoluteFile.getAbsolutePath();
}
findMissionName(absoluteIFilename);
stringBuilder.append(IFILE).append("=").append(absoluteIFilename).append("\n");
} else {
stringBuilder.append(line).append("\n");
}
}
}
}
MultilevelProcessorRow row = getRow(section);
if (row != null) {
row.setParamString("plusToChain=1", retainIFile);
if (stringBuilder.length() > 0) {
row.setParamString(stringBuilder.toString(), retainIFile);
}
// } else {
// row.setParamString("plusToChain=1", retainIFile);
// }
if (row.getName().equals(Processor.MAIN.toString())) {
if (row.getParamList().getValue("overwrite").equals(ParamInfo.BOOLEAN_TRUE)) {
overwriteCheckBox.setSelected(true);
} else {
overwriteCheckBox.setSelected(false);
}
if (row.getParamList().getValue("use_existing").equals(ParamInfo.BOOLEAN_TRUE)) {
use_existingCheckBox.setSelected(true);
} else {
use_existingCheckBox.setSelected(false);
}
if (row.getParamList().getValue("deletefiles").equals(ParamInfo.BOOLEAN_TRUE)) {
deletefilesCheckBox.setSelected(true);
} else {
deletefilesCheckBox.setSelected(false);
}
if (row.getParamList().getValue("use_ancillary").equals(ParamInfo.BOOLEAN_TRUE)) {
use_ancillaryCheckBox.setSelected(true);
} else {
use_ancillaryCheckBox.setSelected(false);
}
if (row.getParamList().getValue("combine_files").equals(ParamInfo.BOOLEAN_TRUE)) {
combine_filesCheckBox.setSelected(true);
} else {
combine_filesCheckBox.setSelected(false);
}
}
}
String newODir = getRow(Processor.MAIN.toString()).getParamList().getValue(MultilevelProcessorRow.ODIR_PARAM);
propertyChangeSupport.firePropertyChange(ODIR_EVENT, oldODir, newODir);
for (MultilevelProcessorRow row2 : rows) {
String name = row2.getName();
if (!row2.getParamList().getParamArray().isEmpty()){
if (name.equals(Processor.MODIS_L1B.toString()) ||
name.equals(Processor.MIXED_L1B.toString()) ||
name.equals(Processor.CALIBRATE_VIIRS.toString()) ||
name.equals(Processor.L1BGEN.toString())) {
if (!str.contains("level 1b")) {
if (row2.getParamList().getValue(MultilevelProcessorRow.PLUS_PARAM).equals(ParamInfo.BOOLEAN_FALSE)) {
row2.deselectPlusCheckBox();
} else {
row2.setParamValue(MultilevelProcessorRow.PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
}
row2.setParamValue(MultilevelProcessorRow.ODIR_PARAM, "");
row2.clearConfigPanel();
}
} else if (name.equals(Processor.MODIS_GEO.toString()) ||
name.equals(Processor.MIXED_GEO.toString()) ||
name.equals(Processor.GEOLOCATE_HAWKEYE.toString()) ||
name.equals(Processor.GEOLOCATE_VIIRS.toString())) {
if (!str.contains("geo")) {
row2.setParamValue(MultilevelProcessorRow.ODIR_PARAM, "");
if (row2.getParamList().getValue(MultilevelProcessorRow.PLUS_PARAM).equals(ParamInfo.BOOLEAN_FALSE)) {
row2.deselectPlusCheckBox();
} else {
row2.setParamValue(MultilevelProcessorRow.PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
}
row2.clearConfigPanel();
}
} else {
if (!str.contains(name)) {
row2.setParamValue(MultilevelProcessorRow.ODIR_PARAM, "");
if (row2.getParamList().getValue(MultilevelProcessorRow.PLUS_PARAM).equals(ParamInfo.BOOLEAN_FALSE)) {
row2.deselectPlusCheckBox();
} else {
row2.setParamValue(MultilevelProcessorRow.PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
}
row2.clearConfigPanel();
}
}
}
}
updateParamString();
}
private void updateParamString() {
ArrayList<File> fileArrayList = new ArrayList<File>();
String fileList = getRow(Processor.MAIN.toString()).getParamList().getValue(IFILE);
String filenameArray[] = fileList.split(",");
for (String filename : filenameArray) {
fileArrayList.add(new File(filename));
}
String oldIfileName = null;
if (sourceProductFileSelector.getSelectedFile() != null) {
oldIfileName = sourceProductFileSelector.getSelectedFile().getAbsolutePath();
}
String newIfileName = getRow(Processor.MAIN.toString()).getParamList().getValue(IFILE);
if (newIfileName != null && !newIfileName.equals(oldIfileName) || oldIfileName != null && !oldIfileName.equals(newIfileName)) {
if (fileArrayList.size() > 1) {
File listFile = setSelectedMultiFileList(fileArrayList);
sourceProductFileSelector.setSelectedFile(listFile);
} else {
File file = new File(getRow(Processor.MAIN.toString()).getParamList().getValue(IFILE));
sourceProductFileSelector.setSelectedFile(file);
}
}
//todo this should not be needed but is needed at the moment because parfileTextArea doesn't trigger event in this case
// String newODir = getRow(Processor.MAIN.toString()).getParamList().getValue("odir");
// propertyChangeSupport.firePropertyChange(ODIR_EVENT, null, newODir);
parfileTextArea.setText(getParamString());
}
public File setSelectedMultiFileList(ArrayList<File> tmpArrayList) {
File[] files = new File[tmpArrayList.size()];
tmpArrayList.toArray(files);
String homeDirPath = SystemUtils.getUserHomeDir().getPath();
String openDir = appContext.getPreferences().getPropertyString(PROPERTY_KEY_APP_LAST_OPEN_DIR,
homeDirPath);
File currentDirectory = new File(openDir);
File fileListFile = new File(currentDirectory, "_inputFiles.lst");
StringBuilder fileNames = new StringBuilder();
for (File file : files) {
fileNames.append(file.getAbsolutePath() + "\n");
}
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(fileListFile);
fileWriter.write(fileNames.toString());
fileWriter.close();
} catch (IOException ioe) {
}
return fileListFile;
}
private void handleParamStringChange() {
String newStr = parfileTextArea.getText();
String oldStr = getParamString();
if (!newStr.equals(oldStr)) {
setParamString(newStr);
}
}
private void handleIFileChanged() {
String ifileName = sourceProductFileSelector.getSelectedFile().getAbsolutePath();
MultilevelProcessorRow row = getRow(Processor.MAIN.toString());
String oldIFile = row.getParamList().getValue(IFILE);
if (!ifileName.equals(oldIFile)) {
findMissionName(ifileName);
row.setParamValue(IFILE, ifileName);
for (MultilevelProcessorRow row2 : rows) { //clear the paramList
if (!row2.getName().equals(Processor.MAIN.toString())) {
if (!row2.getParamList().getParamArray().isEmpty()) {
row2.setParamString("plusToChain=0", retainIFileCheckbox.isSelected());
row2.getParamList().clear();
// row2.setParamValue(MultilevelProcessorRow.PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
};
}
}
if (missionName != null) {
if (missionName.contains("HAWKEYE")) {
MultilevelProcessorRow row_geo_hawkeye = getRow(Processor.GEOLOCATE_HAWKEYE.toString());
row_geo_hawkeye.setParamValue(MultilevelProcessorRow.PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
} else if (missionName.contains("VIIRS")) {
MultilevelProcessorRow row_cal_viirs= getRow(Processor.CALIBRATE_VIIRS.toString());
MultilevelProcessorRow row_geo_viirs = getRow(Processor.GEOLOCATE_VIIRS.toString());
row_cal_viirs.setParamValue(MultilevelProcessorRow.PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
row_geo_viirs.setParamValue(MultilevelProcessorRow.PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
} else if (missionName.contains("MODIS")) {
MultilevelProcessorRow row_modis_geo= getRow(Processor.MODIS_GEO.toString());
MultilevelProcessorRow row_modis_l1b = getRow(Processor.MODIS_L1B.toString());
row_modis_geo.setParamValue(MultilevelProcessorRow.PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
row_modis_l1b.setParamValue(MultilevelProcessorRow.PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
} else if (missionName.contains("mixed")) {
MultilevelProcessorRow row_mixed_geo= getRow(Processor.MIXED_GEO.toString());
MultilevelProcessorRow row_mixed_l1b = getRow(Processor.MIXED_L1B.toString());
row_mixed_geo.setParamValue(MultilevelProcessorRow.PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
row_mixed_l1b.setParamValue(MultilevelProcessorRow.PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
} else if (!missionName.equals("unknown")){
MultilevelProcessorRow row_l1bgen = getRow(Processor.L1BGEN.toString());
row_l1bgen.setParamValue(MultilevelProcessorRow.PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
}
}
parfileTextArea.setText(getParamString());
}
}
private void handleOdirChanged() {
String odirName = odirSelector.getFilename();
MultilevelProcessorRow row = getRow(Processor.MAIN.toString());
String oldOdir = row.getParamList().getValue(MultilevelProcessorRow.ODIR_PARAM);
if (!odirName.equals(oldOdir)) {
row.setParamValue(MultilevelProcessorRow.ODIR_PARAM, odirName);
parfileTextArea.setText(getParamString());
}
}
public String getIFile() {
return getRow(Processor.MAIN.toString()).getParamList().getValue(IFILE);
}
public String getFirstIFile() {
String fileName = getIFile();
if (fileName.contains(",")) {
String[] files = fileName.split(",");
fileName = files[0].trim();
} else if (fileName.contains(" ")) {
String[] files = fileName.trim().split(" ");
fileName = files[0].trim();
}
// todo : need to check for file being a list of files.
return fileName;
}
public void addPropertyChangeListener(String name, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(name, listener);
}
public void removePropertyChangeListener(String name, PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(name, listener);
}
public void setCheckboxControlHandlerEnabled(boolean checkboxControlHandlerEnabled) {
this.checkboxControlHandlerEnabled = checkboxControlHandlerEnabled;
}
private void handleOverwriteCheckBox() {
ParamList paramList = getRow(Processor.MAIN.toString()).getParamList();
String oldParamString = getParamString();
if (overwriteCheckBox.isSelected()) {
paramList.setValue("overwrite", ParamInfo.BOOLEAN_TRUE);
} else {
paramList.setValue("overwrite", ParamInfo.BOOLEAN_FALSE);
}
String str = getParamString();
parfileTextArea.setText(str);
propertyChangeSupport.firePropertyChange("paramString", oldParamString, str);
}
private void handleUse_existingCheckBox() {
ParamList paramList = getRow(Processor.MAIN.toString()).getParamList();
String oldParamString = getParamString();
if (use_existingCheckBox.isSelected()) {
paramList.setValue("use_existing", ParamInfo.BOOLEAN_TRUE);
} else {
paramList.setValue("use_existing", ParamInfo.BOOLEAN_FALSE);
}
String str = getParamString();
parfileTextArea.setText(str);
propertyChangeSupport.firePropertyChange("paramString", oldParamString, str);
}
private void handleDeletefilesCheckBox() {
ParamList paramList = getRow(Processor.MAIN.toString()).getParamList();
String oldParamString = getParamString();
if (deletefilesCheckBox.isSelected()) {
paramList.setValue("deletefiles", ParamInfo.BOOLEAN_TRUE);
} else {
paramList.setValue("deletefiles", ParamInfo.BOOLEAN_FALSE);
}
String str = getParamString();
parfileTextArea.setText(str);
propertyChangeSupport.firePropertyChange("paramString", oldParamString, str);
}
private void handleUse_ancillaryCheckBox() {
ParamList paramList = getRow(Processor.MAIN.toString()).getParamList();
String oldParamString = getParamString();
if (use_ancillaryCheckBox.isSelected()) {
paramList.setValue("use_ancillary", ParamInfo.BOOLEAN_TRUE);
} else {
paramList.setValue("use_ancillary", ParamInfo.BOOLEAN_FALSE);
}
String str = getParamString();
parfileTextArea.setText(str);
propertyChangeSupport.firePropertyChange("paramString", oldParamString, str);
}
private void handleCombine_filesCheckBox() {
ParamList paramList = getRow(Processor.MAIN.toString()).getParamList();
String oldParamString = getParamString();
if (combine_filesCheckBox.isSelected()) {
paramList.setValue("combine_files", ParamInfo.BOOLEAN_TRUE);
} else {
paramList.setValue("combine_files", ParamInfo.BOOLEAN_FALSE);
}
String str = getParamString();
parfileTextArea.setText(str);
propertyChangeSupport.firePropertyChange("paramString", oldParamString, str);
}
private void findMissionName(String fileName) {
fileInfoFinder = new FileInfoFinder(fileName, ocssw);
missionName = fileInfoFinder.getMissionName();
if (missionName != null) {
if (missionName.equals("unknown")) {
if (!SeadasFileUtils.isTextFile(fileName)) { // a single file with unknown mission
SimpleDialogMessage dialog = new SimpleDialogMessage(null, "ERROR!! Ifile contains UNKNOWN mission");
dialog.setVisible(true);
dialog.setEnabled(true);
setProcessorChainFormVisible("unknown");
} else { // a list of files
String instrument = "unknown";
final ArrayList<String> fileList = SeadasGuiUtils.myReadDataFile(fileName);
int nonExistingFileCount = 0;
int fileCount = 0;
int unknownMissionFileCount = 0;
for (String nextFileName : fileList) {
if (nextFileName.length() > 0 && (nextFileName.charAt(0) != '#')) {
if (!nextFileName.contains(File.separator)) {
File iFile = new File(fileName);
String iFilePath = iFile.getParent();
String absoluteFileName = iFilePath + File.separator + nextFileName;
fileInfoFinder = new FileInfoFinder(absoluteFileName, ocssw);
fileCount++;
if (fileInfoFinder.getMissionName() == null) {
nonExistingFileCount++;
continue;
} else if (fileInfoFinder.getMissionName().equals("unknown")) {
unknownMissionFileCount++;
continue;
} else {
missionName = fileInfoFinder.getMissionName();
}
} else {
fileInfoFinder = new FileInfoFinder(nextFileName, ocssw);
fileCount++;
if (fileInfoFinder.getMissionName() == null) {
nonExistingFileCount++;
continue;
} else if (fileInfoFinder.getMissionName().equals("unknown")) {
unknownMissionFileCount++;
continue;
} else {
missionName = fileInfoFinder.getMissionName();
}
}
if (instrument.equals("unknown")) {
if (missionName.contains(" ")) {
instrument = missionName.split(" ")[0];
} else {
instrument = missionName;
}
} else if (!missionName.contains(instrument)) {
missionName = "mixed";
setProcessorChainFormVisible("mixed");
break;
}
}
}
String fileCountStr = String.valueOf(fileCount);
if (nonExistingFileCount == fileCount) {
SimpleDialogMessage dialog = new SimpleDialogMessage(null,
"ERROR!! Mission cannot be determined because no files contained in your ifile list exist\n" +
"\n" + "At least one valid file must exist in order configure this processor.");
dialog.setVisible(true);
dialog.setEnabled(true);
} else if (unknownMissionFileCount == fileCount) {
SimpleDialogMessage dialog = new SimpleDialogMessage(null,
"ERROR!! Mission cannot be determined because all files contained in your ifile list have UNKNOWN mission\n" +
"\n" +
"At least one file must have valid mission in order configure this processor.");
dialog.setVisible(true);
dialog.setEnabled(true);
} else if (nonExistingFileCount > 0) {
String nonExsistingFileCountStr = String.valueOf(nonExistingFileCount);
SimpleDialogMessage dialog = new SimpleDialogMessage(null, "WARNING!! " +
nonExsistingFileCountStr + " out of " + fileCountStr +
" files contained in your ifile list don't exist.");
dialog.setVisible(true);
dialog.setEnabled(true);
} else if (unknownMissionFileCount > 0) {
String unknownMissionFileCountStr = String.valueOf(unknownMissionFileCount);
SimpleDialogMessage dialog = new SimpleDialogMessage(null, "WARNING!! " +
unknownMissionFileCountStr + " out of " + fileCountStr +
" files contained in your ifile list don't have a valid mission.");
dialog.setVisible(true);
dialog.setEnabled(true);
}
if (missionName.equals("unknown")) {
setProcessorChainFormVisible("unknown");
} else {
if (missionName.contains("VIIRS")) {
setProcessorChainFormVisible("VIIRS");
} else if (missionName.contains("MODIS")) {
setProcessorChainFormVisible("MODIS");
} else if (missionName.contains("HAWKEYE")) {
setProcessorChainFormVisible("HAWKEYE");
} else if (!missionName.contains("mixed")) {
setProcessorChainFormVisible("GENERIC");
}
}
}
} else { //file is a single file
if (missionName.contains("VIIRS")) {
setProcessorChainFormVisible("VIIRS");
} else if (missionName.contains("MODIS")) {
setProcessorChainFormVisible("MODIS");
} else if (missionName.contains("HAWKEYE")) {
setProcessorChainFormVisible("HAWKEYE");
} else {
setProcessorChainFormVisible("GENERIC");
}
}
} else {
SimpleDialogMessage dialog = new SimpleDialogMessage(null, "ERROR!! Ifile does not exist");
dialog.setVisible(true);
dialog.setEnabled(true);
setProcessorChainFormVisible("unknown");
}
}
private void setRowVisible(String rowName, Boolean visible) {
if (displayDisabledProcessors) {
if (rowName.contains("mixed_")) {
getRow(rowName).getConfigButton().setVisible(visible);
getRow(rowName).getPlusCheckBox().setVisible(visible);
getRow(rowName).getParamTextField().setVisible(visible);
getRow(rowName).getOdirSelector().setVisible(visible);
} else {
getRow(rowName).getConfigButton().setEnabled(visible);
getRow(rowName).getPlusCheckBox().setEnabled(visible);
getRow(rowName).getParamTextField().setVisible(visible);
getRow(rowName).getOdirSelector().setVisible(visible);
}
}
}
private void setProcessorChainFormVisible(String missionName) {
if (missionName.contains("MODIS")) {
setRowVisible(Processor.MODIS_L1A.toString(), true);
setRowVisible(Processor.GEOLOCATE_VIIRS.toString(), false);
setRowVisible(Processor.GEOLOCATE_HAWKEYE.toString(), false);
setRowVisible(Processor.MODIS_GEO.toString(), true);
setRowVisible(Processor.MIXED_GEO.toString(), false);
setRowVisible(Processor.CALIBRATE_VIIRS.toString(), false);
setRowVisible(Processor.MODIS_L1B.toString(), true);
setRowVisible(Processor.MIXED_L1B.toString(), false);
setRowVisible(Processor.L1BGEN.toString(), false);
} else if (missionName.contains("VIIRS")) {
setRowVisible(Processor.MODIS_L1A.toString(), false);
setRowVisible(Processor.GEOLOCATE_VIIRS.toString(), true);
setRowVisible(Processor.GEOLOCATE_HAWKEYE.toString(), false);
setRowVisible(Processor.MODIS_GEO.toString(), false);
setRowVisible(Processor.MIXED_GEO.toString(), false);
setRowVisible(Processor.CALIBRATE_VIIRS.toString(), true);
setRowVisible(Processor.MODIS_L1B.toString(), false);
setRowVisible(Processor.MIXED_L1B.toString(), false);
setRowVisible(Processor.L1BGEN.toString(), false);
} else if (missionName.contains("HAWKEYE")) {
setRowVisible(Processor.MODIS_L1A.toString(), false);
setRowVisible(Processor.GEOLOCATE_VIIRS.toString(), false);
setRowVisible(Processor.GEOLOCATE_HAWKEYE.toString(), true);
setRowVisible(Processor.MODIS_GEO.toString(), false);
setRowVisible(Processor.MIXED_GEO.toString(), false);
setRowVisible(Processor.CALIBRATE_VIIRS.toString(), false);
setRowVisible(Processor.MODIS_L1B.toString(), false);
setRowVisible(Processor.MIXED_L1B.toString(), false);
setRowVisible(Processor.L1BGEN.toString(), true);
} else if (missionName.contains("mixed")) {
setRowVisible(Processor.MODIS_L1A.toString(), false);
setRowVisible(Processor.GEOLOCATE_VIIRS.toString(), false);
setRowVisible(Processor.GEOLOCATE_HAWKEYE.toString(), false);
setRowVisible(Processor.MODIS_GEO.toString(), false);
setRowVisible(Processor.MIXED_GEO.toString(), true);
setRowVisible(Processor.CALIBRATE_VIIRS.toString(), false);
setRowVisible(Processor.MODIS_L1B.toString(), false);
setRowVisible(Processor.MIXED_L1B.toString(), true);
setRowVisible(Processor.L1BGEN.toString(), false);
} else if (missionName.contains("GENERIC")) {
setRowVisible(Processor.MODIS_L1A.toString(), false);
setRowVisible(Processor.GEOLOCATE_VIIRS.toString(), false);
setRowVisible(Processor.GEOLOCATE_HAWKEYE.toString(), false);
setRowVisible(Processor.MODIS_GEO.toString(), false);
setRowVisible(Processor.MIXED_GEO.toString(), false);
setRowVisible(Processor.CALIBRATE_VIIRS.toString(), false);
setRowVisible(Processor.MODIS_L1B.toString(), false);
setRowVisible(Processor.MIXED_L1B.toString(), false);
setRowVisible(Processor.L1BGEN.toString(), true);
} else if (missionName.equals("unknown")) {
setRowVisible(Processor.MODIS_L1A.toString(), false);
setRowVisible(Processor.GEOLOCATE_VIIRS.toString(), false);
setRowVisible(Processor.GEOLOCATE_HAWKEYE.toString(), false);
setRowVisible(Processor.MODIS_GEO.toString(), false);
setRowVisible(Processor.MIXED_GEO.toString(), false);
setRowVisible(Processor.CALIBRATE_VIIRS.toString(), false);
setRowVisible(Processor.MODIS_L1B.toString(), false);
setRowVisible(Processor.MIXED_L1B.toString(), false);
setRowVisible(Processor.L1BGEN.toString(), false);
}
}
} | 60,467 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ActiveFileSelector.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/processor/ActiveFileSelector.java | package gov.nasa.gsfc.seadas.processing.processor;
import gov.nasa.gsfc.seadas.processing.common.FileSelector;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import org.esa.snap.rcp.SnapApp;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 7/12/13
* Time: 2:52 PM
* To change this template use File | Settings | File Templates.
*/
public class ActiveFileSelector {
private SwingPropertyChangeSupport externalPropertyChangeSupport;
private SwingPropertyChangeSupport thisPropertyChangeSupport;
private FileSelector fileSelector;
private String label;
private ParamInfo.Type type;
private boolean allowReFireOnChange = false;
private String propertyName;
boolean controlHandlerEnabled = true;
ActiveFileSelector(SwingPropertyChangeSupport externalPropertyChangeSupport, final String propertyName, String label, ParamInfo.Type type) {
this.externalPropertyChangeSupport = externalPropertyChangeSupport;
this.propertyName = propertyName;
this.label = label;
this.type = type;
thisPropertyChangeSupport = new SwingPropertyChangeSupport(this);
fileSelector = new FileSelector(SnapApp.getDefault().getAppContext(), type, label);
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
getFileSelector().addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
if (isControlHandlerEnabled()) {
thisPropertyChangeSupport.firePropertyChange(propertyName, null, getFileSelector().getFileName());
}
}
});
}
private void addEventListeners() {
externalPropertyChangeSupport.addPropertyChangeListener(propertyName, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (!allowReFireOnChange) {
disableControlHandler();
}
getFileSelector().setFilename((String) evt.getNewValue());
enableControlHandler();
}
});
}
private boolean isControlHandlerEnabled() {
return controlHandlerEnabled;
}
private void enableControlHandler() {
controlHandlerEnabled = true;
}
private void disableControlHandler() {
controlHandlerEnabled = false;
}
public FileSelector getFileSelector() {
return fileSelector;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
thisPropertyChangeSupport.addPropertyChangeListener(propertyName, listener);
}
public String getFilename() {
return getFileSelector().getFileName();
}
public JPanel getJPanel() {
return getFileSelector().getjPanel();
}
public void setVisible(boolean visible) {
getFileSelector().setVisible(visible);
}
}
| 3,196 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MultilevelProcessorAction.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/processor/MultilevelProcessorAction.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* 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 gov.nasa.gsfc.seadas.processing.processor;
import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction;
import gov.nasa.gsfc.seadas.processing.common.CloProgramUI;
import org.esa.snap.ui.AppContext;
/**
* Geographic collocation action.
*
* @author Ralf Quast
* @version $Revision: 2535 $ $Date: 2008-07-09 14:10:01 +0200 (Mi, 09 Jul 2008) $
*/
public class MultilevelProcessorAction extends CallCloProgramAction {
@Override
public CloProgramUI getProgramUI(AppContext appContext) {
return new MultlevelProcessorForm(appContext, getXmlFileName(), ocssw);
}
}
| 1,325 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MultilevelProcessorRow.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/processor/MultilevelProcessorRow.java | package gov.nasa.gsfc.seadas.processing.processor;
import gov.nasa.gsfc.seadas.processing.common.CloProgramUI;
import gov.nasa.gsfc.seadas.processing.common.GridBagConstraintsCustom;
import gov.nasa.gsfc.seadas.processing.common.ProgramUIFactory;
import gov.nasa.gsfc.seadas.processing.core.L2genData;
import gov.nasa.gsfc.seadas.processing.core.ParamInfo;
import gov.nasa.gsfc.seadas.processing.core.ParamList;
import gov.nasa.gsfc.seadas.processing.l2gen.userInterface.L2genForm;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.UIUtils;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Created with IntelliJ IDEA.
* User: dshea
* Date: 8/21/12
* Time: 8:21 AM
* To change this template use File | Settings | File Templates.
*/
public class MultilevelProcessorRow {
public static final String PARAM_STRING_EVENT = "paramString";
// public static final String KEEPFILES_PARAM = "keepfiles";
public static final String PLUS_PARAM = "plusToChain";
public static final String ODIR_PARAM = "odir";
private static final String LONGEST_BUTTON_LABEL = "multilevel_processor";
private String name;
private CloProgramUI cloProgramUI;
private MultlevelProcessorForm parentForm;
private JButton configButton;
// private JCheckBox keepCheckBox;
private JCheckBox plusCheckBox;
private JTextField paramTextField;
private ActiveFileSelector odirSelector;
private JPanel configPanel;
private ParamList paramList;
private SwingPropertyChangeSupport propertyChangeSupport;
private boolean checkboxControlHandlerEnabled = true;
OCSSW ocssw;
public MultilevelProcessorRow(String name, MultlevelProcessorForm parentForm, OCSSW ocssw) {
this.name = name;
this.parentForm = parentForm;
this.ocssw = ocssw;
propertyChangeSupport = new SwingPropertyChangeSupport(this);
paramList = new ParamList();
configButton = new JButton(LONGEST_BUTTON_LABEL);
configButton.setPreferredSize(configButton.getPreferredSize());
configButton.setText(name);
configButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
handleButtonEvent();
}
});
plusCheckBox = new JCheckBox();
plusCheckBox.setSelected(false);
plusCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (checkboxControlHandlerEnabled) {
setCheckboxControlHandlerEnabled(false);
handleplusCheckBox();
setCheckboxControlHandlerEnabled(true);
}
}
});
paramTextField = new JTextField();
paramTextField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
handleParamTextField();
}
});
paramTextField.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
handleParamTextField();
}
});
odirSelector = new ActiveFileSelector(propertyChangeSupport, "ODIR", "", ParamInfo.Type.DIR);
odirSelector.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
handleOdirChanged();
}
});
// todo made this change to fix problem where l2gen unchecks the box after user checks the box
// essentially now all config user at startup
// if (name.equals(MultlevelProcessorForm.Processor.MAIN.toString()) || name.equals("l2gen")) {
// createConfigPanel();plus
// }
if (name.equals(MultlevelProcessorForm.Processor.MAIN.toString())) {
createConfigPanel();
}
}
public JButton getConfigButton() {
return configButton;
}
public JCheckBox getPlusCheckBox() {
return plusCheckBox;
}
public ActiveFileSelector getOdirSelector() {
return odirSelector;
}
public JTextField getParamTextField() {
return paramTextField;
}
public String getName() {
return name;
}
// this method assumes the the JPanel passed in is using a grid bag layout
public void attachComponents(JPanel base, int row) {
if (name.equals("geolocate_hawkeye") || name.equals("mixed_GEO") || name.equals("mixed_GEO")) {
plusCheckBox.setToolTipText(configButton.getText() + " <html>processor add to the chain <br>(no parameters available for mixed list mode)</html>");
configButton.setToolTipText("No parameters available for " + configButton.getText()+ " in mixed list mode");
} else {
plusCheckBox.setToolTipText(configButton.getText() + " processor add to the chain");
configButton.setToolTipText("Open " + configButton.getText() + " GUI to set params");
}
base.add(configButton,
new GridBagConstraintsCustom(0, row, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 0)));
base.add(plusCheckBox,
new GridBagConstraintsCustom(1, row, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 0, 2, 0)));
base.add(paramTextField,
new GridBagConstraintsCustom(2, row, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 0, 2, 2)));
// if (!name.equals("main")) {
base.add(odirSelector.getJPanel(),
new GridBagConstraintsCustom(3, row, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 0, 2, 2)));
// }
}
private void createConfigPanel() {
createConfigPanel(false);
}
private void createConfigPanel(boolean plusfiles) {
if (configPanel == null) {
if (name.equals(MultlevelProcessorForm.Processor.MAIN.toString())) {
cloProgramUI = new ProgramUIFactory("multilevel_processor", "multilevel_processor.xml", ocssw);
// configPanel = (JPanel) cloProgramUI;
configPanel = cloProgramUI.getParamPanel();
} else if (name.equals("geo")) {
cloProgramUI = new ProgramUIFactory("modis_GEO", "modis_GEO.xml", ocssw);
configPanel = cloProgramUI.getParamPanel();
} else if (name.equals("l2gen")) {
// cloProgramUI = new L2genForm(parentForm.getAppContext(), "l2gen.xml", getTinyIFile(), false, L2genData.Mode.L2GEN, true, true);
cloProgramUI = new L2genForm(parentForm.getAppContext(), "l2gen.xml", null , false, L2genData.Mode.L2GEN, true, true, ocssw);
configPanel = cloProgramUI.getParamPanel();
} else if (name.equals("l2extract")) {
cloProgramUI = new ProgramUIFactory("l2extract", "l1aextract.xml", ocssw);
configPanel = cloProgramUI.getParamPanel();
} else {
String xmlFile = name.replace("", "").concat(".xml");
cloProgramUI = new ProgramUIFactory(name, xmlFile, ocssw);
configPanel = cloProgramUI.getParamPanel();
}
// set parameters to default values
getParamListFromCloProgramUI();
if (plusfiles) {
paramList.setParamString(PLUS_PARAM + "=" + plusfiles);
paramList.setParamString(ODIR_PARAM + "=" + "");
} else {
paramList.setParamString("");
}
paramList.setParamString("");
}
}
public void clearConfigPanel() {
cloProgramUI = null;
configPanel = null;
paramTextField.setText("");
paramList = new ParamList();
}
public void deselectPlusCheckBox() {
plusCheckBox.setSelected(false);
odirSelector.getFileSelector().setFilename("");
paramTextField.setText("");
paramList.clear();
}
private void getParamListFromCloProgramUI() {
paramList = (ParamList) cloProgramUI.getProcessorModel().getParamList().clone();
cleanIOParams(paramList);
if (plusCheckBox.isSelected()) {
paramList.addInfo(new ParamInfo(PLUS_PARAM, ParamInfo.BOOLEAN_TRUE, ParamInfo.Type.BOOLEAN, ParamInfo.BOOLEAN_FALSE));
if (paramList.getInfo(ODIR_PARAM) == null) {
paramList.addInfo(new ParamInfo(ODIR_PARAM, ""));
}
} else {
paramList.addInfo(new ParamInfo(PLUS_PARAM, ParamInfo.BOOLEAN_FALSE, ParamInfo.Type.BOOLEAN, ParamInfo.BOOLEAN_FALSE));
}
}
private void handleplusCheckBox() {
boolean plusSelected = plusCheckBox.isSelected();
boolean test2 = paramList.isValueTrue(PLUS_PARAM);
createConfigPanel(plusCheckBox.isSelected());
if (paramList.getParamArray().isEmpty()) {
getParamListFromCloProgramUI();
paramList.setParamString("");
}
if (plusCheckBox.isSelected() != plusSelected) {
plusCheckBox.setSelected(plusSelected);
}
// test1 = keepCheckBox.isSelected();
// test2 = paramList.isValueTrue(KEEPFILES_PARAM);
if (plusCheckBox.isSelected() != paramList.isValueTrue(PLUS_PARAM)) {
String oldParamString = getParamString();
if (plusCheckBox.isSelected()) {
paramList.setValue(PLUS_PARAM, ParamInfo.BOOLEAN_TRUE);
paramList.setValue(ODIR_PARAM, "");
} else {
paramList.clear();
paramList.addInfo(new ParamInfo(PLUS_PARAM, ParamInfo.BOOLEAN_TRUE, ParamInfo.Type.BOOLEAN, ParamInfo.BOOLEAN_FALSE));
paramList.setValue(PLUS_PARAM, ParamInfo.BOOLEAN_FALSE);
}
updateParamTextField();
updateOdir();
String str = getParamString();
if (!plusCheckBox.isSelected()) {
paramList.clear();
}
propertyChangeSupport.firePropertyChange(PARAM_STRING_EVENT, oldParamString, str);
}
}
private void handleOdirChanged() {
if (paramList.getParamArray().isEmpty()) {
createConfigPanel(true);
paramList.setValue(PLUS_PARAM, ParamInfo.BOOLEAN_TRUE);
}
if (paramList.getInfo(ODIR_PARAM) == null) {
paramList.addInfo(new ParamInfo(ODIR_PARAM, ""));
}
String oldParamString = paramList.getParamString();
String odirName = odirSelector.getFilename();
String oldOdir = paramList.getValue(ODIR_PARAM);
if (odirName != null && !odirName.equals(oldOdir)) {
paramList.setValue(ODIR_PARAM, odirName);
}
updateplusCheckbox();
String str = paramList.getParamString();
propertyChangeSupport.firePropertyChange(PARAM_STRING_EVENT, oldParamString, str);
}
private void handleParamTextField() {
createConfigPanel();
if (paramList.getParamArray().isEmpty()) {
getParamListFromCloProgramUI();
paramList.setParamString("");
}
String oldParamString = getParamString();
String str = paramTextField.getText();
ParamInfo param = paramList.getInfo(PLUS_PARAM);
if (param != null) {
str = str + " " + param.getParamString();
}
paramList.setParamString(str);
str = getParamString();
updateParamTextField();
updateplusCheckbox();
if (!oldParamString.equals(str)) {
propertyChangeSupport.firePropertyChange(PARAM_STRING_EVENT, oldParamString, str);
}
}
private void handleButtonEvent() {
createConfigPanel();
final Window parent = parentForm.getAppContext().getApplicationWindow();
final ModalDialog modalDialog = new ModalDialog(parent, name, configPanel, ModalDialog.ID_OK_CANCEL_HELP, name);
// modalDialog.getButton(ModalDialog.ID_OK).setEnabled(true);
modalDialog.getButton(ModalDialog.ID_OK).setText("Save");
modalDialog.getButton(ModalDialog.ID_HELP).setText("");
modalDialog.getButton(ModalDialog.ID_HELP).setIcon(UIUtils.loadImageIcon("icons/Help24.gif"));
//Make sure program is only executed when the "run" button is clicked.
((JButton) modalDialog.getButton(ModalDialog.ID_OK)).setDefaultCapable(false);
modalDialog.getJDialog().getRootPane().setDefaultButton(null);
// load the UI with the current param values
ParamList list = (ParamList) paramList.clone();
list.removeInfo(PLUS_PARAM);
String paramString_orig = list.getParamString("\n");
if (paramString_orig.contains("=\"")) {
String paramString_trim = paramString_orig.replaceAll("\"", "");
cloProgramUI.setParamString(paramString_trim);
} else {
cloProgramUI.setParamString(paramString_orig);
}
// cloProgramUI.setParamString(list.getParamString("\n"));
String oldUIParamString = cloProgramUI.getParamString();
final int dialogResult = modalDialog.show();
//SeadasLogger.getLogger().info("dialog result: " + dialogResult);
if (dialogResult != ModalDialog.ID_OK) {
return;
}
String str = cloProgramUI.getParamString();
if (!oldUIParamString.equals(str)) {
getParamListFromCloProgramUI();
updateParamList();
propertyChangeSupport.firePropertyChange(PARAM_STRING_EVENT, oldUIParamString, str);
}
}
private void updateplusCheckbox() {
Boolean check = paramList.isValueTrue(PLUS_PARAM) || !paramList.isDefault();
plusCheckBox.setSelected(check);
}
private void updateOdir() {
String str = "";
ParamList list = (ParamList) paramList.clone();
list.removeInfo(PLUS_PARAM);
if (paramList.getInfo(ODIR_PARAM) != null) {
str = paramList.getInfo(ODIR_PARAM).getValue();
}
odirSelector.getFileSelector().setFilename(str);
}
private void updateParamTextField() {
ParamList list = (ParamList) paramList.clone();
list.removeInfo(PLUS_PARAM);
if (!name.equals("main")) {
list.removeInfo(ODIR_PARAM);
}
paramTextField.setText(list.getParamString(" "));
}
private void updateParamList() {
updateOdir();
updateParamTextField();
updateplusCheckbox();
}
public ParamList getParamList() {
return paramList;
}
public String getParamString(String separator) {
return paramList.getParamString(separator);
}
public String getParamString() {
return paramList.getParamString();
}
public void setParamString(String str, boolean retainIFile) {
createConfigPanel();
if (paramList.getParamArray().isEmpty()) {
getParamListFromCloProgramUI();
paramList.setParamString("");
}
if (paramList.getValue(PLUS_PARAM).equals(ParamInfo.BOOLEAN_TRUE)) {
if (paramList.getInfo(ODIR_PARAM) == null) {
paramList.addInfo(new ParamInfo(ODIR_PARAM, ""));
}
}
String oldParamString = getParamString();
paramList.setParamString(str, retainIFile, true);
if (name.equals("main")) {
paramList.setValue(PLUS_PARAM, ParamInfo.BOOLEAN_TRUE);
}
str = getParamString();
if (!oldParamString.equals(str)) {
updateParamList();
propertyChangeSupport.firePropertyChange(PARAM_STRING_EVENT, oldParamString, str);
}
}
public void setParamValue(String name, String str) {
String oldParamString = getParamString();
paramList.setValue(name, str);
str = getParamString();
if (!oldParamString.equals(str)) {
updateParamList();
propertyChangeSupport.firePropertyChange(PARAM_STRING_EVENT, oldParamString, str);
}
}
private void cleanIOParams(ParamList list) {
if (name.equals(MultlevelProcessorForm.Processor.MAIN.toString())) {
return;
}
String[] IOParams = {"ifile", "ofile", "infile", "geofile"};
for (String IOParam : IOParams) {
ParamInfo param = list.getInfo(IOParam);
if (param != null) {
list.setValue(param.getName(), param.getDefaultValue());
}
}
}
public void addPropertyChangeListener(String name, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(name, listener);
}
public void removePropertyChangeListener(String name, PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(name, listener);
}
// private File getTinyIFile() {
// String ifileName = parentForm.getFirstIFile();
// FileInfo fileInfo = null;
// String missionName = (new MissionInfo(MissionInfo.Id.SEAWIFS)).getName();
//
// if (ifileName != null) {
// fileInfo = new FileInfo(ifileName);
// MissionInfo.Id missionId = fileInfo.getMissionId();
// if (missionId == MissionInfo.Id.SEAWIFS ||
// missionId == MissionInfo.Id.MODISA ||
// missionId == MissionInfo.Id.MODIST ||
// missionId == MissionInfo.Id.MERIS ||
// missionId == MissionInfo.Id.CZCS ||
// missionId == MissionInfo.Id.OCTS) {
// missionName = fileInfo.getMissionName();
// }
// }
//
// missionName = missionName.replace(' ', '_');
// String tinyFileName = "tiny_" + missionName;
//
// if (fileInfo != null && fileInfo.isGeofileRequired()) {
// L2genData.installResource(tinyFileName + ".GEO");
// }
//
// return L2genData.installResource(tinyFileName);
// }
public boolean isCheckboxControlHandlerEnabled() {
return checkboxControlHandlerEnabled;
}
public void setCheckboxControlHandlerEnabled(boolean checkboxControlHandlerEnabled) {
this.checkboxControlHandlerEnabled = checkboxControlHandlerEnabled;
}
}
| 18,737 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
MultilevelProcessorModel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/processor/MultilevelProcessorModel.java | package gov.nasa.gsfc.seadas.processing.processor;
import gov.nasa.gsfc.seadas.processing.core.ProcessorModel;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 7/15/13
* Time: 11:16 AM
* To change this template use File | Settings | File Templates.
*/
public class MultilevelProcessorModel extends ProcessorModel {
public MultilevelProcessorModel(String name, String parXMLFileName, OCSSW ocssw) {
super(name, parXMLFileName, ocssw);
}
// public String[] getProgramCmdArray() {
// final String PAR_EQUAL = "par=";
//
// String[] commandArray = super.getProgramCmdArray();
//
// for (int i = 0; i < commandArray.length; i++) {
//
// if (commandArray[i] != null && commandArray[i].startsWith(PAR_EQUAL)) {
// commandArray[i] = commandArray[i].substring(PAR_EQUAL.length());
// }
// }
//
// return commandArray;
// }
}
| 983 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
SeaDASAboutBox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-kit/src/main/java/gov/nasa/gsfc/seadas/about/SeaDASAboutBox.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gov.nasa.gsfc.seadas.about;
import com.bc.ceres.core.runtime.Version;
import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfoGUI;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.rcp.about.AboutBox;
import org.esa.snap.rcp.util.BrowserUtils;
import org.openide.modules.ModuleInfo;
import org.openide.modules.Modules;
import javax.swing.*;
import java.awt.*;
/**
* @author Aynur Abdurazik
* @author Daniel Knowles
*/
@AboutBox(displayName = "SeaDAS-Toolbox", position = 15)
public class SeaDASAboutBox extends JPanel {
private final static String PACKAGE = "SeaDAS-Toolbox";
private final static String RELEASE_NOTES_URL = "https://seadas.gsfc.nasa.gov/release-notes";
private final static String OCEAN_COLOR_WEB_URL = "https://oceancolor.gsfc.nasa.gov/";
private final static String OCEAN_COLOR_WEB_URL_NAME = "NASA Ocean Color Web";
private final static String SEADAS_WEB_URL = "https://seadas.gsfc.nasa.gov/";
private final static String SEADAS_WEB_URL_NAME = "SeaDAS Web";
public SeaDASAboutBox() {
super(new BorderLayout());
ImageIcon aboutImage = new ImageIcon(SeaDASAboutBox.class.getResource("about_seadas.png"));
JLabel banner = new JLabel(aboutImage);
JLabel infoText = new JLabel("<html>"
+ "The <i>SeaDAS-Toolbox</i> contains all the NASA Ocean Biology science processing<br>"
+ "science tools. This tools allow users to process data between the various levels<br>"
+ "(i.e. Level 0 through Level 3). This toolbox also provides additional GUI tools<br> "
+ "related to ocean sciences."
+ "</html>"
);
GridBagConstraints gbc = new GridBagConstraints();
JPanel jPanel = new JPanel(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 1;
gbc.weighty = 0;
gbc.insets.left = 5;
gbc.insets.top = 5;
gbc.gridy = 0;
infoText.setMinimumSize(infoText.getPreferredSize());
jPanel.add(infoText, gbc);
gbc.gridy = 1;
gbc.insets.left = 15;
// jPanel.add(getUrlJLabel(RELEASE_NOTES_URL, RELEASE_NOTES_URL_NAME), gbc);
//
// gbc.gridy = 2;
jPanel.add(getUrlJLabel(SEADAS_WEB_URL, SEADAS_WEB_URL_NAME), gbc);
gbc.gridy = 2;
jPanel.add(getUrlJLabel(OCEAN_COLOR_WEB_URL, OCEAN_COLOR_WEB_URL_NAME), gbc);
gbc.gridy = 3;
jPanel.add(banner, gbc);
gbc.gridy = 4;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
jPanel.add(new JLabel(), gbc);
gbc.gridy = 5;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets.bottom=10;
jPanel.add(createVersionPanel(), gbc);
add(jPanel, BorderLayout.WEST);
ModuleInfo seadasProcessingModuleInfo = Modules.getDefault().ownerOf(OCSSWInfoGUI.class);
// System.out.println("SeaDAS Toolbox Specification Version: " + seadasProcessingModuleInfo.getSpecificationVersion());
// System.out.println("SeaDAS Toolbox Implementation Version: " + seadasProcessingModuleInfo.getImplementationVersion());
}
private JPanel createVersionPanel() {
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
// final ModuleInfo moduleInfo = Modules.getDefault().ownerOf(SeaDASAboutBox.class);
// todo Overrode this because SeaDASAboutBox version not defined in macro
final ModuleInfo moduleInfo = Modules.getDefault().ownerOf(OCSSWInfoGUI.class);
panel.add(new JLabel("<html><b>SeaDAS Toolbox version " + moduleInfo.getSpecificationVersion() + "</b>", SwingConstants.RIGHT));
// Version specVersion = Version.parseVersion(moduleInfo.getSpecificationVersion().toString());
// String versionString = String.format("%s.%s.%s", specVersion.getMajor(), specVersion.getMinor(), specVersion.getMicro());
// String changelogUrl = releaseNotesUrlString + versionString;
final JLabel releaseNoteLabel = new JLabel("<html><a href=\"" + RELEASE_NOTES_URL + "\">Release Notes</a>", SwingConstants.RIGHT);
releaseNoteLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
releaseNoteLabel.addMouseListener(new BrowserUtils.URLClickAdaptor(RELEASE_NOTES_URL));
panel.add(releaseNoteLabel);
return panel;
}
private JLabel getUrlJLabel(String url, String name) {
final JLabel jLabel = new JLabel("<html> " +
"<a href=\"" + url + "\">" + name + "</a></html>");
jLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
jLabel.addMouseListener(new BrowserUtils.URLClickAdaptor(url));
return jLabel;
}
}
| 5,068 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
SeaDASAboutAction.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-kit/src/main/java/gov/nasa/gsfc/seadas/about/SeaDASAboutAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gov.nasa.gsfc.seadas.about;
import org.jfree.ui.about.AboutPanel;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;
import javax.swing.JDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Displays the {@link SeaDASAboutPanel} in a modal dialog.
*
* @author Norman Fomferra
*/
@ActionID(category = "Help", id = "org.esa.snap.rcp.about.SeaDASAboutAction" )
@ActionRegistration(displayName = "#CTL_SeaDASAboutAction_Name" )
@ActionReference(path = "Menu/Help/SeaDAS", position = 1000, separatorBefore = 999)
// position = 1510, separatorBefore = 1500)
@Messages({
"CTL_SeaDASAboutAction_Name=About SeaDAS-Toolbox",
"CTL_SeaDASAboutAction_Title=About SeaDAS-Toolbox",
})
public final class SeaDASAboutAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog(WindowManager.getDefault().getMainWindow(), Bundle.CTL_SeaDASAboutAction_Title(), true);
dialog.setContentPane(new SeaDASAboutPanel());
dialog.pack();
dialog.setLocationRelativeTo(WindowManager.getDefault().getMainWindow());
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
}
| 1,600 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
SeaDASAboutPanel.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-kit/src/main/java/gov/nasa/gsfc/seadas/about/SeaDASAboutPanel.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gov.nasa.gsfc.seadas.about;
import org.esa.snap.rcp.about.SnapAboutBox;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.ImageUtilities;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.awt.Image;
import java.util.Arrays;
import java.util.List;
/**
* The UI component displayed by the {@link SeaDASAboutAction}. Processes {@code AboutBox} file objects generated from
* {@link SeaDASAboutBox} annotations.
*
* @author Norman Fomferra
* @author Marco Peters
*/
class SeaDASAboutPanel extends JPanel {
public SeaDASAboutPanel() {
setLayout(new BorderLayout(8, 8));
setBorder(new EmptyBorder(8, 8, 8, 8));
FileObject configFile = FileUtil.getConfigFile("AboutBox");
if (configFile != null) {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("SeaDAS-Toolbox", new SeaDASAboutBox());
// addAboutBoxPlugins(tabbedPane, configFile);
add(tabbedPane, BorderLayout.CENTER);
} else {
add(new SeaDASAboutBox(), BorderLayout.CENTER);
}
}
private void addAboutBoxPlugins(JTabbedPane tabbedPane, FileObject configFile) {
FileObject aboutBoxPanels[] = configFile.getChildren();
List<FileObject> orderedAboutBoxPanels = FileUtil.getOrder(Arrays.asList(aboutBoxPanels), true);
for (FileObject aboutBoxFileObject : orderedAboutBoxPanels) {
JComponent panel = FileUtil.getConfigObject(aboutBoxFileObject.getPath(), JComponent.class);
if (panel != null) {
String displayName = (String) aboutBoxFileObject.getAttribute("displayName");
if (displayName != null && !displayName.trim().isEmpty()) {
Icon icon = null;
String iconPath = (String) aboutBoxFileObject.getAttribute("iconPath");
if (iconPath != null && !iconPath.trim().isEmpty()) {
Image image = ImageUtilities.loadImage(iconPath, false);
if (image != null) {
icon = new ImageIcon(image);
}
}
tabbedPane.addTab(displayName, icon, panel);
}
}
}
}
}
| 2,672 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ShowImageAnimatorAction.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/action/ShowImageAnimatorAction.java | package gov.nasa.gsfc.seadas.imageanimator.action;
import gov.nasa.gsfc.seadas.imageanimator.ui.ImageAnimatorDialog;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.ui.product.ProductSceneView;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.*;
import org.openide.util.actions.Presenter;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
/**
* @author Aynur Abdurazik
*/
@ActionID(category = "View", id = "ImageAnimatorAction")
@ActionRegistration(displayName = "#CTL_ImageAnimatorActionName")
@ActionReferences({
@ActionReference(path = "Menu/SeaDAS-Toolbox/General Tools", position = 100),
@ActionReference(path = "Menu/View", position = 600),
@ActionReference(path = "Toolbars/SeaDAS Toolbox", position = 100)
})
@NbBundle.Messages({
"CTL_ImageAnimatorActionName=Image Animator",
"CTL_ImageAnimatorActionToolTip=Show/hide Image Animator for the selected images"
})
public class ShowImageAnimatorAction extends AbstractSnapAction implements LookupListener, Presenter.Menu, Presenter.Toolbar {
Product product;
// private boolean enabled = false;
public static String SMALLICON = "gov/nasa/gsfc/seadas/image-animator/ui/icons/ImageAnimatorWhite24.png";
public static String LARGEICON = "gov/nasa/gsfc/seadas/image-animator/ui/icons/ImageAnimatorWhite24.png";
private final Lookup lookup;
private final Lookup.Result<ProductSceneView> viewResult;
public ShowImageAnimatorAction() {
this(null);
}
public ShowImageAnimatorAction(Lookup lookup) {
putValue(ACTION_COMMAND_KEY, getClass().getName());
putValue(SELECTED_KEY, false);
putValue(NAME, Bundle.CTL_ImageAnimatorActionName());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon(SMALLICON, false));
putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon(LARGEICON, false));
putValue(SHORT_DESCRIPTION, Bundle.CTL_ImageAnimatorActionToolTip());
this.lookup = lookup != null ? lookup : Utilities.actionsGlobalContext();
this.viewResult = this.lookup.lookupResult(ProductSceneView.class);
this.viewResult.addLookupListener(WeakListeners.create(LookupListener.class, this, viewResult));
updateEnabledState();
}
@Override
public void actionPerformed(ActionEvent event) {
SnapApp snapApp = SnapApp.getDefault();
product = snapApp.getSelectedProduct(SnapApp.SelectionSourceHint.VIEW);
ProductNodeGroup<Band> products = product.getBandGroup();
SMALLICON = "gov/nasa/gsfc/seadas/image-animator/ui/icons/ImageAnimatorGreen24.png";
LARGEICON = "gov/nasa/gsfc/seadas/image-animator/ui/icons/ImageAnimatorGreen24.png";
putValue(SMALL_ICON, ImageUtilities.loadImageIcon(SMALLICON, false));
putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon(LARGEICON, false));
updateEnabledState();
ImageAnimatorDialog imageAnimatorDialog = new ImageAnimatorDialog(product, getActiveBands(products));
imageAnimatorDialog.setVisible(true);
imageAnimatorDialog.dispose();
SMALLICON = "gov/nasa/gsfc/seadas/image-animator/ui/icons/ImageAnimatorWhite24.png";
LARGEICON = "gov/nasa/gsfc/seadas/image-animator/ui/icons/ImageAnimatorWhite24.png";
putValue(SMALL_ICON, ImageUtilities.loadImageIcon(SMALLICON, false));
putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon(LARGEICON, false));
updateEnabledState();
}
private ArrayList<String> getActiveBands(ProductNodeGroup<Band> products) {
Band[] bands = new Band[products.getNodeCount()];
ArrayList<Band> activeBands = new ArrayList<>();
ArrayList<String> activeBandNames = new ArrayList<>();
products.toArray(bands);
for (Band band : bands) {
if (band.getImageInfo() != null) {
activeBands.add(band);
activeBandNames.add(band.getName());
}
}
return activeBandNames;
}
@Override
public JMenuItem getMenuPresenter() {
JMenuItem menuItem = new JMenuItem(this);
menuItem.setIcon(null);
return menuItem;
}
@Override
public Component getToolbarPresenter() {
JButton button = new JButton(this);
button.setText(null);
button.setIcon(ImageUtilities.loadImageIcon(LARGEICON,false));
return button;
}
@Override
public void resultChanged(LookupEvent ignored) {
updateEnabledState();
}
protected void updateEnabledState() {
final Product selectedProduct = SnapApp.getDefault().getSelectedProduct(SnapApp.SelectionSourceHint.AUTO);
boolean productSelected = selectedProduct != null;
boolean hasBands = false;
// boolean hasGeoCoding = false;
if (productSelected) {
hasBands = selectedProduct.getNumBands() > 0;
// hasGeoCoding = selectedProduct.getSceneGeoCoding() != null;
}
// super.setEnabled(!viewResult.allInstances().isEmpty() && hasBands);
super.setEnabled(hasBands);
}
}
| 5,360 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
JCheckBoxTree.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/ui/JCheckBoxTree.java | package gov.nasa.gsfc.seadas.imageanimator.ui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.EventListener;
import java.util.EventObject;
import java.util.HashMap;
import java.util.HashSet;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.EventListenerList;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeSelectionModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
public class JCheckBoxTree extends JTree {
private static final long serialVersionUID = -4194122328392241790L;
JCheckBoxTree selfPointer = this;
// Defining data structure that will enable to fast check-indicate the state of each node
// It totally replaces the "selection" mechanism of the JTree
private class CheckedNode {
boolean isSelected;
boolean hasChildren;
boolean allChildrenSelected;
public CheckedNode(boolean isSelected_, boolean hasChildren_, boolean allChildrenSelected_) {
isSelected = isSelected_;
hasChildren = hasChildren_;
allChildrenSelected = allChildrenSelected_;
}
}
HashMap<TreePath, CheckedNode> nodesCheckingState;
HashSet<TreePath> checkedPaths = new HashSet<TreePath>();
// Defining a new event type for the checking mechanism and preparing event-handling mechanism
protected EventListenerList listenerList = new EventListenerList();
public class CheckChangeEvent extends EventObject {
private static final long serialVersionUID = -8100230309044193368L;
public CheckChangeEvent(Object source) {
super(source);
}
}
public interface CheckChangeEventListener extends EventListener {
public void checkStateChanged(CheckChangeEvent event);
}
public void addCheckChangeEventListener(CheckChangeEventListener listener) {
listenerList.add(CheckChangeEventListener.class, listener);
}
public void removeCheckChangeEventListener(CheckChangeEventListener listener) {
listenerList.remove(CheckChangeEventListener.class, listener);
}
void fireCheckChangeEvent(CheckChangeEvent evt) {
Object[] listeners = listenerList.getListenerList();
for (int i = 0; i < listeners.length; i++) {
if (listeners[i] == CheckChangeEventListener.class) {
((CheckChangeEventListener) listeners[i + 1]).checkStateChanged(evt);
}
}
}
// Override
public void setModel(TreeModel newModel) {
super.setModel(newModel);
resetCheckingState();
}
// New method that returns only the checked paths (totally ignores original "selection" mechanism)
public TreePath[] getCheckedPaths() {
return checkedPaths.toArray(new TreePath[checkedPaths.size()]);
}
// Returns true in case that the node is selected, has children but not all of them are selected
public boolean isSelectedPartially(TreePath path) {
CheckedNode cn = nodesCheckingState.get(path);
return cn.isSelected && cn.hasChildren && !cn.allChildrenSelected;
}
private void resetCheckingState() {
nodesCheckingState = new HashMap<TreePath, CheckedNode>();
checkedPaths = new HashSet<TreePath>();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)getModel().getRoot();
if (node == null) {
return;
}
addSubtreeToCheckingStateTracking(node);
}
// Creating data structure of the current model for the checking mechanism
private void addSubtreeToCheckingStateTracking(DefaultMutableTreeNode node) {
TreeNode[] path = node.getPath();
TreePath tp = new TreePath(path);
CheckedNode cn = new CheckedNode(false, node.getChildCount() > 0, false);
nodesCheckingState.put(tp, cn);
for (int i = 0 ; i < node.getChildCount() ; i++) {
addSubtreeToCheckingStateTracking((DefaultMutableTreeNode) tp.pathByAddingChild(node.getChildAt(i)).getLastPathComponent());
}
}
// Overriding cell renderer by a class that ignores the original "selection" mechanism
// It decides how to show the nodes due to the checking-mechanism
private class CheckBoxCellRenderer extends JPanel implements TreeCellRenderer {
private static final long serialVersionUID = -7341833835878991719L;
JCheckBox checkBox;
public CheckBoxCellRenderer() {
super();
this.setLayout(new BorderLayout());
checkBox = new JCheckBox();
add(checkBox, BorderLayout.CENTER);
setOpaque(false);
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
Object obj = node.getUserObject();
TreePath tp = new TreePath(node.getPath());
CheckedNode cn = nodesCheckingState.get(tp);
if (cn == null) {
return this;
}
checkBox.setSelected(cn.isSelected);
checkBox.setText(obj.toString());
checkBox.setOpaque(cn.isSelected && cn.hasChildren && ! cn.allChildrenSelected);
return this;
}
}
public JCheckBoxTree() {
super();
// Disabling toggling by double-click
this.setToggleClickCount(0);
// Overriding cell renderer by new one defined above
CheckBoxCellRenderer cellRenderer = new CheckBoxCellRenderer();
this.setCellRenderer(cellRenderer);
// Overriding selection model by an empty one
DefaultTreeSelectionModel dtsm = new DefaultTreeSelectionModel() {
private static final long serialVersionUID = -8190634240451667286L;
// Totally disabling the selection mechanism
public void setSelectionPath(TreePath path) {
}
public void addSelectionPath(TreePath path) {
}
public void removeSelectionPath(TreePath path) {
}
public void setSelectionPaths(TreePath[] pPaths) {
}
};
// Calling checking mechanism on mouse click
this.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent arg0) {
TreePath tp = selfPointer.getPathForLocation(arg0.getX(), arg0.getY());
if (tp == null) {
return;
}
boolean checkMode = ! nodesCheckingState.get(tp).isSelected;
checkSubTree(tp, checkMode);
updatePredecessorsWithCheckMode(tp, checkMode);
// Firing the check change event
fireCheckChangeEvent(new CheckChangeEvent(new Object()));
// Repainting tree after the data structures were updated
selfPointer.repaint();
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
}
public void mouseReleased(MouseEvent arg0) {
}
});
this.setSelectionModel(dtsm);
}
// When a node is checked/unchecked, updating the states of the predecessors
protected void updatePredecessorsWithCheckMode(TreePath tp, boolean check) {
TreePath parentPath = tp.getParentPath();
// If it is the root, stop the recursive calls and return
if (parentPath == null) {
return;
}
CheckedNode parentCheckedNode = nodesCheckingState.get(parentPath);
DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) parentPath.getLastPathComponent();
parentCheckedNode.allChildrenSelected = true;
parentCheckedNode.isSelected = false;
for (int i = 0 ; i < parentNode.getChildCount() ; i++) {
TreePath childPath = parentPath.pathByAddingChild(parentNode.getChildAt(i));
CheckedNode childCheckedNode = nodesCheckingState.get(childPath);
// It is enough that even one subtree is not fully selected
// to determine that the parent is not fully selected
if (! childCheckedNode.allChildrenSelected) {
parentCheckedNode.allChildrenSelected = false;
}
// If at least one child is selected, selecting also the parent
if (childCheckedNode.isSelected) {
parentCheckedNode.isSelected = true;
}
}
if (parentCheckedNode.isSelected) {
checkedPaths.add(parentPath);
} else {
checkedPaths.remove(parentPath);
}
// Go to upper predecessor
updatePredecessorsWithCheckMode(parentPath, check);
}
// Recursively checks/unchecks a subtree
protected void checkSubTree(TreePath tp, boolean check) {
CheckedNode cn = nodesCheckingState.get(tp);
cn.isSelected = check;
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp.getLastPathComponent();
for (int i = 0 ; i < node.getChildCount() ; i++) {
checkSubTree(tp.pathByAddingChild(node.getChildAt(i)), check);
}
cn.allChildrenSelected = check;
if (check) {
checkedPaths.add(tp);
} else {
checkedPaths.remove(tp);
}
}
} | 9,838 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
AngularAnimationTopComponent.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/ui/AngularAnimationTopComponent.java | /*
* Copyright (C) 2014 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* 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 gov.nasa.gsfc.seadas.imageanimator.ui;
import com.bc.ceres.glayer.support.ImageLayer;
import com.bc.ceres.glevel.MultiLevelModel;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.image.ImageManager;
import org.esa.snap.core.util.ProductUtils;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.help.HelpAction;
import org.esa.snap.rcp.placemark.PlacemarkUtils;
import org.esa.snap.rcp.statistics.XYPlotMarker;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.rcp.windows.ToolTopComponent;
import org.esa.snap.ui.GridBagUtils;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.product.ProductSceneView;
import org.esa.snap.ui.product.angularview.*;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.jfree.chart.*;
import org.jfree.chart.annotations.XYTitleAnnotation;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.block.LineBorder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.ui.HorizontalAlignment;
import org.jfree.chart.ui.RectangleAnchor;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.data.Range;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.locationtech.jts.geom.Point;
import org.openide.util.HelpCtx;
import javax.media.jai.PlanarImage;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.*;
import static java.lang.Math.abs;
public class AngularAnimationTopComponent extends ToolTopComponent {
// public static final String ID = AngularAnimtaionTopComponent.class.getName();
private static final String SUPPRESS_MESSAGE_KEY = "plugin.spectrum.tip";
private static final String angularAnimationString = "Angular View Animation";
private static final String angularAnimationHelpString = "showAngularViewAnimationWnd";
private final Map<RasterDataNode, DisplayableAngularview[]> rasterToAngularMap;
private final Map<RasterDataNode, List<AngularBand>> rasterToAngularBandsMap;
private final ProductNodeListenerAdapter productNodeHandler;
private final PinSelectionChangeListener pinSelectionChangeListener;
// private final PixelPositionListener pixelPositionListener;
private AbstractButton filterButton;
private AbstractButton showAngularViewsForCursorButton;
private AbstractButton showAngularViewsForSelectedPinsButton;
private AbstractButton showAngularViewsForAllPinsButton;
private AbstractButton showGridButton;
private JRadioButton useSensorZenithButton;
private JRadioButton useSensorAzimuthButton;
private JRadioButton useScatteringAngleButton;
private JRadioButton useViewAngleButton;
private boolean tipShown;
private boolean useViewAngle;
private boolean useSensorZenith;
private boolean useSensorAzimuth;
private boolean useScatteringAngle;
private ProductSceneView currentView;
private Product currentProduct;
private ChartPanel chartPanel;
private ChartHandler chartHandler;
private boolean domainAxisAdjustmentIsFrozen;
private boolean rangeAxisAdjustmentIsFrozen;
private boolean isCodeInducedAxisChange;
private boolean isUserInducedAutomaticAdjustmentChosen;
public List<AngularBand> sensor_azimuth_Bands = new ArrayList<>();
public List<AngularBand> sensor_zenith_Bands = new ArrayList<>();
public List<AngularBand> scattering_angle_Bands = new ArrayList<>();
public AngularAnimationTopComponent() {
productNodeHandler = new ProductNodeHandler();
pinSelectionChangeListener = new PinSelectionChangeListener();
rasterToAngularMap = new HashMap<>();
rasterToAngularBandsMap = new HashMap<>();
// pixelPositionListener = new CursorAngularViewPixelPositionListener((AngularTopComponent)this);
initUI();
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(angularAnimationHelpString);
}
private void setCurrentView(ProductSceneView view) {
ProductSceneView oldView = currentView;
currentView = view;
if (oldView != currentView) {
if (oldView != null) {
oldView.removePropertyChangeListener(ProductSceneView.PROPERTY_NAME_SELECTED_PIN, pinSelectionChangeListener);
}
if (currentView != null) {
currentView.addPropertyChangeListener(ProductSceneView.PROPERTY_NAME_SELECTED_PIN, pinSelectionChangeListener);
setCurrentProduct(currentView.getProduct());
// if (currentProduct.getName().contains("HARP2")) {
// currentProduct.setAutoGrouping("I_*_549:I_*_669:I_*_867:I_*_441:Q_*_549:Q_*_669:Q_*_867:Q_*_441:" +
// "U_*_549:U_*_669:U_*_867:U_*_441:DOLP_*_549:DOLP_*_669:DOLP_*_867:DOLP_*_441:" +
// "I_noise_*_549:I_noise_*_669:I_noise_*_867:I_noise_*_441:Q_noise_*_549:Q_noise_*_669:Q_noise_*_867:Q_noise_*_441:" +
// "U_noise_*_549:U_noise_*_669:U_noise_*_867:U_noise_*_441:DOLP_noise_*_549:DOLP_noise_*_669:DOLP_noise_*_867:DOLP_noise_*_441:" +
// "Sensor_Zenith:Sensor_Azimuth:Solar_Zenith:Solar_Azimuth:obs_per_view:view_time_offsets:" +
// "i:i_*_550:i_*_667:i_*_867:i_*_440:q:q_*_550:q_*_667:q_*_867:q_*_440:" +
// "qc:qc_*_550:qc_*_664:qc_*_867:qc_*_440:u:u_*_550:u_*_664:u_*_867:u_*_440: " +
// "dolp:dolp_*_550:dolp_*_664:dolp_*_867:dolp_*_440:dolp:aolp:aolp_*_550:aolp_*_664:aolp_*_867:aolp_*_440:" +
// "i_variability:i_variability_*_550:i_variability_*_664:i_variability_*_867:i_variability_*_440:" +
// "q_variability:q_variability_*_550:q_variability_*_664:q_variability_*_867:q_variability_*_440:" +
// "u_variability_*_550:u_variability_*_664:u_variability_*_867:u_variability_*_440:" +
// "dolp_variability:dolp_variability_*_550:dolp_variability_*_664:dolp_variability_*_867:dolp_variability_*_440:" +
// "aolp_variability:aolp_variability_*_550:aolp_variability_*_664:aolp_variability_*_867:aolp_variability_*_440:" +
// "sensor_zenith-angle:sensor_azimuth_angle:solar_zenith_angle:solar_azimuth_angle:rotation_angle");
// };
if (currentProduct.getName().contains("SPEX")) {
String autoGroupingStr = "QC:QC_bitwise:QC_polsample_bitwise:QC_polsample:";
for (int wvl = 380; wvl < 390; wvl++) {
autoGroupingStr += "I_*_" + wvl + ":";
}
for (int wvl = 380; wvl < 390; wvl++) {
autoGroupingStr += "i_*_" + wvl + ":";
}
for (int wvl = 380; wvl < 390; wvl++) {
autoGroupingStr += "aolp_*_" + wvl + ":";
}
for (int wvl = 380; wvl < 390; wvl++) {
autoGroupingStr += "dolp_*_" + wvl + ":";
}
for (int wvl = 380; wvl < 390; wvl++) {
autoGroupingStr += "q_*_" + wvl + ":";
}
for (int wvl = 380; wvl < 390; wvl++) {
autoGroupingStr += "u_*_" + wvl + ":";
}
for (int wvl = 380; wvl < 390; wvl++) {
autoGroupingStr += "qc_*_" + wvl + ":";
}
for (int wvl = 380; wvl < 390; wvl++) {
autoGroupingStr += "q_over_i_*_" + wvl + ":";
}
for (int wvl = 380; wvl < 390; wvl++) {
autoGroupingStr += "u_over_i_*_" + wvl + ":";
}
autoGroupingStr += "I:I_noise:I_noisefree:I_polsample:" +
"I_polsample_noise:I_noisefree_polsample:DOLP:DOLP_noise:DOLP_noisefree:" +
"Q_over_I:Q_over_I_noise:Q_over_I_noisefree:AOLP:AOLP_noisefree:" +
"U_over_I:U_over_I_noise:U_over_I_noisefree:scattering_angle:" +
"sensor_azimuth:sensor_zenith:solar_azimuth:solar_zenith:" +
"obs_per_view:view_time_offsets";
currentProduct.setAutoGrouping(autoGroupingStr);
// currentProduct.setAutoGrouping("QC:QC_bitwise:QC_polsample_bitwise:QC_polsample:" +
// "I_*_380:I_*_381:I_*_382:I_*_383:I_*_384:I_*_385:I:I_noise:I_noisefree:I_polsample:" +
// "I_polsample_noise:I_noisefree_polsample:DOLP:DOLP_noise:DOLP_noisefree:" +
// "Q_over_I:Q_over_I_noise:Q_over_I_noisefree:AOLP:AOLP_noisefree:" +
// "U_over_I:U_over_I_noise:U_over_I_noisefree:scattering_angle:" +
// "sensor_azimuth:sensor_zenith:solar_azimuth:solar_zenith:" +
// "obs_per_view:view_time_offsets");
}
if (!rasterToAngularMap.containsKey(currentView.getRaster())) {
setUpAngularViews();
}
recreateChart();
}
updateUIState();
}
}
private Product getCurrentProduct() {
return currentProduct;
}
private void setCurrentProduct(Product product) {
Product oldProduct = currentProduct;
currentProduct = product;
if (currentProduct != oldProduct) {
if (oldProduct != null) {
oldProduct.removeProductNodeListener(productNodeHandler);
}
if (currentProduct != null) {
currentProduct.addProductNodeListener(productNodeHandler);
}
if (currentProduct == null) {
chartHandler.setEmptyPlot();
}
updateUIState();
}
}
private void updateUIState() {
boolean hasView = currentView != null;
boolean hasProduct = getCurrentProduct() != null;
boolean hasSelectedPins = hasView && currentView.getSelectedPins().length > 0;
boolean hasPins = hasProduct && getCurrentProduct().getPinGroup().getNodeCount() > 0;
filterButton.setEnabled(hasProduct);
// showAngularViewsForCursorButton.setEnabled(hasView);
showAngularViewsForCursorButton.setVisible(false);
showAngularViewsForSelectedPinsButton.setVisible(false);
// showAngularViewsForSelectedPinsButton.setEnabled(hasSelectedPins);
showAngularViewsForAllPinsButton.setEnabled(hasPins);
showGridButton.setEnabled(hasView);
chartPanel.setEnabled(hasProduct); // todo - hasAngularViewsGraphs
showGridButton.setSelected(hasView);
chartHandler.setGridVisible(showGridButton.isSelected());
}
void setPrepareForUpdateMessage() {
chartHandler.setCollectingAngularInformationMessage();
}
void updateData(int pixelX, int pixelY, int level, boolean pixelPosInRasterBounds) {
chartHandler.setPosition(pixelX, pixelY, level, pixelPosInRasterBounds);
chartHandler.updateData();
}
void updateChart(boolean adjustAxes) {
chartHandler.setAutomaticRangeAdjustments(adjustAxes);
updateChart();
}
void updateChart() {
maybeShowTip();
chartHandler.updateChart();
chartPanel.repaint();
}
private void maybeShowTip() {
if (!tipShown) {
final String message = "<html>Tip: If you press the SHIFT key while moving the mouse cursor over<br/>" +
"an image, " + SnapApp.getDefault().getInstanceName() + " adjusts the diagram axes " +
"to the local values at the<br/>" +
"current pixel position, if you release the SHIFT key again, then the<br/>" +
"min/max are accumulated again.</html>";
Dialogs.showInformation("Angular View Tip", message, SUPPRESS_MESSAGE_KEY);
tipShown = true;
}
}
private AngularBand[] getAvailableAngularBands(RasterDataNode currentRaster) {
if (!rasterToAngularBandsMap.containsKey(currentRaster)) {
rasterToAngularBandsMap.put(currentRaster, new ArrayList<>());
}
List<AngularBand> angularViewBands = rasterToAngularBandsMap.get(currentRaster);
Band[] bands = currentProduct.getBands();
for (Band band : bands) {
if (isAngularBand(band) && !band.isFlagBand()) {
boolean isAlreadyIncluded = false;
for (AngularBand angularViewBand : angularViewBands) {
if (angularViewBand.getOriginalBand() == band) {
isAlreadyIncluded = true;
break;
}
}
if (!isAlreadyIncluded) {
angularViewBands.add(new AngularBand(band, true));
}
}
}
setScatteringZenithBands(angularViewBands);
if (angularViewBands.isEmpty()) {
// Dialogs.showWarning("<html>Angular View Tool <br>requires bands with View Angle property,<br>" +
// "such as PACE OCI, HARP2,and SPEXone bands</html>");
}
return angularViewBands.toArray(new AngularBand[angularViewBands.size()]);
}
private void setScatteringZenithBands(List<AngularBand> angularBands) {
sensor_azimuth_Bands = new ArrayList<>();
sensor_zenith_Bands = new ArrayList<>();
scattering_angle_Bands = new ArrayList<>();
for (AngularBand angularBand : angularBands) {
if (angularBand.getName().contains("Sensor_Azimuth") || angularBand.getName().contains("sensor_azimuth")) {
sensor_azimuth_Bands.add(angularBand);
}
if (angularBand.getName().contains("Sensor_Zenith") || angularBand.getName().contains("sensor_zenith")) {
sensor_zenith_Bands.add(angularBand);
}
if (angularBand.getName().contains("scattering_angle")) {
scattering_angle_Bands.add(angularBand);
}
}
useScatteringAngleButton.setEnabled((scattering_angle_Bands.size() != 0));
useViewAngleButton.setSelected((true));
}
private boolean isAngularBand(Band band) { return (band.getAngularBandIndex() != -1 );}
protected void initUI() {
final JFreeChart chart = ChartFactory.createXYLineChart(angularAnimationString,
"View Angle", "", null, PlotOrientation.VERTICAL,
true, true, false);
chart.getXYPlot().getRangeAxis().addChangeListener(axisChangeEvent -> {
if (!isCodeInducedAxisChange) {
rangeAxisAdjustmentIsFrozen = !((ValueAxis) axisChangeEvent.getAxis()).isAutoRange();
}
});
chart.getXYPlot().getDomainAxis().addChangeListener(axisChangeEvent -> {
if (!isCodeInducedAxisChange) {
domainAxisAdjustmentIsFrozen = !((ValueAxis) axisChangeEvent.getAxis()).isAutoRange();
}
});
chart.getXYPlot().getRangeAxis().setAutoRange(false);
rangeAxisAdjustmentIsFrozen = false;
chart.getXYPlot().getDomainAxis().setAutoRange(false);
domainAxisAdjustmentIsFrozen = false;
chartPanel = new ChartPanel(chart);
chartHandler = new ChartHandler(chart);
final XYPlotMarker plotMarker = new XYPlotMarker(chartPanel, new XYPlotMarker.Listener() {
@Override
public void pointSelected(XYDataset xyDataset, int seriesIndex, Point2D dataPoint) {
//do nothing
}
@Override
public void pointDeselected() {
//do nothing
}
});
filterButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Filter24.gif"), false);
filterButton.setName("filterButton");
filterButton.setEnabled(false);
filterButton.addActionListener(e -> {
selectAngularBands();
recreateChart();
});
showAngularViewsForCursorButton = ToolButtonFactory.createButton(
UIUtils.loadImageIcon("icons/CursorSpectrum24.gif"), true);
showAngularViewsForCursorButton.addActionListener(e -> recreateChart());
showAngularViewsForCursorButton.setName("showAngularViewsForCursorButton");
showAngularViewsForCursorButton.setSelected(true);
showAngularViewsForCursorButton.setToolTipText("Show angular views at cursor position.");
showAngularViewsForSelectedPinsButton = ToolButtonFactory.createButton(
UIUtils.loadImageIcon("icons/SelectedPinSpectra24.gif"), true);
showAngularViewsForSelectedPinsButton.addActionListener(e -> {
if (isShowingAngularViewsForAllPins()) {
showAngularViewsForAllPinsButton.setSelected(false);
} else if (!isShowingAngularViewsForSelectedPins()) {
plotMarker.setInvisible();
}
recreateChart();
});
showAngularViewsForSelectedPinsButton.setName("showAngularViewsForSelectedPinsButton");
showAngularViewsForSelectedPinsButton.setToolTipText("Show AngularViews for selected pins.");
showAngularViewsForAllPinsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/PinSpectra24.gif"),
true);
showAngularViewsForAllPinsButton.addActionListener(e -> {
if (isShowingAngularViewsForSelectedPins()) {
showAngularViewsForSelectedPinsButton.setSelected(false);
} else if (!isShowingAngularViewsForAllPins()) {
plotMarker.setInvisible();
}
// recreateChart();
animateChart();
recreateChart();
});
showAngularViewsForAllPinsButton.setName("showAngularViewsForAllPinsButton");
showAngularViewsForAllPinsButton.setToolTipText("Animate Angular Views for all pins.");
showGridButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/SpectrumGrid24.gif"), true);
showGridButton.addActionListener(e -> chartHandler.setGridVisible(showGridButton.isSelected()));
showGridButton.setName("showGridButton");
showGridButton.setToolTipText("Show diagram grid.");
useViewAngleButton = new JRadioButton("View Angle");
useViewAngleButton.setToolTipText("Use View Angle as x-axis.");
useViewAngleButton.setName("useViewAngleButton");
useSensorZenithButton = new JRadioButton("Sensor Zenith");
useSensorZenithButton.setToolTipText("Use Sensor Zenith Angle as x-axis.");
useSensorZenithButton.setName("useSensorZenith");
useSensorAzimuthButton = new JRadioButton("Sensor Azimuth");
useSensorAzimuthButton.setToolTipText("Use Sensor Azimuth as x-axis.");
useSensorAzimuthButton.setName("useuseSensorAzimuthButton");
useScatteringAngleButton = new JRadioButton("Scattering Angle");
useScatteringAngleButton.setToolTipText("Use Scattering Angle as x-axis.");
useScatteringAngleButton.setName("useScatteringAngleButton");
final ButtonGroup angleAxisGroup = new ButtonGroup();
angleAxisGroup.add(useViewAngleButton);
angleAxisGroup.add(useSensorZenithButton);
angleAxisGroup.add(useSensorAzimuthButton);
angleAxisGroup.add(useScatteringAngleButton);
useViewAngleButton.setSelected(true);
useViewAngleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
useViewAngle = useViewAngleButton.isSelected();
recreateChart();
}
});
useSensorZenithButton.setSelected(false);
useSensorZenithButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
useSensorZenith = useSensorZenithButton.isSelected();
recreateChart();
}
});
useSensorAzimuthButton.setSelected(false);
useSensorAzimuthButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
useSensorAzimuth = useSensorAzimuthButton.isSelected();
recreateChart();
}
});
useScatteringAngleButton.setSelected(false);
useScatteringAngleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
useScatteringAngle = useScatteringAngleButton.isSelected();
recreateChart();
}
});
JPanel angleButtonPanel = new JPanel( new GridLayout(4, 1) );
angleButtonPanel.add(useViewAngleButton);
angleButtonPanel.add(useSensorZenithButton);
angleButtonPanel.add(useSensorAzimuthButton);
angleButtonPanel.add(useScatteringAngleButton);
// AbstractButton exportAngularViewsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Export24.gif"),
// false);
// exportAngularViewsButton.addActionListener(new AngularViewsExportAction(this));
// exportAngularViewsButton.setToolTipText("Export angular Views to text file.");
// exportAngularViewsButton.setName("exportAngularViewsButton");
//
AbstractButton helpButton = ToolButtonFactory.createButton(new HelpAction(this), false);
helpButton.setName("helpButton");
helpButton.setToolTipText("Help.");
final JPanel buttonPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.NONE;
gbc.insets.top = 2;
gbc.gridy = 0;
buttonPane.add(filterButton, gbc);
gbc.gridy++;
buttonPane.add(showAngularViewsForCursorButton, gbc);
gbc.gridy++;
buttonPane.add(showAngularViewsForSelectedPinsButton, gbc);
gbc.gridy++;
buttonPane.add(showAngularViewsForAllPinsButton, gbc);
gbc.gridy++;
buttonPane.add(showGridButton, gbc);
// gbc.gridy++;
// buttonPane.add(exportAngularViewsButton, gbc);
gbc.gridy++;
buttonPane.add(angleButtonPanel,gbc);
gbc.gridy++;
gbc.insets.bottom = 0;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1.0;
gbc.gridwidth = 2;
buttonPane.add(new JLabel(" "), gbc); // filler
gbc.fill = GridBagConstraints.NONE;
gbc.weighty = 0.0;
gbc.gridy = 10;
gbc.anchor = GridBagConstraints.EAST;
buttonPane.add(helpButton, gbc);
chartPanel.setPreferredSize(new Dimension(1000, 500));
// chartPanel.setPreferredSize(getPreferredSize());
chartPanel.setBackground(Color.white);
chartPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createBevelBorder(BevelBorder.LOWERED),
BorderFactory.createEmptyBorder(2, 2, 2, 2)));
chartPanel.addChartMouseListener(plotMarker);
JPanel mainPane = new JPanel(new BorderLayout(4, 4));
mainPane.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
mainPane.add(BorderLayout.CENTER, chartPanel);
mainPane.add(BorderLayout.EAST, buttonPane);
// mainPane.setPreferredSize(new Dimension(1020, 520));
// mainPane.setPreferredSize(getPreferredSize());
SnapApp.getDefault().getProductManager().addListener(new ProductManager.Listener() {
@Override
public void productAdded(ProductManager.Event event) {
// ignored
}
@Override
public void productRemoved(ProductManager.Event event) {
final Product product = event.getProduct();
if (getCurrentProduct() == product) {
chartPanel.getChart().getXYPlot().setDataset(null);
setCurrentView(null);
setCurrentProduct(null);
}
if (currentView != null) {
final RasterDataNode currentRaster = currentView.getRaster();
if (rasterToAngularMap.containsKey(currentRaster)) {
rasterToAngularMap.remove(currentRaster);
}
if (rasterToAngularBandsMap.containsKey(currentRaster)) {
rasterToAngularBandsMap.remove(currentRaster);
}
}
PlacemarkGroup pinGroup = product.getPinGroup();
for (int i = 0; i < pinGroup.getNodeCount(); i++) {
chartHandler.removePinInformation(pinGroup.get(i));
}
}
});
final ProductSceneView view = getSelectedProductSceneView();
if (view != null) {
productSceneViewSelected(view);
}
setDisplayName(angularAnimationString);
setLayout(new BorderLayout());
add(mainPane, BorderLayout.CENTER);
updateUIState();
}
private void selectAngularBands() {
final RasterDataNode currentRaster = currentView.getRaster();
final DisplayableAngularview[] allAngularViews = rasterToAngularMap.get(currentRaster);
final AngularViewChooser angularViewChooser = new AngularViewChooser(SwingUtilities.getWindowAncestor(this), allAngularViews);
if (angularViewChooser.show() == ModalDialog.ID_OK) {
final DisplayableAngularview[] angularViews = angularViewChooser.getAngularViews();
rasterToAngularMap.put(currentRaster, angularViews);
}
}
boolean isShowingCursorAngularView() {
return showAngularViewsForCursorButton.isSelected();
}
public boolean isShowingPinAngularViews() {
return isShowingAngularViewsForSelectedPins() || isShowingAngularViewsForAllPins();
}
private boolean isShowingAngularViewsForAllPins() {
return showAngularViewsForAllPinsButton.isSelected();
}
private void recreateChart() {
chartHandler.updateData();
chartHandler.updateChart();
chartPanel.repaint();
updateUIState();
}
private void animateChart() {
List<DisplayableAngularview> angularViews = getSelectedAngularViews();
if (!isShowingAngularViewsForAllPins()) {
showAngularViewsForAllPinsButton.setSelected(true);
}
chartHandler.updateData();
chartHandler.updateInitialChart();
ImageIcon[] images = new ImageIcon[angularViews.size()];
for (int i = 0; i < angularViews.size(); i++) {
List<DisplayableAngularview> singleAngularView = Collections.singletonList(angularViews.get(i));
chartHandler.updateAnimationData(singleAngularView);
chartHandler.updateAnimationChart(singleAngularView);
// chartPanel.repaint();
BufferedImage chartImage = chartPanel.getChart().createBufferedImage(1024, 768);
images[i] = new ImageIcon(chartImage);
System.out.println("plot AngularViews i= " +i);
}
AnimationWithSpeedControl.animate(images);
updateUIState();
}
public Placemark[] getDisplayedPins() {
if (isShowingAngularViewsForSelectedPins() && currentView != null) {
return currentView.getSelectedPins();
} else if (isShowingAngularViewsForAllPins() && getCurrentProduct() != null) {
ProductNodeGroup<Placemark> pinGroup = getCurrentProduct().getPinGroup();
return pinGroup.toArray(new Placemark[pinGroup.getNodeCount()]);
} else {
return new Placemark[0];
}
}
private void setUpAngularViews() {
if (currentView == null) {
return;
}
DisplayableAngularview[] angularViews;
final RasterDataNode raster = currentView.getRaster();
final AngularBand[] availableAngularBands = getAvailableAngularBands(raster);
if (availableAngularBands.length == 0) {
angularViews = new DisplayableAngularview[]{};
} else {
final Product.AutoGrouping autoGrouping = currentProduct.getAutoGrouping();
if (autoGrouping != null) {
final int selectedAngularViewIndex = autoGrouping.indexOf(raster.getName());
DisplayableAngularview[] autoGroupingAngularViews = new DisplayableAngularview[autoGrouping.size()];
final Iterator<String[]> iterator = autoGrouping.iterator();
int i = 0;
while (iterator.hasNext()) {
final String[] autoGroupingNameAsArray = iterator.next();
StringBuilder angularViewNameBuilder = new StringBuilder(autoGroupingNameAsArray[0]);
if (autoGroupingNameAsArray.length > 1) {
for (int j = 1; j < autoGroupingNameAsArray.length; j++) {
String autoGroupingNamePart = autoGroupingNameAsArray[j];
angularViewNameBuilder.append("_").append(autoGroupingNamePart);
}
}
final String angularViewName = angularViewNameBuilder.toString();
int symbolIndex = AngularViewShapeProvider.getValidIndex(i, false);
DisplayableAngularview angularView = new DisplayableAngularview(angularViewName, symbolIndex);
angularView.setSelected(i == selectedAngularViewIndex);
angularView.setLineStyle(AngularViewStrokeProvider.getStroke(i));
autoGroupingAngularViews[i++] = angularView;
}
List<AngularBand> ungroupedBandsList = new ArrayList<>();
for (AngularBand availableAngularBand : availableAngularBands) {
final String bandName = availableAngularBand.getName();
availableAngularBand.setSelected(false);
if (currentProduct.getName().contains("SPEX")) {
if (bandName.contains("385") && availableAngularBand.getOriginalBand().getDescription().equals("I")) {
availableAngularBand.setSelected(true);
}
}
if (currentProduct.getName().contains("HARP2")) {
if (bandName.contains("549") && availableAngularBand.getOriginalBand().getDescription().equals("I")) {
availableAngularBand.setSelected(true);
}
}
final int angularViewIndex = autoGrouping.indexOf(bandName);
if (angularViewIndex != -1) {
autoGroupingAngularViews[angularViewIndex].addBand(availableAngularBand);
} else {
ungroupedBandsList.add(availableAngularBand);
}
}
if (ungroupedBandsList.size() == 0) {
angularViews = autoGroupingAngularViews;
} else {
final DisplayableAngularview[] angularViewsFromUngroupedBands =
createAngularViewsFromUngroupedBands(ungroupedBandsList.toArray(new AngularBand[0]),
AngularViewShapeProvider.getValidIndex(i, false), i);
angularViews = new DisplayableAngularview[autoGroupingAngularViews.length + angularViewsFromUngroupedBands.length];
System.arraycopy(autoGroupingAngularViews, 0, angularViews, 0, autoGroupingAngularViews.length);
System.arraycopy(angularViewsFromUngroupedBands, 0, angularViews, autoGroupingAngularViews.length, angularViewsFromUngroupedBands.length);
}
} else {
angularViews = createAngularViewsFromUngroupedBands(availableAngularBands, 1, 0);
}
}
rasterToAngularMap.put(raster, angularViews);
}
//package local for testing
static DisplayableAngularview[] createAngularViewsFromUngroupedBands(AngularBand[] ungroupedBands, int symbolIndex, int strokeIndex) {
List<String> knownUnits = new ArrayList<>();
List<DisplayableAngularview> displayableAngularViewList = new ArrayList<>();
DisplayableAngularview defaultAngularView = new DisplayableAngularview("tbd", -1);
for (AngularBand ungroupedBand : ungroupedBands) {
final String unit = ungroupedBand.getOriginalBand().getUnit();
if (StringUtils.isNullOrEmpty(unit)) {
defaultAngularView.addBand(ungroupedBand);
} else if (knownUnits.contains(unit)) {
displayableAngularViewList.get(knownUnits.indexOf(unit)).addBand(ungroupedBand);
} else {
knownUnits.add(unit);
final DisplayableAngularview angularView = new DisplayableAngularview("Bands measured in " + unit, symbolIndex++);
angularView.setLineStyle(AngularViewStrokeProvider.getStroke(strokeIndex++));
angularView.addBand(ungroupedBand);
displayableAngularViewList.add(angularView);
}
}
if (strokeIndex == 0) {
defaultAngularView.setName(DisplayableAngularview.DEFAULT_SPECTRUM_NAME);
} else {
defaultAngularView.setName(DisplayableAngularview.REMAINING_BANDS_NAME);
}
defaultAngularView.setSymbolIndex(symbolIndex);
defaultAngularView.setLineStyle(AngularViewStrokeProvider.getStroke(strokeIndex));
displayableAngularViewList.add(defaultAngularView);
return displayableAngularViewList.toArray(new DisplayableAngularview[displayableAngularViewList.size()]);
}
private DisplayableAngularview[] getAllAngularViews() {
if (currentView == null || !rasterToAngularMap.containsKey(currentView.getRaster())) {
return new DisplayableAngularview[0];
}
return rasterToAngularMap.get(currentView.getRaster());
}
private boolean isShowingAngularViewsForSelectedPins() {
return showAngularViewsForSelectedPinsButton.isSelected();
}
List<DisplayableAngularview> getSelectedAngularViews() {
List<DisplayableAngularview> selectedAngularViews = new ArrayList<>();
if (currentView != null) {
final RasterDataNode currentRaster = currentView.getRaster();
if (currentProduct != null && rasterToAngularMap.containsKey(currentRaster)) {
DisplayableAngularview[] allAngularViews = rasterToAngularMap.get(currentRaster);
for (DisplayableAngularview displayableAngularView : allAngularViews) {
if (displayableAngularView.isSelected()) {
selectedAngularViews.add(displayableAngularView);
}
}
}
}
return selectedAngularViews;
}
private void updateAngularViewsUnits() {
for (DisplayableAngularview angularView : getAllAngularViews()) {
angularView.updateUnit();
}
}
void removeCursorAngularViewsFromDataset() {
chartHandler.removeCursorAngularViewsFromDataset();
}
@Override
protected void productSceneViewSelected(ProductSceneView view) {
// view.addPixelPositionListener(pixelPositionListener);
setCurrentView(view);
}
@Override
protected void productSceneViewDeselected(ProductSceneView view) {
// view.removePixelPositionListener(pixelPositionListener);
setCurrentView(null);
}
@Override
protected void componentOpened() {
final ProductSceneView selectedProductSceneView = getSelectedProductSceneView();
if (selectedProductSceneView != null) {
// selectedProductSceneView.addPixelPositionListener(pixelPositionListener);
setCurrentView(selectedProductSceneView);
}
}
@Override
protected void componentClosed() {
if (currentView != null) {
// currentView.removePixelPositionListener(pixelPositionListener);
}
}
public boolean showsValidCursorAngularViews() {
return chartHandler.showsValidCursorAngularViews();
}
private class ChartHandler {
private static final String MESSAGE_NO_ANGULAR_BANDS = "No angular bands available"; /*I18N*/
private static final String MESSAGE_NO_PRODUCT_SELECTED = "No product selected";
private static final String MESSAGE_NO_AngularView_SELECTED = "No angular View selected";
private static final String MESSAGE_COLLECTING_ANGULAR_INFORMATION = "Collecting angular information...";
private final JFreeChart chart;
private final ChartUpdater chartUpdater;
private ChartHandler(JFreeChart chart) {
chartUpdater = new ChartUpdater();
this.chart = chart;
setLegend(chart);
setAutomaticRangeAdjustments(false);
final XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
renderer.setDefaultLinesVisible(true);
renderer.setDefaultShapesFilled(false);
setPlotMessage(MESSAGE_NO_PRODUCT_SELECTED);
}
private void setAutomaticRangeAdjustments(boolean userInducesAutomaticAdjustment) {
final XYPlot plot = chart.getXYPlot();
boolean adjustmentHasChanged = false;
if (userInducesAutomaticAdjustment) {
if (!isUserInducedAutomaticAdjustmentChosen) {
isUserInducedAutomaticAdjustmentChosen = true;
if (!isAutomaticDomainAdjustmentSet()) {
plot.getDomainAxis().setAutoRange(true);
domainAxisAdjustmentIsFrozen = false;
adjustmentHasChanged = true;
}
if (!isAutomaticRangeAdjustmentSet()) {
plot.getRangeAxis().setAutoRange(true);
rangeAxisAdjustmentIsFrozen = false;
adjustmentHasChanged = true;
}
}
} else {
if (isUserInducedAutomaticAdjustmentChosen) {
isUserInducedAutomaticAdjustmentChosen = false;
if (isAutomaticDomainAdjustmentSet()) {
plot.getDomainAxis().setAutoRange(false);
domainAxisAdjustmentIsFrozen = false;
adjustmentHasChanged = true;
}
if (isAutomaticRangeAdjustmentSet()) {
plot.getRangeAxis().setAutoRange(false);
rangeAxisAdjustmentIsFrozen = false;
adjustmentHasChanged = true;
}
}
}
if (adjustmentHasChanged) {
chartUpdater.invalidatePlotBounds();
}
}
private boolean isAutomaticDomainAdjustmentSet() {
return chart.getXYPlot().getDomainAxis().isAutoRange();
}
private boolean isAutomaticRangeAdjustmentSet() {
return chart.getXYPlot().getRangeAxis().isAutoRange();
}
private void setLegend(JFreeChart chart) {
chart.removeLegend();
final LegendTitle legend = new LegendTitle(new AngularViewLegendItemSource());
legend.setPosition(RectangleEdge.BOTTOM);
LineBorder border = new LineBorder(Color.BLACK, new BasicStroke(), new RectangleInsets(2, 2, 2, 2));
legend.setFrame(border);
chart.addLegend(legend);
}
private void setPosition(int pixelX, int pixelY, int level, boolean pixelPosInRasterBounds) {
chartUpdater.setPosition(pixelX, pixelY, level, pixelPosInRasterBounds);
}
private void updateChart() {
if (chartUpdater.isDatasetEmpty()) {
setEmptyPlot();
return;
}
List<DisplayableAngularview> angularViews = getSelectedAngularViews();
chartUpdater.updateChart(chart, angularViews);
chart.getXYPlot().clearAnnotations();
}
private void updateInitialChart() {
if (chartUpdater.isDatasetEmpty()) {
setEmptyPlot();
return;
}
// List<DisplayableAngularview> angularViews = getSelectedAngularViews();
// chartUpdater.updateChart(chart, angularViews);
chartUpdater.updatePlotBounds(chartUpdater.dataset.getDomainBounds(true),
chart.getXYPlot().getDomainAxis(), 0);
chartUpdater.updatePlotBounds(chartUpdater.dataset.getRangeBounds(true),
chart.getXYPlot().getRangeAxis(), 1);
// chart.getXYPlot().clearAnnotations();
}
private void updateAnimationChart(List<DisplayableAngularview> singleAngularViews) {
if (chartUpdater.isDatasetEmpty()) {
setEmptyPlot();
return;
}
// List<DisplayableAngularview> angularViews = getSelectedAngularViews();
chartUpdater.updateAnimationChart(chart, singleAngularViews);
chart.getXYPlot().clearAnnotations();
}
private void updateData() {
List<DisplayableAngularview> angularViews = getSelectedAngularViews();
chartUpdater.updateData(chart, angularViews);
}
private void updateAnimationData(List<DisplayableAngularview> singleAngularViews) {
// List<DisplayableAngularview> angularViews = getSelectedAngularViews();
chartUpdater.updateData(chart, singleAngularViews);
}
private void setEmptyPlot() {
chart.getXYPlot().setDataset(null);
if (getCurrentProduct() == null) {
setPlotMessage(MESSAGE_NO_PRODUCT_SELECTED);
} else if (!chartUpdater.showsValidCursorAngularViews()) {
} else if (getAllAngularViews().length == 0) {
setPlotMessage(MESSAGE_NO_AngularView_SELECTED);
} else {
setPlotMessage(MESSAGE_NO_ANGULAR_BANDS);
}
}
private void setGridVisible(boolean visible) {
chart.getXYPlot().setDomainGridlinesVisible(visible);
chart.getXYPlot().setRangeGridlinesVisible(visible);
}
private void removePinInformation(Placemark pin) {
chartUpdater.removePinInformation(pin);
}
private void removeBandInformation(Band band) {
chartUpdater.removeBandinformation(band);
}
private void setPlotMessage(String messageText) {
chart.getXYPlot().clearAnnotations();
TextTitle tt = new TextTitle(messageText);
tt.setTextAlignment(HorizontalAlignment.RIGHT);
tt.setFont(chart.getLegend().getItemFont());
tt.setBackgroundPaint(new Color(200, 200, 255, 50));
tt.setFrame(new BlockBorder(Color.white));
tt.setPosition(RectangleEdge.BOTTOM);
XYTitleAnnotation message = new XYTitleAnnotation(0.5, 0.5, tt, RectangleAnchor.CENTER);
chart.getXYPlot().addAnnotation(message);
}
public boolean showsValidCursorAngularViews() {
return chartUpdater.showsValidCursorAngularViews();
}
public void removeCursorAngularViewsFromDataset() {
chartUpdater.removeCursorAngularViewsFromDataset();
}
public void setCollectingAngularInformationMessage() {
setPlotMessage(MESSAGE_COLLECTING_ANGULAR_INFORMATION);
}
}
private class ChartUpdater {
private final static int domain_axis_index = 0;
private final static int range_axis_index = 1;
private final static double relativePlotInset = 0.05;
private final Map<Placemark, Map<Band, Double>> pinToEnergies;
private boolean showsValidCursorAngularViews;
private boolean pixelPosInRasterBounds;
private int rasterPixelX;
private int rasterPixelY;
private int rasterLevel;
private final Range[] plotBounds;
private XYSeriesCollection dataset;
private Point2D modelP;
private ChartUpdater() {
pinToEnergies = new HashMap<>();
plotBounds = new Range[2];
invalidatePlotBounds();
}
void invalidatePlotBounds() {
plotBounds[domain_axis_index] = null;
plotBounds[range_axis_index] = null;
}
private void setPosition(int pixelX, int pixelY, int level, boolean pixelPosInRasterBounds) {
this.rasterPixelX = pixelX;
this.rasterPixelY = pixelY;
this.rasterLevel = level;
this.pixelPosInRasterBounds = pixelPosInRasterBounds;
final AffineTransform i2m = currentView.getBaseImageLayer().getImageToModelTransform(level);
modelP = i2m.transform(new Point2D.Double(pixelX + 0.5, pixelY + 0.5), new Point2D.Double());
}
private void updateData(JFreeChart chart, List<DisplayableAngularview> angularViews) {
dataset = new XYSeriesCollection();
if (rasterLevel >= 0) {
fillDatasetWithPinSeries(angularViews, dataset, chart);
// fillDatasetWithCursorSeries(angularViews, dataset, chart);
}
}
private void updateChart(JFreeChart chart, List<DisplayableAngularview> angularViews) {
final XYPlot plot = chart.getXYPlot();
// if (!chartHandler.isAutomaticDomainAdjustmentSet() && !domainAxisAdjustmentIsFrozen) {
// isCodeInducedAxisChange = true;
// updatePlotBounds(dataset.getDomainBounds(true), plot.getDomainAxis(), domain_axis_index);
// isCodeInducedAxisChange = false;
// }
// if (!chartHandler.isAutomaticRangeAdjustmentSet() && !rangeAxisAdjustmentIsFrozen) {
// isCodeInducedAxisChange = true;
// updatePlotBounds(dataset.getRangeBounds(true), plot.getRangeAxis(), range_axis_index);
// isCodeInducedAxisChange = false;
// }
String oldLabel = plot.getDomainAxis().getLabel();
String newLabel;
if (useSensorZenithButton.isSelected()) {
newLabel = "Sensor Zenith Angle";
} else if (useSensorAzimuthButton.isSelected()){
newLabel = "Sensor Azimuth Angle";
} else if (useScatteringAngleButton.isSelected()){
newLabel = "Scattering Angle";
} else {
newLabel = "View Angle";
}
if (!newLabel.equals(oldLabel)) {
plot.getDomainAxis().setLabel(newLabel);
}
plot.setDataset(dataset);
setPlotUnit(angularViews, plot);
}
private void updateAnimationChart(JFreeChart chart, List<DisplayableAngularview> angularViews) {
final XYPlot plot = chart.getXYPlot();
// if (!chartHandler.isAutomaticDomainAdjustmentSet() && !domainAxisAdjustmentIsFrozen) {
// isCodeInducedAxisChange = true;
// updatePlotBounds(dataset.getDomainBounds(true), plot.getDomainAxis(), domain_axis_index);
// isCodeInducedAxisChange = false;
// }
// if (!chartHandler.isAutomaticRangeAdjustmentSet() && !rangeAxisAdjustmentIsFrozen) {
// isCodeInducedAxisChange = true;
// updatePlotBounds(dataset.getRangeBounds(true), plot.getRangeAxis(), range_axis_index);
// isCodeInducedAxisChange = false;
// }
String oldLabel = plot.getDomainAxis().getLabel();
String newLabel;
if (useSensorZenithButton.isSelected()) {
newLabel = "Sensor Zenith Angle";
} else if (useSensorAzimuthButton.isSelected()){
newLabel = "Sensor Azimuth Angle";
} else if (useScatteringAngleButton.isSelected()){
newLabel = "Scattering Angle";
} else {
newLabel = "View Angle";
}
if (!newLabel.equals(oldLabel)) {
plot.getDomainAxis().setLabel(newLabel);
}
plot.setDataset(dataset);
setPlotUnit(angularViews, plot);
}
private void setPlotUnit(List<DisplayableAngularview> angularViews, XYPlot plot) {
String unitToBeDisplayed = "";
if (angularViews.size() > 0) {
unitToBeDisplayed = angularViews.get(0).getUnit();
int i = 1;
while (i < angularViews.size() && !unitToBeDisplayed.equals(DisplayableAngularview.MIXED_UNITS)) {
DisplayableAngularview displayableAngularView = angularViews.get(i++);
if (displayableAngularView.hasSelectedBands() && !unitToBeDisplayed.equals(displayableAngularView.getUnit())) {
unitToBeDisplayed = DisplayableAngularview.MIXED_UNITS;
}
}
}
isCodeInducedAxisChange = true;
plot.getRangeAxis().setLabel(unitToBeDisplayed);
isCodeInducedAxisChange = false;
}
private void updatePlotBounds(Range newBounds, ValueAxis axis, int index) {
if (newBounds != null) {
final Range axisBounds = axis.getRange();
final Range oldBounds = this.plotBounds[index];
this.plotBounds[index] = getNewRange(newBounds, this.plotBounds[index], axisBounds);
if (oldBounds != this.plotBounds[index]) {
axis.setRange(getNewPlotBounds(this.plotBounds[index]));
}
}
}
private Range getNewRange(Range newBounds, Range currentBounds, Range plotBounds) {
if (currentBounds == null) {
currentBounds = newBounds;
} else {
if (plotBounds.getLowerBound() > 0 && newBounds.getLowerBound() < currentBounds.getLowerBound() ||
newBounds.getUpperBound() > currentBounds.getUpperBound()) {
currentBounds = new Range(Math.min(currentBounds.getLowerBound(), newBounds.getLowerBound()),
Math.max(currentBounds.getUpperBound(), newBounds.getUpperBound()));
}
}
return currentBounds;
}
private Range getNewPlotBounds(Range bounds) {
double range = bounds.getLength();
double delta = range * relativePlotInset;
if (bounds.getLowerBound() > -180.0) {
return new Range(bounds.getLowerBound() - delta, bounds.getUpperBound() + delta);
} else {
return new Range(Math.max(0, bounds.getLowerBound() - delta),
bounds.getUpperBound() + delta);
}
}
private void fillDatasetWithCursorSeries(List<DisplayableAngularview> angularViews, XYSeriesCollection dataset, JFreeChart chart) {
showsValidCursorAngularViews = false;
if (modelP == null) {
return;
}
if (isShowingCursorAngularView() && currentView != null) {
for (DisplayableAngularview angularView : angularViews) {
XYSeries series = new XYSeries(angularView.getName());
final Band[] angularBands = angularView.getSelectedBands();
if (!currentProduct.isMultiSize()) {
for (Band angularBand : angularBands) {
final float viewAngle = angularBand.getAngularValue();
float angle_axis;
if (useSensorZenithButton.isSelected()) {
angle_axis = (float) get_sensor_zenith(viewAngle);
} else if (useSensorAzimuthButton.isSelected()){
angle_axis = (float) get_sensor_azimuth(viewAngle);
} else if (useScatteringAngleButton.isSelected()){
angle_axis = (float) get_scattering_angle(viewAngle);
} else {
angle_axis = viewAngle;
}
if (abs(angle_axis) > 180.0) {
return;
}
if (pixelPosInRasterBounds && isPixelValid(angularBand, rasterPixelX, rasterPixelY, rasterLevel)) {
addToSeries(angularBand, rasterPixelX, rasterPixelY, rasterLevel, series, angle_axis);
showsValidCursorAngularViews = true;
}
}
} else {
for (Band angularBand : angularBands) {
final float viewAngle = angularBand.getAngularValue();
float angle_axis;
if (useSensorZenithButton.isSelected()) {
angle_axis = (float) get_sensor_zenith(viewAngle);
} else if (useSensorAzimuthButton.isSelected()){
angle_axis = (float) get_sensor_azimuth(viewAngle);
} else if (useScatteringAngleButton.isSelected()){
angle_axis = (float) get_scattering_angle(viewAngle);
} else {
angle_axis = viewAngle;
}
if (abs(angle_axis) > 180.0) {
return;
}
final AffineTransform i2m = angularBand.getImageToModelTransform();
if (i2m.equals(currentView.getRaster().getImageToModelTransform())) {
if (pixelPosInRasterBounds && isPixelValid(angularBand, rasterPixelX, rasterPixelY, rasterLevel)) {
addToSeries(angularBand, rasterPixelX, rasterPixelY, rasterLevel, series, angle_axis);
showsValidCursorAngularViews = true;
}
} else {
//todo [Multisize_products] use scenerastertransform here
final PixelPos rasterPos = new PixelPos();
final MultiLevelModel multiLevelModel = angularBand.getMultiLevelModel();
int level = getLevel(multiLevelModel);
multiLevelModel.getModelToImageTransform(level).transform(modelP, rasterPos);
final int rasterX = (int) rasterPos.getX();
final int rasterY = (int) rasterPos.getY();
if (coordinatesAreInRasterBounds(angularBand, rasterX, rasterY, level) &&
isPixelValid(angularBand, rasterX, rasterY, level)) {
addToSeries(angularBand, rasterX, rasterY, level, series, angle_axis);
showsValidCursorAngularViews = true;
}
}
}
}
updateRenderer(dataset.getSeriesCount(), Color.BLACK, angularView, chart);
dataset.addSeries(series);
}
}
}
private void addToSeries(Band angularBand, int x, int y, int level, XYSeries series, double wavelength) {
final double energy = ProductUtils.getGeophysicalSampleAsDouble(angularBand, x, y, level);
if (energy != angularBand.getGeophysicalNoDataValue()) {
series.add(wavelength, energy);
}
}
//todo code duplication with pixelinfoviewmodelupdater - move to single class - tf 20151119
private boolean coordinatesAreInRasterBounds(RasterDataNode raster, int x, int y, int level) {
final RenderedImage levelImage = raster.getSourceImage().getImage(level);
return x >= 0 && y >= 0 && x < levelImage.getWidth() && y < levelImage.getHeight();
}
private void fillDatasetWithPinSeries(List<DisplayableAngularview> angularViews, XYSeriesCollection dataset, JFreeChart chart) {
Placemark[] pins = getDisplayedPins();
for (Placemark pin : pins) {
List<XYSeries> pinSeries = createXYSeriesFromPin(pin, dataset.getSeriesCount(), angularViews, chart);
pinSeries.forEach(dataset::addSeries);
}
}
private List<XYSeries> createXYSeriesFromPin(Placemark pin, int seriesIndex, List<DisplayableAngularview> angularViews, JFreeChart chart) {
List<XYSeries> pinSeries = new ArrayList<>();
Color pinColor = PlacemarkUtils.getPlacemarkColor(pin, currentView);
for (DisplayableAngularview angularView : angularViews) {
XYSeries series = new XYSeries(angularView.getName() + "_" + pin.getLabel());
final Band[] angularBands = angularView.getSelectedBands();
Map<Band, Double> bandToEnergy;
if (pinToEnergies.containsKey(pin)) {
bandToEnergy = pinToEnergies.get(pin);
} else {
bandToEnergy = new HashMap<>();
pinToEnergies.put(pin, bandToEnergy);
}
for (Band angularBand : angularBands) {
double energy;
if (bandToEnergy.containsKey(angularBand)) {
energy = bandToEnergy.get(angularBand);
} else {
energy = readEnergy(pin, angularBand);
bandToEnergy.put(angularBand, energy);
}
final float viewAngle = angularBand.getAngularValue();
float angle_axis;
if (useSensorZenithButton.isSelected()) {
angle_axis = (float) get_sensor_zenith(viewAngle);
} else if (useSensorAzimuthButton.isSelected()){
angle_axis = (float) get_sensor_azimuth(viewAngle);
} else {
angle_axis = viewAngle;
}
if (abs(angle_axis) > 180.0) {
return pinSeries;
}
if (energy != angularBand.getGeophysicalNoDataValue()) {
series.add(angle_axis, energy);
}
}
updateRenderer(seriesIndex++, pinColor, angularView, chart);
pinSeries.add(series);
}
return pinSeries;
}
private double get_scattering_angle(double view_angle) {
double scattering_angle = 0.0;
for (AngularBand scattering_angle_Band : scattering_angle_Bands) {
if (scattering_angle_Band.getOriginalBand().getAngularValue() == view_angle) {
scattering_angle = ProductUtils.getGeophysicalSampleAsDouble(scattering_angle_Band.getOriginalBand(), rasterPixelX, rasterPixelY, rasterLevel);
break;
}
}
return scattering_angle;
}
private double get_sensor_azimuth(double view_angle) {
double sensor_azimuth = 0.0;
for (AngularBand sensor_azimuth_Band : sensor_azimuth_Bands) {
if (sensor_azimuth_Band.getOriginalBand().getAngularValue() == view_angle) {
sensor_azimuth = ProductUtils.getGeophysicalSampleAsDouble(sensor_azimuth_Band.getOriginalBand(), rasterPixelX, rasterPixelY, rasterLevel);
break;
}
}
return sensor_azimuth;
}
private double get_sensor_zenith(double view_angle) {
double sensor_zenith_value = 0.0;
double sensor_zenith;
for (AngularBand sensor_zenith_Band : sensor_zenith_Bands) {
if (sensor_zenith_Band.getOriginalBand().getAngularValue() == view_angle) {
sensor_zenith_value = ProductUtils.getGeophysicalSampleAsDouble(sensor_zenith_Band.getOriginalBand(), rasterPixelX, rasterPixelY, rasterLevel);
break;
}
}
sensor_zenith = sensor_zenith_value * view_angle/abs(view_angle);
return sensor_zenith;
}
private void updateRenderer(int seriesIndex, Color seriesColor, DisplayableAngularview angularView, JFreeChart chart) {
final XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
final Stroke lineStyle = angularView.getLineStyle();
renderer.setSeriesStroke(seriesIndex, lineStyle);
Shape symbol = angularView.getScaledShape();
renderer.setSeriesShape(seriesIndex, symbol);
renderer.setSeriesShapesVisible(seriesIndex, true);
renderer.setSeriesPaint(seriesIndex, seriesColor);
}
private double readEnergy(Placemark pin, Band angularBand) {
//todo [Multisize_products] use scenerastertransform here
final Object pinGeometry = pin.getFeature().getDefaultGeometry();
if (pinGeometry == null || !(pinGeometry instanceof Point)) {
return angularBand.getGeophysicalNoDataValue();
}
final Point2D.Double modelPoint = new Point2D.Double(((Point) pinGeometry).getCoordinate().x,
((Point) pinGeometry).getCoordinate().y);
final MultiLevelModel multiLevelModel = angularBand.getMultiLevelModel();
int level = getLevel(multiLevelModel);
final AffineTransform m2iTransform = multiLevelModel.getModelToImageTransform(level);
final PixelPos pinLevelRasterPos = new PixelPos();
m2iTransform.transform(modelPoint, pinLevelRasterPos);
int pinLevelRasterX = (int) Math.floor(pinLevelRasterPos.getX());
int pinLevelRasterY = (int) Math.floor(pinLevelRasterPos.getY());
if (coordinatesAreInRasterBounds(angularBand, pinLevelRasterX, pinLevelRasterY, level) &&
isPixelValid(angularBand, pinLevelRasterX, pinLevelRasterY, level)) {
return ProductUtils.getGeophysicalSampleAsDouble(angularBand, pinLevelRasterX, pinLevelRasterY, level);
}
return angularBand.getGeophysicalNoDataValue();
}
private void removePinInformation(Placemark pin) {
pinToEnergies.remove(pin);
}
private void removeBandinformation(Band band) {
for (Placemark pin : pinToEnergies.keySet()) {
Map<Band, Double> bandToEnergiesMap = pinToEnergies.get(pin);
if (bandToEnergiesMap.containsKey(band)) {
bandToEnergiesMap.remove(band);
}
}
}
public boolean showsValidCursorAngularViews() {
return showsValidCursorAngularViews;
}
void removeCursorAngularViewsFromDataset() {
modelP = null;
if (showsValidCursorAngularViews) {
int numberOfSelectedAngularViews = getSelectedAngularViews().size();
int numberOfPins = getDisplayedPins().length;
int numberOfDisplayedGraphs = numberOfPins * numberOfSelectedAngularViews;
while (dataset.getSeriesCount() > numberOfDisplayedGraphs) {
dataset.removeSeries(dataset.getSeriesCount() - 1);
}
}
}
public boolean isDatasetEmpty() {
return dataset == null || dataset.getSeriesCount() == 0;
}
//todo code duplication with pixelinfoviewmodelupdater - move to single class - tf 20151119
private boolean isPixelValid(RasterDataNode raster, int pixelX, int pixelY, int level) {
if (raster.isValidMaskUsed()) {
PlanarImage image = ImageManager.getInstance().getValidMaskImage(raster, level);
Raster data = getRasterTile(image, pixelX, pixelY);
return data.getSample(pixelX, pixelY, 0) != 0;
} else {
return true;
}
}
//todo code duplication with pixelinfoviewmodelupdater - move to single class - tf 20151119
private Raster getRasterTile(PlanarImage image, int pixelX, int pixelY) {
final int tileX = image.XToTileX(pixelX);
final int tileY = image.YToTileY(pixelY);
return image.getTile(tileX, tileY);
}
//todo code duplication with pixelinfoviewmodelupdater - move to single class - tf 20151119
private int getLevel(MultiLevelModel multiLevelModel) {
if (rasterLevel < multiLevelModel.getLevelCount()) {
return rasterLevel;
}
return ImageLayer.getLevel(multiLevelModel, currentView.getViewport());
}
}
private class AngularViewLegendItemSource implements LegendItemSource {
@Override
public LegendItemCollection getLegendItems() {
LegendItemCollection itemCollection = new LegendItemCollection();
final Placemark[] displayedPins = getDisplayedPins();
final List<DisplayableAngularview> angularViews = getSelectedAngularViews();
for (Placemark pin : displayedPins) {
Paint pinPaint = PlacemarkUtils.getPlacemarkColor(pin, currentView);
angularViews.stream().filter(DisplayableAngularview::hasSelectedBands).forEach(angularView -> {
String legendLabel = pin.getLabel() + "_" + angularView.getName();
LegendItem item = createLegendItem(angularView, pinPaint, legendLabel);
itemCollection.add(item);
});
}
if (isShowingCursorAngularView() && showsValidCursorAngularViews()) {
angularViews.stream().filter(DisplayableAngularview::hasSelectedBands).forEach(angularView -> {
Paint defaultPaint = Color.BLACK;
LegendItem item = createLegendItem(angularView, defaultPaint, angularView.getName());
itemCollection.add(item);
});
}
return itemCollection;
}
private LegendItem createLegendItem(DisplayableAngularview angularView, Paint paint, String legendLabel) {
Stroke outlineStroke = new BasicStroke();
Line2D lineShape = new Line2D.Double(0, 5, 40, 5);
Stroke lineStyle = angularView.getLineStyle();
Shape symbol = angularView.getScaledShape();
return new LegendItem(legendLabel, legendLabel, legendLabel, legendLabel,
true, symbol, false,
paint, true, paint, outlineStroke,
true, lineShape, lineStyle, paint);
}
}
/////////////////////////////////////////////////////////////////////////
// Product change handling
private class ProductNodeHandler extends ProductNodeListenerAdapter {
@Override
public void nodeChanged(final ProductNodeEvent event) {
boolean chartHasChanged = false;
if (event.getSourceNode() instanceof Band) {
final String propertyName = event.getPropertyName();
if (propertyName.equals(DataNode.PROPERTY_NAME_UNIT)) {
updateAngularViewsUnits();
chartHasChanged = true;
} else if (propertyName.equals(Band.PROPERTY_NAME_ANGULAR_VALUE)) {
setUpAngularViews();
chartHasChanged = true;
}
} else if (event.getSourceNode() instanceof Placemark) {
if (event.getPropertyName().equals("geoPos") || event.getPropertyName().equals("pixelPos")) {
chartHandler.removePinInformation((Placemark) event.getSourceNode());
}
if (isShowingPinAngularViews()) {
chartHasChanged = true;
}
} else if (event.getSourceNode() instanceof Product) {
if (event.getPropertyName().equals("autoGrouping")) {
setUpAngularViews();
chartHasChanged = true;
}
}
if (isActive() && chartHasChanged) {
recreateChart();
}
}
@Override
public void nodeAdded(final ProductNodeEvent event) {
if (!isActive()) {
return;
}
if (event.getSourceNode() instanceof Band) {
Band newBand = (Band) event.getSourceNode();
if (isAngularBand(newBand)) {
addBandToAngularViews((Band) event.getSourceNode());
recreateChart();
}
} else if (event.getSourceNode() instanceof Placemark) {
if (isShowingPinAngularViews()) {
recreateChart();
} else {
updateUIState();
}
}
}
@Override
public void nodeRemoved(final ProductNodeEvent event) {
if (!isActive()) {
return;
}
if (event.getSourceNode() instanceof Band) {
Band band = (Band) event.getSourceNode();
removeBandFromAngularViews(band);
chartHandler.removeBandInformation(band);
recreateChart();
} else if (event.getSourceNode() instanceof Placemark) {
if (isShowingPinAngularViews()) {
recreateChart();
}
}
}
private void addBandToAngularViews(Band band) {
DisplayableAngularview[] allAngularViews = rasterToAngularMap.get(currentView.getRaster());
Product.AutoGrouping autoGrouping = currentProduct.getAutoGrouping();
if (autoGrouping != null) {
final int bandIndex = autoGrouping.indexOf(band.getName());
final DisplayableAngularview angularView;
if (bandIndex != -1) {
angularView = allAngularViews[bandIndex];
} else {
angularView = allAngularViews[allAngularViews.length - 1];
}
angularView.addBand(new AngularBand(band, angularView.isSelected()));
} else {
allAngularViews[0].addBand(new AngularBand(band, true));
}
}
private void removeBandFromAngularViews(Band band) {
DisplayableAngularview[] allAngularViews = rasterToAngularMap.get(currentView.getRaster());
for (DisplayableAngularview displayableAngularView : allAngularViews) {
Band[] angularBands = displayableAngularView.getAngularBands();
for (int j = 0; j < angularBands.length; j++) {
Band angularBand = angularBands[j];
if (angularBand == band) {
displayableAngularView.remove(j);
if (displayableAngularView.getSelectedBands().length == 0) {
displayableAngularView.setSelected(false);
}
return;
}
}
}
}
private boolean isActive() {
return isVisible() && getCurrentProduct() != null;
}
}
private class PinSelectionChangeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
recreateChart();
}
}
}
| 74,560 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
SpectrumAnimationTopComponent.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/ui/SpectrumAnimationTopComponent.java | package gov.nasa.gsfc.seadas.imageanimator.ui;
/*
* Copyright (C) 2014 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* 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/
*/
import com.bc.ceres.glayer.support.ImageLayer;
import com.bc.ceres.glevel.MultiLevelModel;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.image.ImageManager;
import org.esa.snap.core.util.ProductUtils;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.help.HelpAction;
import org.esa.snap.rcp.placemark.PlacemarkUtils;
import org.esa.snap.rcp.statistics.XYPlotMarker;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.rcp.windows.ToolTopComponent;
import org.esa.snap.ui.GridBagUtils;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.product.ProductSceneView;
import org.esa.snap.ui.product.spectrum.*;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.jfree.chart.*;
import org.jfree.chart.annotations.XYTitleAnnotation;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.block.LineBorder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.ui.HorizontalAlignment;
import org.jfree.chart.ui.RectangleAnchor;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.data.Range;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.locationtech.jts.geom.Point;
import org.openide.util.HelpCtx;
import javax.media.jai.PlanarImage;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.*;
//import org.esa.snap.rcp.spectrum.Bundle;
//import org.esa.snap.rcp.spectrum.SpectraExportAction;
/**
* A window which displays spectra at selected pixel positions.
*/
public class SpectrumAnimationTopComponent extends ToolTopComponent {
// public static final String ID = org.esa.snap.rcp.spectrum.SpectrumTopComponent.class.getName();
private static final String SUPPRESS_MESSAGE_KEY = "plugin.spectrum.tip";
private static final String spectrumAnimationString = "Spectrum View Animation";
private static final String spectrumAnimationHelpString = "showSpectrumAnimationWnd";
private final Map<RasterDataNode, DisplayableSpectrum[]> rasterToSpectraMap;
private final Map<RasterDataNode, List<SpectrumBand>> rasterToSpectralBandsMap;
private final ProductNodeListenerAdapter productNodeHandler;
private final PinSelectionChangeListener pinSelectionChangeListener;
// private final PixelPositionListener pixelPositionListener;
private AbstractButton filterButton;
private AbstractButton showSpectrumForCursorButton;
private AbstractButton showSpectraForSelectedPinsButton;
private AbstractButton showSpectraForAllPinsButton;
private AbstractButton showGridButton;
private boolean tipShown;
private ProductSceneView currentView;
private Product currentProduct;
private ChartPanel chartPanel;
private ChartHandler chartHandler;
private boolean domainAxisAdjustmentIsFrozen;
private boolean rangeAxisAdjustmentIsFrozen;
private boolean isCodeInducedAxisChange;
private boolean isUserInducedAutomaticAdjustmentChosen;
public SpectrumAnimationTopComponent() {
productNodeHandler = new ProductNodeHandler();
pinSelectionChangeListener = new PinSelectionChangeListener();
rasterToSpectraMap = new HashMap<>();
rasterToSpectralBandsMap = new HashMap<>();
// pixelPositionListener = new CursorSpectrumPixelPositionListener(this);
initUI();
}
//package local for testing
static DisplayableSpectrum[] createSpectraFromUngroupedBands(SpectrumBand[] ungroupedBands, int symbolIndex, int strokeIndex) {
List<String> knownUnits = new ArrayList<>();
List<DisplayableSpectrum> displayableSpectrumList = new ArrayList<>();
DisplayableSpectrum defaultSpectrum = new DisplayableSpectrum("tbd", -1);
for (SpectrumBand ungroupedBand : ungroupedBands) {
final String unit = ungroupedBand.getOriginalBand().getUnit();
if (StringUtils.isNullOrEmpty(unit)) {
defaultSpectrum.addBand(ungroupedBand);
} else if (knownUnits.contains(unit)) {
displayableSpectrumList.get(knownUnits.indexOf(unit)).addBand(ungroupedBand);
} else {
knownUnits.add(unit);
final DisplayableSpectrum spectrum = new DisplayableSpectrum("Bands measured in " + unit, symbolIndex++);
spectrum.setLineStyle(SpectrumStrokeProvider.getStroke(strokeIndex++));
spectrum.addBand(ungroupedBand);
displayableSpectrumList.add(spectrum);
}
}
if (strokeIndex == 0) {
defaultSpectrum.setName(DisplayableSpectrum.DEFAULT_SPECTRUM_NAME);
} else {
defaultSpectrum.setName(DisplayableSpectrum.REMAINING_BANDS_NAME);
}
defaultSpectrum.setSymbolIndex(symbolIndex);
defaultSpectrum.setLineStyle(SpectrumStrokeProvider.getStroke(strokeIndex));
displayableSpectrumList.add(defaultSpectrum);
return displayableSpectrumList.toArray(new DisplayableSpectrum[0]);
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(spectrumAnimationHelpString);
}
private void setCurrentView(ProductSceneView view) {
ProductSceneView oldView = currentView;
currentView = view;
if (oldView != currentView) {
if (oldView != null) {
oldView.removePropertyChangeListener(ProductSceneView.PROPERTY_NAME_SELECTED_PIN, pinSelectionChangeListener);
}
if (currentView != null) {
currentView.addPropertyChangeListener(ProductSceneView.PROPERTY_NAME_SELECTED_PIN, pinSelectionChangeListener);
setCurrentProduct(currentView.getProduct());
if (currentProduct.getName().contains("SPEX")) {
List<Integer> view_Angles = new ArrayList<Integer>();
for (int i = 0; i < currentProduct.getNumBands(); i++ ) {
int viewAngle = (int) currentProduct.getBandAt(i).getAngularValue();
if (!view_Angles.contains(viewAngle)) {
view_Angles.add(viewAngle);
if (view_Angles.size() == 5) {
break;
}
}
}
String autoGroupingStr = "QC:QC_bitwise:QC_polsample_bitwise:QC_polsample:";
if (view_Angles != null) {
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "I_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "DOLP_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "AOLP_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "i_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "i_stdev_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "i_polsample_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "i_polsample_stdev_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "aolp_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "aolp_stdev_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "dolp_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "dolp_stdev_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "q_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "q_stdev_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "u_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "u_stdev_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "q_over_i_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "q_over_i_stdev_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "u_over_i_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "u_over_i_stdev_" + view_Angles.get(i) + "_*:";
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "qc_" + view_Angles.get(i);
}
for (int i = 0; i < 5; i ++) {
autoGroupingStr += "qc_polsample_" + view_Angles.get(i) + "_*:";
}
}
autoGroupingStr += "I:I_noise:I_noisefree:I_polsample:" +
"I_polsample_noise:I_noisefree_polsample:DOLP:DOLP_noise:DOLP_noisefree:" +
"Q_over_I:Q_over_I_noise:Q_over_I_noisefree:AOLP:AOLP_noise:AOLP_noisefree:" +
"U_over_I:U_over_I_noise:U_over_I_noisefree:scattering_angle:rotation_angle:" +
"sensor_azimuth:sensor_azimuth_angle:sensor_zenith:sensor_zenith_angle:" +
"solar_azimuth:solar_azimuth_angle:solar_zenith:solar_zenith_angle:" +
"obs_per_view:view_time_offsets:number_of_observations";
currentProduct.setAutoGrouping(autoGroupingStr);
// currentProduct.setAutoGrouping("I:I_58_*:I_22_*:I_4_*:I_-22_*:I_-58_*:" +
// "AOLP:AOLP_58_*:AOLP_22_*:AOLP_4_*:AOLP_-22_*:AOLP_-58_*:" +
// "DOLP:DOLP_58_*:DOLP_22_*:DOLP_4_*:DOLP_-22_*:DOLP_-58_*:" +
// "QC:QC_58_*:QC_22_*:QC_4_*:QC_-22_*:QC_-58_*:" +
// "I_57_*:I_20_*:I_0_*:I_-20_*:I_-57_*:" +
// "AOLP_57_*:AOLP_20_*:AOLP_0_*:AOLP_-20_*:AOLP_-57_*:" +
// "DOLP_57_*:DOLP_20_*:DOLP_0_*:DOLP_-20_*:DOLP_-57_*:" +
// "QC_57_*:QC_20_*:QC_0_*:QC_-22_*:QC_-57_*:" +
// "QC_bitwise:QC_polsample_bitwise:QC_polsample:" +
// "I_noise:I_noisefree:I_polsample:I_polsample_noise:I_noisefree_polsample:" +
// "DOLP_noise:DOLP_noisefree:AOLP_noise:AOLP_noisefree:" +
// "Q_over_I:Q_over_I_noise:Q_over_I_noisefree:" +
// "U_over_I:U_over_I_noise:U_over_I_noisefree:scattering_angle:" +
// "sensor_azimuth:sensor_zenith:solar_azimuth:solar_zenith:" +
// "obs_per_view:view_time_offsets");
}
if (!rasterToSpectraMap.containsKey(currentView.getRaster())) {
setUpSpectra();
}
recreateChart();
}
updateUIState();
}
}
private Product getCurrentProduct() {
return currentProduct;
}
private void setCurrentProduct(Product product) {
Product oldProduct = currentProduct;
currentProduct = product;
if (currentProduct != oldProduct) {
if (oldProduct != null) {
oldProduct.removeProductNodeListener(productNodeHandler);
}
if (currentProduct != null) {
currentProduct.addProductNodeListener(productNodeHandler);
}
if (currentProduct == null) {
chartHandler.setEmptyPlot();
}
updateUIState();
}
}
private void updateUIState() {
boolean hasView = currentView != null;
boolean hasProduct = getCurrentProduct() != null;
boolean hasSelectedPins = hasView && currentView.getSelectedPins().length > 0;
boolean hasPins = hasProduct && getCurrentProduct().getPinGroup().getNodeCount() > 0;
filterButton.setEnabled(hasProduct);
// showSpectrumForCursorButton.setEnabled(hasView);
showSpectrumForCursorButton.setVisible(false);
// showSpectraForSelectedPinsButton.setEnabled(hasSelectedPins);
showSpectraForSelectedPinsButton.setVisible(false);
showSpectraForAllPinsButton.setEnabled(hasPins);
showGridButton.setEnabled(hasView);
chartPanel.setEnabled(hasProduct); // todo - hasSpectraGraphs
showGridButton.setSelected(hasView);
chartHandler.setGridVisible(showGridButton.isSelected());
}
void setPrepareForUpdateMessage() {
chartHandler.setCollectingSpectralInformationMessage();
}
void updateData(int pixelX, int pixelY, int level, boolean pixelPosInRasterBounds) {
chartHandler.setPosition(pixelX, pixelY, level, pixelPosInRasterBounds);
chartHandler.updateData();
}
void updateChart(boolean adjustAxes) {
chartHandler.setAutomaticRangeAdjustments(adjustAxes);
updateChart();
}
void updateChart() {
maybeShowTip();
chartHandler.updateChart();
chartPanel.repaint();
}
private void maybeShowTip() {
if (!tipShown) {
final String message = "<html>Tip: If you press the SHIFT key while moving the mouse cursor over<br/>" +
"an image, " + SnapApp.getDefault().getInstanceName() + " adjusts the diagram axes " +
"to the local values at the<br/>" +
"current pixel position, if you release the SHIFT key again, then the<br/>" +
"min/max are accumulated again.</html>";
Dialogs.showInformation("Spectrum Tip", message, SUPPRESS_MESSAGE_KEY);
tipShown = true;
}
}
private SpectrumBand[] getAvailableSpectralBands(RasterDataNode currentRaster) {
if (!rasterToSpectralBandsMap.containsKey(currentRaster)) {
rasterToSpectralBandsMap.put(currentRaster, new ArrayList<>());
}
List<SpectrumBand> spectrumBands = rasterToSpectralBandsMap.get(currentRaster);
Band[] bands = currentProduct.getBands();
for (Band band : bands) {
if (isSpectralBand(band) && !band.isFlagBand()) {
boolean isAlreadyIncluded = false;
for (SpectrumBand spectrumBand : spectrumBands) {
if (spectrumBand.getOriginalBand() == band) {
isAlreadyIncluded = true;
break;
}
}
if (!isAlreadyIncluded) {
spectrumBands.add(new SpectrumBand(band, true));
}
}
}
return spectrumBands.toArray(new SpectrumBand[spectrumBands.size()]);
}
private boolean isSpectralBand(Band band) {
return band.getSpectralWavelength() > 0.0;
}
private void initUI() {
final JFreeChart chart = ChartFactory.createXYLineChart(spectrumAnimationString,
"Wavelength (nm)", "", null, PlotOrientation.VERTICAL,
true, true, false);
chart.getXYPlot().getRangeAxis().addChangeListener(axisChangeEvent -> {
if (!isCodeInducedAxisChange) {
rangeAxisAdjustmentIsFrozen = !((ValueAxis) axisChangeEvent.getAxis()).isAutoRange();
}
});
chart.getXYPlot().getDomainAxis().addChangeListener(axisChangeEvent -> {
if (!isCodeInducedAxisChange) {
domainAxisAdjustmentIsFrozen = !((ValueAxis) axisChangeEvent.getAxis()).isAutoRange();
}
});
chart.getXYPlot().getRangeAxis().setAutoRange(false);
rangeAxisAdjustmentIsFrozen = false;
chart.getXYPlot().getDomainAxis().setAutoRange(false);
domainAxisAdjustmentIsFrozen = false;
chartPanel = new ChartPanel(chart);
chartHandler = new ChartHandler(chart);
final XYPlotMarker plotMarker = new XYPlotMarker(chartPanel, new XYPlotMarker.Listener() {
@Override
public void pointSelected(XYDataset xyDataset, int seriesIndex, Point2D dataPoint) {
//do nothing
}
@Override
public void pointDeselected() {
//do nothing
}
});
filterButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Filter24.gif"), false);
filterButton.setName("filterButton");
filterButton.setEnabled(false);
filterButton.addActionListener(e -> {
selectSpectralBands();
recreateChart();
});
showSpectrumForCursorButton = ToolButtonFactory.createButton(
UIUtils.loadImageIcon("icons/CursorSpectrum24.gif"), true);
showSpectrumForCursorButton.addActionListener(e -> recreateChart());
showSpectrumForCursorButton.setName("showSpectrumForCursorButton");
showSpectrumForCursorButton.setSelected(true);
showSpectrumForCursorButton.setToolTipText("Show spectrum at cursor position.");
showSpectraForSelectedPinsButton = ToolButtonFactory.createButton(
UIUtils.loadImageIcon("icons/SelectedPinSpectra24.gif"), true);
showSpectraForSelectedPinsButton.addActionListener(e -> {
if (isShowingSpectraForAllPins()) {
showSpectraForAllPinsButton.setSelected(false);
} else if (!isShowingSpectraForSelectedPins()) {
plotMarker.setInvisible();
}
animateChart();
recreateChart();
});
showSpectraForSelectedPinsButton.setName("showSpectraForSelectedPinsButton");
showSpectraForSelectedPinsButton.setToolTipText("Show spectra for selected pins.");
showSpectraForAllPinsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/PinSpectra24.gif"),
true);
showSpectraForAllPinsButton.addActionListener(e -> {
if (isShowingSpectraForSelectedPins()) {
showSpectraForSelectedPinsButton.setSelected(false);
} else if (!isShowingSpectraForAllPins()) {
plotMarker.setInvisible();
}
animateChart();
recreateChart();
});
showSpectraForAllPinsButton.setName("showSpectraForAllPinsButton");
showSpectraForAllPinsButton.setToolTipText("Animate Spectrum View for all pins.");
showGridButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/SpectrumGrid24.gif"), true);
showGridButton.addActionListener(e -> chartHandler.setGridVisible(showGridButton.isSelected()));
showGridButton.setName("showGridButton");
showGridButton.setToolTipText("Show diagram grid.");
// AbstractButton exportSpectraButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Export24.gif"),
// false);
// exportSpectraButton.addActionListener(new SpectraExportAction(this));
// exportSpectraButton.setToolTipText("Export spectra to text file.");
// exportSpectraButton.setName("exportSpectraButton");
AbstractButton helpButton = ToolButtonFactory.createButton(new HelpAction(this), false);
helpButton.setName("helpButton");
helpButton.setToolTipText("Help.");
final JPanel buttonPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.NONE;
gbc.insets.top = 2;
gbc.gridy = 0;
buttonPane.add(filterButton, gbc);
gbc.gridy++;
buttonPane.add(showSpectrumForCursorButton, gbc);
gbc.gridy++;
buttonPane.add(showSpectraForSelectedPinsButton, gbc);
gbc.gridy++;
buttonPane.add(showSpectraForAllPinsButton, gbc);
gbc.gridy++;
buttonPane.add(showGridButton, gbc);
// gbc.gridy++;
// buttonPane.add(exportSpectraButton, gbc);
gbc.gridy++;
gbc.insets.bottom = 0;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1.0;
gbc.gridwidth = 2;
buttonPane.add(new JLabel(" "), gbc); // filler
gbc.fill = GridBagConstraints.NONE;
gbc.weighty = 0.0;
gbc.gridy = 10;
gbc.anchor = GridBagConstraints.EAST;
buttonPane.add(helpButton, gbc);
chartPanel.setPreferredSize(new Dimension(1000, 500));
chartPanel.setBackground(Color.white);
chartPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createBevelBorder(BevelBorder.LOWERED),
BorderFactory.createEmptyBorder(2, 2, 2, 2)));
chartPanel.addChartMouseListener(plotMarker);
JPanel mainPane = new JPanel(new BorderLayout(4, 4));
mainPane.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
mainPane.add(BorderLayout.CENTER, chartPanel);
mainPane.add(BorderLayout.EAST, buttonPane);
// mainPane.setPreferredSize(new Dimension(320, 200));
SnapApp.getDefault().getProductManager().addListener(new ProductManager.Listener() {
@Override
public void productAdded(ProductManager.Event event) {
// ignored
}
@Override
public void productRemoved(ProductManager.Event event) {
final Product product = event.getProduct();
if (getCurrentProduct() == product) {
chartPanel.getChart().getXYPlot().setDataset(null);
setCurrentView(null);
setCurrentProduct(null);
}
if (currentView != null) {
final RasterDataNode currentRaster = currentView.getRaster();
if (rasterToSpectraMap.containsKey(currentRaster)) {
rasterToSpectraMap.remove(currentRaster);
}
if (rasterToSpectralBandsMap.containsKey(currentRaster)) {
rasterToSpectralBandsMap.remove(currentRaster);
}
}
PlacemarkGroup pinGroup = product.getPinGroup();
for (int i = 0; i < pinGroup.getNodeCount(); i++) {
chartHandler.removePinInformation(pinGroup.get(i));
}
}
});
final ProductSceneView view = getSelectedProductSceneView();
if (view != null) {
productSceneViewSelected(view);
}
setDisplayName(spectrumAnimationString);
setLayout(new BorderLayout());
add(mainPane, BorderLayout.CENTER);
updateUIState();
}
private void selectSpectralBands() {
final RasterDataNode currentRaster = currentView.getRaster();
final DisplayableSpectrum[] allSpectra = rasterToSpectraMap.get(currentRaster);
final SpectrumChooser spectrumChooser = new SpectrumChooser(SwingUtilities.getWindowAncestor(this), allSpectra);
if (spectrumChooser.show() == ModalDialog.ID_OK) {
final DisplayableSpectrum[] spectra = spectrumChooser.getSpectra();
rasterToSpectraMap.put(currentRaster, spectra);
}
}
boolean isShowingCursorSpectrum() {
return showSpectrumForCursorButton.isSelected();
}
private boolean isShowingPinSpectra() {
return isShowingSpectraForSelectedPins() || isShowingSpectraForAllPins();
}
private boolean isShowingSpectraForAllPins() {
return showSpectraForAllPinsButton.isSelected();
}
private void recreateChart() {
chartHandler.updateData();
chartHandler.updateChart();
chartPanel.repaint();
updateUIState();
}
private void animateChart() {
List<DisplayableSpectrum> spectra = getSelectedSpectra();
if (!isShowingSpectraForAllPins()) {
showSpectraForAllPinsButton.setSelected(true);
}
chartHandler.updateData();
chartHandler.updateInitialChart();
ImageIcon[] images = new ImageIcon[spectra.size()];
for (int i = 0; i < spectra.size(); i++) {
List<DisplayableSpectrum> singleSpectrum = Collections.singletonList(spectra.get(i));
chartHandler.updateAnimationData(singleSpectrum);
chartHandler.updateAnimationChart(singleSpectrum);
// chartPanel.repaint();
BufferedImage chartImage = chartPanel.getChart().createBufferedImage(1024, 768);
images[i] = new ImageIcon(chartImage);
System.out.println("plot SpectrumViews i= " +i);
}
AnimationWithSpeedControl.animate(images);
updateUIState();
}
Placemark[] getDisplayedPins() {
if (isShowingSpectraForSelectedPins() && currentView != null) {
return currentView.getSelectedPins();
} else if (isShowingSpectraForAllPins() && getCurrentProduct() != null) {
ProductNodeGroup<Placemark> pinGroup = getCurrentProduct().getPinGroup();
return pinGroup.toArray(new Placemark[pinGroup.getNodeCount()]);
} else {
return new Placemark[0];
}
}
private void setUpSpectra() {
if (currentView == null) {
return;
}
DisplayableSpectrum[] spectra;
final RasterDataNode raster = currentView.getRaster();
final SpectrumBand[] availableSpectralBands = getAvailableSpectralBands(raster);
if (availableSpectralBands.length == 0) {
spectra = new DisplayableSpectrum[]{};
} else {
final Product.AutoGrouping autoGrouping = currentProduct.getAutoGrouping();
if (autoGrouping != null) {
final int selectedSpectrumIndex = autoGrouping.indexOf(raster.getName());
DisplayableSpectrum[] autoGroupingSpectra = new DisplayableSpectrum[autoGrouping.size()];
final Iterator<String[]> iterator = autoGrouping.iterator();
int i = 0;
while (iterator.hasNext()) {
final String[] autoGroupingNameAsArray = iterator.next();
StringBuilder spectrumNameBuilder = new StringBuilder(autoGroupingNameAsArray[0]);
if (autoGroupingNameAsArray.length > 1) {
for (int j = 1; j < autoGroupingNameAsArray.length; j++) {
String autoGroupingNamePart = autoGroupingNameAsArray[j];
spectrumNameBuilder.append("_").append(autoGroupingNamePart);
}
}
final String spectrumName = spectrumNameBuilder.toString();
int symbolIndex = SpectrumShapeProvider.getValidIndex(i, false);
DisplayableSpectrum spectrum = new DisplayableSpectrum(spectrumName, symbolIndex);
spectrum.setSelected(i == selectedSpectrumIndex);
spectrum.setLineStyle(SpectrumStrokeProvider.getStroke(i));
autoGroupingSpectra[i++] = spectrum;
}
List<SpectrumBand> ungroupedBandsList = new ArrayList<>();
for (SpectrumBand availableSpectralBand : availableSpectralBands) {
final String bandName = availableSpectralBand.getName();
if (currentProduct.getName().contains("SPEX")) {
availableSpectralBand.setSelected(false);
}
final int spectrumIndex = autoGrouping.indexOf(bandName);
if (spectrumIndex != -1) {
autoGroupingSpectra[spectrumIndex].addBand(availableSpectralBand);
} else {
ungroupedBandsList.add(availableSpectralBand);
}
}
if (ungroupedBandsList.size() == 0) {
spectra = autoGroupingSpectra;
} else {
final DisplayableSpectrum[] spectraFromUngroupedBands =
createSpectraFromUngroupedBands(ungroupedBandsList.toArray(new SpectrumBand[0]),
SpectrumShapeProvider.getValidIndex(i, false), i);
spectra = new DisplayableSpectrum[autoGroupingSpectra.length + spectraFromUngroupedBands.length];
System.arraycopy(autoGroupingSpectra, 0, spectra, 0, autoGroupingSpectra.length);
System.arraycopy(spectraFromUngroupedBands, 0, spectra, autoGroupingSpectra.length, spectraFromUngroupedBands.length);
}
} else {
spectra = createSpectraFromUngroupedBands(availableSpectralBands, 1, 0);
}
}
rasterToSpectraMap.put(raster, spectra);
}
private DisplayableSpectrum[] getAllSpectra() {
if (currentView == null || !rasterToSpectraMap.containsKey(currentView.getRaster())) {
return new DisplayableSpectrum[0];
}
return rasterToSpectraMap.get(currentView.getRaster());
}
private boolean isShowingSpectraForSelectedPins() {
return showSpectraForSelectedPinsButton.isSelected();
}
List<DisplayableSpectrum> getSelectedSpectra() {
List<DisplayableSpectrum> selectedSpectra = new ArrayList<>();
if (currentView != null) {
final RasterDataNode currentRaster = currentView.getRaster();
if (currentProduct != null && rasterToSpectraMap.containsKey(currentRaster)) {
DisplayableSpectrum[] allSpectra = rasterToSpectraMap.get(currentRaster);
for (DisplayableSpectrum displayableSpectrum : allSpectra) {
if (displayableSpectrum.isSelected()) {
selectedSpectra.add(displayableSpectrum);
}
}
}
}
return selectedSpectra;
}
private void updateSpectraUnits() {
for (DisplayableSpectrum spectrum : getAllSpectra()) {
spectrum.updateUnit();
}
}
void removeCursorSpectraFromDataset() {
chartHandler.removeCursorSpectraFromDataset();
}
@Override
protected void productSceneViewSelected(ProductSceneView view) {
// view.addPixelPositionListener(pixelPositionListener);
setCurrentView(view);
}
@Override
protected void productSceneViewDeselected(ProductSceneView view) {
// view.removePixelPositionListener(pixelPositionListener);
setCurrentView(null);
}
@Override
protected void componentOpened() {
final ProductSceneView selectedProductSceneView = getSelectedProductSceneView();
if (selectedProductSceneView != null) {
// selectedProductSceneView.addPixelPositionListener(pixelPositionListener);
setCurrentView(selectedProductSceneView);
}
}
@Override
protected void componentClosed() {
if (currentView != null) {
// currentView.removePixelPositionListener(pixelPositionListener);
}
}
public boolean showsValidCursorSpectra() {
return chartHandler.showsValidCursorSpectra();
}
private class ChartHandler {
private static final String MESSAGE_NO_SPECTRAL_BANDS = "No spectral bands available"; /*I18N*/
private static final String MESSAGE_NO_PRODUCT_SELECTED = "No product selected";
private static final String MESSAGE_NO_SPECTRA_SELECTED = "No spectra selected";
private static final String MESSAGE_COLLECTING_SPECTRAL_INFORMATION = "Collecting spectral information...";
private final JFreeChart chart;
private final ChartUpdater chartUpdater;
private ChartHandler(JFreeChart chart) {
chartUpdater = new ChartUpdater();
this.chart = chart;
setLegend(chart);
setAutomaticRangeAdjustments(false);
final XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
renderer.setDefaultLinesVisible(true);
renderer.setDefaultShapesFilled(false);
setPlotMessage(MESSAGE_NO_PRODUCT_SELECTED);
}
private void setAutomaticRangeAdjustments(boolean userInducesAutomaticAdjustment) {
final XYPlot plot = chart.getXYPlot();
boolean adjustmentHasChanged = false;
if (userInducesAutomaticAdjustment) {
if (!isUserInducedAutomaticAdjustmentChosen) {
isUserInducedAutomaticAdjustmentChosen = true;
if (!isAutomaticDomainAdjustmentSet()) {
plot.getDomainAxis().setAutoRange(true);
domainAxisAdjustmentIsFrozen = false;
adjustmentHasChanged = true;
}
if (!isAutomaticRangeAdjustmentSet()) {
plot.getRangeAxis().setAutoRange(true);
rangeAxisAdjustmentIsFrozen = false;
adjustmentHasChanged = true;
}
}
} else {
if (isUserInducedAutomaticAdjustmentChosen) {
isUserInducedAutomaticAdjustmentChosen = false;
if (isAutomaticDomainAdjustmentSet()) {
plot.getDomainAxis().setAutoRange(false);
domainAxisAdjustmentIsFrozen = false;
adjustmentHasChanged = true;
}
if (isAutomaticRangeAdjustmentSet()) {
plot.getRangeAxis().setAutoRange(false);
rangeAxisAdjustmentIsFrozen = false;
adjustmentHasChanged = true;
}
}
}
if (adjustmentHasChanged) {
chartUpdater.invalidatePlotBounds();
}
}
private boolean isAutomaticDomainAdjustmentSet() {
return chart.getXYPlot().getDomainAxis().isAutoRange();
}
private boolean isAutomaticRangeAdjustmentSet() {
return chart.getXYPlot().getRangeAxis().isAutoRange();
}
private void setLegend(JFreeChart chart) {
chart.removeLegend();
final LegendTitle legend = new LegendTitle(new SpectrumLegendItemSource());
legend.setPosition(RectangleEdge.BOTTOM);
LineBorder border = new LineBorder(Color.BLACK, new BasicStroke(), new RectangleInsets(2, 2, 2, 2));
legend.setFrame(border);
chart.addLegend(legend);
}
private void setPosition(int pixelX, int pixelY, int level, boolean pixelPosInRasterBounds) {
chartUpdater.setPosition(pixelX, pixelY, level, pixelPosInRasterBounds);
}
private void updateChart() {
if (chartUpdater.isDatasetEmpty()) {
setEmptyPlot();
return;
}
List<DisplayableSpectrum> spectra = getSelectedSpectra();
chartUpdater.updateChart(chart, spectra);
chart.getXYPlot().clearAnnotations();
}
private void updateInitialChart() {
if (chartUpdater.isDatasetEmpty()) {
setEmptyPlot();
return;
}
// List<DisplayableAngularview> angularViews = getSelectedAngularViews();
// chartUpdater.updateChart(chart, angularViews);
chartUpdater.updatePlotBounds(chartUpdater.dataset.getDomainBounds(true),
chart.getXYPlot().getDomainAxis(), 0);
chartUpdater.updatePlotBounds(chartUpdater.dataset.getRangeBounds(true),
chart.getXYPlot().getRangeAxis(), 1);
// chart.getXYPlot().clearAnnotations();
}
private void updateAnimationChart(List<DisplayableSpectrum> singleSpectrum) {
if (chartUpdater.isDatasetEmpty()) {
setEmptyPlot();
return;
}
// List<DisplayableSpectrum> spectra = getSelectedSpectra();
chartUpdater.updateAnimationChart(chart, singleSpectrum);
chart.getXYPlot().clearAnnotations();
}
private void updateData() {
List<DisplayableSpectrum> spectra = getSelectedSpectra();
chartUpdater.updateData(chart, spectra);
}
private void updateAnimationData(List<DisplayableSpectrum> singleSpectrum) {
// List<DisplayableSpectrum> spectra = getSelectedSpectra();
chartUpdater.updateData(chart, singleSpectrum);
}
private void setEmptyPlot() {
chart.getXYPlot().setDataset(null);
if (getCurrentProduct() == null) {
setPlotMessage(MESSAGE_NO_PRODUCT_SELECTED);
} else if (!chartUpdater.showsValidCursorSpectra()) {
return;
} else if (getAllSpectra().length == 0) {
setPlotMessage(MESSAGE_NO_SPECTRA_SELECTED);
} else {
setPlotMessage(MESSAGE_NO_SPECTRAL_BANDS);
}
}
private void setGridVisible(boolean visible) {
chart.getXYPlot().setDomainGridlinesVisible(visible);
chart.getXYPlot().setRangeGridlinesVisible(visible);
}
private void removePinInformation(Placemark pin) {
chartUpdater.removePinInformation(pin);
}
private void removeBandInformation(Band band) {
chartUpdater.removeBandinformation(band);
}
private void setPlotMessage(String messageText) {
chart.getXYPlot().clearAnnotations();
TextTitle tt = new TextTitle(messageText);
tt.setTextAlignment(HorizontalAlignment.RIGHT);
tt.setFont(chart.getLegend().getItemFont());
tt.setBackgroundPaint(new Color(200, 200, 255, 50));
tt.setFrame(new BlockBorder(Color.white));
tt.setPosition(RectangleEdge.BOTTOM);
XYTitleAnnotation message = new XYTitleAnnotation(0.5, 0.5, tt, RectangleAnchor.CENTER);
chart.getXYPlot().addAnnotation(message);
}
public boolean showsValidCursorSpectra() {
return chartUpdater.showsValidCursorSpectra();
}
public void removeCursorSpectraFromDataset() {
chartUpdater.removeCursorSpectraFromDataset();
}
public void setCollectingSpectralInformationMessage() {
setPlotMessage(MESSAGE_COLLECTING_SPECTRAL_INFORMATION);
}
}
private class ChartUpdater {
private final static int domain_axis_index = 0;
private final static int range_axis_index = 1;
private final static double relativePlotInset = 0.05;
private final Map<Placemark, Map<Band, Double>> pinToEnergies;
private boolean showsValidCursorSpectra;
private boolean pixelPosInRasterBounds;
private int rasterPixelX;
private int rasterPixelY;
private int rasterLevel;
private final Range[] plotBounds;
private XYSeriesCollection dataset;
private Point2D modelP;
private ChartUpdater() {
pinToEnergies = new HashMap<>();
plotBounds = new Range[2];
invalidatePlotBounds();
}
void invalidatePlotBounds() {
plotBounds[domain_axis_index] = null;
plotBounds[range_axis_index] = null;
}
private void setPosition(int pixelX, int pixelY, int level, boolean pixelPosInRasterBounds) {
this.rasterPixelX = pixelX;
this.rasterPixelY = pixelY;
this.rasterLevel = level;
this.pixelPosInRasterBounds = pixelPosInRasterBounds;
final AffineTransform i2m = currentView.getBaseImageLayer().getImageToModelTransform(level);
modelP = i2m.transform(new Point2D.Double(pixelX + 0.5, pixelY + 0.5), new Point2D.Double());
}
private void updateData(JFreeChart chart, List<DisplayableSpectrum> spectra) {
dataset = new XYSeriesCollection();
if (rasterLevel >= 0) {
fillDatasetWithPinSeries(spectra, dataset, chart);
fillDatasetWithCursorSeries(spectra, dataset, chart);
}
}
private void updateChart(JFreeChart chart, List<DisplayableSpectrum> spectra) {
final XYPlot plot = chart.getXYPlot();
// if (!chartHandler.isAutomaticDomainAdjustmentSet() && !domainAxisAdjustmentIsFrozen) {
// isCodeInducedAxisChange = true;
// updatePlotBounds(dataset.getDomainBounds(true), plot.getDomainAxis(), domain_axis_index);
// isCodeInducedAxisChange = false;
// }
// if (!chartHandler.isAutomaticRangeAdjustmentSet() && !rangeAxisAdjustmentIsFrozen) {
// isCodeInducedAxisChange = true;
// updatePlotBounds(dataset.getRangeBounds(true), plot.getRangeAxis(), range_axis_index);
// isCodeInducedAxisChange = false;
// }
plot.setDataset(dataset);
setPlotUnit(spectra, plot);
}
private void updateAnimationChart(JFreeChart chart, List<DisplayableSpectrum> spectra) {
final XYPlot plot = chart.getXYPlot();
// if (!chartHandler.isAutomaticDomainAdjustmentSet() && !domainAxisAdjustmentIsFrozen) {
// isCodeInducedAxisChange = true;
// updatePlotBounds(dataset.getDomainBounds(true), plot.getDomainAxis(), domain_axis_index);
// isCodeInducedAxisChange = false;
// }
// if (!chartHandler.isAutomaticRangeAdjustmentSet() && !rangeAxisAdjustmentIsFrozen) {
// isCodeInducedAxisChange = true;
// updatePlotBounds(dataset.getRangeBounds(true), plot.getRangeAxis(), range_axis_index);
// isCodeInducedAxisChange = false;
// }
plot.setDataset(dataset);
setPlotUnit(spectra, plot);
}
private void setPlotUnit(List<DisplayableSpectrum> spectra, XYPlot plot) {
String unitToBeDisplayed = "";
if (spectra.size() > 0) {
unitToBeDisplayed = spectra.get(0).getUnit();
int i = 1;
while (i < spectra.size() && !unitToBeDisplayed.equals(DisplayableSpectrum.MIXED_UNITS)) {
DisplayableSpectrum displayableSpectrum = spectra.get(i++);
if (displayableSpectrum.hasSelectedBands() && !unitToBeDisplayed.equals(displayableSpectrum.getUnit())) {
unitToBeDisplayed = DisplayableSpectrum.MIXED_UNITS;
}
}
}
isCodeInducedAxisChange = true;
plot.getRangeAxis().setLabel(unitToBeDisplayed);
isCodeInducedAxisChange = false;
}
private void updatePlotBounds(Range newBounds, ValueAxis axis, int index) {
if (newBounds != null) {
final Range axisBounds = axis.getRange();
final Range oldBounds = this.plotBounds[index];
this.plotBounds[index] = getNewRange(newBounds, this.plotBounds[index], axisBounds);
if (oldBounds != this.plotBounds[index]) {
axis.setRange(getNewPlotBounds(this.plotBounds[index]));
}
}
}
private Range getNewRange(Range newBounds, Range currentBounds, Range plotBounds) {
if (currentBounds == null) {
currentBounds = newBounds;
} else {
if (plotBounds.getLowerBound() > 0 && newBounds.getLowerBound() < currentBounds.getLowerBound() ||
newBounds.getUpperBound() > currentBounds.getUpperBound()) {
currentBounds = new Range(Math.min(currentBounds.getLowerBound(), newBounds.getLowerBound()),
Math.max(currentBounds.getUpperBound(), newBounds.getUpperBound()));
}
}
return currentBounds;
}
private Range getNewPlotBounds(Range bounds) {
double range = bounds.getLength();
double delta = range * relativePlotInset;
return new Range(Math.max(0, bounds.getLowerBound() - delta),
bounds.getUpperBound() + delta);
}
private void fillDatasetWithCursorSeries(List<DisplayableSpectrum> spectra, XYSeriesCollection dataset, JFreeChart chart) {
showsValidCursorSpectra = false;
if (modelP == null) {
return;
}
if (isShowingCursorSpectrum() && currentView != null) {
for (DisplayableSpectrum spectrum : spectra) {
XYSeries series = new XYSeries(spectrum.getName());
final Band[] spectralBands = spectrum.getSelectedBands();
if (!currentProduct.isMultiSize()) {
for (Band spectralBand : spectralBands) {
final float wavelength = spectralBand.getSpectralWavelength();
if (pixelPosInRasterBounds && isPixelValid(spectralBand, rasterPixelX, rasterPixelY, rasterLevel)) {
addToSeries(spectralBand, rasterPixelX, rasterPixelY, rasterLevel, series, wavelength);
showsValidCursorSpectra = true;
}
}
} else {
for (Band spectralBand : spectralBands) {
final float wavelength = spectralBand.getSpectralWavelength();
final AffineTransform i2m = spectralBand.getImageToModelTransform();
if (i2m.equals(currentView.getRaster().getImageToModelTransform())) {
if (pixelPosInRasterBounds && isPixelValid(spectralBand, rasterPixelX, rasterPixelY, rasterLevel)) {
addToSeries(spectralBand, rasterPixelX, rasterPixelY, rasterLevel, series, wavelength);
showsValidCursorSpectra = true;
}
} else {
//todo [Multisize_products] use scenerastertransform here
final PixelPos rasterPos = new PixelPos();
final MultiLevelModel multiLevelModel = spectralBand.getMultiLevelModel();
int level = getLevel(multiLevelModel);
multiLevelModel.getModelToImageTransform(level).transform(modelP, rasterPos);
final int rasterX = (int) rasterPos.getX();
final int rasterY = (int) rasterPos.getY();
if (coordinatesAreInRasterBounds(spectralBand, rasterX, rasterY, level) &&
isPixelValid(spectralBand, rasterX, rasterY, level)) {
addToSeries(spectralBand, rasterX, rasterY, level, series, wavelength);
showsValidCursorSpectra = true;
}
}
}
}
updateRenderer(dataset.getSeriesCount(), Color.BLACK, spectrum, chart);
dataset.addSeries(series);
}
}
}
private void addToSeries(Band spectralBand, int x, int y, int level, XYSeries series, double wavelength) {
final double energy = ProductUtils.getGeophysicalSampleAsDouble(spectralBand, x, y, level);
if (energy != spectralBand.getGeophysicalNoDataValue()) {
series.add(wavelength, energy);
}
}
//todo code duplication with pixelinfoviewmodelupdater - move to single class - tf 20151119
private boolean coordinatesAreInRasterBounds(RasterDataNode raster, int x, int y, int level) {
final RenderedImage levelImage = raster.getSourceImage().getImage(level);
return x >= 0 && y >= 0 && x < levelImage.getWidth() && y < levelImage.getHeight();
}
private void fillDatasetWithPinSeries(List<DisplayableSpectrum> spectra, XYSeriesCollection dataset, JFreeChart chart) {
Placemark[] pins = getDisplayedPins();
for (Placemark pin : pins) {
List<XYSeries> pinSeries = createXYSeriesFromPin(pin, dataset.getSeriesCount(), spectra, chart);
pinSeries.forEach(dataset::addSeries);
}
}
private List<XYSeries> createXYSeriesFromPin(Placemark pin, int seriesIndex, List<DisplayableSpectrum> spectra, JFreeChart chart) {
List<XYSeries> pinSeries = new ArrayList<>();
Color pinColor = PlacemarkUtils.getPlacemarkColor(pin, currentView);
for (DisplayableSpectrum spectrum : spectra) {
XYSeries series = new XYSeries(spectrum.getName() + "_" + pin.getLabel());
final Band[] spectralBands = spectrum.getSelectedBands();
Map<Band, Double> bandToEnergy;
if (pinToEnergies.containsKey(pin)) {
bandToEnergy = pinToEnergies.get(pin);
} else {
bandToEnergy = new HashMap<>();
pinToEnergies.put(pin, bandToEnergy);
}
for (Band spectralBand : spectralBands) {
double energy;
if (bandToEnergy.containsKey(spectralBand)) {
energy = bandToEnergy.get(spectralBand);
} else {
energy = readEnergy(pin, spectralBand);
bandToEnergy.put(spectralBand, energy);
}
final float wavelength = spectralBand.getSpectralWavelength();
if (energy != spectralBand.getGeophysicalNoDataValue()) {
series.add(wavelength, energy);
}
}
updateRenderer(seriesIndex++, pinColor, spectrum, chart);
pinSeries.add(series);
}
return pinSeries;
}
private void updateRenderer(int seriesIndex, Color seriesColor, DisplayableSpectrum spectrum, JFreeChart chart) {
final XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
final Stroke lineStyle = spectrum.getLineStyle();
renderer.setSeriesStroke(seriesIndex, lineStyle);
Shape symbol = spectrum.getScaledShape();
renderer.setSeriesShape(seriesIndex, symbol);
renderer.setSeriesShapesVisible(seriesIndex, true);
renderer.setSeriesPaint(seriesIndex, seriesColor);
}
private double readEnergy(Placemark pin, Band spectralBand) {
//todo [Multisize_products] use scenerastertransform here
final Object pinGeometry = pin.getFeature().getDefaultGeometry();
if (pinGeometry == null || !(pinGeometry instanceof Point)) {
return spectralBand.getGeophysicalNoDataValue();
}
final Point2D.Double modelPoint = new Point2D.Double(((Point) pinGeometry).getCoordinate().x,
((Point) pinGeometry).getCoordinate().y);
final MultiLevelModel multiLevelModel = spectralBand.getMultiLevelModel();
int level = getLevel(multiLevelModel);
final AffineTransform m2iTransform = multiLevelModel.getModelToImageTransform(level);
final PixelPos pinLevelRasterPos = new PixelPos();
m2iTransform.transform(modelPoint, pinLevelRasterPos);
int pinLevelRasterX = (int) Math.floor(pinLevelRasterPos.getX());
int pinLevelRasterY = (int) Math.floor(pinLevelRasterPos.getY());
if (coordinatesAreInRasterBounds(spectralBand, pinLevelRasterX, pinLevelRasterY, level) &&
isPixelValid(spectralBand, pinLevelRasterX, pinLevelRasterY, level)) {
return ProductUtils.getGeophysicalSampleAsDouble(spectralBand, pinLevelRasterX, pinLevelRasterY, level);
}
return spectralBand.getGeophysicalNoDataValue();
}
private void removePinInformation(Placemark pin) {
pinToEnergies.remove(pin);
}
private void removeBandinformation(Band band) {
for (Placemark pin : pinToEnergies.keySet()) {
Map<Band, Double> bandToEnergiesMap = pinToEnergies.get(pin);
if (bandToEnergiesMap.containsKey(band)) {
bandToEnergiesMap.remove(band);
}
}
}
public boolean showsValidCursorSpectra() {
return showsValidCursorSpectra;
}
void removeCursorSpectraFromDataset() {
modelP = null;
if (showsValidCursorSpectra) {
int numberOfSelectedSpectra = getSelectedSpectra().size();
int numberOfPins = getDisplayedPins().length;
int numberOfDisplayedGraphs = numberOfPins * numberOfSelectedSpectra;
while (dataset.getSeriesCount() > numberOfDisplayedGraphs) {
dataset.removeSeries(dataset.getSeriesCount() - 1);
}
}
}
public boolean isDatasetEmpty() {
return dataset == null || dataset.getSeriesCount() == 0;
}
//todo code duplication with pixelinfoviewmodelupdater - move to single class - tf 20151119
private boolean isPixelValid(RasterDataNode raster, int pixelX, int pixelY, int level) {
if (raster.isValidMaskUsed()) {
PlanarImage image = ImageManager.getInstance().getValidMaskImage(raster, level);
Raster data = getRasterTile(image, pixelX, pixelY);
return data.getSample(pixelX, pixelY, 0) != 0;
} else {
return true;
}
}
//todo code duplication with pixelinfoviewmodelupdater - move to single class - tf 20151119
private Raster getRasterTile(PlanarImage image, int pixelX, int pixelY) {
final int tileX = image.XToTileX(pixelX);
final int tileY = image.YToTileY(pixelY);
return image.getTile(tileX, tileY);
}
//todo code duplication with pixelinfoviewmodelupdater - move to single class - tf 20151119
private int getLevel(MultiLevelModel multiLevelModel) {
if (rasterLevel < multiLevelModel.getLevelCount()) {
return rasterLevel;
}
return ImageLayer.getLevel(multiLevelModel, currentView.getViewport());
}
}
private class SpectrumLegendItemSource implements LegendItemSource {
@Override
public LegendItemCollection getLegendItems() {
LegendItemCollection itemCollection = new LegendItemCollection();
final Placemark[] displayedPins = getDisplayedPins();
final List<DisplayableSpectrum> spectra = getSelectedSpectra();
for (Placemark pin : displayedPins) {
Paint pinPaint = PlacemarkUtils.getPlacemarkColor(pin, currentView);
spectra.stream().filter(DisplayableSpectrum::hasSelectedBands).forEach(spectrum -> {
String legendLabel = pin.getLabel() + "_" + spectrum.getName();
LegendItem item = createLegendItem(spectrum, pinPaint, legendLabel);
itemCollection.add(item);
});
}
if (isShowingCursorSpectrum() && showsValidCursorSpectra()) {
spectra.stream().filter(DisplayableSpectrum::hasSelectedBands).forEach(spectrum -> {
Paint defaultPaint = Color.BLACK;
LegendItem item = createLegendItem(spectrum, defaultPaint, spectrum.getName());
itemCollection.add(item);
});
}
return itemCollection;
}
private LegendItem createLegendItem(DisplayableSpectrum spectrum, Paint paint, String legendLabel) {
Stroke outlineStroke = new BasicStroke();
Line2D lineShape = new Line2D.Double(0, 5, 40, 5);
Stroke lineStyle = spectrum.getLineStyle();
Shape symbol = spectrum.getScaledShape();
return new LegendItem(legendLabel, legendLabel, legendLabel, legendLabel,
true, symbol, false,
paint, true, paint, outlineStroke,
true, lineShape, lineStyle, paint);
}
}
/////////////////////////////////////////////////////////////////////////
// Product change handling
private class ProductNodeHandler extends ProductNodeListenerAdapter {
@Override
public void nodeChanged(final ProductNodeEvent event) {
boolean chartHasChanged = false;
if (event.getSourceNode() instanceof Band) {
final String propertyName = event.getPropertyName();
if (propertyName.equals(DataNode.PROPERTY_NAME_UNIT)) {
updateSpectraUnits();
chartHasChanged = true;
} else if (propertyName.equals(Band.PROPERTY_NAME_SPECTRAL_WAVELENGTH)) {
setUpSpectra();
chartHasChanged = true;
}
} else if (event.getSourceNode() instanceof Placemark) {
if (event.getPropertyName().equals("geoPos") || event.getPropertyName().equals("pixelPos")) {
chartHandler.removePinInformation((Placemark) event.getSourceNode());
}
if (isShowingPinSpectra()) {
chartHasChanged = true;
}
} else if (event.getSourceNode() instanceof Product) {
if (event.getPropertyName().equals("autoGrouping")) {
setUpSpectra();
chartHasChanged = true;
}
}
if (isActive() && chartHasChanged) {
recreateChart();
}
}
@Override
public void nodeAdded(final ProductNodeEvent event) {
if (!isActive()) {
return;
}
if (event.getSourceNode() instanceof Band) {
Band newBand = (Band) event.getSourceNode();
if (isSpectralBand(newBand)) {
addBandToSpectra((Band) event.getSourceNode());
recreateChart();
}
} else if (event.getSourceNode() instanceof Placemark) {
if (isShowingPinSpectra()) {
recreateChart();
} else {
updateUIState();
}
}
}
@Override
public void nodeRemoved(final ProductNodeEvent event) {
if (!isActive()) {
return;
}
if (event.getSourceNode() instanceof Band) {
Band band = (Band) event.getSourceNode();
removeBandFromSpectra(band);
chartHandler.removeBandInformation(band);
recreateChart();
} else if (event.getSourceNode() instanceof Placemark) {
if (isShowingPinSpectra()) {
recreateChart();
}
}
}
private void addBandToSpectra(Band band) {
DisplayableSpectrum[] allSpectra = rasterToSpectraMap.get(currentView.getRaster());
Product.AutoGrouping autoGrouping = currentProduct.getAutoGrouping();
if (autoGrouping != null) {
final int bandIndex = autoGrouping.indexOf(band.getName());
final DisplayableSpectrum spectrum;
if (bandIndex != -1) {
spectrum = allSpectra[bandIndex];
} else {
spectrum = allSpectra[allSpectra.length - 1];
}
spectrum.addBand(new SpectrumBand(band, spectrum.isSelected()));
} else {
allSpectra[0].addBand(new SpectrumBand(band, true));
}
}
private void removeBandFromSpectra(Band band) {
DisplayableSpectrum[] allSpectra = rasterToSpectraMap.get(currentView.getRaster());
for (DisplayableSpectrum displayableSpectrum : allSpectra) {
Band[] spectralBands = displayableSpectrum.getSpectralBands();
for (int j = 0; j < spectralBands.length; j++) {
Band spectralBand = spectralBands[j];
if (spectralBand == band) {
displayableSpectrum.remove(j);
if (displayableSpectrum.getSelectedBands().length == 0) {
displayableSpectrum.setSelected(false);
}
return;
}
}
}
}
private boolean isActive() {
return isVisible() && getCurrentProduct() != null;
}
}
private class PinSelectionChangeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
recreateChart();
}
}
}
| 64,481 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
Animation.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/ui/Animation.java | package gov.nasa.gsfc.seadas.imageanimator.ui;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.core.SubProgressMonitor;
import com.bc.ceres.grender.Viewport;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import eu.esa.snap.netbeans.docwin.WindowUtilities;
import gov.nasa.gsfc.seadas.imageanimator.operator.ImageAnimatorOp;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.util.Debug;
import org.esa.snap.core.util.PreferencesPropertyMap;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.core.util.math.Array;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.window.OpenImageViewAction;
import org.esa.snap.rcp.windows.ProductSceneViewTopComponent;
import org.esa.snap.ui.product.ProductSceneImage;
import org.esa.snap.ui.product.ProductSceneView;
import org.openide.awt.UndoRedo;
import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.prefs.Preferences;
import static org.esa.snap.rcp.actions.window.OpenImageViewAction.getProductSceneView;
import static org.esa.snap.rcp.actions.window.OpenRGBImageViewAction.openDocumentWindow;
import static org.esa.snap.ui.UIUtils.setRootFrameDefaultCursor;
import static org.esa.snap.ui.UIUtils.setRootFrameWaitCursor;
public class Animation {
Product product;
String sortMethod = ImageAnimatorDialog.SORT_BY_BANDNAME;
private final ProgressMonitor pm;
public static void main(String[] args) {
Animation sa = new Animation();
}
public Animation() {
pm = ProgressMonitor.NULL;
}
public void setSortMethod(String sortMethod) {
this.sortMethod = sortMethod;
}
public boolean checkImages(TreePath[] treePaths) {
SnapApp snapApp = SnapApp.getDefault();
product = snapApp.getSelectedProduct(SnapApp.SelectionSourceHint.VIEW);
ArrayList<String> parents = new ArrayList<String>();
final ArrayList<String> selectedBandsList = new ArrayList<>();
String currentSelectedBand;
for (TreePath treePath : treePaths) {
if (treePath.getParentPath() != null) {
parents.add(String.valueOf(treePath.getParentPath().getLastPathComponent()));
}
}
for (TreePath treePath : treePaths) {
currentSelectedBand = String.valueOf(treePath.getLastPathComponent());
if (!parents.contains(currentSelectedBand)) {
selectedBandsList.add(currentSelectedBand);
}
}
final String[] selectedBandNames = selectedBandsList.toArray(new String[0]);
final String[] sortedSelectedBandNames = getSortedBandNames(selectedBandNames, sortMethod);
for (int i = 0; i < sortedSelectedBandNames.length; i++) {
RasterDataNode raster = product.getRasterDataNode(sortedSelectedBandNames[i]);
ProductSceneViewTopComponent tc = OpenImageViewAction.getProductSceneViewTopComponent(raster);
if (tc == null) {
return false;
}
}
return true;
}
public static String[] getSortedBandNames(String[] bandNames, String sort_type) {
if (ImageAnimatorDialog.SORT_BY_BANDNAME.equals(sort_type)) {
Arrays.sort(bandNames);
return bandNames;
}
ArrayList<Band> unsortedBandsArrayList = new ArrayList<Band>();
for (String bandName : bandNames) {
Band band = SnapApp.getDefault().getSelectedProductSceneView().getProduct().getBand(bandName);
if (band != null) {
unsortedBandsArrayList.add(band);
}
}
Band[] unsortedBandsArray = new Band[unsortedBandsArrayList.size()];
unsortedBandsArrayList.toArray(unsortedBandsArray);
Band[] sortedBandsArray = getSortedBands(unsortedBandsArray, sort_type);
ArrayList<String> sortedBandNamesArrayList = new ArrayList<String>();
for (Band band : sortedBandsArray) {
sortedBandNamesArrayList.add(band.getName());
}
String[] sortedBandNamesArray = new String[sortedBandNamesArrayList.size()];
sortedBandNamesArrayList.toArray(sortedBandNamesArray);
return sortedBandNamesArray;
}
public static Band[] getSortedBands(Band[] bands, String sort_type) {
ArrayList<Band> bandsArrayUnsortedList = new ArrayList<Band>();
ArrayList<Band> bandsArraySortedList = new ArrayList<Band>();
for (Band band : bands) {
if (band != null) {
bandsArrayUnsortedList.add(band);
}
}
while (bandsArrayUnsortedList.size() > 1) {
Band minBand = null;
for (Band band1 : bandsArrayUnsortedList) {
if (minBand == null) {
minBand = band1;
} else {
if (ImageAnimatorDialog.SORT_BY_ANGLE.equals(sort_type)) {
if (band1.getAngularValue() < minBand.getAngularValue()) {
minBand = band1;
}
} else if (ImageAnimatorDialog.SORT_BY_WAVELENGTH.equals(sort_type)) {
if (band1.getSpectralWavelength() < minBand.getSpectralWavelength()) {
minBand = band1;
}
} else {
}
}
}
bandsArrayUnsortedList.remove(minBand);
bandsArraySortedList.add(minBand);
}
for (Band band2 : bandsArrayUnsortedList) {
bandsArraySortedList.add(band2);
}
Band[] sortedBandsArray = new Band[bandsArraySortedList.size()];
bandsArraySortedList.toArray(sortedBandsArray);
return sortedBandsArray;
}
public void createImages(TreePath[] treePaths) {
SnapApp snapApp = SnapApp.getDefault();
final ProductSceneView sceneView = snapApp.getSelectedProductSceneView();
product = snapApp.getSelectedProduct(SnapApp.SelectionSourceHint.VIEW);
ArrayList<String> parents = new ArrayList<String>();
final ArrayList<String> selectedBandsList = new ArrayList<>();
String currentSelectedBand;
for (TreePath treePath : treePaths) {
if (treePath.getParentPath() != null) {
parents.add(String.valueOf(treePath.getParentPath().getLastPathComponent()));
}
}
for (TreePath treePath : treePaths) {
currentSelectedBand = String.valueOf(treePath.getLastPathComponent());
if (!parents.contains(currentSelectedBand)) {
selectedBandsList.add(currentSelectedBand);
}
}
final String[] selectedBandNames = selectedBandsList.toArray(new String[0]);
final RasterDataNode[] rasters = new RasterDataNode[selectedBandNames.length];
for (int i = 0; i < selectedBandNames.length; i++) {
RasterDataNode raster = product.getRasterDataNode(selectedBandNames[i]);
OpenImageViewAction.openImageView(raster);
rasters[i] = raster;
}
}
public ImageIcon[] openImages(TreePath[] treePaths) {
SnapApp snapApp = SnapApp.getDefault();
final ProductSceneView sceneView = snapApp.getSelectedProductSceneView();
Viewport standardViewPort = sceneView.getLayerCanvas().getViewport();
ImageAnimatorOp imageAnimatorOp = new ImageAnimatorOp();
product = snapApp.getSelectedProduct(SnapApp.SelectionSourceHint.VIEW);
ArrayList<String> parents = new ArrayList<String>();
final ArrayList<String> selectedBandsList = new ArrayList<>();
String currentSelectedBand;
for (TreePath treePath : treePaths) {
if (treePath.getParentPath() != null) {
parents.add(String.valueOf(treePath.getParentPath().getLastPathComponent()));
}
}
for (TreePath treePath : treePaths) {
currentSelectedBand = String.valueOf(treePath.getLastPathComponent());
if (!parents.contains(currentSelectedBand)) {
selectedBandsList.add(currentSelectedBand);
}
}
final String[] selectedBandNames = selectedBandsList.toArray(new String[0]);
final String[] sortedSelectedBandNames = getSortedBandNames(selectedBandNames, sortMethod);
final RenderedImage[] renderedImages = new RenderedImage[sortedSelectedBandNames.length];
final RasterDataNode[] rasters = new RasterDataNode[sortedSelectedBandNames.length];
// ProductSceneView myView = null;
RenderedImage renderedImage;
for (int i = 0; i < sortedSelectedBandNames.length; i++) {
RasterDataNode raster = product.getRasterDataNode(sortedSelectedBandNames[i]);
OpenImageViewAction.openImageView(raster);
rasters[i] = raster;
}
ImageIcon[] images = new ImageIcon[renderedImages.length];
for (int i = 0; i < sortedSelectedBandNames.length; i++) {
final ProductSceneView myView = getProductSceneView(rasters[i]);
if (myView != null && sceneView != myView) {
sceneView.synchronizeViewportIfPossible(myView);
}
renderedImage = imageAnimatorOp.createImage(myView, standardViewPort);
renderedImages[i] = renderedImage;
images[i] = new ImageIcon((BufferedImage) renderedImage);
images[i].setDescription(rasters[i].getName());
}
return images;
// return sortImages(images);
}
private ImageIcon[] sortImages(ImageIcon[] images){
ImageIcon[] sortedImages = new ImageIcon[images.length];
String[] imageNames = new String[images.length];
HashMap<String, ImageIcon> sortedImagesHashMap = new HashMap<>(images.length);
for (int i = 0; i < images.length; i++) {
imageNames[i] = images[i].getDescription();
sortedImagesHashMap.put(images[i].getDescription(), images[i]);
}
Arrays.sort(imageNames);
for (int i = 0; i < images.length; i++) {
sortedImages[i] = sortedImagesHashMap.get(imageNames[i]);
}
return sortedImages;
}
private static ProductSceneImage createProductSceneImage(final RasterDataNode raster, ProductSceneView existingView, com.bc.ceres.core.ProgressMonitor pm) {
Debug.assertNotNull(raster);
Debug.assertNotNull(pm);
try {
pm.beginTask("Creating image...", 1);
ProductSceneImage sceneImage;
if (existingView != null) {
sceneImage = new ProductSceneImage(raster, existingView);
} else {
final Preferences preferences = SnapApp.getDefault().getPreferences();
PropertyMap propertyMap = new PreferencesPropertyMap(preferences);
sceneImage = new ProductSceneImage(raster,
propertyMap,
SubProgressMonitor.create(pm, 1));
}
sceneImage.initVectorDataCollectionLayer();
sceneImage.initMaskCollectionLayer();
return sceneImage;
} finally {
pm.done();
}
}
public static void openProductSceneView(RasterDataNode rasterDataNode) {
SnapApp snapApp = SnapApp.getDefault();
snapApp.setStatusBarMessage("Opening image view...");
setRootFrameWaitCursor(snapApp.getMainFrame());
String progressMonitorTitle = MessageFormat.format("Creating image for ''{0}''", rasterDataNode.getName());
ProductSceneView existingView = getProductSceneView(rasterDataNode);
ProgressMonitorSwingWorker<ProductSceneImage, Object> worker = new ProgressMonitorSwingWorker<ProductSceneImage, Object>(snapApp.getMainFrame(), progressMonitorTitle) {
@Override
public void done() {
setRootFrameDefaultCursor(snapApp.getMainFrame());
snapApp.setStatusBarMessage("");
try {
ProductSceneImage sceneImage = get();
UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(sceneImage.getProduct());
ProductSceneView view = new ProductSceneView(sceneImage, undoManager);
openDocumentWindow(view);
} catch (Exception e) {
snapApp.handleError(MessageFormat.format("Failed to open image view.\n\n{0}", e.getMessage()), e);
}
}
@Override
protected ProductSceneImage doInBackground(com.bc.ceres.core.ProgressMonitor pm) {
pm.beginTask("Creating Image ", 10);
pm.worked(1);
try {
return createProductSceneImage(rasterDataNode, existingView, pm);
} finally {
if (pm.isCanceled()) {
rasterDataNode.unloadRasterData();
}
}
}
};
worker.executeWithBlocking();
}
}
| 13,443 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
SliderDemo.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/ui/SliderDemo.java | package gov.nasa.gsfc.seadas.imageanimator.ui;
/*
* Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle or the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/*
* SliderDemo.java requires all the files in the images/doggy
* directory.
*/
public class SliderDemo extends JPanel
implements ActionListener,
WindowListener,
ChangeListener {
//Set up animation parameters.
static final int FPS_MIN = 0;
static final int FPS_MAX = 30;
static final int FPS_INIT = 15; //initial frames per second
int frameNumber = 0;
int NUM_FRAMES = 2;
ImageIcon[] images = new ImageIcon[NUM_FRAMES];
int delay;
Timer timer;
boolean frozen = false;
//This label uses ImageIcon to show the doggy pictures.
JLabel picture;
public SliderDemo() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
delay = 1000 / FPS_INIT;
//Create the label.
JLabel sliderLabel = new JLabel("Frames Per Second", JLabel.CENTER);
sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//Create the slider.
JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL,
FPS_MIN, FPS_MAX, FPS_INIT);
framesPerSecond.addChangeListener(this);
//Turn on labels at major tick marks.
framesPerSecond.setMajorTickSpacing(10);
framesPerSecond.setMinorTickSpacing(1);
framesPerSecond.setPaintTicks(true);
framesPerSecond.setPaintLabels(true);
framesPerSecond.setBorder(
BorderFactory.createEmptyBorder(0,0,10,0));
Font font = new Font("Serif", Font.ITALIC, 15);
framesPerSecond.setFont(font);
//Create the label that displays the animation.
picture = new JLabel();
picture.setHorizontalAlignment(JLabel.CENTER);
picture.setAlignmentX(Component.CENTER_ALIGNMENT);
picture.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLoweredBevelBorder(),
BorderFactory.createEmptyBorder(10,10,10,10)));
updatePicture(0); //display first frame
//Put everything together.
add(sliderLabel);
add(framesPerSecond);
add(picture);
setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
//Set up a timer that calls this object's action handler.
timer = new Timer(delay, this);
timer.setInitialDelay(delay * 7); //We pause animation twice per cycle
//by restarting the timer
timer.setCoalesce(true);
}
/** Add a listener for window events. */
void addWindowListener(Window w) {
w.addWindowListener(this);
}
//React to window events.
public void windowIconified(WindowEvent e) {
stopAnimation();
}
public void windowDeiconified(WindowEvent e) {
startAnimation();
}
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
/** Listen to the slider. */
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
int fps = (int)source.getValue();
if (fps == 0) {
if (!frozen) stopAnimation();
} else {
delay = 1000 / fps;
timer.setDelay(delay);
timer.setInitialDelay(delay * 10);
if (frozen) startAnimation();
}
}
}
public void startAnimation() {
//Start (or restart) animating!
timer.start();
frozen = false;
}
public void stopAnimation() {
//Stop the animating thread.
timer.stop();
frozen = true;
}
//Called when the Timer fires.
public void actionPerformed(ActionEvent e) {
//Advance the animation frame.
if (frameNumber == (NUM_FRAMES - 1)) {
frameNumber = 0;
} else {
frameNumber++;
}
updatePicture(frameNumber); //display the next picture
if ( frameNumber==(NUM_FRAMES - 1)
|| frameNumber==(NUM_FRAMES/2 - 1) ) {
timer.restart();
}
}
/** Update the label to display the image for the current frame. */
protected void updatePicture(int frameNum) {
//Get the image if we haven't already.
if (images[frameNumber] == null) {
images[frameNumber] = createImageIcon("/images/A2020113184000_L2_LAC_OC_"
+ frameNumber
+ ".png");
}
//Set the image.
if (images[frameNumber] != null) {
picture.setIcon(images[frameNumber]);
} else { //image not found
picture.setText("image #" + frameNumber + " not found");
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = SliderDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Slider Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SliderDemo animator = new SliderDemo();
//Add content to the window.
frame.add(animator, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
animator.startAnimation();
}
public static void main(String[] args) {
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
/*
~/mainwork/seadas-dev/seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/ui/SliderDemo.java
Warning:(111, 10) Method 'addWindowListener(java.awt.Window)' is never used
Warning:(132, 24) Casting 'source.getValue()' to 'int' is redundant
Warning:(174, 38) Parameter 'frameNum' is never used
Warning:(228, 48) Anonymous new Runnable() can be replaced with method reference
Warning:(228, 48) Anonymous new Runnable() can be replaced with lambda
*/ | 8,467 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
AnimationWithSpeedControl.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/ui/AnimationWithSpeedControl.java | package gov.nasa.gsfc.seadas.imageanimator.ui;
import gov.nasa.gsfc.seadas.imageanimator.util.GifSequenceWriter;
import org.esa.snap.rcp.SnapApp;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static com.sun.java.accessibility.util.AWTEventMonitor.addWindowListener;
public class AnimationWithSpeedControl extends JPanel
implements ActionListener,
// WindowListener,
ChangeListener {
//Set up animation parameters.
static final int FPS_MIN = 0;
static final int FPS_MAX = 30;
static final int FPS_INIT = 5; //initial frames per second
int frameNumber = 0;
int NUM_FRAMES = 2;
ImageIcon[] images;
int delay;
Timer timer;
boolean frozen = false;
static boolean windowClosedBool;
private static String inputFileLocation;
static JFrame frame;
//This label uses ImageIcon to show the doggy pictures.
JLabel picture;
public AnimationWithSpeedControl(){
}
public AnimationWithSpeedControl(ImageIcon[] images) {
NUM_FRAMES = images.length;
this.images = images;
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
delay = 1000 / FPS_INIT;
//Create the label.
JLabel sliderLabel = new JLabel("Frames Per Second", JLabel.CENTER);
sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton pauseButton = new JButton("Pause");
//Create the slider.
JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL,
FPS_MIN, FPS_MAX, FPS_INIT);
framesPerSecond.setToolTipText("Slider that controls the animation speed");
framesPerSecond.addChangeListener(this);
//Turn on labels at major tick marks.
framesPerSecond.setMajorTickSpacing(10);
framesPerSecond.setMinorTickSpacing(1);
framesPerSecond.setPaintTicks(true);
framesPerSecond.setPaintLabels(true);
framesPerSecond.setBorder(
BorderFactory.createEmptyBorder(0,0,10,0));
Font font = new Font("Serif", Font.ITALIC, 15);
framesPerSecond.setFont(font);
//Create the label that displays the animation.
picture = new JLabel();
picture.setHorizontalAlignment(JLabel.CENTER);
picture.setAlignmentX(Component.CENTER_ALIGNMENT);
picture.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLoweredBevelBorder(),
BorderFactory.createEmptyBorder(10,10,10,10)));
updatePicture(0); //display first frame
//Put everything together.
add(sliderLabel);
add(framesPerSecond);
add(picture);
setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
//Set up a timer that calls this object's action handler.
timer = new Timer(delay, this);
timer.setInitialDelay(delay * 7); //We pause animation twice per cycle
//by restarting the timer
timer.setCoalesce(true);
}
public static String getInputFileLocation() {
return inputFileLocation;
}
public static void setInputFileLocation(String inputFileLocation) {
AnimationWithSpeedControl.inputFileLocation = inputFileLocation;
}
protected void updatePicture(int frameNum) {
//Set the image.
if (images[frameNumber] != null) {
picture.setIcon(images[frameNumber]);
} else { //image not found
picture.setText("image #" + frameNumber + " not found");
}
picture.repaint();
this.repaint();
}
/** Listen to the slider. */
public void stateChanged(ChangeEvent e) {
if(windowClosedBool) {
stopAnimation();
return;
}
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
int fps = (int)source.getValue();
if (fps == 0) {
if (!frozen) stopAnimation();
} else {
delay = 1000 / fps;
timer.setDelay(delay);
timer.setInitialDelay(delay * 3);
if (frozen) startAnimation();
}
}
}
public void startAnimation() {
//Start (or restart) animating!
timer.start();
frozen = false;
}
public void stopAnimation() {
//Stop the animating thread.
timer.stop();
frozen = true;
}
//Called when the Timer fires.
public void actionPerformed(ActionEvent e) {
if(frozen || windowClosedBool) {
stopAnimation();
return;
}
//Advance the animation frame.
if (frameNumber == (NUM_FRAMES - 1)) {
frameNumber = 0;
} else {
frameNumber++;
}
updatePicture(frameNumber); //display the next picture
if ( frameNumber==(NUM_FRAMES - 1) ) {
timer.restart();
}
}
/** Update the label to display the image for the current frame. */
protected void updatePictureOriginal(int frameNum) {
//Get the image if we haven't already.
if (images[frameNumber] == null) {
images[frameNumber] = createImageIcon("/images/A2020113184000_L2_LAC_OC_"
+ frameNumber
+ ".png");
}
//Set the image.
if (images[frameNumber] != null) {
picture.setIcon(images[frameNumber]);
} else { //image not found
picture.setText("image #" + frameNumber + " not found");
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = SliderDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public static void closeGUI() {
frame.dispose();
};
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
public static void createAndShowGUI(ImageIcon[] images) {
//Create and set up the window.
// JFrame frame = new JFrame("Band Images Animation");
windowClosedBool = false;
JDialog frame = new JDialog(SnapApp.getDefault().getMainFrame(), "Animation With Speed Control", true);
frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
AnimationWithSpeedControl animator = new AnimationWithSpeedControl(images);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
windowClosedBool = true;
animator.stopAnimation();
}
@Override
public void windowClosing(WindowEvent e) {
windowClosedBool = true;
animator.stopAnimation();
}
@Override
public void windowIconified(WindowEvent e) {
animator.stopAnimation();
}
@Override
public void windowDeiconified(WindowEvent e) {
animator.startAnimation();
}
});
JPanel controllerPanel = new JPanel(new GridBagLayout());
JLabel filler = new JLabel(" ");
JButton pauseButton = new JButton("Pause");
pauseButton.setPreferredSize(pauseButton.getPreferredSize());
pauseButton.setToolTipText("Pause or Resume the animation");
pauseButton.setMinimumSize(pauseButton.getPreferredSize());
pauseButton.setMaximumSize(pauseButton.getPreferredSize());
pauseButton.addActionListener(new ActionListener() {
boolean isPaused = false;
public void actionPerformed(ActionEvent event) {
if (!isPaused ) {
pauseButton.setText("Resume");
isPaused = true;
animator.stopAnimation();
}
else {
pauseButton.setText("Pause");
animator.startAnimation();
isPaused = false;
}
}
});
JButton videoButton = new JButton("Save");
videoButton.setToolTipText("Save the animation as video.");
videoButton.setPreferredSize(videoButton.getPreferredSize());
videoButton.setMinimumSize(videoButton.getPreferredSize());
videoButton.setMaximumSize(videoButton.getPreferredSize());
videoButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// grab the output image type from the first image in the sequence
BufferedImage firstImage = (BufferedImage) images[0].getImage();
ImageOutputStream output = null;
GifSequenceWriter writer = null;
String animationFileName = inputFileLocation + "_animation.gif";
try {
// create a new BufferedOutputStream with the output file name
output = new FileImageOutputStream(new File(animationFileName));
// create a gif sequence with the type of the first image, 1 second between frames, which loops continuously
writer = new GifSequenceWriter(output, firstImage.getType(), 1, true);
// write out the first image to our sequence...
writer.writeToSequence(firstImage);
for (int i = 1; i < images.length; i++) {
BufferedImage nextImage = (BufferedImage) images[i].getImage();
writer.writeToSequence(nextImage);
}
writer.close();
output.close();
JOptionPane.showMessageDialog(null, "Animation is saved as " + animationFileName );
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.setToolTipText("Close the animation window");
cancelButton.setPreferredSize(cancelButton.getPreferredSize());
cancelButton.setMinimumSize(cancelButton.getPreferredSize());
cancelButton.setMaximumSize(cancelButton.getPreferredSize());
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
animator.stopAnimation();
frame.dispose();
}
});
controllerPanel.add(filler,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
controllerPanel.add(pauseButton,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
controllerPanel.add(videoButton,
new ExGridBagConstraints(2, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
controllerPanel.add(cancelButton,
new ExGridBagConstraints(3, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
//Add content to the window.
frame.getContentPane().add(animator, BorderLayout.CENTER);
frame.getContentPane().add(controllerPanel, BorderLayout.SOUTH);
//Display the window.
animator.startAnimation();
frame.pack();
frame.setVisible(true);
}
private static JButton getCancelButton(AnimationWithSpeedControl animator, JDialog frame) {
JButton cancelButton = new JButton("Cancel");
cancelButton.setPreferredSize(cancelButton.getPreferredSize());
cancelButton.setMinimumSize(cancelButton.getPreferredSize());
cancelButton.setMaximumSize(cancelButton.getPreferredSize());
cancelButton.setToolTipText("Close the animation window");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
animator.stopAnimation();
frame.dispose();
}
});
return cancelButton;
}
public static void animate(ImageIcon[] images){
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI(images);
}
});
}
}
| 13,115 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ImageAnimatorDialog.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/ui/ImageAnimatorDialog.java | package gov.nasa.gsfc.seadas.imageanimator.ui;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.product.ProductSceneView;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.openide.util.HelpCtx;
import javax.swing.*;
import javax.swing.event.SwingPropertyChangeSupport;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Hashtable;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 3/9/23
* Time: 12:24 PM
* To change this template use File | Settings | File Templates.
*/
public class ImageAnimatorDialog extends JDialog {
public static final String TITLE = "Choose Images to Animate"; /*I18N*/
static final String NEW_BAND_SELECTED_PROPERTY = "newBandSelected";
static final String DELETE_BUTTON_PRESSED_PROPERTY = "deleteButtonPressed";
private Component helpButton = null;
private final static String helpId = "imageAnimatorHelp";
private final static String HELP_ICON = "icons/Help24.gif";
private Product product;
Band selectedBand;
RasterDataNode raster;
// ArrayList<ImageAnimatorData> imageAnimators;
ArrayList<String> activeBands;
private SwingPropertyChangeSupport propertyChangeSupport;
JPanel imageAnimatorPanel;
JPanel angularViewAnimatorPanel;
JCheckBoxTree bandNamesTree;
JRadioButton bandImages = new JRadioButton("Band Images",true);
JComboBox sortMethodJComboBox = new JComboBox();
JRadioButton angularView = new JRadioButton("Angular View");
JRadioButton spectrumView = new JRadioButton("Spectrum View");
ButtonGroup buttonGroup = new ButtonGroup();
JButton animateImagesButton = new JButton("Animate Images");
JButton createImagesButton = new JButton("Create Images");
public static String SORT_BY_WAVELENGTH = "Sort by Wavelength";
public static String SORT_BY_ANGLE = "Sort by Angle";
public static String SORT_BY_BANDNAME = "Sort by Band Name";
public static String DEFAULT_SORT_BY = SORT_BY_BANDNAME;
File inputFile;
String sortMethod;
private boolean imageAnimatorCanceled;
public ImageAnimatorDialog(Product product, ArrayList<String> activeBands) {
super(SnapApp.getDefault().getMainFrame(), TITLE, JDialog.DEFAULT_MODALITY_TYPE);
this.product = product;
propertyChangeSupport = new SwingPropertyChangeSupport(this);
helpButton = getHelpButton();
ProductSceneView productSceneView = SnapApp.getDefault().getSelectedProductSceneView();
ProductNodeGroup<Band> bandGroup = product.getBandGroup();
inputFile = product.getFileLocation();
if (productSceneView != null) {
Band[] bands = new Band[bandGroup.getNodeCount()];
bandGroup.toArray(bands);
this.activeBands = activeBands;
// imageAnimators = new ArrayList<ImageAnimatorData>();
// propertyChangeSupport.addPropertyChangeListener(NEW_BAND_SELECTED_PROPERTY, getBandPropertyListener());
propertyChangeSupport.addPropertyChangeListener(DELETE_BUTTON_PRESSED_PROPERTY, getDeleteButtonPropertyListener());
createImageAnimatorUI();
}
imageAnimatorCanceled = true;
}
// private PropertyChangeListener getBandPropertyListener() {
// return new PropertyChangeListener() {
// @Override
// public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
// for (ImageAnimatorData imageAnimatorData : imageAnimators) {
// imageAnimatorData.setBand(selectedBand);
// }
// }
// };
// }
private PropertyChangeListener getDeleteButtonPropertyListener() {
return new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
Component[] components = imageAnimatorPanel.getComponents();
for (Component component : components) {
if (component instanceof JPanel) {
Component[] jPanelComponents = ((JPanel) component).getComponents();
for (Component jPanelComponent : jPanelComponents) {
if (component instanceof JPanel && ((JPanel) jPanelComponent).getComponents().length == 0) {
((JPanel) component).remove(jPanelComponent);
}
}
}
imageAnimatorPanel.validate();
imageAnimatorPanel.repaint();
}
}
};
}
@Override
public void addPropertyChangeListener(String name, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(name, listener);
}
@Override
public void removePropertyChangeListener(String name, PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(name, listener);
}
protected AbstractButton getHelpButton() {
if (helpId != null) {
final AbstractButton helpButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon(HELP_ICON),
false);
helpButton.setToolTipText("Help.");
helpButton.setName("helpButton");
helpButton.addActionListener(e ->getHelpCtx().display());
return helpButton;
}
return null;
}
public HelpCtx getHelpCtx() {
return new HelpCtx(helpId);
}
public final JPanel createImageAnimatorUI() {
final int rightInset = 5;
imageAnimatorPanel = new JPanel(new GridBagLayout());
imageAnimatorPanel.setBorder(BorderFactory.createTitledBorder(""));
final JPanel imageAnimatorContainerPanel = new JPanel(new GridBagLayout());
//final JPanel basicPanel = getImageAnimatorPanel();
final JPanel basicPanel = getImageTypePanel();
imageAnimatorContainerPanel.add(basicPanel,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
imageAnimatorContainerPanel.addPropertyChangeListener(DELETE_BUTTON_PRESSED_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
Component[] components = imageAnimatorContainerPanel.getComponents();
for (Component component : components) {
if (((JPanel) component).getComponents().length == 0) {
imageAnimatorContainerPanel.remove(component);
}
}
imageAnimatorContainerPanel.validate();
imageAnimatorContainerPanel.repaint();
}
});
JPanel mainPanel = new JPanel(new GridBagLayout());
bandNamesTree = new JCheckBoxTree();
bandNamesTree.setEditable(true);
bandNamesTree.setDragEnabled(true);
bandNamesTree.setDropMode(DropMode.ON_OR_INSERT);
bandNamesTree.setScrollsOnExpand(true);
DefaultMutableTreeNode root=new DefaultMutableTreeNode("Bands ");
DefaultMutableTreeNode child;
String bandName;
Hashtable<String, DefaultMutableTreeNode> bandHash = new Hashtable<String, DefaultMutableTreeNode>();
Band[] bands = product.getBands();
// ArrayList<DefaultMutableTreeNode> folders = new ArrayList<DefaultMutableTreeNode>();
for (Band band :bands) {
bandName = band.getName();
String[] parts = bandName.split("_");
int partsNum = parts.length;
if (parts.length == 2 && parts[1].matches("\\d+")) { // check if filename matches prefix_number format
String folderName = parts[0];
String number = parts[1];
DefaultMutableTreeNode folder = bandHash.get(folderName);
if (folder == null) {
folder = new DefaultMutableTreeNode(folderName);
bandHash.put(folderName, folder);
folder.setAllowsChildren(true);
root.add(folder);
}
DefaultMutableTreeNode node = new DefaultMutableTreeNode(bandName);
folder.add(node);
} else if (partsNum > 2 && parts[partsNum-1].matches("\\d+|-\\d+")) {
String numberPart = "_" + parts[partsNum -2] + "_" + parts[partsNum -1];
String folderName = bandName.replace(numberPart, "");
DefaultMutableTreeNode folder = bandHash.get(folderName);
if (folder == null) {
folder = new DefaultMutableTreeNode(folderName);
bandHash.put(folderName, folder);
folder.setAllowsChildren(true);
root.add(folder);
}
DefaultMutableTreeNode node = new DefaultMutableTreeNode(bandName);
folder.add(node);
} else {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(bandName);
root.add(node);
}
}
DefaultTreeModel model = new DefaultTreeModel(root);
bandNamesTree.setModel(model);
imageAnimatorPanel.add(imageAnimatorContainerPanel,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
imageAnimatorPanel.add(new JScrollPane(bandNamesTree),
new ExGridBagConstraints(1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 100, 230));
mainPanel.add(imageAnimatorPanel,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 5));
mainPanel.add(getControllerPanel(),
new ExGridBagConstraints(0, 2, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
bandNamesTree.addCheckChangeEventListener(new JCheckBoxTree.CheckChangeEventListener() {
public void checkStateChanged(JCheckBoxTree.CheckChangeEvent event) {
TreePath[] treePath = bandNamesTree.getCheckedPaths();
Animation animation = new Animation();
animation.setSortMethod((String) sortMethodJComboBox.getSelectedItem());
boolean imageOpened = animation.checkImages(treePath);
if (!imageOpened) {
createImagesButton.setEnabled(true);
animateImagesButton.setEnabled(false);
} else {
createImagesButton.setEnabled(false);
animateImagesButton.setEnabled(true);
}
repaint();
}
});
bandNamesTree.setToolTipText("Check bands to be animated");
add(mainPanel);
//this will set the "Create imageAnimator Lines" button as a default button that listens to the Enter key
mainPanel.getRootPane().setDefaultButton((JButton) ((JPanel) mainPanel.getComponent(1)).getComponent(1));
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("Animate Images");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
pack();
return mainPanel;
}
private JPanel getImageTypePanel() {
final JPanel imageTypePanel = new JPanel(new GridBagLayout());
JLabel imageTypePanelLable = new JLabel("Select Image Type: ");
bandImages.setBounds(120, 30, 120, 50);
angularView.setBounds(120, 30, 120, 50);
spectrumView.setBounds(120, 30, 120, 50);
angularView.setToolTipText("Opens a window for angular view animation");
spectrumView.setToolTipText("Opens a window for spectrum view animation");
bandImages.setActionCommand("bandImages");
angularView.setActionCommand("angularView");
spectrumView.setActionCommand("spectrumView");
//bandImages.setAction();
imageTypePanelLable.setBounds(120, 30, 120, 50);
RadioButtonActionListener actionListener = new RadioButtonActionListener();
bandImages.addActionListener(actionListener);
angularView.addActionListener(actionListener);
spectrumView.addActionListener(actionListener);
sortMethodJComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sortMethod = (String) sortMethodJComboBox.getSelectedItem();
}
});
// bandImages.setForeground(Color.BLUE);
// bandImages.setBackground(Color.YELLOW);
// bandImages.setFont(new java.awt.Font("Calibri", Font.BOLD, 16));
bandImages.setToolTipText("Select this option if you want to animate image for multiple bands");
sortMethodJComboBox = new JComboBox();
sortMethodJComboBox.setEditable(false);
sortMethodJComboBox.addItem(SORT_BY_ANGLE);
sortMethodJComboBox.addItem(SORT_BY_WAVELENGTH);
sortMethodJComboBox.addItem(SORT_BY_BANDNAME);
sortMethodJComboBox.setSelectedItem(DEFAULT_SORT_BY);
sortMethodJComboBox.setName("sortMethodJComboBox");
sortMethodJComboBox.setToolTipText("Band sorting for animation");
imageTypePanel.add(imageTypePanelLable, new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
imageTypePanel.add(bandImages, new ExGridBagConstraints(1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
imageTypePanel.add(sortMethodJComboBox, new ExGridBagConstraints(1, 2, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
imageTypePanel.add(angularView, new ExGridBagConstraints(1, 3, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
imageTypePanel.add(spectrumView, new ExGridBagConstraints(1, 4, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
buttonGroup.add(bandImages);
buttonGroup.add(angularView);
buttonGroup.add(spectrumView);
imageTypePanel.setVisible(true);
return imageTypePanel;
}
public ArrayList<Band> getActiveBands() {
ProductSceneView productSceneView = SnapApp.getDefault().getSelectedProductSceneView();
ProductNodeGroup<Band> bandGroup = product.getBandGroup();
if (productSceneView != null) {
ImageInfo selectedImageInfo = productSceneView.getImageInfo();
Band[] bands = new Band[bandGroup.getNodeCount()];
bandGroup.toArray(bands);
for (Band band : bands) {
if (band.getImageInfo() != null) {
if (band.getImageInfo() == selectedImageInfo) {
selectedBand = band;
}
}
}
raster = product.getRasterDataNode(selectedBand.getName());
}
return null;
}
private JPanel getControllerPanel() {
JPanel controllerPanel = new JPanel(new GridBagLayout());
createImagesButton.setEnabled(true);
createImagesButton.setToolTipText("Create images selected for animation");
createImagesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (buttonGroup.getSelection().getActionCommand().equals(bandImages.getActionCommand())) {
imageAnimatorCanceled = false;
TreePath[] treePath = bandNamesTree.getCheckedPaths();
Animation animation = new Animation();
animation.setSortMethod((String) sortMethodJComboBox.getSelectedItem());
animation.createImages(treePath);
animateImagesButton.setEnabled(true);
createImagesButton.setEnabled(false);
repaint();
}
}
});
animateImagesButton.setToolTipText("Animate images selected for animation if they are opened");
animateImagesButton.setPreferredSize(animateImagesButton.getPreferredSize());
animateImagesButton.setMinimumSize(animateImagesButton.getPreferredSize());
animateImagesButton.setMaximumSize(animateImagesButton.getPreferredSize());
animateImagesButton.setEnabled(false);
animateImagesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
imageAnimatorCanceled = false;
if (buttonGroup.getSelection().getActionCommand().equals(bandImages.getActionCommand())) {
TreePath[] treePath = bandNamesTree.getCheckedPaths();
Animation animation = new Animation();
animation.setSortMethod((String) sortMethodJComboBox.getSelectedItem());
ImageIcon[] images = animation.openImages(treePath);
//AnimationWithSpeedControl.setInputFileLocation(inputFile.getParent());
AnimationWithSpeedControl.setInputFileLocation(inputFile.getAbsolutePath());
AnimationWithSpeedControl.animate(images);
animateImagesButton.setEnabled(true);
createImagesButton.setEnabled(false);
repaint();
}
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.setPreferredSize(cancelButton.getPreferredSize());
cancelButton.setMinimumSize(cancelButton.getPreferredSize());
cancelButton.setMaximumSize(cancelButton.getPreferredSize());
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
imageAnimatorCanceled = true;
dispose();
}
});
JLabel filler = new JLabel(" ");
controllerPanel.add(filler,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
controllerPanel.add(createImagesButton,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
controllerPanel.add(animateImagesButton,
new ExGridBagConstraints(3, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
controllerPanel.add(cancelButton,
new ExGridBagConstraints(5, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
controllerPanel.add(helpButton,
new ExGridBagConstraints(7, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
return controllerPanel;
}
class RadioButtonActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
JRadioButton button = (JRadioButton) event.getSource();
if (button == bandImages) {
JDialog bandImageAnimationDialog = new JDialog(SnapApp.getDefault().getMainFrame(), "Band Image Animation", JDialog.DEFAULT_MODALITY_TYPE);
} else if (button == angularView) {
// option Windows is selected
JDialog angularAnimationDialog = new JDialog(SnapApp.getDefault().getMainFrame(), JDialog.DEFAULT_MODALITY_TYPE);
AngularAnimationTopComponent angularAnimationTopComponent = new AngularAnimationTopComponent();
angularAnimationDialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
angularAnimationDialog.getContentPane().add(angularAnimationTopComponent);
angularAnimationDialog.setPreferredSize(angularAnimationTopComponent.getPreferredSize());
angularAnimationDialog.setLocationRelativeTo(null);
angularAnimationDialog.pack();
angularAnimationDialog.setVisible(true);
angularAnimationDialog.dispose();
bandImages.setSelected(true);
} else if (button == spectrumView) {
JDialog spectrumAnimationDialog = new JDialog(SnapApp.getDefault().getMainFrame(), JDialog.DEFAULT_MODALITY_TYPE);
SpectrumAnimationTopComponent spectrumAnimationTopComponent = new SpectrumAnimationTopComponent();
spectrumAnimationDialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
spectrumAnimationDialog.getContentPane().add(spectrumAnimationTopComponent);
spectrumAnimationDialog.setPreferredSize(spectrumAnimationTopComponent.getPreferredSize());
spectrumAnimationDialog.setLocationRelativeTo(null);
spectrumAnimationDialog.pack();
spectrumAnimationDialog.setVisible(true);
spectrumAnimationDialog.dispose();
bandImages.setSelected(true);
}
}
}
}
| 21,897 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ExGridBagConstraints.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/ui/ExGridBagConstraints.java | package gov.nasa.gsfc.seadas.imageanimator.ui;
import java.awt.*;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 1:57 PM
* To change this template use File | Settings | File Templates.
*/
public class ExGridBagConstraints extends GridBagConstraints {
public ExGridBagConstraints(int gridx, int gridy) {
this.gridx = gridx;
this.gridy = gridy;
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, int pad) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
this.insets = new Insets(pad, pad, pad, pad);
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, Insets insets) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
this.insets = insets;
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, int pad, int gridwidth) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
this.insets = new Insets(pad, pad, pad, pad);
this.gridwidth = gridwidth;
}
} | 1,801 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
AnimationTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/ui/AnimationTest.java | package gov.nasa.gsfc.seadas.imageanimator.ui;
import com.bc.ceres.grender.Viewport;
import gov.nasa.gsfc.seadas.imageanimator.operator.ImageAnimatorOp;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.product.ProductSceneView;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import javax.swing.*;
import static gov.nasa.gsfc.seadas.imageanimator.ui.Animation.openProductSceneView;
import static org.esa.snap.rcp.actions.window.OpenImageViewAction.getProductSceneView;
public class AnimationTest extends JPanel implements ActionListener {
ImageIcon images[];
int totalImages = 3, currentImage = 0, animationDelay = 50;
Timer animationTimer;
Product product;
Thread th;
ImageIcon images1;
JFrame frame;
JLabel lbl;
int i = 0;
int j;
public AnimationTest() {
frame = new JFrame("Animation Frame");
th = new Thread();
lbl = new JLabel();
JPanel panel = new JPanel();
panel.add(lbl);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for(j = 1; j <= 2; j++){
SwingAnimator();
if (j == 2)
j = 0;
}
// for (int i = 0; i < images.length; ++i)
// images[i] = new ImageIcon("images/java" + i + ".gif");
//startAnimation();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (images[currentImage].getImageLoadStatus() == MediaTracker.COMPLETE) {
images[currentImage].paintIcon(this, g, 0, 0);
currentImage = (currentImage + 1) % totalImages;
}
}
public void SwingAnimator(){
SnapApp snapApp = SnapApp.getDefault();
final ProductSceneView sceneView = snapApp.getSelectedProductSceneView();
Viewport standardViewPort = sceneView.getLayerCanvas().getViewport();
ImageAnimatorOp imageAnimatorOp = new ImageAnimatorOp();
images = new ImageIcon[totalImages];
product = snapApp.getSelectedProduct(SnapApp.SelectionSourceHint.VIEW);
RenderedImage renderedImage;
RasterDataNode raster1 = product.getRasterDataNode("angstrom");
openProductSceneView(raster1);
RasterDataNode raster2 = product.getRasterDataNode("poc");
openProductSceneView(raster2);
RasterDataNode raster3 = product.getRasterDataNode("ipar");
openProductSceneView(raster3);
ProductSceneView myView;
// ProductSceneView myView = getProductSceneView(raster1);
// renderedImage = imageAnimatorOp.createImage(myView, standardViewPort);
//
//renderedImage = myView.getBaseImageLayer().getImage();
//for (int ii = 0; ii < tiles.length; ii++) {
myView = getProductSceneView(raster1);
renderedImage = imageAnimatorOp.createImage(myView, standardViewPort);
images[0] = new ImageIcon((BufferedImage)renderedImage);
//}
myView = getProductSceneView(raster2);
renderedImage = imageAnimatorOp.createImage(myView, standardViewPort);
images[1] = new ImageIcon((BufferedImage)renderedImage);
myView = getProductSceneView(raster3);
renderedImage = imageAnimatorOp.createImage(myView, standardViewPort);
images[2] = new ImageIcon((BufferedImage)renderedImage);
try{
lbl.setIcon(images[0]);
th.sleep(1000);
lbl.setIcon(images[1]);
th.sleep(1000);
lbl.setIcon(images[2]);
th.sleep(1000);
}
catch(InterruptedException e){}
}
public void actionPerformed(ActionEvent e) {
repaint();
}
public void startAnimation() {
if (animationTimer == null) {
currentImage = 0;
animationTimer = new Timer(animationDelay, this);
animationTimer.start();
} else if (!animationTimer.isRunning())
animationTimer.restart();
}
public void stopAnimation() {
animationTimer.stop();
}
public static void main(String args[]) {
AnimationTest anim = new AnimationTest();
JFrame app = new JFrame("Animator test");
app.add(anim, BorderLayout.CENTER);
app.setSize(500,1000);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setSize(anim.getPreferredSize().width + 10, anim.getPreferredSize().height + 30);
app.setVisible(true);
app.repaint();
}
}
| 4,862 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ImageAnimatorOp.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/operator/ImageAnimatorOp.java | package gov.nasa.gsfc.seadas.imageanimator.operator;
import com.bc.ceres.glayer.support.ImageLayer;
import com.bc.ceres.glevel.MultiLevelImage;
import com.bc.ceres.grender.Viewport;
import com.bc.ceres.grender.support.BufferedImageRendering;
import com.bc.ceres.grender.support.DefaultViewport;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.util.math.MathUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.product.ProductSceneImage;
import org.esa.snap.ui.product.ProductSceneView;
import javax.media.jai.ImageLayout;
import javax.media.jai.JAI;
import javax.media.jai.operator.FormatDescriptor;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.*;
import java.util.Hashtable;
public class ImageAnimatorOp {
private int imageWidth;
private int imageHeight;
double heightWidthRatio;
public ImageAnimatorOp(){
}
public RenderedImage createImage(ProductSceneView view) {
final boolean useAlpha = true; //!BMP_FORMAT_DESCRIPTION[0].equals(imageFormat) && !JPEG_FORMAT_DESCRIPTION[0].equals(imageFormat);
final boolean entireImage = true;
final boolean geoReferenced = false; //GEOTIFF_FORMAT_DESCRIPTION[0].equals(imageFormat)
Dimension dimension = new Dimension(getImageDimensions(view, entireImage));
return createImage(view, entireImage, dimension, useAlpha, geoReferenced);
}
static RenderedImage createImage(ProductSceneView view, boolean fullScene, Dimension dimension,
boolean alphaChannel, boolean geoReferenced) {
final int imageType = alphaChannel ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR;
final BufferedImage bufferedImage = new BufferedImage(dimension.width, dimension.height, imageType);
//final BufferedImage bufferedImage = new BufferedImage(804, 1739, imageType);
final BufferedImageRendering imageRendering = createRendering(view, fullScene,
geoReferenced, bufferedImage);
if (!alphaChannel) {
final Graphics2D graphics = imageRendering.getGraphics();
graphics.setColor(view.getLayerCanvas().getBackground());
graphics.fillRect(0, 0, dimension.width, dimension.height);
}
view.getRootLayer().render(imageRendering);
return bufferedImage;
}
private static BufferedImageRendering createRendering(ProductSceneView view, boolean fullScene,
boolean geoReferenced, BufferedImage bufferedImage) {
final Viewport vp1 = view.getLayerCanvas().getViewport();
final Viewport vp2 = new DefaultViewport(new Rectangle(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight()),
vp1.isModelYAxisDown());
if (fullScene) {
vp2.zoom(view.getBaseImageLayer().getModelBounds());
} else {
setTransform(vp1, vp2);
}
final BufferedImageRendering imageRendering = new BufferedImageRendering(bufferedImage, vp2);
if (geoReferenced) {
// because image to model transform is stored with the exported image we have to invert
// image to view transformation
final AffineTransform m2iTransform = view.getBaseImageLayer().getModelToImageTransform(0);
final AffineTransform v2mTransform = vp2.getViewToModelTransform();
v2mTransform.preConcatenate(m2iTransform);
final AffineTransform v2iTransform = new AffineTransform(v2mTransform);
final Graphics2D graphics2D = imageRendering.getGraphics();
v2iTransform.concatenate(graphics2D.getTransform());
graphics2D.setTransform(v2iTransform);
}
return imageRendering;
}
private static void setTransform(Viewport vp1, Viewport vp2) {
vp2.setTransform(vp1);
final Rectangle rectangle1 = vp1.getViewBounds();
final Rectangle rectangle2 = vp2.getViewBounds();
final double w1 = rectangle1.getWidth();
final double w2 = rectangle2.getWidth();
final double h1 = rectangle1.getHeight();
final double h2 = rectangle2.getHeight();
final double x1 = rectangle1.getX();
final double y1 = rectangle1.getY();
final double cx = (x1 + w1) / 2.0;
final double cy = (y1 + h1) / 2.0;
final double magnification;
if (w1 > h1) {
magnification = w2 / w1;
} else {
magnification = h2 / h1;
}
final Point2D modelCenter = vp1.getViewToModelTransform().transform(new Point2D.Double(cx, cy), null);
final double zoomFactor = vp1.getZoomFactor() * magnification;
if (zoomFactor > 0.0) {
vp2.setZoomFactor(zoomFactor, modelCenter.getX(), modelCenter.getY());
}
}
private void reformatSourceImage(Band band, ImageLayout imageLayout) {
RenderingHints renderingHints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, imageLayout);
MultiLevelImage sourceImage = band.getSourceImage();
Raster r = sourceImage.getData();
DataBuffer db = r.getDataBuffer();
int t = db.getDataType();
int dataType = sourceImage.getData().getDataBuffer().getDataType();
RenderedImage newImage = FormatDescriptor.create(sourceImage, dataType, renderingHints);
band.setSourceImage(newImage);
}
/**
* Converts the given rendered image into an image of the given {#link java.awt.image.BufferedImage} type.
*
* @param image the source image
* @param imageType the {#link java.awt.image.BufferedImage} type
* @return the buffered image of the given type
*/
public static BufferedImage convertImage(RenderedImage image, int imageType) {
final BufferedImage newImage;
final int width = image.getWidth();
final int height = image.getHeight();
if (imageType != BufferedImage.TYPE_CUSTOM) {
newImage = new BufferedImage(width, height, imageType);
} else {
// create custom image
final ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
final ColorModel cm = new ComponentColorModel(cs, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
final WritableRaster wr = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height, 3 * width, 3,
new int[]{2, 1, 0}, null);
newImage = new BufferedImage(cm, wr, false, null);
}
final Graphics2D graphics = newImage.createGraphics();
graphics.drawRenderedImage(image, null);
graphics.dispose();
return newImage;
}
public Dimension getImageDimensions(ProductSceneView view, boolean full) {
view = SnapApp.getDefault().getSelectedProductSceneView();
final Rectangle2D bounds;
if (full) {
final ImageLayer imageLayer = view.getBaseImageLayer();
final Rectangle2D modelBounds = imageLayer.getModelBounds();
Rectangle2D imageBounds = imageLayer.getModelToImageTransform().createTransformedShape(modelBounds).getBounds2D();
final double mScale = modelBounds.getWidth() / modelBounds.getHeight();
final double iScale = imageBounds.getHeight() / imageBounds.getWidth();
double scaleFactorX = mScale * iScale;
bounds = new Rectangle2D.Double(0, 0, scaleFactorX * imageBounds.getWidth(), 1 * imageBounds.getHeight());
} else {
bounds = view.getLayerCanvas().getViewport().getViewBounds();
}
imageWidth = toInteger(bounds.getWidth());
imageHeight = toInteger(bounds.getHeight());
heightWidthRatio = (double) imageHeight / (double) imageWidth;
return new Dimension(imageWidth, imageHeight);
}
private int toInteger(double value) {
return MathUtils.floorInt(value);
}
public static BufferedImage toBufferedImage(RenderedImage image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
ColorModel colorModel = image.getColorModel();
int width = image.getWidth();
int height = image.getHeight();
WritableRaster raster = colorModel.createCompatibleWritableRaster(width, height);
boolean isAlphaPremultiplied = colorModel.isAlphaPremultiplied();
Hashtable props = new Hashtable();
String[] keys = image.getPropertyNames();
if (keys != null) {
for (int i = 0; i < keys.length; i++) {
props.put(keys[i], image.getProperty(keys[i]));
}
}
BufferedImage bufferedImage = new BufferedImage(colorModel, raster, isAlphaPremultiplied, props);
image.copyData(raster);
return bufferedImage;
}
public RenderedImage createImage(ProductSceneView view, Viewport viewPort) {
final boolean useAlpha = true; //!BMP_FORMAT_DESCRIPTION[0].equals(imageFormat) && !JPEG_FORMAT_DESCRIPTION[0].equals(imageFormat);
final boolean entireImage = false;
final boolean geoReferenced = false; //GEOTIFF_FORMAT_DESCRIPTION[0].equals(imageFormat)
Dimension dimension = new Dimension(getImageDimensions(view, entireImage, viewPort));
return createImage(view, entireImage, dimension, useAlpha, geoReferenced);
}
public Dimension getImageDimensions(ProductSceneView view, boolean full, Viewport viewPort) {
Rectangle2D bounds;
if (full) {
final ImageLayer imageLayer = view.getBaseImageLayer();
final Rectangle2D modelBounds = imageLayer.getModelBounds();
Rectangle2D imageBounds = imageLayer.getModelToImageTransform().createTransformedShape(modelBounds).getBounds2D();
final double mScale = modelBounds.getWidth() / modelBounds.getHeight();
final double iScale = imageBounds.getHeight() / imageBounds.getWidth();
double scaleFactorX = mScale * iScale;
bounds = new Rectangle2D.Double(0, 0, scaleFactorX * imageBounds.getWidth(), 1 * imageBounds.getHeight());
} else {
bounds = viewPort.getViewBounds();
}
imageWidth = toInteger(bounds.getWidth());
imageHeight = toInteger(bounds.getHeight());
heightWidthRatio = (double) imageHeight / (double) imageWidth;
return new Dimension(imageWidth, imageHeight);
}
}
| 10,582 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
GifSequenceWriter.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/util/GifSequenceWriter.java | package gov.nasa.gsfc.seadas.imageanimator.util;
import javax.imageio.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.image.*;
import java.io.*;
import java.util.Iterator;
/**
* This class will generate an animated GIF from a sequence of individual images. Embedded in Wayang
* to facilitate capturing animations and interfaces rendered on the Push, for producing great online
* documentation.
*
* Originally created by Elliot Kroo on 2009-04-25. See http://elliot.kroo.net/software/java/GifSequenceWriter/
* James Elliott split the constructor into a variety of different versions, to accommodate the needs of Wayang.
*
* This work is licensed under the Creative Commons Attribution 3.0 Unported License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/
* or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
*
* @author Elliot Kroo (elliot[at]kroo[dot]net)
*/
public class GifSequenceWriter {
protected ImageWriter gifWriter;
protected ImageWriteParam imageWriteParam;
protected IIOMetadata imageMetaData;
/**
* Creates a new GifSequenceWriter from an existing buffered image.
*
* @param outputStream the ImageOutputStream to be written to
* @param image the source image that will be written to the output
* @param timeBetweenFramesMS the time between frames in miliseconds
* @param loopContinuously wether the gif should loop repeatedly
* @throws IIOException if no gif ImageWriters are found
*
* @author James Elliott
*/
public GifSequenceWriter(
ImageOutputStream outputStream,
RenderedImage image,
int timeBetweenFramesMS,
boolean loopContinuously) throws IIOException, IOException {
this(outputStream, ImageTypeSpecifier.createFromRenderedImage(image), timeBetweenFramesMS,
loopContinuously);
}
/**
* Creates a new GifSequenceWriter
*
* @param outputStream the ImageOutputStream to be written to
* @param imageType one of the imageTypes specified in BufferedImage
* @param timeBetweenFramesMS the time between frames in miliseconds
* @param loopContinuously wether the gif should loop repeatedly
* @throws IIOException if no gif ImageWriters are found
*
* @author Elliot Kroo (elliot[at]kroo[dot]net)
*/
public GifSequenceWriter(
ImageOutputStream outputStream,
int imageType,
int timeBetweenFramesMS,
boolean loopContinuously) throws IIOException, IOException {
this(outputStream, ImageTypeSpecifier.createFromBufferedImageType(imageType), timeBetweenFramesMS,
loopContinuously);
}
/**
* Creates a new GifSequenceWriter
*
* @param outputStream the ImageOutputStream to be written to
* @param imageTypeSpecifier the type of images to be written
* @param timeBetweenFramesMS the time between frames in miliseconds
* @param loopContinuously wether the gif should loop repeatedly
* @throws IIOException if no gif ImageWriters are found
*
* @author Elliot Kroo (elliot[at]kroo[dot]net)
*/
public GifSequenceWriter(
ImageOutputStream outputStream,
ImageTypeSpecifier imageTypeSpecifier,
int timeBetweenFramesMS,
boolean loopContinuously) throws IIOException, IOException {
// my method to create a writer
gifWriter = getWriter();
imageWriteParam = gifWriter.getDefaultWriteParam();
imageMetaData =
gifWriter.getDefaultImageMetadata(imageTypeSpecifier,
imageWriteParam);
String metaFormatName = imageMetaData.getNativeMetadataFormatName();
IIOMetadataNode root = (IIOMetadataNode)
imageMetaData.getAsTree(metaFormatName);
IIOMetadataNode graphicsControlExtensionNode = getNode(
root,
"GraphicControlExtension");
graphicsControlExtensionNode.setAttribute("disposalMethod", "none");
graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE");
graphicsControlExtensionNode.setAttribute(
"transparentColorFlag",
"FALSE");
graphicsControlExtensionNode.setAttribute(
"delayTime",
Integer.toString(timeBetweenFramesMS / 10));
graphicsControlExtensionNode.setAttribute(
"transparentColorIndex",
"0");
IIOMetadataNode commentsNode = getNode(root, "CommentExtensions");
commentsNode.setAttribute("CommentExtension", "Created by MAH");
IIOMetadataNode appEntensionsNode = getNode(
root,
"ApplicationExtensions");
IIOMetadataNode child = new IIOMetadataNode("ApplicationExtension");
child.setAttribute("applicationID", "NETSCAPE");
child.setAttribute("authenticationCode", "2.0");
int loop = loopContinuously ? 0 : 1;
child.setUserObject(new byte[]{ 0x1, (byte) (loop & 0xFF), (byte)
((loop >> 8) & 0xFF)});
appEntensionsNode.appendChild(child);
imageMetaData.setFromTree(metaFormatName, root);
gifWriter.setOutput(outputStream);
gifWriter.prepareWriteSequence(null);
}
public void writeToSequence(RenderedImage img) throws IOException {
gifWriter.writeToSequence(
new IIOImage(
img,
null,
imageMetaData),
imageWriteParam);
}
/**
* Close this GifSequenceWriter object. This does not close the underlying
* stream, just finishes off the GIF.
*
* @throws IOException if there is a problem writing the last bytes.
*/
public void close() throws IOException {
gifWriter.endWriteSequence();
}
/**
* Returns the first available GIF ImageWriter using
* ImageIO.getImageWritersBySuffix("gif").
*
* @return a GIF ImageWriter object
* @throws IIOException if no GIF image writers are returned
*/
private static ImageWriter getWriter() throws IIOException {
Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("gif");
if(!iter.hasNext()) {
throw new IIOException("No GIF Image Writers Exist");
} else {
return iter.next();
}
}
/**
* Returns an existing child node, or creates and returns a new child node (if
* the requested node does not exist).
*
* @param rootNode the <tt>IIOMetadataNode</tt> to search for the child node.
* @param nodeName the name of the child node.
*
* @return the child node, if found or a new node created with the given name.
*/
private static IIOMetadataNode getNode(
IIOMetadataNode rootNode,
String nodeName) {
int nNodes = rootNode.getLength();
for (int i = 0; i < nNodes; i++) {
if (rootNode.item(i).getNodeName().compareToIgnoreCase(nodeName)
== 0) {
return((IIOMetadataNode) rootNode.item(i));
}
}
IIOMetadataNode node = new IIOMetadataNode(nodeName);
rootNode.appendChild(node);
return(node);
}
/**
* Support invocation from the command line; provide a list of input file names, followed by a single output
* file name.
*
* @param args the names of the image files to be combined into a GIF sequence, followed by the output file name.
*
* @throws Exception if there is a problem reading the inputs or writing the output.
*/
public static void main(String[] args) throws Exception {
if (args.length > 1) {
// grab the output image type from the first image in the sequence
BufferedImage firstImage = ImageIO.read(new File(args[0]));
// create a new BufferedOutputStream with the last argument
ImageOutputStream output =
new FileImageOutputStream(new File(args[args.length - 1]));
// create a gif sequence with the type of the first image, 1 second
// between frames, which loops continuously
GifSequenceWriter writer =
new GifSequenceWriter(output, firstImage.getType(), 1, false);
// write out the first image to our sequence...
writer.writeToSequence(firstImage);
for(int i=1; i<args.length-1; i++) {
BufferedImage nextImage = ImageIO.read(new File(args[i]));
writer.writeToSequence(nextImage);
}
writer.close();
output.close();
} else {
System.out.println(
"Usage: java GifSequenceWriter [list of gif files] [output file]");
}
}
}
| 9,023 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
CommonUtilities.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/util/CommonUtilities.java | package gov.nasa.gsfc.seadas.imageanimator.util;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 5/30/14
* Time: 3:06 PM
* To change this template use File | Settings | File Templates.
*/
public class CommonUtilities {
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
}
| 581 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
Java2DConverter.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-image-animator/src/main/java/gov/nasa/gsfc/seadas/imageanimator/util/Java2DConverter.java | package gov.nasa.gsfc.seadas.imageanimator.util;
/**
* Created by IntelliJ IDEA.
* User: Aynur Abdurazik (aabduraz)
* Date: 4/11/14
* Time: 6:14 PM
* To change this template use File | Settings | File Templates.
*/
import org.locationtech.jts.awt.GeometryCollectionShape;
import org.locationtech.jts.awt.PolygonShape;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import java.awt.*;
import java.awt.geom.*;
import java.util.ArrayList;
/**
* Converts JTS Geometry objects into Java 2D Shape objects
*/
public class Java2DConverter {
private static double POINT_MARKER_SIZE = 0.0;
private final AffineTransform pointConverter;
public Java2DConverter(AffineTransform pointConverter) {
this.pointConverter = pointConverter;
}
private Shape toShape(Polygon p) {
ArrayList holeVertexCollection = new ArrayList();
for (int j = 0; j < p.getNumInteriorRing(); j++) {
holeVertexCollection.add(toViewCoordinates(p.getInteriorRingN(j)
.getCoordinates()));
}
return new PolygonShape(toViewCoordinates(p.getExteriorRing()
.getCoordinates()), holeVertexCollection);
}
private Coordinate[] toViewCoordinates(Coordinate[] modelCoordinates) {
Coordinate[] viewCoordinates = new Coordinate[modelCoordinates.length];
for (int i = 0; i < modelCoordinates.length; i++) {
Point2D point2D = toViewPoint(modelCoordinates[i]);
viewCoordinates[i] = new Coordinate(point2D.getX(), point2D.getY());
}
return viewCoordinates;
}
private Shape toShape(GeometryCollection gc)
throws NoninvertibleTransformException {
GeometryCollectionShape shape = new GeometryCollectionShape();
for (int i = 0; i < gc.getNumGeometries(); i++) {
Geometry g = gc.getGeometryN(i);
shape.add(toShape(g));
}
return shape;
}
private GeneralPath toShape(MultiLineString mls)
throws NoninvertibleTransformException {
GeneralPath path = new GeneralPath();
for (int i = 0; i < mls.getNumGeometries(); i++) {
LineString lineString = (LineString) mls.getGeometryN(i);
path.append(toShape(lineString), false);
}
// BasicFeatureRenderer expects LineStrings and MultiLineStrings to be
// converted to GeneralPaths. [Jon Aquino]
return path;
}
private GeneralPath toShape(LineString lineString)
throws NoninvertibleTransformException {
GeneralPath shape = new GeneralPath();
Point2D viewPoint = toViewPoint(lineString.getCoordinateN(0));
shape.moveTo((double) viewPoint.getX(), (double) viewPoint.getY());
for (int i = 1; i < lineString.getNumPoints(); i++) {
viewPoint = toViewPoint(lineString.getCoordinateN(i));
shape.lineTo((double) viewPoint.getX(), (double) viewPoint.getY());
}
//BasicFeatureRenderer expects LineStrings and MultiLineStrings to be
//converted to GeneralPaths. [Jon Aquino]
return shape;
}
private Shape toShape(Point point) {
Rectangle2D.Double pointMarker = new Rectangle2D.Double(0.0, 0.0,
POINT_MARKER_SIZE, POINT_MARKER_SIZE);
Point2D viewPoint = toViewPoint(point.getCoordinate());
pointMarker.x = (viewPoint.getX() - (POINT_MARKER_SIZE / 2));
pointMarker.y = (viewPoint.getY() - (POINT_MARKER_SIZE / 2));
return pointMarker;
// GeneralPath path = new GeneralPath();
// return viewPoint;
}
private Point2D toViewPoint(Coordinate modelCoordinate) {
// Do the rounding now; don't rely on Java 2D rounding, because it
// seems to do it differently for drawing and filling, resulting in the
// draw
// being a pixel off from the fill sometimes. [Jon Aquino]
double x = modelCoordinate.x;
double y = modelCoordinate.y;
// x = Math.round(x);
// y = Math.round(y);
Point2D modelPoint = new Point2D.Double(x, y);
Point2D viewPoint = modelPoint;
if (pointConverter != null) {
viewPoint = pointConverter.transform(modelPoint, null);
}
return viewPoint;
}
/**
* If you pass in a common GeometryCollection, note that a Shape cannot
* preserve information gov.nasa.gsfc.seadas.about which elements are 1D and which are 2D. For
* example, if you pass in a GeometryCollection containing a ring and a
* disk, you cannot render them as such: if you use Graphics.fill, you'll
* get two disks, and if you use Graphics.draw, you'll get two rings.
* Solution: create Shapes for each element.
*/
public Shape toShape(Geometry geometry)
throws NoninvertibleTransformException {
if (geometry.isEmpty()) {
return new GeneralPath();
}
if (geometry instanceof Polygon) {
return toShape((Polygon) geometry);
}
if (geometry instanceof MultiPolygon) {
return toShape((MultiPolygon) geometry);
}
if (geometry instanceof LineString) {
return toShape((LineString)geometry);
}
if (geometry instanceof MultiLineString) {
return toShape((MultiLineString) geometry);
}
if (geometry instanceof Point) {
return toShape((Point) geometry);
}
// as of JTS 1.8, the only thing that this might be is a
// jts.geom.MultiPoint, because
// MultiPolygon and MultiLineString are caught above. [Frank Hardisty]
if (geometry instanceof GeometryCollection) {
return toShape((GeometryCollection) geometry);
}
throw new IllegalArgumentException("Unrecognized Geometry class: "
+ geometry.getClass());
}
public static Geometry toMultiGon(GeneralPath path) {
// TODO Auto-generated method stub
return null;
}
}
| 6,114 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
WatermaskOpTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/test/java/gov/nasa/gsfc/seadas/watermask/operator/WatermaskOpTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* 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 gov.nasa.gsfc.seadas.watermask.operator;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.dataop.maptransf.Datum;
import org.esa.snap.core.gpf.GPF;
import org.junit.Before;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
/**
* @author Thomas Storm
* @author Ralf Quast
*/
@SuppressWarnings({"deprecation"})
public class WatermaskOpTest {
private Product sourceProduct;
private Map<String,Object> parameters;
@Before
public void setUp() throws Exception {
sourceProduct = new Product("dummy", "type", 1, 1);
sourceProduct.setSceneGeoCoding(new MyGeoCoding());
parameters = new HashMap<String, Object>();
GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis();
}
// @Test
// public void testWithSubsampling() throws Exception {
// parameters.put("subSamplingFactorX", 10);
// parameters.put("subSamplingFactorY", 10);
// Product lwProduct = GPF.createProduct(OperatorSpi.getOperatorAlias(WatermaskOp.class), parameters, sourceProduct);
// actualTest(lwProduct);
// }
//
// @Test
// public void testWithoutSubsampling() throws Exception {
// Product lwProduct = GPF.createProduct(OperatorSpi.getOperatorAlias(WatermaskOp.class), parameters, sourceProduct);
// actualTest(lwProduct);
// }
private void actualTest(Product lwProduct) {
Band band = lwProduct.getBand("land_water_fraction");
byte sample = (byte) band.getSourceImage().getData().getSample(0, 0, 0);
assertEquals(100, sample);
}
private static class MyGeoCoding implements GeoCoding {
@Override
public boolean isCrossingMeridianAt180() {
return false;
}
@Override
public boolean canGetPixelPos() {
return false;
}
@Override
public boolean canGetGeoPos() {
return true;
}
@Override
public PixelPos getPixelPos(GeoPos geoPos, PixelPos pixelPos) {
return null;
}
@Override
public GeoPos getGeoPos(PixelPos pixelPos, GeoPos geoPos) {
/*
Pixel values and pixel size directly derived from GlobCover map
*/
double pixelSize = 0.002777777777777778;
geoPos.setLocation((float) (66.40278 + (pixelPos.y - 0.5) * pixelSize), (float) (28.063889 + (pixelPos.x - 0.5) * pixelSize));
return geoPos;
}
@Override
public Datum getDatum() {
return null;
}
@Override
public void dispose() {
}
@Override
public CoordinateReferenceSystem getImageCRS() {
return null;
}
@Override
public CoordinateReferenceSystem getMapCRS() {
return null;
}
@Override
public CoordinateReferenceSystem getGeoCRS() {
return null;
}
@Override
public MathTransform getImageToMapTransform() {
return null;
}
@Override
public GeoCoding clone() {
return null;
}
@Override
public boolean canClone() {
return false;
}
}
}
| 4,153 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
WatermaskClassifierTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/test/java/gov/nasa/gsfc/seadas/watermask/operator/WatermaskClassifierTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* 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 gov.nasa.gsfc.seadas.watermask.operator;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.net.URL;
import org.esa.snap.watermask.operator.WatermaskClassifier;
import static org.junit.Assert.*;
/**
* @author Thomas Storm
*/
public class WatermaskClassifierTest {
private WatermaskClassifier gcClassifier;
private WatermaskClassifier modisClassifier;
private WatermaskClassifier fillClassifier;
// @Before
// public void setUp() throws Exception {
// gcClassifier = new WatermaskClassifier(WatermaskClassifier.RESOLUTION_50m, WatermaskClassifier.Mode.SRTM_GC, "50m.zip");
// modisClassifier = new WatermaskClassifier(WatermaskClassifier.RESOLUTION_50m, WatermaskClassifier.Mode.MODIS, "50m.zip");
// fillClassifier = new WatermaskClassifier(WatermaskClassifier.RESOLUTION_50m, WatermaskClassifier.Mode.GSHHS, "50m.zip");
// }
//
// @Test
// public void testFill() throws Exception {
// assertTrue(fillClassifier.isWater(42.908833f, 5.5034647f));
// assertTrue(fillClassifier.isWater(42.092968f, 4.950571f));
// }
//
// @Test
// public void testGetWatermaskSampleAboveSixtyGC() throws Exception {
// assertEquals(WatermaskClassifier.WATER_VALUE, gcClassifier.getWaterMaskSample(70.860277f, 29.205115f));
// assertEquals(WatermaskClassifier.LAND_VALUE, gcClassifier.getWaterMaskSample(70.853971f, 29.210610f));
//
// assertEquals(WatermaskClassifier.WATER_VALUE, gcClassifier.getWaterMaskSample(72.791664f, 105.28333f));
// assertEquals(WatermaskClassifier.LAND_VALUE, gcClassifier.getWaterMaskSample(72.794586f, 105.27786f));
//
// assertEquals(WatermaskClassifier.WATER_VALUE, gcClassifier.getWaterMaskSample(80.19444f, 25.963888f));
// assertEquals(WatermaskClassifier.LAND_VALUE, gcClassifier.getWaterMaskSample(80.14856f, 25.95601f));
//
// assertEquals(WatermaskClassifier.WATER_VALUE, gcClassifier.getWaterMaskSample(80.18703f, 26.04707f));
// assertEquals(WatermaskClassifier.LAND_VALUE, gcClassifier.getWaterMaskSample(80.176834f, 26.054949f));
// }
//
// @Test
// public void testIsWaterCenter() throws Exception {
//
// assertFalse(gcClassifier.isWater(30.30539f, 111.55285f));
// assertTrue(gcClassifier.isWater(30.269484f, 111.55418f));
//
// assertFalse(gcClassifier.isWater(49.68f, 0.581f));
// assertTrue(gcClassifier.isWater(49.434505f, 0.156014f));
//
// assertTrue(gcClassifier.isWater(49.33615f, -0.0096f));
// assertFalse(gcClassifier.isWater(49.32062f, -0.005918f));
//
// assertFalse(gcClassifier.isWater(46.5f, 0.5f));
//
// assertTrue(gcClassifier.isWater(5.01f, 0.01f));
// assertTrue(gcClassifier.isWater(5.95f, 0.93f));
// assertTrue(gcClassifier.isWater(5.04f, 0.95f));
//
// assertTrue(gcClassifier.isWater(5.5f, 0.5f));
// assertFalse(gcClassifier.isWater(5.88f, 0.24f));
//
// assertTrue(gcClassifier.isWater(43.322360f, 4.157f));
// assertTrue(gcClassifier.isWater(43.511243f, 3.869841f));
//
// assertFalse(gcClassifier.isWater(45.981416f, -84.462957f));
// assertTrue(gcClassifier.isWater(45.967423f, -84.477179f));
//
// assertTrue(gcClassifier.isWater(53.5f, 5.92f));
// assertFalse(gcClassifier.isWater(53.458760f, 5.801733f));
//
// assertTrue(gcClassifier.isWater(-4.347463f, 11.443256f));
// assertFalse(gcClassifier.isWater(-4.2652f, 11.49324f));
// }
//
// @Test
// @Ignore
// public void testGetWatermaskSampleBelowSixty() throws Exception {
//
// assertEquals(WatermaskClassifier.WATER_VALUE, modisClassifier.getWaterMaskSample(-62.611664f, -60.20445f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(-62.609562f, -60.204235f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(-62.609562f, -60.20228f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(-62.61169f, -60.202232f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(-62.61392f, -60.202305f));
//
// assertEquals(WatermaskClassifier.WATER_VALUE, modisClassifier.getWaterMaskSample(-62.409748f, -59.565838f));
// assertEquals(WatermaskClassifier.WATER_VALUE, modisClassifier.getWaterMaskSample(-62.412197f, -59.565838f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(-62.409687f, -59.56362f));
//
// assertEquals(WatermaskClassifier.WATER_VALUE, modisClassifier.getWaterMaskSample(-64.12632f, -56.906746f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(-64.124504f, -56.906593f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(-64.12606f, -56.908825f));
// assertEquals(WatermaskClassifier.WATER_VALUE, modisClassifier.getWaterMaskSample(-64.12833f, -56.911137f));
// }
//
// @Test
// @Ignore
// public void testGetWatermaskSampleAboveSixtyMODIS() throws Exception {
//
// assertEquals(WatermaskClassifier.WATER_VALUE, modisClassifier.getWaterMaskSample(70.860277f, 29.205115f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(70.853971f, 29.210610f));
//
// assertEquals(WatermaskClassifier.WATER_VALUE, modisClassifier.getWaterMaskSample(72.791664f, 105.28333f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(72.794586f, 105.27786f));
//
// assertEquals(WatermaskClassifier.WATER_VALUE, modisClassifier.getWaterMaskSample(80.19444f, 25.963888f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(80.14856f, 25.95601f));
//
// assertEquals(WatermaskClassifier.WATER_VALUE, modisClassifier.getWaterMaskSample(80.18703f, 26.04707f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(80.176834f, 26.054949f));
//
// assertEquals(WatermaskClassifier.WATER_VALUE, modisClassifier.getWaterMaskSample(76.36008f, -20.632616f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(76.36008f, -20.63075f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(76.36214f, -20.63075f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(76.362175f, -20.63285f));
// assertEquals(WatermaskClassifier.LAND_VALUE, modisClassifier.getWaterMaskSample(76.357895f, -20.632656f));
// }
//
// @Test
// public void testGetZipfile() throws Exception {
// // north-west
//
// assertEquals("w002n51.img", WatermaskUtils.createImgFileName(51.007f, -1.30f));
// assertFalse("w001n51.img".equals(WatermaskUtils.createImgFileName(51.007f, -1.30f)));
//
// assertEquals("w002n48.img", WatermaskUtils.createImgFileName(48.007f, -1.83f));
// assertFalse("w001n48.img".equals(WatermaskUtils.createImgFileName(48.007f, -1.83f)));
//
// // north-east
//
// assertEquals("e000n51.img", WatermaskUtils.createImgFileName(51.007f, 0.30f));
// assertFalse("e001n51.img".equals(WatermaskUtils.createImgFileName(51.007f, 0.30f)));
//
// assertEquals("e000n49.img", WatermaskUtils.createImgFileName(49.993961334228516f, 0.006230226717889309f));
// assertFalse("w001n49.img".equals(WatermaskUtils.createImgFileName(51.007f, 0.30f)));
//
// assertEquals("e001n51.img", WatermaskUtils.createImgFileName(51.007f, 1.30f));
// assertFalse("e000n51.img".equals(WatermaskUtils.createImgFileName(51.007f, 1.30f)));
//
// assertEquals("e000n45.img", WatermaskUtils.createImgFileName(45.001f, 0.005f));
// assertFalse("w000n45.img".equals(WatermaskUtils.createImgFileName(45.001f, 0.005f)));
//
// assertEquals("e111n30.img", WatermaskUtils.createImgFileName(30.27f, 111.581f));
// assertFalse("e111n30.img".equals(WatermaskUtils.createImgFileName(29.01f, 112.01f)));
//
// // south-west
//
// assertEquals("w001s01.img", WatermaskUtils.createImgFileName(-0.01f, -0.30f));
// assertFalse("w000s01.img".equals(WatermaskUtils.createImgFileName(-0.01f, -0.30f)));
//
// assertEquals("w002s02.img", WatermaskUtils.createImgFileName(-1.01f, -1.30f));
// assertFalse("w001s01.img".equals(WatermaskUtils.createImgFileName(-1.01f, -1.30f)));
//
// // south-east
//
// assertEquals("e000s01.img", WatermaskUtils.createImgFileName(-0.01f, 0.30f));
// assertFalse("e000s00.img".equals(WatermaskUtils.createImgFileName(-0.01f, 0.30f)));
//
// assertEquals("e001s01.img", WatermaskUtils.createImgFileName(-0.01f, 1.30f));
// assertFalse("e001s00.img".equals(WatermaskUtils.createImgFileName(-0.01f, 1.30f)));
// }
//
// @Test
// public void testGetResource() throws Exception {
// URL resource = getClass().getResource("image.properties");
// assertNotNull(resource);
// }
} | 9,874 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ShapeFileRasterizerTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/test/java/gov/nasa/gsfc/seadas/watermask/util/ShapeFileRasterizerTest.java | package gov.nasa.gsfc.seadas.watermask.util;
import junit.framework.TestCase;
import org.esa.snap.watermask.operator.WatermaskUtils;
import org.junit.Test;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipFile;
public class ShapeFileRasterizerTest extends TestCase {
@Test
public void testImageCreation() throws IOException {
final File targetDir = new File("");
final ShapeFileRasterizer rasterizer = new ShapeFileRasterizer(targetDir);
final URL shapeUrl = getClass().getResource("e000n05f.shp");
final File shapeFile = new File(shapeUrl.getFile());
final int resolution = WatermaskUtils.computeSideLength(150);
final BufferedImage image = rasterizer.createImage(shapeFile, resolution);
// test some known values
final Raster imageData = image.getData();
assertEquals(1, imageData.getSample(526, 92, 0));
assertEquals(0, imageData.getSample(312, 115, 0));
assertEquals(1, imageData.getSample(141, 187, 0));
assertEquals(0, imageData.getSample(197, 27, 0));
assertEquals(1, imageData.getSample(308, 701, 0));
}
@Test
public void testFromZip() throws IOException {
final File targetDir = new File("");
final ShapeFileRasterizer rasterizer = new ShapeFileRasterizer(targetDir);
final URL shapeUrl = getClass().getResource("e000n05f.zip");
final int tileSize = WatermaskUtils.computeSideLength(150);
final List<File> tempFiles;
final ZipFile zipFile = new ZipFile(shapeUrl.getFile());
try {
tempFiles = rasterizer.createTempFiles(zipFile);
} finally {
zipFile.close();
}
BufferedImage image = null;
for (File file : tempFiles) {
if (file.getName().endsWith("shp")) {
image = rasterizer.createImage(file, tileSize);
}
}
assertNotNull(image);
// // test some known values
final Raster imageData = image.getData();
assertEquals(1, imageData.getSample(526, 92, 0));
assertEquals(0, imageData.getSample(312, 115, 0));
assertEquals(1, imageData.getSample(141, 187, 0));
assertEquals(0, imageData.getSample(197, 27, 0));
assertEquals(1, imageData.getSample(308, 701, 0));
}
}
| 2,479 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
LandMaskRasterCreatorTest.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/test/java/gov/nasa/gsfc/seadas/watermask/util/LandMaskRasterCreatorTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* 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 gov.nasa.gsfc.seadas.watermask.util;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import static org.junit.Assert.assertEquals;
/**
* @author Thomas Storm
*/
@SuppressWarnings({"ReuseOfLocalVariable"})
public class LandMaskRasterCreatorTest {
@Test
public void testMixedFile() throws Exception {
final BufferedImage image = ImageIO.read(getClass().getResource("156-12.png"));
int sample = image.getData().getSample(220, 40, 0);
assertEquals(0, sample);
sample = image.getData().getSample(220, 41, 0);
assertEquals(1, sample);
sample = image.getData().getSample(187, 89, 0);
assertEquals(0, sample);
sample = image.getData().getSample(186, 89, 0);
assertEquals(1, sample);
sample = image.getData().getSample(188, 89, 0);
assertEquals(1, sample);
}
@Test
public void testAllWaterFile() throws Exception {
final BufferedImage image = ImageIO.read(getClass().getResource("195-10.png"));
Raster imageData = image.getData();
for (int x = 0; x < imageData.getWidth(); x++) {
for (int y = 0; y < imageData.getHeight(); y++) {
assertEquals(0, imageData.getSample(x, y, 0));
}
}
}
@Test
public void testAllLandFile() throws Exception {
final BufferedImage image = ImageIO.read(getClass().getResource("92-10.png"));
Raster imageData = image.getData();
for (int x = 0; x < imageData.getWidth(); x++) {
for (int y = 0; y < imageData.getHeight(); y++) {
assertEquals(1, imageData.getSample(x, y, 0));
}
}
}
}
| 2,481 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
Landmask_Controller.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/preferences/Landmask_Controller.java | /*
* Copyright (C) 2011 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* 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 gov.nasa.gsfc.seadas.watermask.preferences;
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.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.PropertyEditorRegistry;
import com.bc.ceres.swing.binding.PropertyPane;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.rcp.SnapApp;
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.*;
import java.awt.*;
/**
* * Panel handling LandCoastMask preferences. Sub-panel of the "SeaDAS-Toolbox"-panel.
*
* @author Daniel Knowles
*/
@OptionsPanelController.SubRegistration(location = "SeaDAS",
displayName = "#Options_DisplayName_LandCoastMask",
keywords = "#Options_Keywords_LandCoastMask",
keywordsCategory = "General Tools",
id = "LandCoastMask")
@org.openide.util.NbBundle.Messages({
"Options_DisplayName_LandCoastMask=Land Coast Mask",
"Options_Keywords_LandCoastMask=seadas, Land Coast Mask"
})
public final class Landmask_Controller extends DefaultConfigController {
Property restoreDefaults;
boolean propertyValueChangeEventsEnabled = true;
public static final String RESOLUTION_50m = "50 m (SRTM_GC)";
public static final String RESOLUTION_150m = "150 m (SRTM_GC)";
public static final String RESOLUTION_1km = "1 km (GSHHS)";
public static final String RESOLUTION_10km = "10 km (GSHHS)";
// Preferences property prefix
private static final String PROPERTY_LANDMASK_ROOT_KEY = "seadas.toolbox.landcoast";
public static final String PROPERTY_LANDMASK_RESOLUTION_KEY = PROPERTY_LANDMASK_ROOT_KEY + ".landmask.resolution";
public static final String PROPERTY_LANDMASK_RESOLUTION_LABEL = "Resolution";
public static final String PROPERTY_LANDMASK_RESOLUTION_TOOLTIP = "Resolution";
public static final String PROPERTY_LANDMASK_RESOLUTION_DEFAULT = RESOLUTION_1km;
public static final String PROPERTY_LANDMASK_SECTION_KEY = PROPERTY_LANDMASK_ROOT_KEY + ".landmask.section";
public static final String PROPERTY_LANDMASK_SECTION_LABEL = "Land Mask Options";
public static final String PROPERTY_LANDMASK_SECTION_TOOLTIP = "Land mask options";
public static final String PROPERTY_LANDMASK_NAME_KEY = PROPERTY_LANDMASK_ROOT_KEY + ".landmask.name";
public static final String PROPERTY_LANDMASK_NAME_LABEL = "Land Mask Name";
public static final String PROPERTY_LANDMASK_NAME_TOOLTIP = "Land mask name";
public static final String PROPERTY_LANDMASK_NAME_DEFAULT = "LandMask";
public static final String PROPERTY_LANDMASK_COLOR_KEY = PROPERTY_LANDMASK_ROOT_KEY + ".landmask.color";
public static final String PROPERTY_LANDMASK_COLOR_LABEL = "Land Mask Color";
public static final String PROPERTY_LANDMASK_COLOR_TOOLTIP = "Land mask color";
public static final Color PROPERTY_LANDMASK_COLOR_DEFAULT = new Color(70,70,0);
public static final String PROPERTY_LANDMASK_TRANSPARENCY_KEY = PROPERTY_LANDMASK_ROOT_KEY + ".landmask.transparency";
public static final String PROPERTY_LANDMASK_TRANSPARENCY_LABEL = "Land Mask Transparency";
public static final String PROPERTY_LANDMASK_TRANSPARENCY_TOOLTIP = "Land mask transparency ";
public static final double PROPERTY_LANDMASK_TRANSPARENCY_DEFAULT = 0.0;
public static final String PROPERTY_LANDMASK_SHOW_KEY = PROPERTY_LANDMASK_ROOT_KEY + ".landmask.show";
public static final String PROPERTY_LANDMASK_SHOW_LABEL = "Land Mask Show";
public static final String PROPERTY_LANDMASK_SHOW_TOOLTIP = "Land mask will be displayed in all bands ";
public static final boolean PROPERTY_LANDMASK_SHOW_DEFAULT = false;
// Property Setting: Restore Defaults
private static final String PROPERTY_RESTORE_KEY_SUFFIX = PROPERTY_LANDMASK_ROOT_KEY + ".restore.defaults";
public static final String PROPERTY_RESTORE_SECTION_KEY = PROPERTY_RESTORE_KEY_SUFFIX + ".section";
public static final String PROPERTY_RESTORE_SECTION_LABEL = "Restore";
public static final String PROPERTY_RESTORE_SECTION_TOOLTIP = "Restores preferences to the package defaults";
public static final String PROPERTY_RESTORE_DEFAULTS_KEY = PROPERTY_RESTORE_KEY_SUFFIX + ".apply";
public static final String PROPERTY_RESTORE_DEFAULTS_LABEL = "Default (L3mapgen Preferences)";
public static final String PROPERTY_RESTORE_DEFAULTS_TOOLTIP = "Restore all L3mapgen preferences to the original default";
public static final boolean PROPERTY_RESTORE_DEFAULTS_DEFAULT = false;
protected PropertySet createPropertySet() {
return createPropertySet(new SeadasToolboxBean());
}
@Override
protected JPanel createPanel(BindingContext context) {
//
// Initialize the default value contained within each property descriptor
// This is done so subsequently the restoreDefaults actions can be performed
//
initPropertyDefaults(context, PROPERTY_LANDMASK_RESOLUTION_KEY, PROPERTY_LANDMASK_RESOLUTION_DEFAULT);
initPropertyDefaults(context, PROPERTY_LANDMASK_SECTION_KEY, true);
initPropertyDefaults(context, PROPERTY_LANDMASK_COLOR_KEY, PROPERTY_LANDMASK_COLOR_DEFAULT);
initPropertyDefaults(context, PROPERTY_LANDMASK_NAME_KEY, PROPERTY_LANDMASK_NAME_DEFAULT);
initPropertyDefaults(context, PROPERTY_LANDMASK_TRANSPARENCY_KEY, PROPERTY_LANDMASK_TRANSPARENCY_DEFAULT);
initPropertyDefaults(context, PROPERTY_LANDMASK_SHOW_KEY, PROPERTY_LANDMASK_SHOW_DEFAULT);
initPropertyDefaults(context, PROPERTY_RESTORE_SECTION_KEY, true);
restoreDefaults = initPropertyDefaults(context, PROPERTY_RESTORE_DEFAULTS_KEY, PROPERTY_RESTORE_DEFAULTS_DEFAULT);
//
// Create UI
//
TableLayout tableLayout = new TableLayout(2);
tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST);
tableLayout.setTablePadding(new Insets(4, 10, 0, 0));
tableLayout.setTableFill(TableLayout.Fill.BOTH);
tableLayout.setColumnWeightX(1, 1.0);
JPanel pageUI = new JPanel(tableLayout);
PropertyEditorRegistry registry = PropertyEditorRegistry.getInstance();
PropertySet propertyContainer = context.getPropertySet();
Property[] properties = propertyContainer.getProperties();
int currRow = 0;
for (Property property : properties) {
PropertyDescriptor descriptor = property.getDescriptor();
PropertyPane.addComponent(currRow, tableLayout, pageUI, context, registry, descriptor);
currRow++;
}
pageUI.add(tableLayout.createVerticalSpacer());
JPanel parent = new JPanel(new BorderLayout());
parent.add(pageUI, BorderLayout.CENTER);
parent.add(Box.createHorizontalStrut(50), BorderLayout.EAST);
return parent;
}
@Override
protected void configure(BindingContext context) {
// Handle resetDefaults events - set all other components to defaults
restoreDefaults.addPropertyChangeListener(evt -> {
handleRestoreDefaults(context);
});
// Add listeners to all components in order to uncheck restoreDefaults checkbox accordingly
PropertySet propertyContainer = context.getPropertySet();
Property[] properties = propertyContainer.getProperties();
for (Property property : properties) {
if (property != restoreDefaults) {
property.addPropertyChangeListener(evt -> {
handlePreferencesPropertyValueChange(context);
});
}
}
// This call is an initialization call which set restoreDefault initial value
handlePreferencesPropertyValueChange(context);
}
/**
* Test all properties to determine whether the current value is the default value
*
* @param context
* @return
* @author Daniel Knowles
*/
private boolean isDefaults(BindingContext context) {
PropertySet propertyContainer = context.getPropertySet();
Property[] properties = propertyContainer.getProperties();
for (Property property : properties) {
if (property != restoreDefaults && property.getDescriptor().getDefaultValue() != null)
if (!property.getValue().equals(property.getDescriptor().getDefaultValue())) {
return false;
}
}
return true;
}
/**
* Handles the restore defaults action
*
* @param context
* @author Daniel Knowles
*/
private void handleRestoreDefaults(BindingContext context) {
if (propertyValueChangeEventsEnabled) {
propertyValueChangeEventsEnabled = false;
try {
if (restoreDefaults.getValue()) {
PropertySet propertyContainer = context.getPropertySet();
Property[] properties = propertyContainer.getProperties();
for (Property property : properties) {
if (property != restoreDefaults && property.getDescriptor().getDefaultValue() != null)
property.setValue(property.getDescriptor().getDefaultValue());
}
}
} catch (ValidationException e) {
e.printStackTrace();
}
propertyValueChangeEventsEnabled = true;
context.setComponentsEnabled(PROPERTY_RESTORE_DEFAULTS_KEY, false);
}
}
/**
* Set restoreDefault component because a property has changed
* @param context
* @author Daniel Knowles
*/
private void handlePreferencesPropertyValueChange(BindingContext context) {
if (propertyValueChangeEventsEnabled) {
propertyValueChangeEventsEnabled = false;
try {
restoreDefaults.setValue(isDefaults(context));
context.setComponentsEnabled(PROPERTY_RESTORE_DEFAULTS_KEY, !isDefaults(context));
} catch (ValidationException e) {
e.printStackTrace();
}
propertyValueChangeEventsEnabled = true;
}
}
/**
* Initialize the property descriptor default value
*
* @param context
* @param propertyName
* @param propertyDefault
* @return
* @author Daniel Knowles
*/
private Property initPropertyDefaults(BindingContext context, String propertyName, Object propertyDefault) {
System.out.println("propertyName=" + propertyName);
if (context == null) {
System.out.println("WARNING: context is null");
}
Property property = context.getPropertySet().getProperty(propertyName);
if (property == null) {
System.out.println("WARNING: property is null");
}
property.getDescriptor().setDefaultValue(propertyDefault);
return property;
}
// todo add a help page ... see the ColorBarLayerController for example
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx("LandCoast");
}
@SuppressWarnings("UnusedDeclaration")
static class SeadasToolboxBean {
@Preference(key = PROPERTY_LANDMASK_RESOLUTION_KEY,
label = PROPERTY_LANDMASK_RESOLUTION_LABEL,
valueSet = {RESOLUTION_50m, RESOLUTION_150m, RESOLUTION_1km, RESOLUTION_10km},
description = PROPERTY_LANDMASK_RESOLUTION_TOOLTIP)
String landmaskResolutionDefault = PROPERTY_LANDMASK_RESOLUTION_DEFAULT;
@Preference(key = PROPERTY_LANDMASK_SECTION_KEY,
label = PROPERTY_LANDMASK_SECTION_LABEL,
description = PROPERTY_LANDMASK_SECTION_TOOLTIP)
boolean landmaskSectionDefault = true;
@Preference(key = PROPERTY_LANDMASK_NAME_KEY,
label = PROPERTY_LANDMASK_NAME_LABEL,
description = PROPERTY_LANDMASK_NAME_TOOLTIP)
String landmaskNameDefault = PROPERTY_LANDMASK_NAME_DEFAULT;
@Preference(key = PROPERTY_LANDMASK_COLOR_KEY,
label = PROPERTY_LANDMASK_COLOR_LABEL,
description = PROPERTY_LANDMASK_COLOR_TOOLTIP)
Color landmaskColorDefault = PROPERTY_LANDMASK_COLOR_DEFAULT;
@Preference(key = PROPERTY_LANDMASK_TRANSPARENCY_KEY,
label = PROPERTY_LANDMASK_TRANSPARENCY_LABEL,
description = PROPERTY_LANDMASK_TRANSPARENCY_TOOLTIP)
double landmaskTransparencyDefault = PROPERTY_LANDMASK_TRANSPARENCY_DEFAULT;
@Preference(key = PROPERTY_LANDMASK_SHOW_KEY,
label = PROPERTY_LANDMASK_SHOW_LABEL,
description = PROPERTY_LANDMASK_SHOW_TOOLTIP)
boolean landmaskShowDefault = PROPERTY_LANDMASK_SHOW_DEFAULT;
// Restore Defaults Section
@Preference(key = PROPERTY_RESTORE_SECTION_KEY,
label = PROPERTY_RESTORE_SECTION_LABEL,
description = PROPERTY_RESTORE_SECTION_TOOLTIP)
boolean restoreDefaultsSection = true;
@Preference(key = PROPERTY_RESTORE_DEFAULTS_KEY,
label = PROPERTY_RESTORE_DEFAULTS_LABEL,
description = PROPERTY_RESTORE_DEFAULTS_TOOLTIP)
boolean restoreDefaultsDefault = PROPERTY_RESTORE_DEFAULTS_DEFAULT;
}
public static String getPreferenceLandMaskResolution() {
final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences();
return preferences.getPropertyString(PROPERTY_LANDMASK_RESOLUTION_KEY, PROPERTY_LANDMASK_RESOLUTION_DEFAULT);
}
public static String getPreferenceLandMaskName() {
final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences();
String landMaskName = preferences.getPropertyString(PROPERTY_LANDMASK_NAME_KEY, PROPERTY_LANDMASK_NAME_DEFAULT);
if (landMaskName != null && landMaskName.length() > 2) {
return landMaskName;
} else {
return PROPERTY_LANDMASK_NAME_DEFAULT;
}
}
public static Color getPreferenceLandMaskColor() {
final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences();
return preferences.getPropertyColor(PROPERTY_LANDMASK_COLOR_KEY, PROPERTY_LANDMASK_COLOR_DEFAULT);
}
public static double getPreferenceLandMaskTransparency() {
final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences();
return preferences.getPropertyDouble(PROPERTY_LANDMASK_TRANSPARENCY_KEY, PROPERTY_LANDMASK_TRANSPARENCY_DEFAULT);
}
public static boolean getPreferenceLandMaskShow() {
final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences();
return preferences.getPropertyBool(PROPERTY_LANDMASK_SHOW_KEY, PROPERTY_LANDMASK_SHOW_DEFAULT);
}
}
| 15,932 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
SuperSamplingSpinner.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/SuperSamplingSpinner.java | package gov.nasa.gsfc.seadas.watermask.ui;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/5/12
* Time: 11:07 AM
* To change this template use File | Settings | File Templates.
*/
public class SuperSamplingSpinner {
private LandMasksData landMasksData;
private JLabel jLabel;
private JSpinner jSpinner = new JSpinner();
public SuperSamplingSpinner(LandMasksData landMasksData) {
this.landMasksData = landMasksData;
jLabel = new JLabel("Super Sampling Factor");
jLabel.setToolTipText("Super Sampling");
jSpinner.setModel(new SpinnerNumberModel(20, 1, 20, 1));
jSpinner.setPreferredSize(jSpinner.getPreferredSize());
jSpinner.setSize(jSpinner.getPreferredSize());
jSpinner.setModel(new SpinnerNumberModel(landMasksData.getSuperSampling(), 1, 20, 1));
// JSpinner.NumberEditor editor = (JSpinner.NumberEditor) jSpinner.getEditor();
// DecimalFormat format = editor.getFormat();
// format.setMinimumFractionDigits(1);
addControlListeners();
}
private void addControlListeners() {
jSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent changeEvent) {
int value =Integer.parseInt(jSpinner.getValue().toString() );
landMasksData.setSuperSampling(value);
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JSpinner getjSpinner() {
return jSpinner;
}
}
| 1,662 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
LandTransparencySpinner.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/LandTransparencySpinner.java | package gov.nasa.gsfc.seadas.watermask.ui;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.text.DecimalFormat;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 9:19 AM
* To change this template use File | Settings | File Templates.
*/
public class LandTransparencySpinner {
private LandMasksData landMasksData;
private JLabel jLabel;
private JSpinner jSpinner = new JSpinner();
public LandTransparencySpinner(LandMasksData landMasksData) {
this.landMasksData = landMasksData;
jLabel = new JLabel("Transparency");
jLabel.setToolTipText("Land mask transparency");
jSpinner.setToolTipText("Land mask transparency");
jSpinner.setModel(new SpinnerNumberModel(100, 0, 100, 100));
jSpinner.setPreferredSize(jSpinner.getPreferredSize());
jSpinner.setSize(jSpinner.getPreferredSize());
jSpinner.setModel(new SpinnerNumberModel(landMasksData.getLandMaskTransparency(), 0.0, 1.0, 0.1));
JSpinner.NumberEditor editor = (JSpinner.NumberEditor) jSpinner.getEditor();
DecimalFormat format = editor.getFormat();
format.setMinimumFractionDigits(1);
addControlListeners();
}
private void addControlListeners() {
jSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent changeEvent) {
landMasksData.setLandMaskTransparency((Double) jSpinner.getValue());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JSpinner getjSpinner() {
return jSpinner;
}
}
| 1,719 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
CoastlineEnabledAllBandsCheckbox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/CoastlineEnabledAllBandsCheckbox.java | package gov.nasa.gsfc.seadas.watermask.ui;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 10:27 AM
* To change this template use File | Settings | File Templates.
*/
public class CoastlineEnabledAllBandsCheckbox {
private LandMasksData landMasksData;
private JLabel jLabel;
private JCheckBox jCheckBox = new JCheckBox();
private static String DEFAULT_NAME = "Enabled in All Bands";
private static String DEFAULT_TOOLTIPS = "Set Coastline Mask Enabled in All Bands";
public CoastlineEnabledAllBandsCheckbox(LandMasksData landMasksData) {
this.landMasksData = landMasksData;
jLabel = new JLabel(DEFAULT_NAME);
jLabel.setToolTipText(DEFAULT_TOOLTIPS);
jCheckBox.setSelected(landMasksData.isShowCoastlineMaskAllBands());
addControlListeners();
}
private void addControlListeners() {
jCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
landMasksData.setShowCoastlineMaskAllBands(jCheckBox.isSelected());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JCheckBox getjCheckBox() {
return jCheckBox;
}
}
| 1,369 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
CoastalSizeToleranceSpinner.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/CoastalSizeToleranceSpinner.java | package gov.nasa.gsfc.seadas.watermask.ui;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* Created by knowles on 5/25/17.
*/
public class CoastalSizeToleranceSpinner {
private LandMasksData landMasksData;
private JLabel jLabel;
private JSpinner jSpinner = new JSpinner();
public CoastalSizeToleranceSpinner(LandMasksData landMasksData) {
this.landMasksData = landMasksData;
jLabel = new JLabel("Coastal Size Tolerance");
jLabel.setToolTipText("Coastal pixel grid size tolerance");
jSpinner.setModel(new SpinnerNumberModel(100, 1, 100, 5));
jSpinner.setPreferredSize(jSpinner.getPreferredSize());
jSpinner.setSize(jSpinner.getPreferredSize());
jSpinner.setModel(new SpinnerNumberModel(landMasksData.getCoastalSizeTolerance(), 1, 100, 5));
// JSpinner.NumberEditor editor = (JSpinner.NumberEditor) jSpinner.getEditor();
// DecimalFormat format = editor.getFormat();
// format.setMinimumFractionDigits(1);
addControlListeners();
}
private void addControlListeners() {
jSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent changeEvent) {
int value =Integer.parseInt(jSpinner.getValue().toString() );
landMasksData.setCoastalSizeTolerance(value);
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JSpinner getjSpinner() {
return jSpinner;
}
}
| 1,599 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
WaterMaskAction.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/WaterMaskAction.java | package gov.nasa.gsfc.seadas.watermask.ui;
import com.bc.ceres.swing.figure.Interactor;
import org.esa.snap.core.gpf.ui.DefaultSingleTargetProductDialog;
import com.bc.ceres.glevel.MultiLevelImage;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.util.ProductUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.rcp.imgfilter.model.Filter;
import org.esa.snap.ui.product.ProductSceneView;
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.*;
import org.openide.util.actions.Presenter;
import java.awt.event.ActionEvent;
import javax.media.jai.ImageLayout;
import javax.media.jai.JAI;
import javax.media.jai.operator.FormatDescriptor;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.RenderedImage;
import java.util.HashMap;
import java.util.Map;
/**
* This registers an action which calls the "CoastlineLandWaterMasks" Operator and based on its generated "water_fraction"
* band, defines 3 masks in the currently selected product:
* <ol>
* <li>Water: water_fraction > 90</li>
* <li>Land: water_fraction < 10</li>
* <li>Coastline: water_fraction > 0.1 && water_fraction < 99.9 (meaning if water_fraction is not 0 or 100 --> it is a coastline)</li>
* </ol>
* <p/>
* @author Tonio Fincke
* @author Danny Knowles
* @author Marco Peters
*/
@ActionID(category = "Processing", id = "gov.nasa.gsfc.seadas.watermask.ui.WaterMaskAction" )
@ActionRegistration(displayName = "#CTL_WaterMaskAction_Text", lazy = false)
@ActionReferences({
@ActionReference(path = "Menu/SeaDAS-Toolbox/General Tools", position = 300),
@ActionReference(path = "Menu/Raster/Masks"),
@ActionReference(path = "Toolbars/SeaDAS Toolbox", position = 20)
})
@NbBundle.Messages({
"CTL_WaterMaskAction_Text=CoastlineLandWaterMasks",
"CTL_WaterMaskAction_Description=Add coastline, land and water masks."
})
public final class WaterMaskAction extends AbstractSnapAction implements LookupListener, Presenter.Menu, Presenter.Toolbar {
public static final String COMMAND_ID = "Coastline, Land & Water";
public static final String TOOL_TIP = "Add coastline, land and water masks";
// public static final String ICON = "/org/esa/beam/watermask/ui/icons/coastline_24.png";
// public static final String ICON = "icons/Coastline24.png";
public static final String SMALLICON = "gov/nasa/gsfc/seadas/watermask/ui/icons/coastline.png";
public static final String LARGEICON = "gov/nasa/gsfc/seadas/watermask/ui/icons/coastline_24.png";
public static final String LAND_WATER_MASK_OP_ALIAS = "CoastlineLandWaterMasks";
public static final String TARGET_TOOL_BAR_NAME = "layersToolBar";
private static final String HELP_ID = "watermaskScientificTool";
private final Lookup lookup;
private final Lookup.Result<ProductNode> viewResult;
public WaterMaskAction() {
this(null);
}
public WaterMaskAction(Lookup lookup){
putValue(ACTION_COMMAND_KEY, getClass().getName());
putValue(NAME, Bundle.CTL_WaterMaskAction_Text());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon(SMALLICON, false));
putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon(LARGEICON, false));
putValue(SHORT_DESCRIPTION, Bundle.CTL_WaterMaskAction_Description());
this.lookup = lookup != null ? lookup : Utilities.actionsGlobalContext();
this.viewResult = this.lookup.lookupResult(ProductNode.class);
this.viewResult.addLookupListener(WeakListeners.create(LookupListener.class, this, viewResult));
updateEnabledState();
}
private void showLandWaterCoastMasks(final SnapApp snapApp) {
final Product product = snapApp.getSelectedProduct(SnapApp.SelectionSourceHint.AUTO);
if (product != null) {
final ProductNodeGroup<Mask> maskGroup = product.getMaskGroup();
final ProductNodeGroup<Band> bandGroup = product.getBandGroup();
/*
A simple boolean switch to enable this to run with or without the intermediate user dialogs
*/
// todo for Danny: turn this boolean on when it is ready
boolean useDialogs = true;
final LandMasksData landMasksData = new LandMasksData();
if (!useDialogs) {
landMasksData.setCreateMasks(true);
}
/*
Determine whether these auxilliary masks and associated products have already be created.
This would be the case when run a second time on the same product.
*/
final boolean[] masksCreated = {false};
for (String name : maskGroup.getNodeNames()) {
if (name.equals(landMasksData.getCoastlineMaskName()) ||
name.equals(landMasksData.getLandMaskName()) ||
name.equals(landMasksData.getWaterMaskName())) {
masksCreated[0] = true;
}
}
for (String name : bandGroup.getNodeNames()) {
if (name.equals(landMasksData.getWaterFractionBandName()) ||
name.equals(landMasksData.getWaterFractionSmoothedName())) {
masksCreated[0] = true;
}
}
/*
For the case where this is being run a second time, prompt the user to determine whether to delete
and re-create the products and masks.
*/
if (masksCreated[0]) {
if (useDialogs) {
landMasksData.setDeleteMasks(false);
LandMasksDialog landMasksDialog = new LandMasksDialog(landMasksData, masksCreated[0]);
landMasksDialog.setVisible(true);
landMasksDialog.dispose();
}
if (landMasksData.isDeleteMasks() || !useDialogs) {
masksCreated[0] = false;
for (String name : maskGroup.getNodeNames()) {
if (name.equals(landMasksData.getCoastlineMaskName()) ||
name.equals(landMasksData.getLandMaskName()) ||
name.equals(landMasksData.getWaterMaskName())) {
maskGroup.remove(maskGroup.get(name));
}
}
for (String name : bandGroup.getNodeNames()) {
if (name.equals(landMasksData.getWaterFractionBandName()) ||
name.equals(landMasksData.getWaterFractionSmoothedName())) {
bandGroup.remove(bandGroup.get(name));
}
}
}
}
if (!masksCreated[0]) {
if (useDialogs) {
landMasksData.setCreateMasks(false);
LandMasksDialog landMasksDialog = new LandMasksDialog(landMasksData, masksCreated[0]);
landMasksDialog.setVisible(true);
}
if (landMasksData.isCreateMasks()) {
final SourceFileInfo sourceFileInfo = landMasksData.getSourceFileInfo();
if (sourceFileInfo.isEnabled()) {
ProgressMonitorSwingWorker pmSwingWorker = new ProgressMonitorSwingWorker(snapApp.getMainFrame(),
"Computing Masks") {
@Override
protected Void doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception {
pm.beginTask("Creating land, water, coastline masks", 2);
try {
// Product landWaterProduct = GPF.createProduct("LandWaterMask", GPF.NO_PARAMS, product);
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("superSamplingFactor", new Integer(landMasksData.getSuperSampling()));
// parameters.put("subSamplingFactorY", new Integer(landMasksData.getSuperSampling()));
parameters.put("resolution", sourceFileInfo.getResolution(SourceFileInfo.Unit.METER));
parameters.put("mode", sourceFileInfo.getMode().toString());
parameters.put("worldSourceDataFilename", sourceFileInfo.getFile().getName());
parameters.put("copySourceFile", "false"); // when run in GUI don't do this
// parameters.put("coastalGridSize", landMasksData.getCoastalGridSize());
// parameters.put("coastalSizeTolerance", landMasksData.getCoastalSizeTolerance());
parameters.put("includeMasks", false); // don't create masks within the operator, do it later
// parameters.put("sourceFileInfo", sourceFileInfo);
/*
Create a new product, which will contain the land_water_fraction band
*/
Product landWaterProduct = GPF.createProduct(LAND_WATER_MASK_OP_ALIAS, parameters, product);
Band waterFractionBand = landWaterProduct.getBand(landMasksData.getWaterFractionBandName());
// Band coastBand = landWaterProduct.getBand("coast");
// PROBLEM WITH TILE SIZES
// Example: product has tileWidth=498 and tileHeight=611
// resulting image has tileWidth=408 and tileHeight=612
// Why is this happening and where?
// For now we change the image layout here.
reformatSourceImage(waterFractionBand, new ImageLayout(product.getBandAt(0).getSourceImage()));
// reformatSourceImage(coastBand, new ImageLayout(product.getBandAt(0).getSourceImage()));
pm.worked(1);
waterFractionBand.setName(landMasksData.getWaterFractionBandName());
product.addBand(waterFractionBand);
//todo BEAM folks left this as a placeholder
// product.addBand(coastBand);
//todo replace with JAI operator "GeneralFilter" which uses a GeneralFilterFunction
boolean createCoastBand = landMasksData.isCreateCoastline();
Mask coastlineMask = null;
int boxSize = landMasksData.getCoastalGridSize();
if (createCoastBand && boxSize > 1) {
final Filter meanFilter = new Filter("Mean " + Integer.toString(boxSize) + "x" + Integer.toString(boxSize), "mean" + Integer.toString(boxSize), Filter.Operation.MEAN, boxSize, boxSize);
final Kernel meanKernel = new Kernel(meanFilter.getKernelWidth(),
meanFilter.getKernelHeight(),
meanFilter.getKernelOffsetX(),
meanFilter.getKernelOffsetY(),
1.0 / meanFilter.getKernelQuotient(),
meanFilter.getKernelElements());
// final Kernel arithmeticMean3x3Kernel = new Kernel(3, 3, 1.0 / 9.0,
// new double[]{
// +1, +1, +1,
// +1, +1, +1,
// +1, +1, +1,
// });
//todo: 4th argument to ConvolutionFilterBand is a dummy value added to make it compile...may want to look at this...
int count = 1;
// final ConvolutionFilterBand filteredCoastlineBand = new ConvolutionFilterBand(
// landMasksData.getWaterFractionSmoothedName(),
// waterFractionBand,
// arithmeticMean3x3Kernel, count);
final FilterBand filteredCoastlineBand = new GeneralFilterBand(landMasksData.getWaterFractionSmoothedName(), waterFractionBand, GeneralFilterBand.OpType.MEAN, meanKernel, count);
if (waterFractionBand instanceof Band) {
ProductUtils.copySpectralBandProperties((Band) waterFractionBand, filteredCoastlineBand);
}
product.addBand(filteredCoastlineBand);
coastlineMask = Mask.BandMathsType.create(
landMasksData.getCoastlineMaskName(),
landMasksData.getCoastlineMaskDescription(),
product.getSceneRasterWidth(),
product.getSceneRasterHeight(),
landMasksData.getCoastalMath(),
landMasksData.getCoastlineMaskColor(),
landMasksData.getCoastlineMaskTransparency());
maskGroup.add(coastlineMask);
}
Mask landMask = Mask.BandMathsType.create(
landMasksData.getLandMaskName(),
landMasksData.getLandMaskDescription(),
product.getSceneRasterWidth(),
product.getSceneRasterHeight(),
landMasksData.getLandMaskMath(),
landMasksData.getLandMaskColor(),
landMasksData.getLandMaskTransparency());
maskGroup.add(landMask);
Mask waterMask = Mask.BandMathsType.create(
landMasksData.getWaterMaskName(),
landMasksData.getWaterMaskDescription(),
product.getSceneRasterWidth(),
product.getSceneRasterHeight(),
landMasksData.getWaterMaskMath(),
landMasksData.getWaterMaskColor(),
landMasksData.getWaterMaskTransparency());
maskGroup.add(waterMask);
pm.worked(1);
String[] bandNames = product.getBandNames();
for (String bandName : bandNames) {
RasterDataNode raster = product.getRasterDataNode(bandName);
if (createCoastBand && coastlineMask != null) {
if (landMasksData.isShowCoastlineMaskAllBands()) {
raster.getOverlayMaskGroup().add(coastlineMask);
}
}
if (landMasksData.isShowLandMaskAllBands()) {
raster.getOverlayMaskGroup().add(landMask);
}
if (landMasksData.isShowWaterMaskAllBands()) {
raster.getOverlayMaskGroup().add(waterMask);
}
}
//snapApp.setSelectedProductNode(waterFractionBand);
// ProductSceneView selectedProductSceneView = snapApp.getSelectedProductSceneView();
// if (selectedProductSceneView != null) {
// RasterDataNode raster = selectedProductSceneView.getRaster();
// raster.getOverlayMaskGroup().add(landMask);
// raster.getOverlayMaskGroup().add(coastlineMask);
// raster.getOverlayMaskGroup().add(waterMask);
//
// }
} finally {
pm.done();
}
return null;
}
};
pmSwingWorker.executeWithBlocking();
} else {
SimpleDialogMessage dialog = new SimpleDialogMessage(null, "Cannot Create Masks: Resolution File Doesn't Exist");
dialog.setVisible(true);
dialog.setEnabled(true);
}
}
}
}
}
private void reformatSourceImage(Band band, ImageLayout imageLayout) {
RenderingHints renderingHints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, imageLayout);
MultiLevelImage waterFractionSourceImage = band.getSourceImage();
int waterFractionDataType = waterFractionSourceImage.getData().getDataBuffer().getDataType();
RenderedImage newImage = FormatDescriptor.create(waterFractionSourceImage, waterFractionDataType,
renderingHints);
band.setSourceImage(newImage);
}
@Override
public void actionPerformed(ActionEvent e) {
// final AppContext appContext = getAppContext();
// setOverlayEnableState(SnapApp.getDefault().getSelectedProductSceneView());
// updateActionState();
showLandWaterCoastMasks(SnapApp.getDefault());
// final DefaultSingleTargetProductDialog dialog = new DefaultSingleTargetProductDialog(LAND_WATER_MASK_OP_ALIAS, appContext,
// "Land Water Mask3",
// HELP_ID);
// dialog.setTargetProductNameSuffix("_watermask3");
// dialog.getJDialog().pack();
// dialog.show();
}
@Override
public JMenuItem getMenuPresenter() {
JMenuItem menuItem = new JMenuItem(this);
menuItem.setIcon(null);
return menuItem;
}
@Override
public Component getToolbarPresenter() {
JButton button = new JButton(this);
button.setText(null);
button.setIcon(ImageUtilities.loadImageIcon(LARGEICON,false));
return button;
}
@Override
public void resultChanged(LookupEvent ignored) {
updateEnabledState();
}
protected void updateEnabledState() {
final Product selectedProduct = SnapApp.getDefault().getSelectedProduct(SnapApp.SelectionSourceHint.AUTO);
boolean productSelected = selectedProduct != null;
boolean hasBands = false;
boolean hasGeoCoding = false;
if (productSelected) {
hasBands = selectedProduct.getNumBands() > 0;
hasGeoCoding = selectedProduct.getSceneGeoCoding() != null;
}
super.setEnabled(!viewResult.allInstances().isEmpty() && hasBands && hasGeoCoding);
}
// @Override
// public void start(final SnapApp snapApp) {
// final ExecCommand action = snapApp.getCommandManager().createExecCommand(COMMAND_ID,
// new ToolbarCommand(snapApp));
//
// String iconFilename = ResourceInstallationUtils.getIconFilename(ICON, WaterMaskAction.class);
// // action.setLargeIcon(UIUtils.loadImageIcon(ICON));
// try {
// URL iconUrl = new URL(iconFilename);
// ImageIcon imageIcon = new ImageIcon(iconUrl);
// action.setLargeIcon(imageIcon);
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
//
//
// final AbstractButton lwcButton = snapApp.createToolButton(COMMAND_ID);
// lwcButton.setToolTipText(TOOL_TIP);
//
// final AbstractButton lwcButton2 = snapApp.createToolButton(COMMAND_ID);
// lwcButton2.setToolTipText(TOOL_TIP);
//
// snapApp.getMainFrame().addWindowListener(new WindowAdapter() {
// @Override
// public void windowOpened(WindowEvent e) {
// CommandBar layersBar = snapApp.getToolBar(TARGET_TOOL_BAR_NAME);
// if (layersBar != null) {
// layersBar.add(lwcButton);
// }
//
//
// CommandBar seadasDefaultBar = snapApp.getToolBar("seadasDeluxeToolsToolBar");
// if (seadasDefaultBar != null) {
// seadasDefaultBar.add(lwcButton2);
// }
// }
//
// });
// }
//
//
// private class ToolbarCommand extends CommandAdapter {
// private final SnapApp snapApp;
//
// public ToolbarCommand(SnapApp snapApp) {
// this.snapApp = snapApp;
// }
//
// @Override
// public void actionPerformed(
// CommandEvent event) {
// showLandWaterCoastMasks(
// snapApp);
//
// }
//
// @Override
// public void updateState(
// CommandEvent event) {
// Product selectedProduct = snapApp.getSelectedProduct();
// boolean productSelected = selectedProduct != null;
// boolean hasBands = false;
// boolean hasGeoCoding = false;
// if (productSelected) {
// hasBands = selectedProduct.getNumBands() > 0;
// hasGeoCoding = selectedProduct.getGeoCoding() != null;
// }
// event.getCommand().setEnabled(
// productSelected && hasBands && hasGeoCoding);
// }
// }
}
| 23,198 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
WaterColorComboBox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/WaterColorComboBox.java | package gov.nasa.gsfc.seadas.watermask.ui;
import org.openide.awt.ColorComboBox;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 11:40 AM
* To change this template use File | Settings | File Templates.
*/
public class WaterColorComboBox { private LandMasksData landMasksData;
private JLabel jLabel;
private ColorComboBox colorExComboBox = new ColorComboBox();
public WaterColorComboBox(LandMasksData landMasksData) {
this.landMasksData = landMasksData;
jLabel = new JLabel("Color");
jLabel.setToolTipText("Water mask color");
colorExComboBox.setSelectedColor(new Color(225,225,225));
colorExComboBox.setPreferredSize(colorExComboBox.getPreferredSize());
colorExComboBox.setMinimumSize(colorExComboBox.getPreferredSize());
colorExComboBox.setSelectedColor((landMasksData.getWaterMaskColor()));
addControlListeners();
}
private void addControlListeners() {
colorExComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
landMasksData.setWaterMaskColor(colorExComboBox.getSelectedColor());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JComboBox getColorExComboBox() {
return colorExComboBox;
}
}
| 1,519 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
CoastlineColorComboBox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/CoastlineColorComboBox.java | package gov.nasa.gsfc.seadas.watermask.ui;
import org.openide.awt.ColorComboBox;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 10:57 AM
* To change this template use File | Settings | File Templates.
*/
public class CoastlineColorComboBox {
private LandMasksData landMasksData;
private JLabel jLabel;
private ColorComboBox colorExComboBox = new ColorComboBox();
public CoastlineColorComboBox(LandMasksData landMasksData) {
this.landMasksData = landMasksData;
jLabel = new JLabel("Color");
jLabel.setToolTipText("Coastline mask color");
colorExComboBox.setSelectedColor(new Color(225,225,225));
colorExComboBox.setPreferredSize(colorExComboBox.getPreferredSize());
colorExComboBox.setMinimumSize(colorExComboBox.getPreferredSize());
colorExComboBox.setSelectedColor(landMasksData.getCoastlineMaskColor());
addControlListeners();
}
private void addControlListeners() {
colorExComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
landMasksData.setCoastlineMaskColor(colorExComboBox.getSelectedColor());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JComboBox getColorExComboBox() {
return colorExComboBox;
}
}
| 1,539 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
SourceFileInfo.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/SourceFileInfo.java | package gov.nasa.gsfc.seadas.watermask.ui;
import gov.nasa.gsfc.seadas.watermask.operator.WatermaskClassifier;
import gov.nasa.gsfc.seadas.watermask.util.ResourceInstallationUtils;
import java.io.File;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/5/12
* Time: 9:53 AM
* To change this template use File | Settings | File Templates.
*/
public class SourceFileInfo {
public enum Unit {
METER("m"),
KILOMETER("km");
private Unit(String name) {
this.name = name;
}
private final String name;
public String toString() {
return name;
}
}
private int resolution;
private Unit unit;
private String description;
private WatermaskClassifier.Mode mode;
private File file;
private boolean status;
private String statusMessage;
public SourceFileInfo(int resolution, Unit unit, WatermaskClassifier.Mode mode, String filename) {
setUnit(unit);
setResolution(resolution);
setMode(mode);
setFile(filename);
setDescription();
}
public int getResolution() {
return resolution;
}
public int getResolution(Unit unit) {
// resolution is returned in units of meters
if (unit == getUnit()) {
return resolution;
} else if (unit == Unit.METER && getUnit() == Unit.KILOMETER) {
return resolution * 1000;
} else if (unit == Unit.KILOMETER && getUnit() == Unit.METER) {
float x = resolution / 1000;
return Math.round(x);
}
return resolution;
}
private void setResolution(int resolution) {
this.resolution = resolution;
}
public Unit getUnit() {
return unit;
}
private void setUnit(Unit unit) {
this.unit = unit;
}
public String getDescription() {
return description;
}
private void setDescription() {
String core = "Filename=" + getFile().getAbsolutePath() +"<br>Uses the " + Integer.toString(getResolution()) + " " + getUnit().toString() +
" dataset obtained from the<br> "
+ getMode().getDescription();
if (isEnabled()) {
this.description = "<html>" + core + "</html>";
} else {
this.description = "<html>" + core + "<br> NOTE: this file is not currently installed -- see help</html>";
}
}
public WatermaskClassifier.Mode getMode() {
return mode;
}
private void setMode(WatermaskClassifier.Mode mode) {
this.mode = mode;
}
public File getFile() {
return file;
}
private void setFile(String filename) {
try{
file = ResourceInstallationUtils.installAuxdata(WatermaskClassifier.class, filename);
setStatus(true, null);
} catch (Exception e) {
setStatus(false, e.getMessage());
}
}
public boolean isEnabled() {
if (getMode() == WatermaskClassifier.Mode.SRTM_GC) {
File gcFile = ResourceInstallationUtils.getTargetFile(WatermaskClassifier.GC_WATER_MASK_FILE);
return gcFile.exists() && file.exists() && getStatus();
} else {
return file.exists() && getStatus();
}
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public void setStatus(boolean status,String statusMessage) {
this.status = status;
this.statusMessage = statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
public String getStatusMessage() {
return statusMessage;
}
public boolean getStatus() {
return status;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
// StringBuilder resolutionStringBuilder = new StringBuilder(Integer.toString(getResolution()));
//
// while (resolutionStringBuilder.length() < 5) {
// resolutionStringBuilder.insert(0, " ");
// }
//
// stringBuilder.append(resolutionStringBuilder.toString());
if (resolution >= 1000) {
stringBuilder.append(String.valueOf(resolution / 1000));
stringBuilder.append(" ");
stringBuilder.append(Unit.KILOMETER.toString());
} else {
stringBuilder.append(Integer.toString(getResolution()));
stringBuilder.append(" ");
stringBuilder.append(getUnit().toString());
}
stringBuilder.append(" (");
stringBuilder.append(getMode().toString());
stringBuilder.append(")");
return stringBuilder.toString();
}
}
| 4,822 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
CoastlineCreateCheckbox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/CoastlineCreateCheckbox.java | package gov.nasa.gsfc.seadas.watermask.ui;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 10:27 AM
* To change this template use File | Settings | File Templates.
*/
public class CoastlineCreateCheckbox {
private LandMasksData landMasksData;
private JLabel jLabel;
private JCheckBox jCheckBox = new JCheckBox();
private static String DEFAULT_NAME = "Create Coastline Mask/Bands";
private static String DEFAULT_TOOLTIPS = "Note: this can take longer to run";
public CoastlineCreateCheckbox(LandMasksData landMasksData) {
this.landMasksData = landMasksData;
jLabel = new JLabel(DEFAULT_NAME);
jLabel.setToolTipText(DEFAULT_TOOLTIPS);
jCheckBox.setSelected(landMasksData.isCreateCoastline());
addControlListeners();
}
private void addControlListeners() {
jCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
landMasksData.setCreateCoastline(jCheckBox.isSelected());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JCheckBox getjCheckBox() {
return jCheckBox;
}
}
| 1,332 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
FileInstallRunnable.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/FileInstallRunnable.java | package gov.nasa.gsfc.seadas.watermask.ui;
import gov.nasa.gsfc.seadas.watermask.operator.WatermaskClassifier;
import gov.nasa.gsfc.seadas.watermask.util.ResourceInstallationUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 2/18/13
* Time: 4:07 PM
* To change this template use File | Settings | File Templates.
*/
class FileInstallRunnable implements Runnable {
URL sourceUrl;
LandMasksData landMasksData;
SourceFileInfo sourceFileInfo;
String filename;
boolean valid = true;
public FileInstallRunnable(URL sourceUrl, String filename, SourceFileInfo sourceFileInfo, LandMasksData landMasksData) {
if (sourceUrl== null || filename == null || sourceFileInfo == null || landMasksData == null) {
valid = false;
return;
}
this.sourceUrl = sourceUrl;
this.sourceFileInfo = sourceFileInfo;
this.landMasksData = landMasksData;
this.filename = filename;
}
public void run() {
if (!valid) {
return;
}
// final String filename = sourceFileInfo.getFile().getName().toString();
try {
ResourceInstallationUtils.installAuxdata(sourceUrl, filename);
if (sourceFileInfo.getMode() == WatermaskClassifier.Mode.SRTM_GC) {
File gcFile = ResourceInstallationUtils.getTargetFile(WatermaskClassifier.GC_WATER_MASK_FILE);
if (!gcFile.exists()) {
final URL northSourceUrl = new URL(LandMasksData.LANDMASK_URL + "/" + gcFile.getName());
ResourceInstallationUtils.installAuxdata(northSourceUrl, gcFile.getName());
}
}
} catch (IOException e) {
sourceFileInfo.setStatus(false, e.getMessage());
}
landMasksData.fireEvent(LandMasksData.NOTIFY_USER_FILE_INSTALL_RESULTS_EVENT, null, sourceFileInfo);
}
}
| 1,991 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
WaterTransparencySpinner.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/WaterTransparencySpinner.java | package gov.nasa.gsfc.seadas.watermask.ui;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.text.DecimalFormat;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 9:12 AM
* To change this template use File | Settings | File Templates.
*/
public class WaterTransparencySpinner {
private LandMasksData landMasksData;
private JLabel jLabel;
private JSpinner jSpinner = new JSpinner();
public WaterTransparencySpinner(LandMasksData landMasksData) {
this.landMasksData = landMasksData;
jLabel = new JLabel("Transparency");
jLabel.setToolTipText("Water mask transparency");
jSpinner.setModel(new SpinnerNumberModel(100, 0, 100, 100));
jSpinner.setPreferredSize(jSpinner.getPreferredSize());
jSpinner.setSize(jSpinner.getPreferredSize());
jSpinner.setModel(new SpinnerNumberModel(landMasksData.getWaterMaskTransparency(), 0.0, 1.0, 0.1));
JSpinner.NumberEditor editor = (JSpinner.NumberEditor) jSpinner.getEditor();
DecimalFormat format = editor.getFormat();
format.setMinimumFractionDigits(1);
addControlListeners();
}
private void addControlListeners() {
jSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent changeEvent) {
landMasksData.setWaterMaskTransparency((Double) jSpinner.getValue());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JSpinner getjSpinner() {
return jSpinner;
}
}
| 1,665 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
WaterEnabledAllBandsCheckbox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/WaterEnabledAllBandsCheckbox.java | package gov.nasa.gsfc.seadas.watermask.ui;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 10:25 AM
* To change this template use File | Settings | File Templates.
*/
public class WaterEnabledAllBandsCheckbox {
private LandMasksData landMasksData;
private JLabel jLabel;
private JCheckBox jCheckBox = new JCheckBox();
private static String DEFAULT_NAME = "Enabled in All Bands";
private static String DEFAULT_TOOLTIPS = "Set Water Mask Enabled in All Bands";
public WaterEnabledAllBandsCheckbox(LandMasksData landMasksData) {
this.landMasksData = landMasksData;
jLabel = new JLabel(DEFAULT_NAME);
jLabel.setToolTipText(DEFAULT_TOOLTIPS);
jCheckBox.setSelected(landMasksData.isShowWaterMaskAllBands());
addControlListeners();
}
private void addControlListeners() {
jCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
landMasksData.setShowWaterMaskAllBands(jCheckBox.isSelected());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JCheckBox getjCheckBox() {
return jCheckBox;
}
}
| 1,349 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
LandColorComboBox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/LandColorComboBox.java | package gov.nasa.gsfc.seadas.watermask.ui;
import org.openide.awt.ColorComboBox;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 11:39 AM
* To change this template use File | Settings | File Templates.
*/
public class LandColorComboBox {
private LandMasksData landMasksData;
private JLabel jLabel;
private ColorComboBox colorExComboBox = new ColorComboBox();
public LandColorComboBox(LandMasksData landMasksData) {
this.landMasksData = landMasksData;
jLabel = new JLabel("Color");
jLabel.setToolTipText("Land mask color");
colorExComboBox.setSelectedColor(new Color(225,225,225));
colorExComboBox.setPreferredSize(colorExComboBox.getPreferredSize());
colorExComboBox.setMinimumSize(colorExComboBox.getPreferredSize());
colorExComboBox.setSelectedColor((landMasksData.getLandMaskColor()));
addControlListeners();
}
private void addControlListeners() {
colorExComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
landMasksData.setLandMaskColor(colorExComboBox.getSelectedColor());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JComboBox getColorExComboBox() {
return colorExComboBox;
}
}
| 1,515 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
CoastalGridSizeSpinner.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/CoastalGridSizeSpinner.java | package gov.nasa.gsfc.seadas.watermask.ui;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* Created by knowles on 5/25/17.
*/
public class CoastalGridSizeSpinner {
private LandMasksData landMasksData;
private JLabel jLabel;
private JSpinner jSpinner = new JSpinner();
public CoastalGridSizeSpinner(LandMasksData landMasksData) {
this.landMasksData = landMasksData;
jLabel = new JLabel("Coastal Grid Size");
jLabel.setToolTipText("Coastal pixel grid size");
jSpinner.setModel(new SpinnerNumberModel(19, 2, 19, 2));
jSpinner.setPreferredSize(jSpinner.getPreferredSize());
jSpinner.setSize(jSpinner.getPreferredSize());
jSpinner.setModel(new SpinnerNumberModel(landMasksData.getCoastalGridSize(), 1, 19, 2));
// JSpinner.NumberEditor editor = (JSpinner.NumberEditor) jSpinner.getEditor();
// DecimalFormat format = editor.getFormat();
// format.setMinimumFractionDigits(1);
addControlListeners();
}
private void addControlListeners() {
jSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent changeEvent) {
int value =Integer.parseInt(jSpinner.getValue().toString() );
landMasksData.setCoastalGridSize(value);
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JSpinner getjSpinner() {
return jSpinner;
}
}
| 1,561 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
LandMasksData.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/LandMasksData.java | package gov.nasa.gsfc.seadas.watermask.ui;
import gov.nasa.gsfc.seadas.watermask.operator.WatermaskClassifier;
import gov.nasa.gsfc.seadas.watermask.preferences.Landmask_Controller;
import javax.swing.event.SwingPropertyChangeSupport;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 9:13 AM
* To change this template use File | Settings | File Templates.
*/
class LandMasksData {
LandMasksData landMasksData = this;
public static String NOTIFY_USER_FILE_INSTALL_RESULTS_EVENT = "NOTIFY_USER_FILE_INSTALL_RESULTS_EVENT";
public static String FILE_INSTALLED_EVENT2 = "FILE_INSTALLED_EVENT2";
public static String PROMPT_REQUEST_TO_INSTALL_FILE_EVENT = "REQUEST_TO_INSTALL_FILE_EVENT";
public static String CONFIRMED_REQUEST_TO_INSTALL_FILE_EVENT = "CONFIRMED_REQUEST_TO_INSTALL_FILE_EVENT";
public static String LANDMASK_URL = "https://oceandata.sci.gsfc.nasa.gov/SeaDAS/installer/landmask";
private boolean createMasks = false;
private boolean deleteMasks = false;
private int superSampling = 1;
private int coastalGridSize = 3;
private int coastalSizeTolerance = 50;
private double landMaskTransparency = 0.0;
private double waterMaskTransparency = 0.5;
private double coastlineMaskTransparency = 0.0;
private boolean showLandMaskAllBands = true;
private boolean showWaterMaskAllBands = false;
private boolean showCoastlineMaskAllBands = false;
private boolean createCoastline = false;
private Color landMaskColor = new Color(51, 51, 51);
private Color waterMaskColor = new Color(0, 125, 255);
private Color coastlineMaskColor = new Color(0, 0, 0);
private String waterFractionBandName = "water_fraction";
private String waterFractionSmoothedName = "water_fraction_mean";
private String landMaskName = "LandMask";
private String landMaskMath = getWaterFractionBandName() + " == 0";
private String landMaskDescription = "Land masked pixels";
private String coastlineMaskName = "CoastalMask";
// private String coastlineMath = getWaterFractionSmoothedName() + " > 25 and " + getWaterFractionSmoothedName() + " < 75";
// private String coastlineMath = getWaterFractionSmoothedName() + " > 0 and " + getWaterFractionSmoothedName() + " < 100";
private String coastlineMaskDescription = "Coastline masked pixels";
private String waterMaskName = "WaterMask";
private String waterMaskMath = getWaterFractionBandName() + " > 0";
private String waterMaskDescription = "Water masked pixels";
private ArrayList<SourceFileInfo> sourceFileInfos = new ArrayList<SourceFileInfo>();
private SourceFileInfo sourceFileInfo;
private final SwingPropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this);
public LandMasksData() {
landMaskName = Landmask_Controller.getPreferenceLandMaskName();
landMaskColor = Landmask_Controller.getPreferenceLandMaskColor();
showLandMaskAllBands = Landmask_Controller.getPreferenceLandMaskShow();
landMaskTransparency = Landmask_Controller.getPreferenceLandMaskTransparency();
String landMaskResolution = Landmask_Controller.getPreferenceLandMaskResolution();
SourceFileInfo sourceFileInfo;
sourceFileInfo = new SourceFileInfo(WatermaskClassifier.RESOLUTION_50m,
SourceFileInfo.Unit.METER,
WatermaskClassifier.Mode.SRTM_GC,
WatermaskClassifier.FILENAME_SRTM_GC_50m);
getSourceFileInfos().add(sourceFileInfo);
if (sourceFileInfo.toString().equals(landMaskResolution)) {
this.sourceFileInfo = sourceFileInfo;
}
sourceFileInfo = new SourceFileInfo(WatermaskClassifier.RESOLUTION_150m,
SourceFileInfo.Unit.METER,
WatermaskClassifier.Mode.SRTM_GC,
WatermaskClassifier.FILENAME_SRTM_GC_150m);
getSourceFileInfos().add(sourceFileInfo);
if (sourceFileInfo.toString().equals(landMaskResolution)) {
this.sourceFileInfo = sourceFileInfo;
}
sourceFileInfo = new SourceFileInfo(WatermaskClassifier.RESOLUTION_1km,
SourceFileInfo.Unit.METER,
WatermaskClassifier.Mode.GSHHS,
WatermaskClassifier.FILENAME_GSHHS_1km);
getSourceFileInfos().add(sourceFileInfo);
if (sourceFileInfo.toString().equals(landMaskResolution)) {
this.sourceFileInfo = sourceFileInfo;
}
// set the default
// this.sourceFileInfo = sourceFileInfo;
sourceFileInfo = new SourceFileInfo(WatermaskClassifier.RESOLUTION_10km,
SourceFileInfo.Unit.METER,
WatermaskClassifier.Mode.GSHHS,
WatermaskClassifier.FILENAME_GSHHS_10km);
getSourceFileInfos().add(sourceFileInfo);
if (sourceFileInfo.toString().equals(landMaskResolution)) {
this.sourceFileInfo = sourceFileInfo;
}
// sourceFileInfo = new SourceFileInfo(WatermaskClassifier.RESOLUTION_50m,
// SourceFileInfo.Unit.METER,
// WatermaskClassifier.Mode.DEFAULT,
// WatermaskClassifier.FILENAME_SRTM_GC_50m);
// getSourceFileInfos().add(sourceFileInfo);
//
// sourceFileInfo = new SourceFileInfo(WatermaskClassifier.RESOLUTION_150m,
// SourceFileInfo.Unit.METER,
// WatermaskClassifier.Mode.DEFAULT,
// WatermaskClassifier.FILENAME_SRTM_GC_150m);
// getSourceFileInfos().add(sourceFileInfo);
//
//
// sourceFileInfo = new SourceFileInfo(WatermaskClassifier.RESOLUTION_1km,
// SourceFileInfo.Unit.METER,
// WatermaskClassifier.Mode.DEFAULT,
// WatermaskClassifier.FILENAME_GSHHS_1km);
// getSourceFileInfos().add(sourceFileInfo);
// // set the default
// this.sourceFileInfo = sourceFileInfo;
//
// sourceFileInfo = new SourceFileInfo(WatermaskClassifier.RESOLUTION_10km,
// SourceFileInfo.Unit.METER,
// WatermaskClassifier.Mode.DEFAULT,
// WatermaskClassifier.FILENAME_GSHHS_10km);
// getSourceFileInfos().add(sourceFileInfo);
this.addPropertyChangeListener(LandMasksData.NOTIFY_USER_FILE_INSTALL_RESULTS_EVENT, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
SourceFileInfo sourceFileInfo = (SourceFileInfo) evt.getNewValue();
InstallResolutionFileDialog dialog = new InstallResolutionFileDialog(landMasksData, sourceFileInfo, InstallResolutionFileDialog.Step.CONFIRMATION);
dialog.setVisible(true);
dialog.setEnabled(true);
}
});
}
public boolean isCreateMasks() {
return createMasks;
}
public void setCreateMasks(boolean closeClicked) {
this.createMasks = closeClicked;
}
public double getLandMaskTransparency() {
return landMaskTransparency;
}
public void setLandMaskTransparency(double landMaskTransparency) {
this.landMaskTransparency = landMaskTransparency;
}
public double getWaterMaskTransparency() {
return waterMaskTransparency;
}
public void setWaterMaskTransparency(double waterMaskTransparency) {
this.waterMaskTransparency = waterMaskTransparency;
}
public double getCoastlineMaskTransparency() {
return coastlineMaskTransparency;
}
public void setCoastlineMaskTransparency(double coastlineMaskTransparency) {
this.coastlineMaskTransparency = coastlineMaskTransparency;
}
public boolean isShowLandMaskAllBands() {
return showLandMaskAllBands;
}
public void setShowLandMaskAllBands(boolean showLandMaskAllBands) {
this.showLandMaskAllBands = showLandMaskAllBands;
}
public boolean isShowWaterMaskAllBands() {
return showWaterMaskAllBands;
}
public void setShowWaterMaskAllBands(boolean showWaterMaskAllBands) {
this.showWaterMaskAllBands = showWaterMaskAllBands;
}
public boolean isShowCoastlineMaskAllBands() {
return showCoastlineMaskAllBands;
}
public void setShowCoastlineMaskAllBands(boolean showCoastlineMaskAllBands) {
this.showCoastlineMaskAllBands = showCoastlineMaskAllBands;
}
public boolean isCreateCoastline() {
return createCoastline;
}
public void setCreateCoastline(boolean createCoastline) {
this.createCoastline = createCoastline;
}
public Color getLandMaskColor() {
return landMaskColor;
}
public void setLandMaskColor(Color landMaskColor) {
this.landMaskColor = landMaskColor;
}
public Color getWaterMaskColor() {
return waterMaskColor;
}
public void setWaterMaskColor(Color waterMaskColor) {
this.waterMaskColor = waterMaskColor;
}
public Color getCoastlineMaskColor() {
return coastlineMaskColor;
}
public void setCoastlineMaskColor(Color coastlineMaskColor) {
this.coastlineMaskColor = coastlineMaskColor;
}
public int getSuperSampling() {
return superSampling;
}
public void setSuperSampling(int superSampling) {
this.superSampling = superSampling;
}
public SourceFileInfo getSourceFileInfo() {
return sourceFileInfo;
}
public void setSourceFileInfo(SourceFileInfo resolution) {
this.sourceFileInfo = resolution;
}
public String getWaterFractionBandName() {
return waterFractionBandName;
}
public void setWaterFractionBandName(String waterFractionBandName) {
this.waterFractionBandName = waterFractionBandName;
}
public String getWaterFractionSmoothedName() {
return waterFractionSmoothedName + getCoastalGridSize();
}
public void setWaterFractionSmoothedName(String waterFractionSmoothedName) {
this.waterFractionSmoothedName = waterFractionSmoothedName;
}
public String getLandMaskName() {
return landMaskName;
}
public void setLandMaskName(String landMaskName) {
this.landMaskName = landMaskName;
}
public String getLandMaskMath() {
return landMaskMath;
}
public void setLandMaskMath(String landMaskMath) {
this.landMaskMath = landMaskMath;
}
public String getLandMaskDescription() {
return landMaskDescription;
}
public void setLandMaskDescription(String landMaskDescription) {
this.landMaskDescription = landMaskDescription;
}
public String getCoastlineMaskName() {
return coastlineMaskName;
}
public void setCoastlineMaskName(String coastlineMaskName) {
this.coastlineMaskName = coastlineMaskName;
}
public String getCoastalMath() {
double min = 50 - getCoastalSizeTolerance()/2;
double max = 50 + getCoastalSizeTolerance()/2;
return getWaterFractionSmoothedName() + " > "+ Double.toString(min) + " and " + getWaterFractionSmoothedName() + " < " + Double.toString(max);
}
// public void setCoastlineMath(String coastlineMath) {
// this.coastlineMath = coastlineMath;
// }
public String getCoastlineMaskDescription() {
return coastlineMaskDescription;
}
public void setCoastlineMaskDescription(String coastlineMaskDescription) {
this.coastlineMaskDescription = coastlineMaskDescription;
}
public String getWaterMaskName() {
return waterMaskName;
}
public void setWaterMaskName(String waterMaskName) {
this.waterMaskName = waterMaskName;
}
public String getWaterMaskMath() {
return waterMaskMath;
}
public void setWaterMaskMath(String waterMaskMath) {
this.waterMaskMath = waterMaskMath;
}
public String getWaterMaskDescription() {
return waterMaskDescription;
}
public void setWaterMaskDescription(String waterMaskDescription) {
this.waterMaskDescription = waterMaskDescription;
}
public boolean isDeleteMasks() {
return deleteMasks;
}
public void setDeleteMasks(boolean deleteMasks) {
this.deleteMasks = deleteMasks;
}
public ArrayList<SourceFileInfo> getSourceFileInfos() {
return sourceFileInfos;
}
public void setSourceFileInfos(ArrayList<SourceFileInfo> sourceFileInfos) {
this.sourceFileInfos = sourceFileInfos;
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(propertyName, listener);
}
public void fireEvent(String propertyName) {
propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(this, propertyName, null, null));
}
public void fireEvent(String propertyName, SourceFileInfo oldValue, SourceFileInfo newValue) {
propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(this, propertyName, oldValue, newValue));
}
public int getCoastalGridSize() {
return coastalGridSize;
}
public void setCoastalGridSize(int coastalGridSize) {
this.coastalGridSize = coastalGridSize;
}
public int getCoastalSizeTolerance() {
return coastalSizeTolerance;
}
public void setCoastalSizeTolerance(int coastalSizeTolerance) {
this.coastalSizeTolerance = coastalSizeTolerance;
}
}
| 13,871 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ExGridBagConstraints.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/ExGridBagConstraints.java | package gov.nasa.gsfc.seadas.watermask.ui;
import java.awt.*;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 1:57 PM
* To change this template use File | Settings | File Templates.
*/
public class ExGridBagConstraints extends GridBagConstraints {
public ExGridBagConstraints(int gridx, int gridy) {
this.gridx = gridx;
this.gridy = gridy;
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, int pad) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
this.insets = new Insets(pad, pad, pad, pad);
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, Insets insets) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
this.insets = insets;
}
public ExGridBagConstraints(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, int pad, int gridwidth) {
this.gridx = gridx;
this.gridy = gridy;
this.weightx = weightx;
this.weighty = weighty;
this.anchor = anchor;
this.fill = fill;
this.insets = new Insets(pad, pad, pad, pad);
this.gridwidth = gridwidth;
}
} | 1,797 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
InstallResolutionFileDialog.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/InstallResolutionFileDialog.java | package gov.nasa.gsfc.seadas.watermask.ui;
import gov.nasa.gsfc.seadas.watermask.util.ResourceInstallationUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URL;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 1/16/13
* Time: 1:01 PM
* To change this template use File | Settings | File Templates.
*/
class InstallResolutionFileDialog extends JDialog {
public static enum Step {
INSTALLATION,
CONFIRMATION
}
public SourceFileInfo sourceFileInfo;
private JLabel jLabel;
private LandMasksData landMasksData;
public InstallResolutionFileDialog(LandMasksData landMasksData, SourceFileInfo sourceFileInfo, Step step) {
this.landMasksData = landMasksData;
this.sourceFileInfo = sourceFileInfo;
if (step == Step.INSTALLATION) {
installationRequestUI();
} else if (step == Step.CONFIRMATION) {
installationResultsUI();
}
}
public final void installationRequestUI() {
JButton installButton = new JButton("Install File");
installButton.setPreferredSize(installButton.getPreferredSize());
installButton.setMinimumSize(installButton.getPreferredSize());
installButton.setMaximumSize(installButton.getPreferredSize());
installButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
// acquire in example: "https://oceandata.sci.gsfc.nasa.gov/SeaDAS/installer/landmask/50m.zip"
try {
landMasksData.fireEvent(LandMasksData.CONFIRMED_REQUEST_TO_INSTALL_FILE_EVENT);
final String filename = sourceFileInfo.getFile().getName().toString();
final URL sourceUrl = new URL(LandMasksData.LANDMASK_URL + "/" + filename);
File targetFile = ResourceInstallationUtils.getTargetFile(filename);
if (!targetFile.exists()) {
Thread t = new Thread(new FileInstallRunnable(sourceUrl, filename, sourceFileInfo, landMasksData));
t.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.setPreferredSize(cancelButton.getPreferredSize());
cancelButton.setMinimumSize(cancelButton.getPreferredSize());
cancelButton.setMaximumSize(cancelButton.getPreferredSize());
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
JLabel filler = new JLabel(" ");
JPanel buttonsJPanel = new JPanel(new GridBagLayout());
buttonsJPanel.add(cancelButton,
new ExGridBagConstraints(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
buttonsJPanel.add(filler,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
buttonsJPanel.add(installButton,
new ExGridBagConstraints(2, 0, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
//buttonsJPanel.add(helpButton,
// new ExGridBagConstraints(3, 0, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
jLabel = new JLabel("Do you want to install file " + sourceFileInfo.getFile().getName().toString() + " ?");
JPanel jPanel = new JPanel(new GridBagLayout());
jPanel.add(jLabel,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
jPanel.add(buttonsJPanel,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
add(jPanel);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("File Installation");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setPreferredSize(getPreferredSize());
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
setSize(getPreferredSize());
}
public final void installationResultsUI() {
JButton okayButton = new JButton("Okay");
okayButton.setPreferredSize(okayButton.getPreferredSize());
okayButton.setMinimumSize(okayButton.getPreferredSize());
okayButton.setMaximumSize(okayButton.getPreferredSize());
okayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
if (sourceFileInfo.isEnabled()) {
jLabel = new JLabel("File " + sourceFileInfo.getFile().getName().toString() + " has been installed");
landMasksData.fireEvent(LandMasksData.FILE_INSTALLED_EVENT2);
} else {
jLabel = new JLabel("File " + sourceFileInfo.getFile().getName().toString() + " installation failure");
}
JPanel jPanel = new JPanel(new GridBagLayout());
jPanel.add(jLabel,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
jPanel.add(okayButton,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
add(jPanel);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("File Installation");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setPreferredSize(getPreferredSize());
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
setSize(getPreferredSize());
}
}
| 6,025 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
LandMasksDialog.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/LandMasksDialog.java | package gov.nasa.gsfc.seadas.watermask.ui;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.openide.awt.ColorComboBox;
import org.openide.util.HelpCtx;
import javax.help.HelpBroker;
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;
class LandMasksDialog extends JDialog {
private LandMasksData landMasksData = null;
private Component helpButton = null;
private HelpBroker helpBroker = null;
private final static String HELP_ID = "coastlineLandMasks";
private final static String HELP_ICON = "icons/Help24.gif";
public LandMasksDialog(LandMasksData landMasksData, boolean masksCreated) {
this.landMasksData = landMasksData;
helpButton = getHelpButton(HELP_ID);
if (masksCreated) {
createNotificationUI();
} else {
createLandMasksUI();
}
}
protected AbstractButton getHelpButton(String helpId) {
if (helpId != null) {
final AbstractButton helpButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon(HELP_ICON),
false);
helpButton.setToolTipText("Help.");
helpButton.setName("helpButton");
helpButton.addActionListener(e ->getHelpCtx(helpId).display());
return helpButton;
}
return null;
}
public HelpCtx getHelpCtx(String helpId) {
return new HelpCtx(helpId);
}
public final void createNotificationUI() {
JButton createMasks = new JButton("Create New Masks");
createMasks.setPreferredSize(createMasks.getPreferredSize());
createMasks.setMinimumSize(createMasks.getPreferredSize());
createMasks.setMaximumSize(createMasks.getPreferredSize());
createMasks.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
landMasksData.setDeleteMasks(true);
dispose();
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.setPreferredSize(cancelButton.getPreferredSize());
cancelButton.setMinimumSize(cancelButton.getPreferredSize());
cancelButton.setMaximumSize(cancelButton.getPreferredSize());
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
JLabel filler = new JLabel(" ");
JPanel buttonsJPanel = new JPanel(new GridBagLayout());
buttonsJPanel.add(cancelButton,
new ExGridBagConstraints(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
buttonsJPanel.add(filler,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
buttonsJPanel.add(createMasks,
new ExGridBagConstraints(2, 0, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
buttonsJPanel.add(helpButton,
new ExGridBagConstraints(3, 0, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
JLabel jLabel = new JLabel("Masks have already been created for this product");
JPanel jPanel = new JPanel(new GridBagLayout());
jPanel.add(jLabel,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
jPanel.add(buttonsJPanel,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
add(jPanel);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("Land Masks");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setPreferredSize(getPreferredSize());
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
setSize(getPreferredSize());
}
public final void createLandMasksUI() {
final int rightInset = 5;
final CoastlineCreateCheckbox coastlineCreateCheckbox = new CoastlineCreateCheckbox(landMasksData);
final CoastlineEnabledAllBandsCheckbox coastlineEnabledAllBandsCheckbox = new CoastlineEnabledAllBandsCheckbox(landMasksData);
final WaterEnabledAllBandsCheckbox waterEnabledAllBandsCheckbox = new WaterEnabledAllBandsCheckbox(landMasksData);
final LandEnabledAllBandsCheckbox landEnabledAllBandsCheckbox = new LandEnabledAllBandsCheckbox(landMasksData);
final CoastlineTransparencySpinner coastlineTransparencySpinner = new CoastlineTransparencySpinner(landMasksData);
final WaterTransparencySpinner waterTransparencySpinner = new WaterTransparencySpinner(landMasksData);
final LandTransparencySpinner landTransparencySpinner = new LandTransparencySpinner(landMasksData);
final CoastlineColorComboBox coastlineColorComboBox = new CoastlineColorComboBox(landMasksData);
final WaterColorComboBox waterColorComboBox = new WaterColorComboBox(landMasksData);
final LandColorComboBox landColorComboBox = new LandColorComboBox(landMasksData);
final ResolutionComboBox resolutionComboBox = new ResolutionComboBox(landMasksData);
final SuperSamplingSpinner superSamplingSpinner = new SuperSamplingSpinner(landMasksData);
final CoastalGridSizeSpinner coastalGridSizeSpinner = new CoastalGridSizeSpinner(landMasksData);
final CoastalSizeToleranceSpinner coastalSizeToleranceSpinner = new CoastalSizeToleranceSpinner(landMasksData);
JPanel resolutionSamplingPanel = new JPanel(new GridBagLayout());
resolutionSamplingPanel.setBorder(BorderFactory.createTitledBorder(""));
resolutionSamplingPanel.add(resolutionComboBox.getjLabel(),
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
JComboBox jComboBox = resolutionComboBox.getjComboBox();
landMasksData.addPropertyChangeListener(LandMasksData.PROMPT_REQUEST_TO_INSTALL_FILE_EVENT, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
SourceFileInfo sourceFileInfo = (SourceFileInfo) resolutionComboBox.getjComboBox().getSelectedItem();
InstallResolutionFileDialog dialog = new InstallResolutionFileDialog(landMasksData, sourceFileInfo, InstallResolutionFileDialog.Step.INSTALLATION);
dialog.setVisible(true);
dialog.setEnabled(true);
}
});
resolutionSamplingPanel.add(jComboBox,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
resolutionSamplingPanel.add(superSamplingSpinner.getjLabel(),
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
resolutionSamplingPanel.add(superSamplingSpinner.getjSpinner(),
new ExGridBagConstraints(1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
JPanel coastlineJPanel = new JPanel(new GridBagLayout());
coastlineJPanel.setBorder(BorderFactory.createTitledBorder(""));
JTextField coastlineNameTextfield = new JTextField(landMasksData.getCoastlineMaskName());
coastlineNameTextfield.setEditable(false);
coastlineNameTextfield.setToolTipText("Name of the mask (this field is not editable)");
JLabel coastlineNameLabel = new JLabel("Mask Name");
coastlineJPanel.add(coastlineCreateCheckbox.getjLabel(),
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
coastlineJPanel.add(coastlineCreateCheckbox.getjCheckBox(),
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
coastlineJPanel.add(coastlineNameLabel,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
coastlineJPanel.add(coastlineNameTextfield,
new ExGridBagConstraints(1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
coastlineJPanel.add(coastalGridSizeSpinner.getjLabel(),
new ExGridBagConstraints(0, 2, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
coastlineJPanel.add(coastalGridSizeSpinner.getjSpinner(),
new ExGridBagConstraints(1, 2, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
coastlineJPanel.add(coastalSizeToleranceSpinner.getjLabel(),
new ExGridBagConstraints(0, 3, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
coastlineJPanel.add(coastalSizeToleranceSpinner.getjSpinner(),
new ExGridBagConstraints(1, 3, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
coastlineJPanel.add(coastlineColorComboBox.getjLabel(),
new ExGridBagConstraints(0, 4, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
coastlineJPanel.add(coastlineColorComboBox.getColorExComboBox(),
new ExGridBagConstraints(1, 4, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
coastlineJPanel.add(coastlineTransparencySpinner.getjLabel(),
new ExGridBagConstraints(0, 5, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
coastlineJPanel.add(coastlineTransparencySpinner.getjSpinner(),
new ExGridBagConstraints(1, 5, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
coastlineJPanel.add(coastlineEnabledAllBandsCheckbox.getjLabel(),
new ExGridBagConstraints(0, 6, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
coastlineJPanel.add(coastlineEnabledAllBandsCheckbox.getjCheckBox(),
new ExGridBagConstraints(1, 6, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
coastlineNameLabel.setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineNameTextfield.setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastalGridSizeSpinner.getjLabel().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastalGridSizeSpinner.getjSpinner().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastalSizeToleranceSpinner.getjLabel().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastalSizeToleranceSpinner.getjSpinner().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineColorComboBox.getjLabel().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineColorComboBox.getColorExComboBox().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineTransparencySpinner.getjLabel().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineTransparencySpinner.getjSpinner().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineEnabledAllBandsCheckbox.getjCheckBox().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineEnabledAllBandsCheckbox.getjLabel().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineCreateCheckbox.getjCheckBox().addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
coastlineNameLabel.setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineNameTextfield.setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastalGridSizeSpinner.getjLabel().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastalGridSizeSpinner.getjSpinner().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastalSizeToleranceSpinner.getjLabel().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastalSizeToleranceSpinner.getjSpinner().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineColorComboBox.getjLabel().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineColorComboBox.getColorExComboBox().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
// if (coastlineCreateCheckbox.getjCheckBox().isSelected()) {
// ((ColorComboBox) coastlineColorComboBox.getColorExComboBox()).setSelectedColor(landMasksData.getCoastlineMaskColor());
// } else {
// ((ColorComboBox) coastlineColorComboBox.getColorExComboBox()).setSelectedColor(Color.lightGray);
// }
coastlineTransparencySpinner.getjLabel().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineTransparencySpinner.getjSpinner().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineEnabledAllBandsCheckbox.getjCheckBox().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
coastlineEnabledAllBandsCheckbox.getjLabel().setEnabled(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineNameLabel.setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineNameTextfield.setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastalGridSizeSpinner.getjLabel().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastalGridSizeSpinner.getjSpinner().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastalSizeToleranceSpinner.getjLabel().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastalSizeToleranceSpinner.getjSpinner().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineColorComboBox.getjLabel().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineColorComboBox.getColorExComboBox().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineTransparencySpinner.getjLabel().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineTransparencySpinner.getjSpinner().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineEnabledAllBandsCheckbox.getjLabel().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineEnabledAllBandsCheckbox.getjCheckBox().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineEnabledAllBandsCheckbox.getjLabel().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
}
});
JPanel waterJPanel = new JPanel(new GridBagLayout());
waterJPanel.setBorder(BorderFactory.createTitledBorder(""));
JTextField waterNameTextfield = new JTextField(landMasksData.getWaterMaskName());
waterNameTextfield.setEditable(false);
waterNameTextfield.setToolTipText("Name of the mask (this field is not editable)");
waterJPanel.add(new JLabel("Mask Name"),
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
waterJPanel.add(waterNameTextfield,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
waterJPanel.add(waterColorComboBox.getjLabel(),
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
waterJPanel.add(waterColorComboBox.getColorExComboBox(),
new ExGridBagConstraints(1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
waterJPanel.add(waterTransparencySpinner.getjLabel(),
new ExGridBagConstraints(0, 2, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
waterJPanel.add(waterTransparencySpinner.getjSpinner(),
new ExGridBagConstraints(1, 2, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
waterJPanel.add(waterEnabledAllBandsCheckbox.getjLabel(),
new ExGridBagConstraints(0, 3, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
waterJPanel.add(waterEnabledAllBandsCheckbox.getjCheckBox(),
new ExGridBagConstraints(1, 3, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
JPanel landJPanel = new JPanel(new GridBagLayout());
landJPanel.setBorder(BorderFactory.createTitledBorder(""));
JTextField landNameTextfield = new JTextField(landMasksData.getLandMaskName());
landNameTextfield.setEditable(false);
landNameTextfield.setToolTipText("Name of the mask (this field is not editable)");
landJPanel.add(new JLabel("Mask Name"),
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
landJPanel.add(landNameTextfield,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
landJPanel.add(landColorComboBox.getjLabel(),
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
landJPanel.add(landColorComboBox.getColorExComboBox(),
new ExGridBagConstraints(1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
landJPanel.add(landTransparencySpinner.getjLabel(),
new ExGridBagConstraints(0, 2, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
landJPanel.add(landTransparencySpinner.getjSpinner(),
new ExGridBagConstraints(1, 2, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
landJPanel.add(landEnabledAllBandsCheckbox.getjLabel(),
new ExGridBagConstraints(0, 3, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, rightInset)));
landJPanel.add(landEnabledAllBandsCheckbox.getjCheckBox(),
new ExGridBagConstraints(1, 3, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.add(resolutionSamplingPanel,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3));
mainPanel.add(coastlineJPanel,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3));
mainPanel.add(landJPanel,
new ExGridBagConstraints(0, 2, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3));
mainPanel.add(waterJPanel,
new ExGridBagConstraints(0, 3, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3));
JButton createMasks = new JButton("Create Masks");
createMasks.setPreferredSize(createMasks.getPreferredSize());
createMasks.setMinimumSize(createMasks.getPreferredSize());
createMasks.setMaximumSize(createMasks.getPreferredSize());
createMasks.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
landMasksData.setCreateMasks(true);
dispose();
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.setPreferredSize(cancelButton.getPreferredSize());
cancelButton.setMinimumSize(cancelButton.getPreferredSize());
cancelButton.setMaximumSize(cancelButton.getPreferredSize());
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
JLabel filler = new JLabel(" ");
JPanel buttonsJPanel = new JPanel(new GridBagLayout());
buttonsJPanel.add(cancelButton,
new ExGridBagConstraints(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE));
buttonsJPanel.add(filler,
new ExGridBagConstraints(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL));
buttonsJPanel.add(createMasks,
new ExGridBagConstraints(2, 0, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
buttonsJPanel.add(helpButton,
new ExGridBagConstraints(3, 0, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE));
createMasks.setAlignmentX(0.5f);
mainPanel.add(buttonsJPanel,
new ExGridBagConstraints(0, 4, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 5));
add(mainPanel);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("Create Coastline & Land Masks");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// setLocationRelativeTo(null);
setBounds(300,100,100,100);
pack();
setPreferredSize(getPreferredSize());
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
setSize(getPreferredSize());
// coastlineNameLabel.setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineNameTextfield.setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastalGridSizeSpinner.getjLabel().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastalGridSizeSpinner.getjSpinner().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastalSizeToleranceSpinner.getjLabel().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastalSizeToleranceSpinner.getjSpinner().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineColorComboBox.getjLabel().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineColorComboBox.getColorExComboBox().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineTransparencySpinner.getjLabel().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineTransparencySpinner.getjSpinner().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineEnabledAllBandsCheckbox.getjLabel().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineEnabledAllBandsCheckbox.getjCheckBox().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
// coastlineEnabledAllBandsCheckbox.getjLabel().setVisible(coastlineCreateCheckbox.getjCheckBox().isSelected());
}
}
| 23,428 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
ResolutionComboBox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/ResolutionComboBox.java | package gov.nasa.gsfc.seadas.watermask.ui;
import javax.swing.*;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/5/12
* Time: 11:07 AM
* To change this template use File | Settings | File Templates.
*/
public class ResolutionComboBox {
private LandMasksData landMasksData;
private JLabel jLabel;
private JComboBox jComboBox;
private int validSelectedIndex;
public ResolutionComboBox(final LandMasksData landMasksData) {
this.landMasksData = landMasksData;
ArrayList<SourceFileInfo> jComboBoxArrayList = new ArrayList<SourceFileInfo>();
ArrayList<String> toolTipsArrayList = new ArrayList<String>();
ArrayList<Boolean> enabledArrayList = new ArrayList<Boolean>();
for (SourceFileInfo sourceFileInfo : landMasksData.getSourceFileInfos()) {
jComboBoxArrayList.add(sourceFileInfo);
if (sourceFileInfo.getDescription() != null) {
toolTipsArrayList.add(sourceFileInfo.getDescription());
} else {
toolTipsArrayList.add(null);
}
enabledArrayList.add(new Boolean(sourceFileInfo.isEnabled()));
}
final SourceFileInfo[] jComboBoxArray = new SourceFileInfo[jComboBoxArrayList.size()];
int i = 0;
for (SourceFileInfo sourceFileInfo : landMasksData.getSourceFileInfos()) {
jComboBoxArray[i] = sourceFileInfo;
i++;
}
final String[] toolTipsArray = new String[jComboBoxArrayList.size()];
int j = 0;
for (String validValuesToolTip : toolTipsArrayList) {
toolTipsArray[j] = validValuesToolTip;
j++;
}
final Boolean[] enabledArray = new Boolean[jComboBoxArrayList.size()];
int k = 0;
for (Boolean enabled : enabledArrayList) {
enabledArray[k] = enabled;
k++;
}
jComboBox = new JComboBox(jComboBoxArray);
final MyComboBoxRenderer myComboBoxRenderer = new MyComboBoxRenderer();
myComboBoxRenderer.setTooltipList(toolTipsArray);
myComboBoxRenderer.setEnabledList(enabledArray);
jComboBox.setRenderer(myComboBoxRenderer);
jComboBox.setEditable(false);
for (SourceFileInfo sourceFileInfo : jComboBoxArray) {
if (sourceFileInfo == landMasksData.getSourceFileInfo()) {
jComboBox.setSelectedItem(sourceFileInfo);
}
}
validSelectedIndex = jComboBox.getSelectedIndex();
jLabel = new JLabel("World Source Data");
jLabel.setToolTipText("Determines which world source land/water data to use when generating the masks");
addControlListeners();
addEventHandlers();
}
private void addEventHandlers() {
landMasksData.addPropertyChangeListener(LandMasksData.FILE_INSTALLED_EVENT2, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateJComboBox();
}
});
landMasksData.addPropertyChangeListener(LandMasksData.CONFIRMED_REQUEST_TO_INSTALL_FILE_EVENT, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
SourceFileInfo sourceFileInfo = (SourceFileInfo) jComboBox.getSelectedItem();
jComboBox.setSelectedIndex(getValidSelectedIndex());
}
});
}
private void addControlListeners() {
jComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SourceFileInfo sourceFileInfo = (SourceFileInfo) jComboBox.getSelectedItem();
if (sourceFileInfo.isEnabled()) {
landMasksData.setSourceFileInfo(sourceFileInfo);
validSelectedIndex = jComboBox.getSelectedIndex();
} else {
// restore to prior selection
// jComboBox.setSelectedIndex(selectedIndex);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
landMasksData.fireEvent(LandMasksData.PROMPT_REQUEST_TO_INSTALL_FILE_EVENT);
}
});
}
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JComboBox getjComboBox() {
return jComboBox;
}
public void updateJComboBox() {
ArrayList<SourceFileInfo> jComboBoxArrayList = new ArrayList<SourceFileInfo>();
ArrayList<String> toolTipsArrayList = new ArrayList<String>();
ArrayList<Boolean> enabledArrayList = new ArrayList<Boolean>();
for (SourceFileInfo sourceFileInfo : landMasksData.getSourceFileInfos()) {
jComboBoxArrayList.add(sourceFileInfo);
if (sourceFileInfo.getDescription() != null) {
toolTipsArrayList.add(sourceFileInfo.getDescription());
} else {
toolTipsArrayList.add(null);
}
enabledArrayList.add(new Boolean(sourceFileInfo.isEnabled()));
}
final SourceFileInfo[] jComboBoxArray = new SourceFileInfo[jComboBoxArrayList.size()];
int i = 0;
for (SourceFileInfo sourceFileInfo : landMasksData.getSourceFileInfos()) {
jComboBoxArray[i] = sourceFileInfo;
i++;
}
final String[] toolTipsArray = new String[jComboBoxArrayList.size()];
int j = 0;
for (String validValuesToolTip : toolTipsArrayList) {
toolTipsArray[j] = validValuesToolTip;
j++;
}
final Boolean[] enabledArray = new Boolean[jComboBoxArrayList.size()];
int k = 0;
for (Boolean enabled : enabledArrayList) {
enabledArray[k] = enabled;
k++;
}
final MyComboBoxRenderer myComboBoxRenderer = new MyComboBoxRenderer();
myComboBoxRenderer.setTooltipList(toolTipsArray);
myComboBoxRenderer.setEnabledList(enabledArray);
jComboBox.setRenderer(myComboBoxRenderer);
jComboBox.setEditable(false);
for (SourceFileInfo sourceFileInfo : jComboBoxArray) {
if (sourceFileInfo == landMasksData.getSourceFileInfo()) {
jComboBox.setSelectedItem(sourceFileInfo);
}
}
validSelectedIndex = jComboBox.getSelectedIndex();
// int i = 0;
// for (SourceFileInfo sourceFileInfo : jComboBoxArray) {
// enabledArray[i] = sourceFileInfo.isEnabled();
// i++;
// }
//
//
// final MyComboBoxRenderer myComboBoxRenderer = new MyComboBoxRenderer();
// myComboBoxRenderer.setTooltipList(toolTipsArray);
// myComboBoxRenderer.setEnabledList(enabledArray);
//
// jComboBox.setRenderer(myComboBoxRenderer);
//
//
// for (SourceFileInfo sourceFileInfo : jComboBoxArray) {
// if (sourceFileInfo == landMasksData.getSourceFileInfo()) {
// jComboBox.setSelectedItem(sourceFileInfo);
// }
// }
//
// selectedIndex = jComboBox.getSelectedIndex();
//
}
public int getValidSelectedIndex() {
return validSelectedIndex;
}
class MyComboBoxRenderer extends BasicComboBoxRenderer {
private String[] tooltips;
private Boolean[] enabledList;
// public void MyComboBoxRenderer(String[] tooltips) {
// this.tooltips = tooltips;
// }
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected) {
if (-1 < index && index < tooltips.length) {
list.setToolTipText(tooltips[index]);
}
if (-1 < index && index < enabledList.length) {
if (enabledList[index] == true) {
// list.setSelectionBackground(Color.white);
// list.setSelectionForeground(Color.black);
setBackground(Color.blue);
setForeground(Color.white);
// setEnabled(true);
// setFocusable(true);
//
} else {
// list.setSelectionBackground(Color.white);
// list.setSelectionForeground(Color.gray);
// setBackground(Color.white);
// setForeground(Color.gray);
setBackground(Color.blue);
setForeground(Color.gray);
// setEnabled(false);
// setFocusable(false);
}
}
} else {
if (-1 < index && index < enabledList.length) {
if (enabledList[index] == true) {
// list.setSelectionBackground(Color.white);
// list.setSelectionForeground(Color.black);
setBackground(Color.white);
setForeground(Color.black);
// setEnabled(true);
// setFocusable(true);
} else {
// list.setSelectionBackground(Color.white);
// list.setSelectionForeground(Color.gray);
setBackground(Color.white);
setForeground(Color.gray);
// setEnabled(false);
// setFocusable(false);
}
}
}
//
// list.setSelectionBackground(Color.white);
// list.setSelectionForeground(Color.black);
setFont(list.getFont());
setText((value == null) ? "" : value.toString());
return this;
}
public void setTooltipList(String[] tooltipList) {
this.tooltips = tooltipList;
}
public void setEnabledList(Boolean[] enabledList) {
this.enabledList = enabledList;
}
}
}
| 10,542 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
CoastlineTransparencySpinner.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/CoastlineTransparencySpinner.java | package gov.nasa.gsfc.seadas.watermask.ui;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.text.DecimalFormat;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 9:20 AM
* To change this template use File | Settings | File Templates.
*/
public class CoastlineTransparencySpinner {
private LandMasksData landMasksData;
private JLabel jLabel;
private JSpinner jSpinner = new JSpinner();
public CoastlineTransparencySpinner(LandMasksData landMasksData) {
this.landMasksData = landMasksData;
jLabel = new JLabel("Transparency");
jLabel.setToolTipText("Coastline mask transparency");
jSpinner.setModel(new SpinnerNumberModel(100, 0, 100, 100));
jSpinner.setPreferredSize(jSpinner.getPreferredSize());
jSpinner.setSize(jSpinner.getPreferredSize());
jSpinner.setModel(new SpinnerNumberModel(landMasksData.getCoastlineMaskTransparency(), 0.0, 1.0, 0.1));
JSpinner.NumberEditor editor = (JSpinner.NumberEditor) jSpinner.getEditor();
DecimalFormat format = editor.getFormat();
format.setMinimumFractionDigits(1);
addControlListeners();
}
private void addControlListeners() {
jSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent changeEvent) {
landMasksData.setCoastlineMaskTransparency((Double) jSpinner.getValue());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JSpinner getjSpinner() {
return jSpinner;
}
}
| 1,685 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
LandEnabledAllBandsCheckbox.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/LandEnabledAllBandsCheckbox.java | package gov.nasa.gsfc.seadas.watermask.ui;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 9/4/12
* Time: 9:43 AM
* To change this template use File | Settings | File Templates.
*/
public class LandEnabledAllBandsCheckbox {
private LandMasksData landMasksData;
private JLabel jLabel;
private JCheckBox jCheckBox = new JCheckBox();
private static String DEFAULT_NAME = "Enabled in All Bands";
private static String DEFAULT_TOOLTIPS = "Set Land Mask Enabled in All Bands";
public LandEnabledAllBandsCheckbox(LandMasksData landMasksData) {
this.landMasksData = landMasksData;
jLabel = new JLabel(DEFAULT_NAME);
jLabel.setToolTipText(DEFAULT_TOOLTIPS);
jCheckBox.setSelected(landMasksData.isShowLandMaskAllBands());
addControlListeners();
}
private void addControlListeners() {
jCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
landMasksData.setShowLandMaskAllBands(jCheckBox.isSelected());
}
});
}
public JLabel getjLabel() {
return jLabel;
}
public JCheckBox getjCheckBox() {
return jCheckBox;
}
}
| 1,343 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
SimpleDialogMessage.java | /FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-watermask-operator/src/main/java/gov/nasa/gsfc/seadas/watermask/ui/SimpleDialogMessage.java | package gov.nasa.gsfc.seadas.watermask.ui;
import gov.nasa.gsfc.seadas.watermask.operator.WatermaskClassifier;
import gov.nasa.gsfc.seadas.watermask.util.ResourceInstallationUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URL;
/**
* Created with IntelliJ IDEA.
* User: knowles
* Date: 1/16/13
* Time: 1:01 PM
* To change this template use File | Settings | File Templates.
*/
public class SimpleDialogMessage extends JDialog {
public SimpleDialogMessage(String title, String message) {
JButton okayButton = new JButton("Okay");
okayButton.setPreferredSize(okayButton.getPreferredSize());
okayButton.setMinimumSize(okayButton.getPreferredSize());
okayButton.setMaximumSize(okayButton.getPreferredSize());
okayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
JLabel jLabel = new JLabel(message);
JPanel jPanel = new JPanel(new GridBagLayout());
jPanel.add(jLabel,
new ExGridBagConstraints(0, 0, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
jPanel.add(okayButton,
new ExGridBagConstraints(0, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE));
add(jPanel);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle(title);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setPreferredSize(getPreferredSize());
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
setSize(getPreferredSize());
}
} | 1,809 | Java | .java | seadas/seadas-toolbox | 17 | 2 | 5 | 2018-06-28T18:46:30Z | 2024-05-08T21:01:05Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.