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
Mission.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/Mission.java
package gov.nasa.gsfc.seadas.processing.common; /** * Created by aabduraz on 6/16/17. */ public class Mission { private String missionName; private String alternativeMissionNames; private boolean isMissionExist; private String[] missionSuites; public Mission(String missionName){ this.missionName = missionName; } public String getMissionName() { return missionName; } public void setMissionName(String missionName) { this.missionName = missionName; } public boolean isMissionExist() { return isMissionExist; } public void setMissionExist(boolean missionExist) { isMissionExist = missionExist; } public String[] getMissionSuites() { return missionSuites; } public void setMissionSuites(String[] missionSuites) { this.missionSuites = missionSuites; } public String getAlternativeMissionNames() { return alternativeMissionNames; } public void setAlternativeMissionNames(String alternativeMissionNames) { this.alternativeMissionNames = alternativeMissionNames; } }
1,136
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
ParFileUI.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/ParFileUI.java
package gov.nasa.gsfc.seadas.processing.common; import static gov.nasa.gsfc.seadas.processing.common.FileSelector.PROPERTY_KEY_APP_LAST_OPEN_DIR; import gov.nasa.gsfc.seadas.processing.core.ParamInfo; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.util.logging.Logger; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.core.util.io.FileUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.SnapFileChooser; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 6/7/12 * Time: 9:48 AM * To change this template use File | Settings | File Templates. */ public class ParFileUI { private ProcessorModel processorModel; private final JCheckBox openInAppCheckBox; private final JCheckBox showDefaultCheckBox; private JPanel parStringPanel; public ParFileUI(ProcessorModel pm) { processorModel = pm; openInAppCheckBox = new JCheckBox("Open in " + SnapApp.getDefault().getAppContext().getApplicationName()); openInAppCheckBox.setSelected(pm.isOpenInSeadas()); if ("l2bin".equals(pm.getProgramName()) || "l3bin".equals(pm.getProgramName()) || "l3binmerge".equals(pm.getProgramName()) ) { openInAppCheckBox.setSelected(false); openInAppCheckBox.setVisible(false); } parStringPanel = new JPanel(new GridBagLayout()); showDefaultCheckBox = new JCheckBox("Show Default Values"); createParStringButtonPanel(); } public JPanel getParStringPanel() { return parStringPanel; } private JTextArea createParStringEditor(String parString) { JTextArea parStringEditor = new JTextArea(parString); parStringEditor.setPreferredSize(parStringEditor.getPreferredSize()); return parStringEditor; } public boolean isOpenOutputInApp() { return openInAppCheckBox.isSelected(); } private void createParStringButtonPanel() { final JButton saveParameterFileButton = new JButton("Save Parameters..."); saveParameterFileButton.setName("saveParameters"); final JButton loadParameterButton = new JButton("Load Parameters..."); loadParameterButton.setName("loadParameters"); //The above two buttons are only active if an ocssw processor accepts par file. if (processorModel.acceptsParFile()) { saveParameterFileButton.addActionListener(createSafeAsAction()); loadParameterButton.addActionListener(createLoadParameterAction()); } else { saveParameterFileButton.setEnabled(false); loadParameterButton.setEnabled(false); } showDefaultCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { //To change body of implemented methods use File | Settings | File Templates. } }); parStringPanel.add(loadParameterButton, new GridBagConstraintsCustom(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE)); parStringPanel.add(saveParameterFileButton, new GridBagConstraintsCustom(1, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE)); //TODO: add a checkbox to show default values of params // parStringPanel.add(showDefaultCheckBox, // new GridBagConstraintsCustom(2, 0, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE)); parStringPanel.add(openInAppCheckBox, new GridBagConstraintsCustom(3, 0, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE)); parStringPanel.setMaximumSize(parStringPanel.getPreferredSize()); parStringPanel.setMinimumSize(parStringPanel.getPreferredSize()); } private ActionListener createLoadParameterAction() { return new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final Component parent = (Component) e.getSource(); Logger.getGlobal().info("current working directory: " + processorModel.getRootDir().getAbsolutePath()); String homeDirPath = SystemUtils.getUserHomeDir().getPath(); AppContext appContext = SnapApp.getDefault().getAppContext(); String openDir = appContext.getPreferences().getPropertyString(PROPERTY_KEY_APP_LAST_OPEN_DIR, homeDirPath); final SnapFileChooser beamFileChooser = new SnapFileChooser(new File(openDir)); final int status = beamFileChooser.showOpenDialog(parent); if (status == JFileChooser.APPROVE_OPTION) { final File file = beamFileChooser.getSelectedFile(); if (!file.exists()) { JOptionPane.showMessageDialog(parent, "Unable to load parameter file '" + file + "'.\n" + "The file does not exist.", "Error", JOptionPane.ERROR_MESSAGE); return; } LineNumberReader reader = null; try { reader = new LineNumberReader(new FileReader(file)); String line; line = reader.readLine(); String[] option; ParamInfo pi; while (line != null) { if (line.indexOf("=") != -1) { option = line.split("=", 2); option[0] = option[0].trim(); option[1] = option[1].trim(); if(!option[0].substring(0,1).equals("#")) { // ignore comments with = signs Logger.getGlobal().info("option1: " + option[0] + " option2: " + option[1]) ; pi = processorModel.getParamInfo(option[0]); if (pi == null) { JOptionPane.showMessageDialog(parent, file.getName() + " is not a correct par file for " + processorModel.getProgramName() + "'.\n", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (option[0].equals(processorModel.getPrimaryInputFileOptionName())) { // make a relative ifile relative to the par file File tmpFile = SeadasFileUtils.createFile(file.getParentFile(), option[1]); option[1] = tmpFile.getAbsolutePath(); if (!processorModel.updateIFileInfo(option[1])) { JOptionPane.showMessageDialog(parent, "ifile " + option[1] + " is not found. Please include absolute path in the ifile name or select ifile through file chooser.", "Error", JOptionPane.ERROR_MESSAGE); //showErrorMessage(parent, "ifile is not found. Please include absolute path in the ifile name or select ifile through file chooser."); return; } } else if (option[0].equals(processorModel.getPrimaryOutputFileOptionName())) { String ofileName = option[1]; if ( ! ofileName.startsWith(System.getProperty("file.separator"))) { ofileName = processorModel.getIFileDir().getAbsolutePath() + ofileName; } if (!processorModel.updateOFileInfo(ofileName)) { showErrorMessage(parent, "ofile directory does not exist!"); return; } } else { processorModel.updateParamInfo(pi, option[1]); } } // not comment line } line = reader.readLine(); } } catch (IOException e1) { System.err.println(e1.getMessage()); e1.printStackTrace(); JOptionPane.showMessageDialog(parent, "Unable to load parameter file '" + file + "'.\n" + "Error reading file.", "Error", JOptionPane.ERROR_MESSAGE); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } } } }; } private ActionListener createSafeAsAction() { return new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final JComponent parent = (JComponent) e.getSource(); File selectedFile = getParameterFile(); try { saveParameterFile(parent, selectedFile); } catch (IOException e1) { showErrorMessage(parent, selectedFile.getName()); } } }; } private File saveParameterFile(JComponent parent, File selectedFile) throws IOException { final SnapFileChooser beamFileChooser = new SnapFileChooser(); if (selectedFile != null) { beamFileChooser.setSelectedFile(selectedFile); } final int status = beamFileChooser.showSaveDialog(parent); if (JFileChooser.APPROVE_OPTION == status) { selectedFile = beamFileChooser.getSelectedFile(); if (selectedFile.canWrite()) { final int i = JOptionPane.showConfirmDialog(parent, "The file exists.\nDo you really want to overwrite the existing file?"); if (i == JOptionPane.OK_OPTION) { return writeParameterFileTo(selectedFile); } else { saveParameterFile(parent, null); } } else if (selectedFile.createNewFile()) { return writeParameterFileTo(selectedFile); } else { showErrorMessage(parent, selectedFile.getName()); } } return null; } private File writeParameterFileTo(File parameterFile) throws IOException { FileWriter fileWriter = null; ParFileManager parFileManager = new ParFileManager(processorModel); try { fileWriter = new FileWriter(parameterFile); fileWriter.write(parFileManager.getParString()); return parameterFile; } finally { if (fileWriter != null) { fileWriter.close(); } } } private File getParameterFile() { final File productFile = new File(processorModel.getParamValue(processorModel.getPrimaryInputFileOptionName())); if (productFile !=null){ return FileUtils.exchangeExtension(productFile, ".par"); } else { return null; } } private void showErrorMessage(Component parent, String parFileName) { JOptionPane.showMessageDialog(parent, "Unable to create parameter file:\n'" + parFileName + "'", "", JOptionPane.ERROR_MESSAGE); } }
12,523
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SeadasFileUtils.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/SeadasFileUtils.java
package gov.nasa.gsfc.seadas.processing.common; import gov.nasa.gsfc.seadas.processing.core.ParamInfo; import gov.nasa.gsfc.seadas.processing.ocssw.OsUtils; import gov.nasa.gsfc.seadas.processing.utilities.SeadasArrayUtils; import org.esa.snap.rcp.util.Dialogs; import javax.activation.MimetypesFileTypeMap; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.System.out; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 6/20/12 * Time: 2:46 PM * To change this template use File | Settings | File Templates. */ public class SeadasFileUtils { private static boolean debug = false; public static File createFile(String parent, String fileName) { File pFile; if (parent == null) { pFile = null; } else { pFile = new File(parent); } return createFile(pFile, fileName); } public static File createFile(File parent, String fileName) { if (fileName == null) { return null; } String expandedFilename = SeadasFileUtils.expandEnvironment(fileName); File file = new File(expandedFilename); if (!file.isAbsolute() && parent != null) { file = new File(parent, expandedFilename); } return file; } public static void copyFileUsingStream(File source, File dest) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(source); os = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { is.close(); os.close(); } } public static String getKeyValueFromParFile(File file, String key) { try { LineNumberReader reader = new LineNumberReader(new FileReader(file)); String line; line = reader.readLine(); String[] option; ParamInfo pi; while (line != null) { if (line.indexOf("=") != -1) { option = line.split("=", 2); option[0] = option[0].trim(); option[1] = option[1].trim(); if (option[0].trim().equals(key)) { return option[1]; } } line = reader.readLine(); } } catch (FileNotFoundException fnfe) { } catch (IOException ioe) { } return null; } public static void writeToFile(InputStream downloadedInputStream, String downloadedFileLocation) { try { File file = new File(downloadedFileLocation); OutputStream outputStream = new FileOutputStream(file); int read = 0; byte[] bytes = new byte[8192]; while ((read = downloadedInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } downloadedInputStream.close(); outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } public static boolean copyFileWithPath(String sourceFilePathName, String targetFilePathName) { Path copied = Paths.get(targetFilePathName); Path originalPath = Paths.get(sourceFilePathName); SeadasFileUtils.debug("source file path: " + originalPath); SeadasFileUtils.debug("destination file path: " + copied); try { Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING); Files.move(originalPath, copied, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { SeadasFileUtils.debug("file copy failed: " + e.getMessage()); } return new File(targetFilePathName).exists(); } /** * * @param sourceFilePathName file to be copied * @param targetFilePathName destination file name with full path * This method executes command line (OS) copy command. * @return */ public static Process cloFileCopy(String sourceFilePathName, String targetFilePathName) { SeadasFileUtils.debug( "cloFileCopy"); String[] commandArrayParams = new String[2]; commandArrayParams[0] = sourceFilePathName; commandArrayParams[1] = targetFilePathName; String[] copyCommandArray = SeadasArrayUtils.concat(OsUtils.getCopyCommandSyntax(), commandArrayParams); StringBuilder sb = new StringBuilder(); for (String item : copyCommandArray) { sb.append(item + " "); } SeadasFileUtils.debug("command array content: " + sb.toString()); ProcessBuilder processBuilder = new ProcessBuilder(copyCommandArray); Process process = null; try { process = processBuilder.start(); process.waitFor(); } catch (Exception e) { SeadasFileUtils.debug( e.getMessage()); e.printStackTrace(); } return process; } /** * Guess whether given file is binary. Just checks for anything under 0x09. */ public static boolean isBinaryFile(File f) throws IOException { FileInputStream in = new FileInputStream(f); int size = in.available(); if (size > 1024) size = 1024; byte[] data = new byte[size]; in.read(data); in.close(); int ascii = 0; int other = 0; for (int i = 0; i < data.length; i++) { byte b = data[i]; if (b < 0x09) return true; if (b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D) ascii++; else if (b >= 0x20 && b <= 0x7E) ascii++; else other++; } if (other == 0) return false; return 100 * other / (ascii + other) > 95; } public static boolean isTextFileOld(String fileName) { try { return !isBinaryFile(new File(fileName)); } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean isTextFile(String fileName){ String fileType = identifyFileTypeUsingFilesProbeContentType(fileName); if (fileType.startsWith("text")) { return true; } else { //type isn't text or type couldn't be determined, assume binary return false; } } /** * Identify file type of file with provided path and name * using JDK 7's Files.probeContentType(Path). * * @param fileName Name of file whose type is desired. * @return String representing identified type of file with provided name. */ public static String identifyFileTypeUsingFilesProbeContentType(final String fileName) { String fileType = "Undetermined"; final File file = new File(fileName); try { fileType = Files.probeContentType(file.toPath()); } catch (IOException ioException) { out.println( "ERROR: Unable to determine file type for " + fileName + " due to exception " + ioException); } return fileType; } /** * Identify file type of file with provided name using * JDK 6's MimetypesFileTypeMap. * * See Javadoc documentation for MimetypesFileTypeMap class * (http://docs.oracle.com/javase/8/docs/api/javax/activation/MimetypesFileTypeMap.html) * for details on how to configure mapping of file types or extensions. */ public static String identifyFileTypeUsingMimetypesFileTypeMap(final String fileName) { final MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap(); return fileTypeMap.getContentType(fileName); } /** * Identify file type of file with provided path and name * using JDK's URLConnection.getContentType(). * * @param fileName Name of file whose type is desired. * @return Type of file for which name was provided. */ public static String identifyFileTypeUsingUrlConnectionGetContentType(final String fileName) { String fileType = "Undetermined"; try { final URL url = new URL("file://" + fileName); final URLConnection connection = url.openConnection(); fileType = connection.getContentType(); } catch (MalformedURLException badUrlEx) { out.println("ERROR: Bad URL - " + badUrlEx); } catch (IOException ioEx) { out.println("Cannot access URLConnection - " + ioEx); } return fileType; } /** * Identify file type of file with provided path and name * using JDK's URLConnection.guessContentTypeFromName(String). * * @param fileName Name of file whose type is desired. * @return Type of file for which name was provided. */ public static String identifyFileTypeUsingUrlConnectionGuessContentTypeFromName(final String fileName) { return URLConnection.guessContentTypeFromName(fileName); } public static String getGeoFileNameFromIFile(String ifileName) { String geoFileName = (ifileName.substring(0, ifileName.indexOf("."))).concat(".GEO"); int pos1 = ifileName.indexOf("."); int pos2 = ifileName.lastIndexOf("."); if (pos2 > pos1) { geoFileName = ifileName.substring(0, pos1 + 1) + "GEO" + ifileName.substring(pos2); } if (new File(geoFileName).exists()) { return geoFileName; } else { Dialogs.showError(ifileName + " requires a GEO file to be extracted. " + geoFileName + " does not exist."); return null; } } public static String expandEnvironment(String string1) { if (string1 == null) { return string1; } String environmentPattern = "([A-Za-z0-9_]+)"; Pattern pattern1 = Pattern.compile("\\$\\{" + environmentPattern + "\\}"); Pattern pattern2 = Pattern.compile("\\$" + environmentPattern); String string2 = null; while (!string1.equals(string2)) { if (string2 != null) { string1 = string2; } string2 = expandEnvironment(pattern1, string1); string2 = expandEnvironment(pattern2, string2); if (string2 == null) { return string2; } } return string2; } private static String expandEnvironment(Pattern pattern, String string) { if (string == null || pattern == null) { return string; } Matcher matcher = pattern.matcher(string); Map<String, String> envMap = null; while (matcher.find()) { // Retrieve environment variables if (envMap == null) { envMap = System.getenv(); } String envNameOnly = matcher.group(1); if (envMap.containsKey(envNameOnly)) { String envValue = envMap.get(envNameOnly); if (envValue != null) { String escapeStrings[] = {"\\", "$", "{", "}"}; for (String escapeString : escapeStrings) { envValue = envValue.replace(escapeString, "\\" + escapeString); } Pattern envNameClausePattern = Pattern.compile(Pattern.quote(matcher.group(0))); string = envNameClausePattern.matcher(string).replaceAll(envValue); } } } return string; } public static void debug(String message) { if (debug) { out.println("Debugging: " + message); } } public static void writeToDisk(String fileName, String log) throws IOException { FileWriter fileWriter = null; try { fileWriter = new FileWriter(new File(fileName)); fileWriter.write(log); } finally { if (fileWriter != null) { fileWriter.close(); } } } public String tail(File file) { RandomAccessFile fileHandler = null; try { fileHandler = new RandomAccessFile(file, "r"); long fileLength = fileHandler.length() - 1; StringBuilder sb = new StringBuilder(); for (long filePointer = fileLength; filePointer != -1; filePointer--) { fileHandler.seek(filePointer); int readByte = fileHandler.readByte(); if (readByte == 0xA) { if (filePointer == fileLength) { continue; } break; } else if (readByte == 0xD) { if (filePointer == fileLength - 1) { continue; } break; } sb.append((char) readByte); } String lastLine = sb.reverse().toString(); return lastLine; } catch (java.io.FileNotFoundException e) { e.printStackTrace(); return null; } catch (java.io.IOException e) { e.printStackTrace(); return null; } finally { if (fileHandler != null) try { fileHandler.close(); } catch (IOException e) { /* ignore */ } } } public String tail2(File file, int lines) { java.io.RandomAccessFile fileHandler = null; try { fileHandler = new java.io.RandomAccessFile(file, "r"); long fileLength = fileHandler.length() - 1; StringBuilder sb = new StringBuilder(); int line = 0; for (long filePointer = fileLength; filePointer != -1; filePointer--) { fileHandler.seek(filePointer); int readByte = fileHandler.readByte(); if (readByte == 0xA) { if (filePointer < fileLength) { line = line + 1; } } else if (readByte == 0xD) { if (filePointer < fileLength - 1) { line = line + 1; } } if (line >= lines) { break; } sb.append((char) readByte); } String lastLine = sb.reverse().toString(); return lastLine; } catch (java.io.FileNotFoundException e) { e.printStackTrace(); return null; } catch (java.io.IOException e) { e.printStackTrace(); return null; } finally { if (fileHandler != null) try { fileHandler.close(); } catch (IOException e) { } } } public static File writeStringToFile(String fileContent, String fileLocation) { try { final File parFile = new File(fileLocation); FileWriter fileWriter = null; try { fileWriter = new FileWriter(parFile); fileWriter.write(fileContent); } finally { if (fileWriter != null) { fileWriter.close(); } } return parFile; } catch (IOException e) { e.printStackTrace(); return null; } } }
16,246
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
GridBagConstraintsCustom.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/GridBagConstraintsCustom.java
package gov.nasa.gsfc.seadas.processing.common; import java.awt.*; /** * Created by IntelliJ IDEA. * User: knowles * Date: 4/24/12 * Time: 9:51 AM * To change this template use File | Settings | File Templates. */ public class GridBagConstraintsCustom extends GridBagConstraints { // Creates a GridBagConstraints class with modifications to some of the defaults // This class is usefull because the GridBagConstraints class does not contain many constructor choices // This class enables setting several params conveniently and cleanly without a lot of lines of code // To best know which constructor to use here are the default values: // DEFAULT VALUES // gridx = 0 // gridy = 0 // weightx = 0 // weighty = 0 // anchor = CENTER // fill = NONE // insets = new Insets(0, 0, 0, 0) which means for this class: pad = 0 // gridwidth = 1 // gridheight = 1 // NOTE that the order is consistent relative to each constructor however the order of the GridBagConstraints // full constructor differs slightly for this custom version. This is because this custom class is built based // on the order of usefullness of each param. This is a subjective decision based on our current coding. Essentially // gridwidth and gridheight have been shifted to be a later param in the list in this custom version. The rest // of the params are maintained in the GridBagConstraints order. // identical to GridBagConstraints // just a convenience constructor for consistency // EXAMPLE: // myPanel.add(myComponent, new GridBagConstraintsCustom()); public GridBagConstraintsCustom() { } // EXAMPLE: // myPanel.add(myComponent, new GridBagConstraintsCustom(0, 2)); public GridBagConstraintsCustom(int gridx, int gridy) { this.gridx = gridx; this.gridy = gridy; } // EXAMPLE: // myPanel.add(myComponent, new GridBagConstraintsCustom(0, 2, 1, 0, GridBagConstraints.CENTER)); public GridBagConstraintsCustom(int gridx, int gridy, double weightx, double weighty, int anchor) { this(gridx, gridy); this.weightx = weightx; this.weighty = weighty; this.anchor = anchor; } // EXAMPLE: // myPanel.add(myComponent, new GridBagConstraintsCustom(0, 2, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE)); public GridBagConstraintsCustom(int gridx, int gridy, double weightx, double weighty, int anchor, int fill) { this(gridx, gridy, weightx, weighty, anchor); this.fill = fill; } // Enables uniform cell padding (left, top, right, bottom) with one variable // EXAMPLE: // myPanel.add(myComponent,new GridBagConstraintsCustom(0, 2, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, 2)); public GridBagConstraintsCustom(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, int pad) { this(gridx, gridy, weightx, weighty, anchor, fill); this.insets = new Insets(pad, pad, pad, pad); } // Cell padding (left, top, right, bottom) is not uniform so needs to use Insets // The example below shows how to make a cell's contents potentially expand outside of the cell // this example is useful in the case of a table type layout where the length of the column title would normally // cause the column to expand wider than is desired // EXAMPLE: // myPanel.add(myComponent,new GridBagConstraintsCustom(0, 2, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, -6, 0, -6))); public GridBagConstraintsCustom(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, Insets insets) { this(gridx, gridy, weightx, weighty, anchor, fill); this.insets = insets; } // EXAMPLE: // myPanel.add(myComponent,new GridBagConstraintsCustom(0, 2, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 2, 0, 2), 3)); public GridBagConstraintsCustom(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, int pad, int gridwidth) { this(gridx, gridy, weightx, weighty, anchor, fill, pad); this.gridwidth = gridwidth; } // EXAMPLE: // myPanel.add(myComponent,new GridBagConstraintsCustom(0, 2, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 2, 0, 2), 3, 3)); public GridBagConstraintsCustom(int gridx, int gridy, double weightx, double weighty, int anchor, int fill, int pad, int gridwidth, int gridheight) { this(gridx, gridy, weightx, weighty, anchor, fill, pad, gridwidth); this.gridheight = gridheight; } }
4,668
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SeadasFileSelector.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/SeadasFileSelector.java
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.swing.selection.SelectionChangeListener; import com.bc.ceres.swing.selection.support.ComboBoxSelectionContext; import org.esa.snap.core.dataio.ProductIOPlugInManager; import org.esa.snap.core.dataio.ProductReaderPlugIn; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductFilter; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.SnapFileChooser; import javax.swing.*; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import javax.swing.filechooser.FileFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; import static gov.nasa.gsfc.seadas.processing.common.FileSelector.PROPERTY_KEY_APP_LAST_OPEN_DIR; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 8/27/13 * Time: 3:18 PM * To change this template use File | Settings | File Templates. */ public class SeadasFileSelector { private AppContext appContext; private ProductFilter productFilter; private File currentDirectory; private DefaultComboBoxModel productListModel; private DefaultComboBoxModel<java.io.Serializable> fileListModel; private JLabel fileNameLabel; private JButton productFileChooserButton; private JButton fileChooserButton; private JComboBox<java.io.Serializable> fileNameComboBox; private final ProductManager.Listener productManagerListener; private ComboBoxSelectionContext selectionContext; private RegexFileFilter regexFileFilter; private JTextField filterRegexField; private JLabel filterRegexLabel; private boolean selectMultipleIFiles; private Product sampleProductForMultiIfiles; public SeadasFileSelector(AppContext appContext, String labelText) { this(appContext, labelText, false); } public SeadasFileSelector(AppContext appContext, String labelText, boolean selectMultipleIFiles) throws IllegalArgumentException { this.selectMultipleIFiles = selectMultipleIFiles; this.appContext = appContext; fileListModel = new DefaultComboBoxModel<>(); fileNameLabel = new JLabel(labelText); productFileChooserButton = new JButton(new FileChooserAction()); productFileChooserButton.setName("productFileChooserButton"); fileChooserButton = new JButton(new FileChooserAction()); fileNameComboBox = new JComboBox<>(fileListModel); fileChooserButton.setName("fileChooserButton"); fileNameComboBox.setPrototypeDisplayValue("[1] 123456789 123456789 123456789 123456789 123456789"); fileNameComboBox.setRenderer(new ProductListCellRenderer()); fileNameComboBox.setPreferredSize(fileNameComboBox.getPreferredSize()); fileNameComboBox.setMinimumSize(fileNameComboBox.getPreferredSize()); fileNameComboBox.addPopupMenuListener(new ProductPopupMenuListener()); fileNameComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final File file = (File) fileNameComboBox.getSelectedItem(); if (file != null) { fileNameComboBox.setToolTipText(file.getPath()); } else { fileNameComboBox.setToolTipText("Select an input file."); } } }); selectionContext = new ComboBoxSelectionContext(fileNameComboBox); productManagerListener = new ProductManager.Listener() { @Override public void productAdded(ProductManager.Event event) { fileListModel.addElement(event.getProduct().getFileLocation()); } @Override public void productRemoved(ProductManager.Event event) { Product product = event.getProduct(); if (fileListModel.getSelectedItem() == product.getFileLocation()) { fileListModel.setSelectedItem(null); } fileListModel.removeElement(product.getFileLocation()); } }; regexFileFilter = new RegexFileFilter(); sampleProductForMultiIfiles = null; } public void setEnabled(boolean enabled) { fileNameComboBox.setEnabled(enabled); fileNameLabel.setEnabled(enabled); productFileChooserButton.setEnabled(enabled); filterRegexField.setEnabled(enabled); filterRegexLabel.setEnabled(enabled); } /* Original initProducts method, which initializes the file chooser combo box with the products opened in the SeaDAS file browser. It should only list file names, without associated prodcut details. */ public synchronized void initProducts() { fileListModel.removeAllElements(); for (Product product : appContext.getProductManager().getProducts()) { if (regexFileFilter.accept(product.getFileLocation())) { fileListModel.addElement(product.getFileLocation()); } } final Product selectedProduct = appContext.getSelectedProduct(); if (selectedProduct != null && regexFileFilter.accept(selectedProduct.getFileLocation())) { fileListModel.setSelectedItem(selectedProduct.getFileLocation()); } appContext.getProductManager().addListener(productManagerListener); } public void setSelectedFile(File file) throws IllegalArgumentException{ try { if (file == null) { fileListModel.setSelectedItem(null); return; } if (regexFileFilter.accept(file)) { if (fileListModelContains(file)) { fileListModel.setSelectedItem(file); } else { fileListModel.addElement(file); fileListModel.setSelectedItem(file); } } fileNameComboBox.revalidate(); fileNameComboBox.repaint(); } catch (Exception e) { } } public File getSelectedFile() throws IllegalArgumentException{ return (File) fileListModel.getSelectedItem(); } public void addSelectionChangeListener(SelectionChangeListener listener) { selectionContext.addSelectionChangeListener(listener); } public synchronized void releaseFiles() { appContext.getProductManager().removeListener(productManagerListener); fileListModel.removeAllElements(); } public JComboBox<java.io.Serializable> getFileNameComboBox() { return fileNameComboBox; } public JLabel getFileNameLabel() { return fileNameLabel; } public void setFileNameLabel(JLabel jLabel) throws IllegalArgumentException{ this.fileNameLabel = jLabel; } public JButton getFileChooserButton() { return fileChooserButton; } private boolean fileListModelContains(File file) throws IllegalArgumentException { for (int i = 0; i < fileListModel.getSize(); i++) { if (fileListModel.getElementAt(i).equals(file)) { return true; } } return false; } public JPanel createDefaultPanel() { return createDefaultPanel(true); } public JPanel createDefaultPanel(boolean includeLabel) { JPanel mainPanel = new JPanel(new GridBagLayout()); if (includeLabel) { addLabelToMainPanel(mainPanel); } mainPanel.add(getFileNameComboBox(), new GridBagConstraintsCustom(1, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 2)); mainPanel.add(getFileChooserButton(), new GridBagConstraintsCustom(2, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2)); return mainPanel; } private void addLabelToMainPanel(JPanel jPanel) throws IllegalArgumentException { jPanel.add(getFileNameLabel(), new GridBagConstraintsCustom(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2)); } private File[] files; private class FileChooserAction extends AbstractAction { private String APPROVE_BUTTON_TEXT = "Select"; private JFileChooser fileChooser; private FileChooserAction() { super("..."); fileChooser = new SnapFileChooser(); fileChooser.setMultiSelectionEnabled(selectMultipleIFiles); fileChooser.setDialogTitle("Select Input File"); final Iterator<ProductReaderPlugIn> iterator = ProductIOPlugInManager.getInstance().getAllReaderPlugIns(); while (iterator.hasNext()) { // todo - (mp, 2008/04/22)check if product file filter is applicable fileChooser.addChoosableFileFilter(iterator.next().getProductFileFilter()); } // todo - (mp, 2008/04/22)check if product file filter is applicable fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setFileFilter(fileChooser.getAcceptAllFileFilter()); fileChooser.setFileHidingEnabled(true); } @Override public void actionPerformed(ActionEvent event) throws IllegalArgumentException { final Window window = SwingUtilities.getWindowAncestor((JComponent) event.getSource()); String homeDirPath = SystemUtils.getUserHomeDir().getPath(); String openDir = appContext.getPreferences().getPropertyString(PROPERTY_KEY_APP_LAST_OPEN_DIR, homeDirPath); currentDirectory = new File(openDir); fileChooser.setCurrentDirectory(currentDirectory); if (fileChooser.showDialog(window, APPROVE_BUTTON_TEXT) == JFileChooser.APPROVE_OPTION) { currentDirectory = fileChooser.getCurrentDirectory(); appContext.getPreferences().setPropertyString(PROPERTY_KEY_APP_LAST_OPEN_DIR, currentDirectory.getAbsolutePath()); if (selectMultipleIFiles && fileChooser.getSelectedFiles().length > 1) { handleMultipFileSelection(window); return; } final File file = fileChooser.getSelectedFile(); if (regexFileFilter.accept(file)) { setSelectedFile(file); } else { try { final String message = String.format("File [%s] is not a valid source.", file.getCanonicalPath()); handleError(window, message); } catch (IOException ioe) { SeadasFileUtils.debug(file + "is not a valid file!"); } } } } /** * creates a text file that lists file names to be binned. * This method is only used by l2bin and l3bin. As such, input files should L2 file type. * * @param window */ private void handleMultipFileSelection(Window window) throws IllegalArgumentException{ File[] tmpFiles = fileChooser.getSelectedFiles(); setSelectedMultiFileList(tmpFiles); } public void setSelectedMultiFileList(File[] selectedMultiFileList) { files = selectedMultiFileList; 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) { } setSelectedFile(fileListFile); currentDirectory = fileChooser.getCurrentDirectory(); appContext.getPreferences().setPropertyString(PROPERTY_KEY_APP_LAST_OPEN_DIR, currentDirectory.getAbsolutePath()); } private void handleError(final Component component, final String message) throws IllegalArgumentException{ SwingUtilities.invokeLater(new Runnable() { public void run() { //@Override //JOptionPane.showMessageDialog(component, message, "Error", JOptionPane.ERROR_MESSAGE); //JOptionPane.showMessageDialog(<Window>component, message, "test", JOptionPane.ERROR_MESSAGE); } }); } } private static class ProductListCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) throws IllegalArgumentException{ final Component cellRendererComponent = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (cellRendererComponent instanceof JLabel && value instanceof Product) { final JLabel label = (JLabel) cellRendererComponent; final Product product = (Product) value; label.setText(product.getDisplayName()); label.setToolTipText(product.getDescription()); } return cellRendererComponent; } } /** * To let the popup menu be wider than the closed combobox. * Adapted an idea from http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6257236 */ private static class ProductPopupMenuListener implements PopupMenuListener { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) throws IllegalArgumentException{ JComboBox box = (JComboBox) e.getSource(); Object comp = box.getUI().getAccessibleChild(box, 0); if (!(comp instanceof JPopupMenu)) { return; } JComponent scrollPane = (JComponent) ((JPopupMenu) comp) .getComponent(0); Dimension size = new Dimension(); size.width = scrollPane.getPreferredSize().width; final int boxItemCount = box.getModel().getSize(); for (int i = 0; i < boxItemCount; i++) { Product product = (Product) box.getModel().getElementAt(i); final JLabel label = new JLabel(); label.setText(product.getDisplayName()); size.width = Math.max(label.getPreferredSize().width, size.width); } size.height = scrollPane.getPreferredSize().height; scrollPane.setPreferredSize(size); scrollPane.setMaximumSize(size); } @Override public void popupMenuCanceled(PopupMenuEvent e) { } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { } } private class RegexFileFilter extends FileFilter { private String regex; public RegexFileFilter() { this(null); } public RegexFileFilter(String regex) throws IllegalStateException, IllegalArgumentException{ if (regex == null) { return; } //Replace wildcards with regular expression. if (regex.indexOf("*") != -1) { regex = regex.replaceAll("\\*", ".*"); } if (regex.trim().length() == 0) { //throw new IllegalStateException(); return; } this.regex = ".*" + regex + ".*"; } /* (non-Javadoc) * @see java.io.FileFilter#accept(java.io.File) */ public boolean accept(File pathname) throws IllegalArgumentException { if (regex == null) { return true; } return (pathname.isFile() && pathname.getName().matches(this.regex)); } public String getDescription() { return "Files matching regular expression: '" + regex + "'"; } } }
16,541
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
CallCloProgramAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/CallCloProgramAction.java
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import gov.nasa.gsfc.seadas.processing.core.L2genData; import gov.nasa.gsfc.seadas.processing.core.ProcessObserver; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfoGUI; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWLocal; import gov.nasa.gsfc.seadas.processing.utilities.ScrolledPane; import org.codehaus.plexus.util.FileUtils; import org.esa.snap.core.dataio.ProductIO; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.actions.AbstractSnapAction; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.runtime.Config; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.ModalDialog; import org.esa.snap.ui.UIUtils; import org.openide.util.ContextAwareAction; import org.openide.util.LookupListener; import org.openide.util.actions.Presenter; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.logging.Logger; import java.util.prefs.Preferences; import java.util.regex.Matcher; import java.util.regex.Pattern; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSW.*; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWConfigData.SEADAS_OCSSW_TAG_PROPERTY; /** * @author Aynur Abdurazik * @since SeaDAS 7.0 */ public class CallCloProgramAction extends AbstractSnapAction implements Presenter.Menu { public static final String CONTEXT_LOG_LEVEL_PROPERTY = SystemUtils.getApplicationContextId() + ".logLevel"; public static final String LOG_LEVEL_PROPERTY = "logLevel"; private static final Pattern PATTERN = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); private String programName; private String dialogTitle; private String xmlFileName; private boolean printLogToConsole = false; private boolean openOutputInApp = true; protected OCSSW ocssw; public final static int TOTAL_WORK_DEFAULT = 100; private static final Set<String> KNOWN_KEYS = new HashSet<>(Arrays.asList("displayName", "programName", "dialogTitle", "helpId", "targetProductNameSuffix")); protected OCSSWInfo ocsswInfo = OCSSWInfo.getInstance(); public static CallCloProgramAction create(Map<String, Object> properties) { CallCloProgramAction action = new CallCloProgramAction(); for (Map.Entry<String, Object> entry : properties.entrySet()) { if (KNOWN_KEYS.contains(entry.getKey())) { action.putValue(entry.getKey(), entry.getValue()); } } return action; } // @Override // public void configure(ConfigurationElement config) throws CoreException { // programName = getConfigString(config, "programName"); // if (programName == null) { // throw new CoreException("Missing DefaultOperatorAction property 'programName'."); // } // dialogTitle = getValue(config, "dialogTitle", programName); // xmlFileName = getValue(config, "xmlFileName", ParamUtils.NO_XML_FILE_SPECIFIED); // super.configure(config); // //super.setEnabled(programName.equals(OCSSWInfo.OCSSW_INSTALLER_PROGRAM_NAME) || ocsswInfo.isOCSSWExist()); // } public String getXmlFileName() { return xmlFileName; } public CloProgramUI getProgramUI(AppContext appContext) { if (programName.indexOf("extract") != -1) { return new ExtractorUI(programName, xmlFileName, ocssw); } else if (programName.indexOf("modis_GEO") != -1 || programName.indexOf("modis_L1B") != -1) { return new ModisGEO_L1B_UI(programName, xmlFileName, ocssw); } else if (programName.indexOf(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) != -1) { ocssw.downloadOCSSWInstaller(); if (!ocssw.isOcsswInstalScriptDownloadSuccessful()) { return null; } if (ocsswInfo.getOcsswLocation() == null || ocsswInfo.getOcsswLocation().equals(OCSSWInfo.OCSSW_LOCATION_LOCAL)) { return new OCSSWInstallerFormLocal(appContext, programName, xmlFileName, ocssw); } else { return new OCSSWInstallerFormRemote(appContext, programName, xmlFileName, ocssw); } }else if (programName.indexOf("update_luts") != -1 ) { return new UpdateLutsUI(programName, xmlFileName, ocssw); } return new ProgramUIFactory(programName, xmlFileName, ocssw);//, multiIFile); } public static boolean validate(final String ip) { return PATTERN.matcher(ip).matches(); } public void initializeOcsswClient() { ocssw = OCSSW.getOCSSWInstance(); if ( ocssw == null ) { final AppContext appContext = getAppContext(); final Window parent = appContext.getApplicationWindow(); OCSSWInfoGUI ocsswInfoGUI = new OCSSWInfoGUI(); ocsswInfoGUI.init(parent); ocsswInfo = OCSSWInfo.getInstance(); ocssw = OCSSW.getOCSSWInstance(); } } @Override public void actionPerformed(ActionEvent event) { initializeOcsswClient(); if (ocssw == null) { return; } if (!(ocssw instanceof OCSSWLocal) && !OCSSWInfo.getInstance().isOcsswServerUp()) { OCSSWInfo.displayRemoteServerDownMessage(); return; } ocssw.setProgramName(programName); final AppContext appContext = getAppContext(); final CloProgramUI cloProgramUI = getProgramUI(appContext); if (cloProgramUI == null) { SeadasFileUtils.debug("getting the GUI for the program failed"); return; } final Window parent = appContext.getApplicationWindow(); final ModalDialog modalDialog = new ModalDialog(parent, dialogTitle, cloProgramUI, ModalDialog.ID_OK_APPLY_CANCEL_HELP, programName); modalDialog.getButton(ModalDialog.ID_OK).setEnabled(cloProgramUI.getProcessorModel().isReadyToRun()); // todo this block of comments may be deleted at some point if GUI sizing isn't a problem - but keep for the moment just in case // double resizeBoost = 1.1; // resize the OSCCW generic GUIs to help in the case of scroll bar // Dimension dim = modalDialog.getJDialog().getPreferredSize(); // int width = (int) Math.round(dim.width * resizeBoost); // int height = (int) Math.round(dim.height * resizeBoost); // modalDialog.getJDialog().setPreferredSize(new Dimension(width, height)); cloProgramUI.getProcessorModel().addPropertyChangeListener(cloProgramUI.getProcessorModel().getRunButtonPropertyName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (cloProgramUI.getProcessorModel().isReadyToRun()) { modalDialog.getButton(ModalDialog.ID_OK).setEnabled(true); } else { modalDialog.getButton(ModalDialog.ID_OK).setEnabled(false); } modalDialog.getJDialog().pack(); } }); cloProgramUI.getProcessorModel().addPropertyChangeListener("geofile", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { modalDialog.getJDialog().validate(); modalDialog.getJDialog().pack(); } }); cloProgramUI.getProcessorModel().addPropertyChangeListener("infile", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { modalDialog.getJDialog().validate(); modalDialog.getJDialog().pack(); } }); modalDialog.getButton(ModalDialog.ID_OK).setText("Run"); 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); final int dialogResult = modalDialog.show(); Logger.getLogger(programName).info("dialog result: " + dialogResult); if (dialogResult != ModalDialog.ID_OK) { cloProgramUI.getProcessorModel().getParamList().clearPropertyChangeSupport(); cloProgramUI.getProcessorModel().fireEvent(L2genData.CANCEL); return; } modalDialog.getButton(ModalDialog.ID_OK).setEnabled(false); final ProcessorModel processorModel = cloProgramUI.getProcessorModel(); programName = processorModel.getProgramName(); openOutputInApp = cloProgramUI.isOpenOutputInApp(); if (!ocssw.isProgramValid()) { return; } if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) && !ocssw.isOcsswInstalScriptDownloadSuccessful()) { displayMessage(programName, "ocssw installation script does not exist." + "\n" + "Please check network connection and rerun ''Install Processor''"); return; } if (programName.equals(UPDATE_LUTS_PROGRAM_NAME)) { String message = ocssw.executeUpdateLuts(processorModel); Dialogs.showInformation(dialogTitle, message, null); } else { executeProgram(processorModel); } cloProgramUI.getProcessorModel().fireEvent(L2genData.CANCEL); } /** * @param pm is the model of the ocssw program to be executed * @output this is executed as a native process */ public void executeProgram(ProcessorModel pm) { final ProcessorModel processorModel = pm; ProgressMonitorSwingWorker swingWorker = new ProgressMonitorSwingWorker<String, Object>(getAppContext().getApplicationWindow(), "Running " + programName + " ...") { @Override protected String doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception { ocssw.setMonitorProgress(true); final Process process = ocssw.execute(processorModel); if (process == null) { throw new IOException(programName + " failed to create process."); } final ProcessObserver processObserver = ocssw.getOCSSWProcessObserver(process, programName, pm); final ConsoleHandler ch = new ConsoleHandler(programName); if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME)) { Preferences preferences = Config.instance("seadas").load().preferences(); preferences.put(SEADAS_OCSSW_TAG_PROPERTY, processorModel.getParamValue("--tag")); } pm.beginTask(programName, TOTAL_WORK_DEFAULT); processObserver.addHandler(new ProgressHandler(programName, processorModel.getProgressPattern())); processObserver.addHandler(ch); processObserver.startAndWait(); processorModel.setExecutionLogMessage(ch.getExecutionErrorLog()); int exitCode = processObserver.getProcessExitValue(); pm.done(); if (exitCode == 0) { String logDir = ocssw.getOCSSWLogDirPath(); //ocsswInfo.getLogDirPath(); SeadasFileUtils.writeToDisk(logDir + File.separator + "OCSSW_LOG_" + programName + ".txt", "Execution log for " + "\n" + Arrays.toString(ocssw.getCommandArray()) + "\n" + processorModel.getExecutionLogMessage()); } else { throw new IOException(programName + " failed with exit code " + exitCode + ".\nCheck log for more details."); } ocssw.setMonitorProgress(false); return processorModel.getOfileName(); } @Override protected void done() { try { final String outputFileName = get(); ocssw.getOutputFiles(processorModel); displayOutput(processorModel); Dialogs.showInformation(dialogTitle, "Program execution completed!\n" + ((outputFileName == null) ? "" : (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) ? "" : ("Output written to:\n" + outputFileName))), null); if (ocsswInfo.getOcsswLocation()!= null && programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) && ocsswInfo.getOcsswLocation().equals(OCSSWInfo.OCSSW_LOCATION_LOCAL)) { ocssw.updateOCSSWRootProperty(processorModel.getParamValue("--install_dir")); if (!ocssw.isOCSSWExist()) { enableProcessors(); } } ProcessorModel secondaryProcessor = processorModel.getSecondaryProcessor(); if (secondaryProcessor != null) { ocssw.setIfileName(secondaryProcessor.getParamValue(secondaryProcessor.getPrimaryInputFileOptionName())); int exitCode = ocssw.execute(secondaryProcessor.getParamList()).exitValue(); if (exitCode == 0) { Dialogs.showInformation(secondaryProcessor.getProgramName(), secondaryProcessor.getProgramName() + " done!\n", null); } } //delete the directories that temporaraly holds install_ocssw, maifest_ocssw and etc if(TMP_OCSSW_INSTALLER_DIR.exists()){ FileUtils.deleteDirectory(TMP_OCSSW_INSTALLER_DIR); // TMP_OCSSW_INSTALLER_DIR.delete(); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { displayMessage(programName, "execution exception: " + e.getMessage() + "\n" + processorModel.getExecutionLogMessage()); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }; swingWorker.execute(); } void displayOutput(ProcessorModel processorModel) throws Exception { String ofileName = processorModel.getOfileName(); if (openOutputInApp) { File ifileDir = processorModel.getIFileDir(); StringTokenizer st = new StringTokenizer(ofileName); while (st.hasMoreTokens()) { File ofile = SeadasFileUtils.createFile(ocssw.getOfileDir(), st.nextToken()); getAppContext().getProductManager().addProduct(ProductIO.readProduct(ofile)); } } } private void enableProcessors() { // CommandManager commandManager = getAppContext().getApplicationPage().getCommandManager(); // String namesToExclude = ProcessorTypeInfo.getExcludedProcessorNames(); // for (String processorName : ProcessorTypeInfo.getProcessorNames()) { // if (!namesToExclude.contains(processorName)) { // if (commandManager.getCommand(processorName) != null) { // commandManager.getCommand(processorName).setEnabled(true); // } // } // } // commandManager.getCommand("install_ocssw").setText("Update Data Processors"); } private void displayMessage(String programName, String message) { ScrolledPane messagePane = new ScrolledPane(programName, message, this.getAppContext().getApplicationWindow()); messagePane.setVisible(true); } public String getProgramName() { return programName; } public void setProgramName(String programName) { this.programName = programName; } public String getDialogTitle() { return dialogTitle; } public void setDialogTitle(String dialogTitle) { this.dialogTitle = dialogTitle; } public void setXmlFileName(String xmlFileName) { this.xmlFileName = xmlFileName; } /** * Handler that tries to extract progress from stdout of ocssw processor */ public static class ProgressHandler implements ProcessObserver.Handler { protected boolean stdoutOn; protected String programName; protected Pattern progressPattern; private double percentWorkedInProgressMonitor = 0; private int totalSteps = -1; private boolean debug = false; private int NULL_MATCH_VALUE = -9999; public ProgressHandler(String programName, Pattern progressPattern) { this.programName = programName; this.progressPattern = progressPattern; } private void handleLineRead(String line, Process process, com.bc.ceres.core.ProgressMonitor progressMonitor) { Matcher matcher = progressPattern.matcher(line); if (matcher != null && matcher.find()) { int stepCurrentLine = NULL_MATCH_VALUE; int totalStepsCurrentLine = NULL_MATCH_VALUE; debugPrint("line=" + line); debugPrint("pattern=" + progressPattern.toString()); try { stepCurrentLine = Integer.parseInt(matcher.group(1)); totalStepsCurrentLine = Integer.parseInt(matcher.group(2)); } catch (Exception e) { debugPrint("Exception thrown on following line:"); } if (stepCurrentLine != NULL_MATCH_VALUE && totalStepsCurrentLine != NULL_MATCH_VALUE) { debugPrint("stepCurrentLine=" + stepCurrentLine); debugPrint("totalStepsCurrentLine=" + totalStepsCurrentLine); // set only once if (totalSteps < 0) { totalSteps = totalStepsCurrentLine; debugPrint("totalSteps=" + totalSteps); if (totalSteps < 1) { // can't allow illegal value which would cause math errors totalSteps = 1; debugPrint("Resetting - totalSteps=" + totalSteps); } } // only proceed with incrementing if totalSteps matches if (totalStepsCurrentLine == totalSteps) { double percentWorkedCurrentLine = 100 * (stepCurrentLine - 1) / totalSteps; debugPrint("percentWorkedCurrentLine=" + percentWorkedCurrentLine); if (percentWorkedCurrentLine > percentWorkedInProgressMonitor) { int newWork = (int) Math.round(percentWorkedCurrentLine - percentWorkedInProgressMonitor); if (newWork > 0) { // don't allow progress to fill up to 100, hold it at 99% if ((percentWorkedInProgressMonitor + newWork) <= 99) { debugPrint("percentWorkedInProgressMonitor=" + percentWorkedInProgressMonitor); debugPrint("Adding to progress monitor newWork=" + newWork); progressMonitor.worked(newWork); percentWorkedInProgressMonitor += newWork; } } } } } } progressMonitor.setTaskName(programName); progressMonitor.setSubTaskName(line); } private void debugPrint(String msg) { if (debug) { System.out.println(msg); } } @Override public void handleLineOnStdoutRead(String line, Process process, com.bc.ceres.core.ProgressMonitor progressMonitor) { stdoutOn = true; handleLineRead(line, process, progressMonitor); } @Override public void handleLineOnStderrRead(String line, Process process, com.bc.ceres.core.ProgressMonitor progressMonitor) { if (!stdoutOn) { handleLineRead(line, process, progressMonitor); } } } public static class ConsoleHandler implements ProcessObserver.Handler { String programName; private String executionErrorLog = ""; public ConsoleHandler(String programName) { this.programName = programName; } @Override public void handleLineOnStdoutRead(String line, Process process, com.bc.ceres.core.ProgressMonitor progressMonitor) { Logger.getLogger(programName).info(programName + ": " + line); executionErrorLog = executionErrorLog + line + "\n"; } @Override public void handleLineOnStderrRead(String line, Process process, com.bc.ceres.core.ProgressMonitor progressMonitor) { Logger.getLogger(programName).info(programName + " stderr: " + line); executionErrorLog = executionErrorLog + line + "\n"; } public String getExecutionErrorLog() { return executionErrorLog; } } private static class TerminationHandler implements ProcessObserver.Handler { @Override public void handleLineOnStdoutRead(String line, Process process, com.bc.ceres.core.ProgressMonitor progressMonitor) { if (progressMonitor.isCanceled()) { process.destroy(); } } @Override public void handleLineOnStderrRead(String line, Process process, com.bc.ceres.core.ProgressMonitor progressMonitor) { if (progressMonitor.isCanceled()) { process.destroy(); } } } // todo This entire block of code is needed now since ProgressHandler is being called. This block cab be deleted sometime in future after testing // /** // * Handler that tries to extract progress from stderr of ocssw_installer // */ // public static class InstallerHandler extends ProgressHandler { // // public InstallerHandler(String programName, Pattern progressPattern) { // super(programName, progressPattern); // } // // // public void handleLineRead(String line, Process process, com.bc.ceres.core.ProgressMonitor progressMonitor) { // // Matcher matcher = progressPattern.matcher(line); // if (matcher.find()) { // int currentWork = Integer.parseInt(matcher.group(1)); // int totalWork = Integer.parseInt(matcher.group(2))+1; // note: buffer added so as not to fill // if (!progressSeen) { // progressSeen = true; // progressMonitor.beginTask(programName, totalWork); // // } // // // System.out.println("WORK of TOTAL=" + currentWork + "of " + totalWork); // // // Note: if statement used to prevent progress monitor from filling // // up here so that the GUI doesn't close too early. // // The progress monitor will be specifically closed when finished. // if (currentWork < totalWork) { // progressMonitor.worked(1); // } // // currentText = line; // } // // progressMonitor.setTaskName(programName); // progressMonitor.setSubTaskName(line); // } // // // @Override // public void handleLineOnStdoutRead(String line, Process process, com.bc.ceres.core.ProgressMonitor progressMonitor) { // stdoutOn = true; // // handleLineRead(line, process, progressMonitor); // } // // // // @Override // public void handleLineOnStderrRead(String line, Process process, com.bc.ceres.core.ProgressMonitor progressMonitor) { // if (!super.stdoutOn) { // handleLineRead(line, process, progressMonitor); // } // } // } @Override public JMenuItem getMenuPresenter() { JMenuItem menuItem = new JMenuItem(this); menuItem.setIcon(null); menuItem.setName((String) getValue(Action.NAME)); menuItem.setToolTipText((String) getValue(Action.SHORT_DESCRIPTION)); return menuItem; } }
25,175
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SeadasProcess.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/SeadasProcess.java
package gov.nasa.gsfc.seadas.processing.common; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo; import javax.ws.rs.client.WebTarget; import java.io.InputStream; import java.io.OutputStream; /** * Created by aabduraz on 6/11/15. */ public class SeadasProcess extends Process { int exitValue = 1; private InputStream inputStream; private InputStream errorStream; private OutputStream outputStream; int waitFor; OCSSWInfo ocsswInfo; WebTarget target; String jobId; public SeadasProcess(OCSSWInfo ocsswInfo, String jobId){ super(); this.ocsswInfo = ocsswInfo; this.jobId = jobId; } public void destroy(){ } public int exitValue(){ return exitValue; } public void setExitValue(int exitValue){ this.exitValue = exitValue; } @Override public InputStream getErrorStream(){ return null; } @Override public InputStream getInputStream() { return null; } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } public void setErrorStream(InputStream errorStream) { this.errorStream = errorStream; } @Override public OutputStream getOutputStream() { return outputStream; } public void setOutputStream(OutputStream outputStream) { this.outputStream = outputStream; } @Override public int waitFor(){ return waitFor; } }
1,492
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OutputFileSelector.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/OutputFileSelector.java
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.swing.binding.BindingContext; import javax.swing.*; 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 org.esa.snap.core.dataio.ProductIOPlugInManager; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.FileChooserFactory; /** * Created by IntelliJ IDEA. * * @author: Aynur Abdurazik Date: 3/30/12 Time: 11:12 AM */ public class OutputFileSelector { private JLabel outputFileNameLabel; private JTextField outputFileNameTextField; private JLabel outputFileDirLabel; private JTextField outputFileDirTextField; private JButton outputFileDirChooserButton; private JCheckBox openInAppCheckBox; private OutputFileSelectorModel model; private AppContext appContext; private String outFrameLabel; public OutputFileSelector(SnapApp app, String outputFrameLabel) { this(app, outputFrameLabel, new OutputFileSelectorModel()); } public OutputFileSelector(SnapApp app, String outputFrameLabel, OutputFileSelectorModel model) { this.model = model; appContext = (AppContext) app; this.outFrameLabel = outputFrameLabel; initComponents(); bindComponents(); updateUIState(); } private void initComponents() { outputFileNameLabel = new JLabel("Name: "); outputFileNameLabel.setPreferredSize(outputFileNameLabel.getPreferredSize()); outputFileNameLabel.setMinimumSize(outputFileNameLabel.getPreferredSize()); outputFileNameLabel.setMaximumSize(outputFileNameLabel.getPreferredSize()); outputFileNameTextField = new JTextField("123456789 123456789 12345"); outputFileNameTextField.setPreferredSize(outputFileNameTextField.getPreferredSize()); outputFileNameTextField.setMaximumSize(outputFileNameTextField.getPreferredSize()); outputFileNameTextField.setMinimumSize(outputFileNameTextField.getPreferredSize()); outputFileNameTextField.setText(""); outputFileDirLabel = new JLabel("Directory:"); outputFileDirLabel.setPreferredSize(outputFileDirLabel.getPreferredSize()); outputFileDirLabel.setMinimumSize(outputFileDirLabel.getPreferredSize()); outputFileDirLabel.setMaximumSize(outputFileDirLabel.getPreferredSize()); outputFileDirTextField = new JTextField("123456789 123456789 12345"); outputFileDirTextField.setPreferredSize(outputFileDirTextField.getPreferredSize()); outputFileDirTextField.setMinimumSize(outputFileDirTextField.getPreferredSize()); outputFileDirTextField.setMaximumSize(outputFileDirTextField.getPreferredSize()); outputFileDirTextField.setText(""); outputFileDirChooserButton = new JButton(new ProductDirChooserAction()); outputFileDirChooserButton.setMargin(new Insets(0, -7, 0, -7)); final Dimension size = new Dimension(outputFileDirChooserButton.getPreferredSize().width, outputFileDirTextField.getPreferredSize().height); outputFileDirChooserButton.setPreferredSize(size); outputFileDirChooserButton.setMinimumSize(size); outputFileDirChooserButton.setMaximumSize(size); openInAppCheckBox = new JCheckBox("Open in " + appContext.getApplicationName()); } private void bindComponents() { final BindingContext bc = new BindingContext(model.getValueContainer()); bc.bind("productName", outputFileNameTextField); bc.bind("openInAppSelected", openInAppCheckBox); bc.bind("productDir", outputFileDirTextField); model.getValueContainer().addPropertyChangeListener("productDir", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { outputFileDirTextField.setToolTipText(model.getProductDir().getPath()); } }); } public OutputFileSelectorModel getModel() { return model; } public JLabel getOutputFileNameLabel() { return outputFileNameLabel; } public JTextField getOutputFileNameTextField() { return outputFileNameTextField; } public JTextField getOutputFileNameTextField(int length) { outputFileNameTextField.setColumns(length); return outputFileNameTextField; } public JLabel getOutputFileDirLabel() { return outputFileDirLabel; } public JTextField getOutputFileDirTextField() { return outputFileDirTextField; } public JButton getOutputFileDirChooserButton() { return outputFileDirChooserButton; } public JCheckBox getOpenInAppCheckBox() { return openInAppCheckBox; } public void setOutputFileNameLabel(JLabel jLabel) { this.outputFileNameLabel = jLabel; } public void setOutputFileDirLabel(JLabel jLabel) { this.outputFileDirLabel = jLabel; } public JPanel createDefaultPanel() { final JPanel mainPanel = new JPanel(new GridBagLayout()); mainPanel.add(getOutputFileNameLabel(), new GridBagConstraintsCustom(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2)); mainPanel.add(getOutputFileNameTextField(), new GridBagConstraintsCustom(1, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 2)); mainPanel.add(getOutputFileDirLabel(), new GridBagConstraintsCustom(2, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2)); mainPanel.add(getOutputFileDirTextField(), new GridBagConstraintsCustom(3, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 2)); mainPanel.add(getOutputFileDirChooserButton(), new GridBagConstraintsCustom(4, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2)); return mainPanel; } private void updateUIState() { if (model.isSaveToFileSelected()) { openInAppCheckBox.setEnabled(canReadOutputFormat(model.getFormatName())); outputFileDirLabel.setEnabled(true); outputFileDirTextField.setEnabled(true); outputFileDirChooserButton.setEnabled(true); } else { openInAppCheckBox.setEnabled(false); outputFileDirTextField.setEnabled(false); outputFileDirTextField.setEnabled(false); outputFileDirChooserButton.setEnabled(false); } } public void setEnabled(boolean enabled) { outputFileNameLabel.setEnabled(enabled); outputFileNameTextField.setEnabled(enabled); outputFileDirLabel.setEnabled(enabled); outputFileDirTextField.setEnabled(enabled); outputFileDirChooserButton.setEnabled(enabled); openInAppCheckBox.setEnabled(enabled); } private static boolean canReadOutputFormat(String formatName) { return ProductIOPlugInManager.getInstance().getReaderPlugIns(formatName).hasNext(); } private class UIStateUpdater implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (!canReadOutputFormat(model.getFormatName())) { model.setOpenInAppSelected(false); } updateUIState(); } } private class ProductDirChooserAction extends AbstractAction { private static final String APPROVE_BUTTON_TEXT = "Select"; public ProductDirChooserAction() { super("..."); } @Override public void actionPerformed(ActionEvent event) { Window windowAncestor = null; if (event.getSource() instanceof JComponent) { JButton button = (JButton) event.getSource(); if (button != null) { windowAncestor = SwingUtilities.getWindowAncestor(button); } } final JFileChooser chooser = FileChooserFactory.getInstance().createDirChooser(model.getProductDir()); chooser.setDialogTitle("Select Output File Directory"); if (chooser.showDialog(windowAncestor, APPROVE_BUTTON_TEXT) == JFileChooser.APPROVE_OPTION) { final File selectedDir = chooser.getSelectedFile(); if (selectedDir != null) { if (selectedDir.canWrite()) { model.setProductDir(selectedDir); } else { JOptionPane.showMessageDialog(chooser, "Directory " + selectedDir.toString() + "has no write permission", "Error", JOptionPane.ERROR_MESSAGE); chooser.requestFocus(); } } else { model.setProductDir(new File(".")); } } } } }
9,068
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSWInstallerForm.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/OCSSWInstallerForm.java
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.swing.TableLayout; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo; import gov.nasa.gsfc.seadas.processing.core.ParamUtils; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import org.esa.snap.ui.AppContext; import javax.swing.*; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.*; import java.util.*; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo.OCSSW_SRC_DIR_NAME; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 3/13/13 * Time: 11:11 AM * To change this template use File | Settings | File Templates. */ public abstract class OCSSWInstallerForm extends JPanel implements CloProgramUI { //private FileSelector ocsswDirSelector; JTextField fileTextField; //private SwingPropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this); ProcessorModel processorModel; private AppContext appContext; private JPanel dirPanel; private JPanel tagPanel; private JPanel configPanel; private JPanel missionPanel; private JPanel otherPanel; //private JPanel superParamPanel; public static final String INSTALL_DIR_OPTION_NAME = "--install_dir"; public final static String VALID_TAGS_OPTION_NAME = "--tag"; public final static String CURRENT_TAG_OPTION_NAME = "--current_tag"; public String missionDataDir; public OCSSW ocssw; private static final Set<String> MISSIONS = new HashSet<String>(Arrays.asList( new String[]{"AVHRR", "CZCS", "GOCI", "HAWKEYE", "HICO", "MERIS", "MSIS2A", "MSIS2B", "OCI", "MODISA", "MODIST", "MOS", "OCM1", "OCM2", "OCRVC", "OCTS", "OLCIS3A", "OLCIS3B", "OLIL8", "OLIL9", "OSMI", "SGLI", "SEAWIFS", "VIIRSN", "VIIRSJ1", "VIIRSJ2"} )); private static final Set<String> DEFAULT_MISSIONS = new HashSet<String>(Arrays.asList( new String[]{ //"GOCI", //"HICO", "OCRVC" } )); ArrayList<String> validOCSSWTagList = new ArrayList<>(); String latestOCSSWTagForInstalledRelease; // a hard default which get replace by JSON value if internet connection HashMap<String, Boolean> missionDataStatus; SeadasToolboxVersion seadasToolboxVersion; public OCSSWInstallerForm(AppContext appContext, String programName, String xmlFileName, OCSSW ocssw) { this.appContext = appContext; this.ocssw = ocssw; seadasToolboxVersion = new SeadasToolboxVersion(); validOCSSWTagList = seadasToolboxVersion.getOCSSWTagListForInstalledRelease(); // getSeaDASVersionTags(); // set default // if (validOCSSWTagList != null && validOCSSWTagList.size() >= 1) { latestOCSSWTagForInstalledRelease = seadasToolboxVersion.getLatestOCSSWTagForInstalledRelease(); // } // for (String tag : validOCSSWTagList) { // System.out.println("tag=" + tag); // } processorModel = ProcessorModel.valueOf(programName, xmlFileName, ocssw); processorModel.setReadyToRun(true); setMissionDataDir(OCSSWInfo.getInstance().getOcsswDataDirPath()); init(); updateMissionValues(); createUserInterface(); processorModel.updateParamInfo(INSTALL_DIR_OPTION_NAME, getInstallDir()); processorModel.addPropertyChangeListener(INSTALL_DIR_OPTION_NAME, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { setMissionDataDir(processorModel.getParamValue(INSTALL_DIR_OPTION_NAME) + File.separator + OCSSWInfo.OCSSW_DATA_DIR_SUFFIX); updateMissionStatus(); updateMissionValues(); createUserInterface(); } }); } String getMissionDataDir() { return missionDataDir; } void setMissionDataDir(String currentMissionDataDir) { missionDataDir = currentMissionDataDir; } abstract void updateMissionStatus(); abstract void updateMissionValues(); String getInstallDir() { return OCSSWInfo.getInstance().getOcsswRoot(); } abstract void init(); public ProcessorModel getProcessorModel() { return processorModel; } public File getSelectedSourceProduct() { return null; } public boolean isOpenOutputInApp() { return false; } public String getParamString() { return processorModel.getParamList().getParamString(); } public void setParamString(String paramString) { processorModel.getParamList().setParamString(paramString); } protected void createUserInterface() { this.setLayout(new GridBagLayout()); JPanel paramPanel = new ParamUIFactory(processorModel).createParamPanel(); reorganizePanel(paramPanel); // add(dirPanel, // new GridBagConstraintsCustom(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3)); add(configPanel, new GridBagConstraintsCustom(0, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, 3)); add(missionPanel, new GridBagConstraintsCustom(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3)); add(otherPanel, new GridBagConstraintsCustom(0, 2, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3)); setMinimumSize(getPreferredSize()); setMaximumSize(getPreferredSize()); } public JPanel getParamPanel() { JPanel newPanel = new JPanel(new GridBagLayout()); newPanel.add(missionPanel, new GridBagConstraintsCustom(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3)); newPanel.add(otherPanel, new GridBagConstraintsCustom(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 2)); return newPanel; } //ToDo: missionDataDir test should be differentiated for local and remote servers protected void reorganizePanel(JPanel paramPanel) { String selectedOcsswTagString = (seadasToolboxVersion.getInstalledOCSSWTag() != null) ? seadasToolboxVersion.getInstalledOCSSWTag() : seadasToolboxVersion.getLatestOCSSWTagForInstalledRelease(); TableLayout dirPanelTableLayout = new TableLayout(1); dirPanelTableLayout.setTablePadding(0,0); dirPanelTableLayout.setTableAnchor(TableLayout.Anchor.WEST); dirPanel = new JPanel(); TableLayout tagPanelTableLayout = new TableLayout(2); tagPanelTableLayout.setTablePadding(0,0); tagPanelTableLayout.setTableAnchor(TableLayout.Anchor.WEST); tagPanel = new JPanel(tagPanelTableLayout); TableLayout configPanelTableLayout = new TableLayout(1); configPanelTableLayout.setTablePadding(5,10); configPanelTableLayout.setTableAnchor(TableLayout.Anchor.WEST); configPanel = new JPanel(configPanelTableLayout); configPanel.setBorder(BorderFactory.createTitledBorder("Configuration")); TableLayout missionTableLayout = new TableLayout(5); missionTableLayout.setTablePadding(35,10); // missionTableLayout.setTableAnchor(TableLayout.Anchor.WEST); missionPanel = new JPanel(missionTableLayout); missionPanel.setBorder(BorderFactory.createTitledBorder("Missions")); TableLayout otherTableLayout = new TableLayout(5); otherTableLayout.setTablePadding(35,10); // otherTableLayout.setTableAnchor(TableLayout.Anchor.WEST); otherPanel = new JPanel(otherTableLayout); otherPanel.setBorder(BorderFactory.createTitledBorder("Other")); OCSSWInfo ocsswInfo = OCSSWInfo.getInstance(); JScrollPane jsp = (JScrollPane) paramPanel.getComponent(0); JPanel panel = (JPanel) findJPanel(jsp, "param panel"); Component[] options = panel.getComponents(); String tmpString; for (Component option : options) { if (option.getName().equals("boolean field panel")) { Component[] bps = ((JPanel) option).getComponents(); for (Component c : bps) { tmpString = ParamUtils.removePreceedingDashes(c.getName()).toUpperCase(); if (MISSIONS.contains(tmpString)) { if (!DEFAULT_MISSIONS.contains(tmpString)) { if (ocssw.isMissionDirExist(tmpString) || missionDataStatus.get(tmpString)) { ((JPanel) c).getComponents()[0].setEnabled(false); } else { ((JPanel) c).getComponents()[0].setEnabled(true); } missionPanel.add(c); } } else { if (tmpString.equals("SRC")) { ((JLabel) ((JPanel) c).getComponent(0)).setText("Source Code"); if (new File(ocsswInfo.getOcsswRoot() + System.getProperty("file.separator") + OCSSW_SRC_DIR_NAME).exists()) { ((JPanel) c).getComponents()[0].setEnabled(false); } } else if (tmpString.equals("CLEAN")) { ((JLabel) ((JPanel) c).getComponent(0)).setText("Clean Install"); ((JPanel) c).getComponents()[0].setEnabled(true); } else if (tmpString.equals("VIIRSDEM")) { ((JLabel) ((JPanel) c).getComponent(0)).setText("VIIRS DEM files"); if (new File(ocsswInfo.getOcsswRoot() + System.getProperty("file.separator") + "share" + System.getProperty("file.separator") + "viirs" + System.getProperty("file.separator") + "dem").exists()) { ((JPanel) c).getComponents()[0].setEnabled(false); } } otherPanel.add(c); // otherPanel.add(new JLabel(" ")); } } } else if (option.getName().equals("file parameter panel")) { Component[] bps = ((JPanel) option).getComponents(); for (Component c : bps) { dirPanel = (JPanel) c; } if (!ocsswInfo.getOcsswLocation().equals(ocsswInfo.OCSSW_LOCATION_LOCAL)) { //if ocssw is not local, then disable the button to choose ocssw installation directory ((JLabel) dirPanel.getComponent(0)).setText("Remote install_dir: "); } else { ((JLabel) dirPanel.getComponent(0)).setText("Local install_dir: "); } ((JLabel) dirPanel.getComponent(0)).setToolTipText("This directory can be set in SeaDAS-Toolobox > Configure OCSSW Location"); ((JTextField) dirPanel.getComponent(1)).setEditable(false); ((JTextField) dirPanel.getComponent(1)).setFocusable(false); ((JTextField) dirPanel.getComponent(1)).setEnabled(false); ((JTextField) dirPanel.getComponent(1)).setBorder(null); ((JTextField) dirPanel.getComponent(1)).setDisabledTextColor(Color.BLUE); ((JTextField) dirPanel.getComponent(1)).setForeground(Color.BLUE); ((JTextField) dirPanel.getComponent(1)).setBackground(dirPanel.getBackground()); // ((JTextField) dirPanel.getComponent(1)).setBackground(new Color(250,250,250)); ((JTextField) dirPanel.getComponent(1)).setToolTipText("This directory can be set in SeaDAS-OCSSW > Configure OCSSW Location"); dirPanel.getComponent(2).setVisible(false); } else if (option.getName().equals("text field panel")) { Component[] bps = ((JPanel) option).getComponents(); JPanel tempPanel1, tempPanel2; for (Component c : bps) { if (c.getName().equals(VALID_TAGS_OPTION_NAME)) { tempPanel1 = (JPanel) c; if (SeadasToolboxVersion.isLatestSeadasToolboxVersion()) { if (latestOCSSWTagForInstalledRelease == null) { ((JLabel) tempPanel1.getComponent(0)).setText("OCSSW Tag:"); ((JLabel) tempPanel1.getComponent(0)).setForeground(Color.BLACK); } else if (latestOCSSWTagForInstalledRelease.equals(selectedOcsswTagString)) { ((JLabel) tempPanel1.getComponent(0)).setText("OCSSW Tag: (latest tag installed)"); ((JLabel) tempPanel1.getComponent(0)).setForeground(Color.BLACK); } else { ((JLabel) tempPanel1.getComponent(0)).setText("<html>OCSSW Tag: WARNING!! <br> latest tag is " + latestOCSSWTagForInstalledRelease + "</html>"); ((JLabel) tempPanel1.getComponent(0)).setForeground(Color.RED); } } else { if (latestOCSSWTagForInstalledRelease == null) { ((JLabel) tempPanel1.getComponent(0)).setText("<html>OCSSW Tag: <br>Newer version of SeaDAS Toolbox available</html>"); } else if (latestOCSSWTagForInstalledRelease.equals(selectedOcsswTagString)) { if (selectedOcsswTagString.equals(seadasToolboxVersion.getLatestOCSSWTagForLatestRelease())) { ((JLabel) tempPanel1.getComponent(0)).setText("<html>OCSSW Tag: <br>Newer version of SeaDAS Toolbox available</html>"); } else { ((JLabel) tempPanel1.getComponent(0)).setText("<html>OCSSW Tag: WARNING!! <br> Not the latest tag<br>Newer version of SeaDAS Toolbox available</html>"); } } else { if (selectedOcsswTagString.equals(seadasToolboxVersion.getLatestOCSSWTagForLatestRelease())) { ((JLabel) tempPanel1.getComponent(0)).setText("<html>OCSSW Tag: WARNING!! <br> May not be applicable tag to installed version<br>Newer version of SeaDAS Toolbox available</html>"); } else { ((JLabel) tempPanel1.getComponent(0)).setText("<html>OCSSW Tag: WARNING!! <br> May not be latest/applicable tag<br>Newer version of SeaDAS Toolbox available</html>"); } } ((JLabel) tempPanel1.getComponent(0)).setForeground(Color.RED); } JComboBox tags = ((JComboBox) tempPanel1.getComponent(1)); tags.setMaximumRowCount(15); JLabel tmp = new JLabel("12345678901234567890"); tags.setMinimumSize(tmp.getPreferredSize()); //This segment of code is to disable tags that are not compatible with the current SeaDAS version ArrayList<String> validOcsswTags = ocssw.getOcsswTagsValid4CurrentSeaDAS(); Font f1 = tags.getFont(); Font f2 = new Font("Tahoma", 0, 14); if (selectedOcsswTagString != null) { tags.setSelectedItem(selectedOcsswTagString); } tags.setToolTipText("Latest tag for this release is " + selectedOcsswTagString); tags.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value instanceof JComponent) return (JComponent) value; boolean itemEnabled = validOCSSWTagList.contains((String) value); super.getListCellRendererComponent(list, value, index, isSelected && itemEnabled, cellHasFocus); if (itemEnabled) { if (selectedOcsswTagString.equals(value.toString().trim())) { list.setToolTipText(value.toString() + " is latest operational tag for this release"); } else { list.setToolTipText(value.toString() + " is NOT the latest operational tag for this release"); } if (isSelected) { setBackground(Color.blue); setForeground(Color.white); } else { setBackground(Color.white); setForeground(Color.black); } } else { if (value.toString().toUpperCase().startsWith("V")) { list.setToolTipText(value.toString() + " is NOT an optimum operational tag for this release"); } else { list.setToolTipText(value.toString() + " is NOT an operational tag"); } if (isSelected) { setBackground(Color.darkGray); setForeground(Color.white); } else { setBackground(Color.white); setForeground(Color.gray); } } return this; } }); // code segment ends here tagPanel.add(tempPanel1); ; } else if (c.getName().contains(CURRENT_TAG_OPTION_NAME)) { //|| CURRENT_TAG_OPTION_NAME.contains(c.getName())) { tempPanel2 = (JPanel) c; ((JLabel) tempPanel2.getComponent(0)).setText("Last Installed OCSSW Tag:"); tagPanel.add(tempPanel2); } } } } configPanel.add(tagPanel); configPanel.add(dirPanel); } private Component findJPanel(Component comp, String panelName) { if (comp.getClass() == JPanel.class) return comp; if (comp instanceof Container) { Component[] components = ((Container) comp).getComponents(); for (int i = 0; i < components.length; i++) { Component child = findJPanel(components[i], components[i].getName()); if (child != null) { return child; } } } return null; } }
20,416
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SMItoPPMUI.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/SMItoPPMUI.java
package gov.nasa.gsfc.seadas.processing.common; import gov.nasa.gsfc.seadas.processing.core.ParamInfo; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import org.esa.snap.rcp.SnapApp; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 6/7/12 * Time: 9:30 AM * To change this template use File | Settings | File Templates. */ public class SMItoPPMUI { private JCheckBox smitoppmCheckBox; private FileSelector ppmFile; private ProcessorModel processorModel; public SMItoPPMUI(ProcessorModel pm) { processorModel = pm; } public JPanel getSMItoPPMPanel() { return createSmiToPpmPanel(); } private JPanel createSmiToPpmPanel() { final JPanel smitoppmPanel = new JPanel(); smitoppmPanel.setLayout(new FlowLayout()); final String smitoppmLabelName = "smitoppm"; JLabel smitoppmLabel = new JLabel(smitoppmLabelName); smitoppmCheckBox = new JCheckBox(); smitoppmCheckBox.setSelected(false); ppmFile = new FileSelector(SnapApp.getDefault().getAppContext(), ParamInfo.Type.OFILE, "ppm file"); ppmFile.getFileTextField().setColumns(20); ppmFile.addPropertyChangeListener(ppmFile.getPropertyName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (ppmFile.getFileName().trim().length() != 0) { processorModel.setReadyToRun(processorModel.getParamValue(processorModel.getPrimaryOutputFileOptionName()).trim().length() > 0); } else { processorModel.setReadyToRun(false); } } }); processorModel.addPropertyChangeListener(processorModel.getPrimaryInputFileOptionName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (smitoppmCheckBox.isSelected()) { ppmFile.setFilename(processorModel.getOcssw().getOfileName(processorModel.getParamValue(processorModel.getPrimaryOutputFileOptionName()), "smitoppm", null)); smitoppmPanel.add(ppmFile.getjPanel()); smitoppmPanel.validate(); smitoppmPanel.repaint(); } } }); processorModel.addPropertyChangeListener(processorModel.getPrimaryOutputFileOptionName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (smitoppmCheckBox.isSelected()) { ppmFile.setFilename(processorModel.getOcssw().getOfileName(processorModel.getParamValue(processorModel.getPrimaryOutputFileOptionName()), "smitoppm", null)); smitoppmPanel.add(ppmFile.getjPanel()); smitoppmPanel.validate(); smitoppmPanel.repaint(); } } }); smitoppmPanel.add(smitoppmLabel); smitoppmPanel.add(smitoppmCheckBox); smitoppmCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (smitoppmCheckBox.isSelected()) { ppmFile.setFilename(processorModel.getOcssw().getOfileName(processorModel.getParamValue(processorModel.getPrimaryOutputFileOptionName()), "smitoppm", null)); smitoppmPanel.add(ppmFile.getjPanel()); processorModel.setReadyToRun(processorModel.getParamValue(processorModel.getPrimaryOutputFileOptionName()).trim().length() > 0 && ppmFile.getFileName().trim().length() > 0); processorModel.createsmitoppmProcessorModel(ppmFile.getFileName()); smitoppmPanel.validate(); smitoppmPanel.repaint(); } else { smitoppmPanel.remove(ppmFile.getjPanel()); smitoppmPanel.validate(); smitoppmPanel.repaint(); processorModel.setReadyToRun(processorModel.getParamValue(processorModel.getPrimaryOutputFileOptionName()).trim().length() > 0); processorModel.setSecondaryProcessor(null); } } }); return smitoppmPanel; } }
4,632
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SeadasToolboxVersion.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/SeadasToolboxVersion.java
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.core.runtime.Version; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWConfigData; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfoGUI; import org.esa.snap.runtime.Config; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.openide.modules.ModuleInfo; import org.openide.modules.Modules; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.prefs.Preferences; import java.util.regex.Matcher; import java.util.regex.Pattern; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWConfigData.SEADAS_OCSSW_TAG_PROPERTY; // Purpose: returns installation info/status on SeaDAS Toolbox version and OCSSW tag version. public class SeadasToolboxVersion { static String SEADAS_TOOLBOX_VERSION_URL = "https://seadas.gsfc.nasa.gov/downloads/SEADAS_TOOLBOX_VERSION.txt"; public static enum SeadasToolboxRelease { INSTALLED_RELEASE, LATEST_RELEASE } ArrayList<String> OCSSWTagList; public static boolean isLatestSeadasToolboxVersion() { final Version remoteVersion = getSeadasToolboxLatestVersion(); final Version localVersion = getSeadasToolboxInstalledVersion(); // System.out.println("remoteVersion=" + remoteVersion); // System.out.println("localVersion=" + localVersion); if (remoteVersion != null && localVersion != null) { return localVersion.compareTo(remoteVersion) >= 0; } else { return true; } } public static Version getSeadasToolboxInstalledVersion() { ModuleInfo seadasProcessingModuleInfo = Modules.getDefault().ownerOf(OCSSWInfoGUI.class); String seadasToolboxVersion = String.valueOf(seadasProcessingModuleInfo.getSpecificationVersion()); return Version.parseVersion(seadasToolboxVersion.toUpperCase()); } public String getSeadasToolboxInstalledVersionString() { return String.valueOf(getSeadasToolboxInstalledVersion()); } public static Version getSeadasToolboxLatestVersion() { try { String seadasToolBoxVerionUrlString = SEADAS_TOOLBOX_VERSION_URL; return readVersionFromStream(new URL(seadasToolBoxVerionUrlString).openStream()); } catch (IOException e) { e.printStackTrace(); return null; } } public String getSeadasToolboxLatestVersionString() { return String.valueOf(getSeadasToolboxLatestVersion()); } private static Version readVersionFromStream(InputStream inputStream) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { String line; line = reader.readLine(); if (line != null) { return Version.parseVersion(line.toUpperCase()); } } return null; } public ArrayList<String> getOCSSWTagListForInstalledRelease() { getOCSSWTagList(SeadasToolboxRelease.INSTALLED_RELEASE); return OCSSWTagList; } public String getLatestOCSSWTagForInstalledRelease() { getOCSSWTagList(SeadasToolboxRelease.INSTALLED_RELEASE); if (OCSSWTagList != null && OCSSWTagList.size() > 0) { String latestTag = OCSSWTagList.get(0); for (String tag: OCSSWTagList) { if (compareOcsswTags(latestTag, tag)) { latestTag = tag; } } return latestTag; } else { return OCSSWConfigData.SEADAS_OCSSW_TAG_DEFAULT_VALUE; } } public boolean compareOcsswTags(String latestTag, String tag) { boolean latestTagValid = false; boolean tagValid = false; boolean tagIsNewer = false; String vTagPatternString = "^V\\d\\d\\d\\d.\\d+$"; Pattern vTagPattern = Pattern.compile(vTagPatternString); int latestTagPrefixValue = -1; int tagPrefixValue = -1; int latestTagSuffixValue = -1; int tagSuffixValue = -1; if (latestTag != null) { Matcher vMatcher = vTagPattern.matcher(latestTag); if (vMatcher != null && vMatcher.find()) { String latestTagPrefix = latestTag.substring(1,5); String latestTagSuffix = latestTag.substring(6); try { latestTagPrefixValue = Integer.valueOf(latestTagPrefix); latestTagSuffixValue = Integer.valueOf(latestTagSuffix); latestTagValid = true; } catch(Exception e) { } } } if (tag != null) { Matcher vMatcher = vTagPattern.matcher(tag); if (vMatcher != null && vMatcher.find()) { String tagPrefix = tag.substring(1,5); String tagSuffix = tag.substring(6); try { tagPrefixValue = Integer.valueOf(tagPrefix); tagSuffixValue = Integer.valueOf(tagSuffix); tagValid = true; } catch(Exception e) { } } } if (latestTagValid && tagValid) { if (tagPrefixValue > latestTagPrefixValue) { tagIsNewer = true; } else if (tagPrefixValue == latestTagPrefixValue) { if (tagSuffixValue > latestTagSuffixValue) { tagIsNewer = true; } else { tagIsNewer = false; } } else { tagIsNewer = false; } } else if (tagValid) { tagIsNewer = true; } else { tagIsNewer = false; } return tagIsNewer; } public ArrayList<String> getOCSSWTagListForLatestRelease() { getOCSSWTagList(SeadasToolboxRelease.LATEST_RELEASE); return OCSSWTagList; } public String getLatestOCSSWTagForLatestRelease() { getOCSSWTagList(SeadasToolboxRelease.LATEST_RELEASE); if (OCSSWTagList != null && OCSSWTagList.size() > 0) { return OCSSWTagList.get(0); } else { return null; } } private ArrayList<String> getOCSSWTagList(SeadasToolboxRelease id) { OCSSWTagList = new ArrayList<>(); 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, id)); in.close(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return OCSSWTagList; } private void parseValidSeaDASTagObject(JSONObject tagObject, SeadasToolboxRelease id) { String seadasToolboxVersion; if (id == SeadasToolboxRelease.LATEST_RELEASE) { seadasToolboxVersion = getSeadasToolboxLatestVersionString(); } else { seadasToolboxVersion = getSeadasToolboxInstalledVersionString(); } String seadasToolboxVersionJson = (String) tagObject.get("seadas"); if (seadasToolboxVersionJson.equals(seadasToolboxVersion)) { //Get corresponding ocssw tags for seadas JSONArray ocsswTags = (JSONArray) tagObject.get("ocssw"); if (ocsswTags != null) { for (int i = 0; i < ocsswTags.size(); i++) { try { OCSSWTagList.add((String) ocsswTags.get(i)); } catch (Exception e) { e.printStackTrace(); } } } } } // todo this could be retrieved instead by an ocssw call public String getInstalledOCSSWTag() { return getInstalledOCSSWTagGUI(); } public String getInstalledOCSSWTagGUI() { final Preferences preferences = Config.instance("seadas").load().preferences(); return preferences.get(SEADAS_OCSSW_TAG_PROPERTY, null); } }
8,852
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OutputFileSelectorModel.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/OutputFileSelectorModel.java
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.binding.*; import com.bc.ceres.binding.validators.NotNullValidator; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.text.MessageFormat; import java.util.Arrays; import org.esa.snap.core.dataio.ProductIO; import org.esa.snap.core.dataio.ProductIOPlugInManager; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.core.util.StringUtils; import org.esa.snap.core.util.io.FileUtils; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik * Date: 3/30/12 * Time: 12:56 PM * To change this template use File | Settings | File Templates. */ public class OutputFileSelectorModel { private static final String ENVISAT_FORMAT_NAME = "ENVISAT"; // used by object binding private String productName; private boolean saveToFileSelected; private boolean openInAppSelected; private File productDir; private String formatName; private String[] formatNames; private final PropertyContainer propertyContainer; public OutputFileSelectorModel() { this(ProductIOPlugInManager.getInstance().getAllProductWriterFormatStrings()); } public OutputFileSelectorModel(String[] formatNames) { propertyContainer = PropertyContainer.createObjectBacked(this); propertyContainer.addPropertyChangeListener("saveToFileSelected", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (!(Boolean) evt.getNewValue()) { setOpenInAppSelected(true); } } }); propertyContainer.addPropertyChangeListener("openInAppSelected", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (!(Boolean) evt.getNewValue()) { setSaveToFileSelected(true); } } }); PropertyDescriptor productNameDescriptor = propertyContainer.getDescriptor("productName"); productNameDescriptor.setValidator(new ProductNameValidator()); productNameDescriptor.setDisplayName("target product name"); PropertyDescriptor productDirDescriptor = propertyContainer.getDescriptor("productDir"); productDirDescriptor.setValidator(new NotNullValidator()); productDirDescriptor.setDisplayName("target product directory"); setOpenInAppSelected(true); setSaveToFileSelected(true); this.formatNames = formatNames; if (StringUtils.contains(this.formatNames, ProductIO.DEFAULT_FORMAT_NAME)) { setFormatName(ProductIO.DEFAULT_FORMAT_NAME); } else { setFormatName(formatNames[0]); } } // public static OutputFileSelectorModel createEnvisatTargetProductSelectorModel() { // return new EnvisatTargetProductSelectorModel(); // } public String getProductName() { return productName; } public boolean isSaveToFileSelected() { return saveToFileSelected; } public boolean isOpenInAppSelected() { return openInAppSelected; } public File getProductDir() { return productDir; } public File getProductFile() { if (productName == null) { return null; } return new File(productDir, productName); } String getProductFileName() { String productFileName = productName; // Iterator<ProductWriterPlugIn> iterator = ProductIOPlugInManager.getInstance().getWriterPlugIns(formatName); // if (iterator.hasNext()) { // final ProductWriterPlugIn writerPlugIn = iterator.next(); // // boolean ok = false; // for (String extension : writerPlugIn.getDefaultFileExtensions()) { // if (productFileName.endsWith(extension)) { // ok = true; // break; // } // } // if (!ok) { // productFileName = productFileName.concat(writerPlugIn.getDefaultFileExtensions()[0]); // } // } return productFileName; } public String getFormatName() { return formatName; } public String[] getFormatNames() { return formatNames; } public void setProductName(String productName) { setValueContainerValue("productName", productName); } public void setSaveToFileSelected(boolean saveToFileSelected) { setValueContainerValue("saveToFileSelected", saveToFileSelected); } public void setOpenInAppSelected(boolean openInAppSelected) { setValueContainerValue("openInAppSelected", openInAppSelected); } public void setProductDir(File productDir) { setValueContainerValue("productDir", productDir); } public void setFormatName(String formatName) { setValueContainerValue("formatName", formatName); } public PropertyContainer getValueContainer() { return propertyContainer; } private void setValueContainerValue(String name, Object value) { propertyContainer.setValue(name, value); } private static class ProductNameValidator implements Validator { @Override public void validateValue(Property property, Object value) throws ValidationException { final String name = (String) value; if (!ProductNode.isValidNodeName(name)) { final String message = MessageFormat.format("The product name ''{0}'' is not valid.\n\n" + "Names must not start with a dot and must not\n" + "contain any of the following characters: \\/:*?\"<>|", name); throw new ValidationException(message); } } } public static class SeadasTargetProductSelectorModel extends OutputFileSelectorModel { private SeadasTargetProductSelectorModel() { super(createFormats()); } @Override public File getProductFile() { if (!ENVISAT_FORMAT_NAME.equals(getFormatName())) { return super.getProductFile(); } final String productName = getProductName(); return new File(getProductDir(), FileUtils.ensureExtension(productName, ".N1")); } private static String[] createFormats() { final String[] productWriterFormatStrings = ProductIOPlugInManager.getInstance().getAllProductWriterFormatStrings(); final String[] formatNames = Arrays.copyOf(productWriterFormatStrings, productWriterFormatStrings.length + 1); formatNames[formatNames.length - 1] = ENVISAT_FORMAT_NAME; return formatNames; } } }
6,997
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SeadasProcessorInfo.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/SeadasProcessorInfo.java
package gov.nasa.gsfc.seadas.processing.common; /** * Created by IntelliJ IDEA. * User: knowles * Date: 6/8/12 * Time: 11:00 AM * To change this template use File | Settings | File Templates. */ public class SeadasProcessorInfo { public static enum Id { L1AEXTRACT_MODIS, L1AEXTRACT_SEAWIFS, L1AEXTRACT, L1AGEN, GEOGEN, L1BGEN, // L1MAPGEN, L1BRSGEN, L2EXTRACT, L2GEN, L2MERGE, L3BINMERGE, GEOREGION_GEN, // L2GEN_AQUARIUS, // L2MAPGEN, L2BRSGEN, L2BIN, L3BIN, L3GEN // SMIGEN } private Id id; private FileInfo fileInfo; private String executable; private boolean validIfile = false; public SeadasProcessorInfo(Id id) { this.id = id; } public SeadasProcessorInfo(Id id, FileInfo fileInfo) { this.id = id; this.fileInfo = fileInfo; setExecutable(); setValidIfile(); } public void setFileInfo(FileInfo fileInfo) { this.fileInfo = fileInfo; setExecutable(); setValidIfile(); } private void setExecutable() { executable = getExecutable(fileInfo, id); } static public String getExecutable(FileInfo iFileInfo, SeadasProcessorInfo.Id processorId) { if (processorId == null || iFileInfo == null) { return null; } if (iFileInfo.isSupportedMission()) { switch (processorId) { case L1AEXTRACT: if (iFileInfo.isMissionId(MissionInfo.Id.MODISA) || iFileInfo.isMissionId(MissionInfo.Id.MODIST)) { return "l1aextract_modis"; } else if (iFileInfo.isMissionId(MissionInfo.Id.SEAWIFS)) { return "l1aextract_seawifs"; } else { return "l2extract"; } case L1AGEN: if (iFileInfo.isMissionId(MissionInfo.Id.MODISA) || iFileInfo.isMissionId(MissionInfo.Id.MODIST)) { return "modis_L1A"; } else if (iFileInfo.isMissionId(MissionInfo.Id.SEAWIFS)) { return "l1aextract_seawifs"; } else { return "modis_L1A"; } case GEOGEN: if (iFileInfo.isGeofileRequired()) { return "modis_GEO"; } else { return null; } case L1BGEN: if (iFileInfo.isMissionId(MissionInfo.Id.MODISA) || iFileInfo.isMissionId(MissionInfo.Id.MODIST)) { return "modis_L1B"; } else { return "l1bgen_generic"; } // case L1MAPGEN: // return "l1mapgen"; case L1BRSGEN: return "l1brsgen"; case L2EXTRACT: return "l2extract"; case L2MERGE: return "l2merge"; case L3BINMERGE: return "l3binmerge"; case GEOREGION_GEN: return "georegion_gen"; case L2GEN: return "l2gen"; // case L2GEN_AQUARIUS: // return "l2gen_aquarius"; // case L2MAPGEN: // return "l2mapgen"; case L2BRSGEN: return "l2brsgen"; case L2BIN: return "l2bin"; case L3BIN: return "l3bin"; case L3GEN: return "l3gen"; // case SMIGEN: // return "smigen"; default: return null; } } else { return null; } } static public boolean isSupportedMission(FileInfo iFileInfo, SeadasProcessorInfo.Id processorId) { if (processorId == null || iFileInfo == null) { return false; } switch (processorId) { case L1AEXTRACT_MODIS: return iFileInfo.isSupportedMission() && !iFileInfo.isMissionId(MissionInfo.Id.SEAWIFS); case L1AEXTRACT_SEAWIFS: return iFileInfo.isMissionId(MissionInfo.Id.SEAWIFS); case L1AEXTRACT: return iFileInfo.isSupportedMission(); case L1AGEN: return iFileInfo.isSupportedMission(); case GEOGEN: return iFileInfo.isSupportedMission() && iFileInfo.isGeofileRequired(); case L1BGEN: return iFileInfo.isSupportedMission(); // case L1MAPGEN: // return iFileInfo.isSupportedMission(); case L1BRSGEN: return iFileInfo.isSupportedMission(); case L2EXTRACT: return iFileInfo.isSupportedMission(); case L2MERGE: return true; case L3BINMERGE: return true; case GEOREGION_GEN: return true; case L2GEN: return iFileInfo.isSupportedMission(); // case L2GEN_AQUARIUS: // return iFileInfo.isSupportedMission(); // case L2MAPGEN: // return iFileInfo.isSupportedMission(); case L2BRSGEN: return iFileInfo.isSupportedMission(); case L2BIN: return iFileInfo.isSupportedMission(); case L3BIN: return iFileInfo.isSupportedMission(); case L3GEN: return iFileInfo.isSupportedMission(); // case SMIGEN: // return iFileInfo.isSupportedMission(); default: return false; } } static public boolean isValidFileType(FileInfo iFileInfo, SeadasProcessorInfo.Id processorId) { if (processorId == null || iFileInfo == null) { return false; } switch (processorId) { case L1AEXTRACT_MODIS: return iFileInfo.isTypeId(FileTypeInfo.Id.L1A); case L1AEXTRACT_SEAWIFS: return iFileInfo.isTypeId(FileTypeInfo.Id.L1A); case L1AEXTRACT: return iFileInfo.isTypeId(FileTypeInfo.Id.L1A); case L1AGEN: return iFileInfo.isTypeId(FileTypeInfo.Id.L0); case GEOGEN: return iFileInfo.isTypeId(FileTypeInfo.Id.L1A); case L1BGEN: return isValidL2genFileType(iFileInfo); // same requirements as L2GEN // case L1MAPGEN: // return isValidL2genFileType(iFileInfo); // same requirements as L2GEN case L1BRSGEN: return isValidL2genFileType(iFileInfo); // same requirements as L2GEN case L2EXTRACT: return iFileInfo.isTypeId(FileTypeInfo.Id.L2); case L2GEN: return isValidL2genFileType(iFileInfo); // case L2GEN_AQUARIUS: // return isValidL2genFileType(iFileInfo); // case L2MAPGEN: // return iFileInfo.isTypeId(FileTypeInfo.Id.L2); case L2BRSGEN: return iFileInfo.isTypeId(FileTypeInfo.Id.L2); case L2BIN: return iFileInfo.isTypeId(FileTypeInfo.Id.L2); case L2MERGE: return true; case L3BINMERGE: return true; case GEOREGION_GEN: return true; case L3BIN: return iFileInfo.isTypeId(FileTypeInfo.Id.L3); case L3GEN: return iFileInfo.isTypeId(FileTypeInfo.Id.L3BIN); // case SMIGEN: // return iFileInfo.isTypeId(FileTypeInfo.Id.L3BIN); default: return false; } } static public boolean isValidIfile(FileInfo iFileInfo, SeadasProcessorInfo.Id processorId) { if (iFileInfo != null && iFileInfo.getFile().exists() && iFileInfo.getFile().isAbsolute()) { return isValidFileType(iFileInfo, processorId) && isSupportedMission(iFileInfo, processorId); } return false; } private void setValidIfile() { validIfile = isValidIfile(fileInfo, id); } static private boolean isValidL2genFileType(FileInfo iFileInfo) { if (iFileInfo == null) { return false; } if (iFileInfo.isMissionId(MissionInfo.Id.VIIRSN) || iFileInfo.isMissionId(MissionInfo.Id.VIIRSJ1) || iFileInfo.isMissionId(MissionInfo.Id.VIIRSJ2)) { if (iFileInfo.isTypeId(FileTypeInfo.Id.SDR) || iFileInfo.isTypeId(FileTypeInfo.Id.L1A) || iFileInfo.isTypeId(FileTypeInfo.Id.L1B) ) { return true; } } else if (iFileInfo.isMissionId(MissionInfo.Id.MODISA) || iFileInfo.isMissionId(MissionInfo.Id.MODIST) || iFileInfo.isMissionId(MissionInfo.Id.MERIS) ) { if (iFileInfo.isTypeId(FileTypeInfo.Id.L1B)) { return true; } } else { if (iFileInfo.isTypeId(FileTypeInfo.Id.L1A) || iFileInfo.isTypeId(FileTypeInfo.Id.L1B)) { return true; } } return false; } public FileInfo getFileInfo() { return fileInfo; } public String getExecutable() { return executable; } public boolean isValidIfile() { return validIfile; } }
9,974
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
XmlReader.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/XmlReader.java
package gov.nasa.gsfc.seadas.processing.common; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; public class XmlReader { public final String PROCESSOR_OPTION_XML_NODE_NAME = "option"; Document dom; public XmlReader() { } public Document parseXmlFile(InputStream inputStream) { //get the factory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { //Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); //parse using builder to get DOM representation of the XML file dom = db.parse(inputStream); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXException se) { se.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return dom; } public Document getDom(){ return dom; } public Element parseAndGetRootElement(InputStream inputStream) { parseXmlFile(inputStream); return dom.getDocumentElement(); } /** * I take a xml element and the tag name, look for the tag and get * the text content * i.e for <employee><name>John</name></employee> xml snippet if * the Element points to employee node and tagName is name I will return John * * @param ele * @param tagName * @return */ public static String getTextValue(Element ele, String tagName) { String textVal = null; NodeList nl = ele.getElementsByTagName(tagName); if (nl != null && nl.getLength() > 0) { Element el = (Element) nl.item(0); if (el.hasChildNodes()) { textVal = el.getFirstChild().getNodeValue(); } } return textVal; } public static String getAttributeTextValue(Element ele, String attributeName) { String textVal = null; textVal = ele.getAttribute(attributeName); return textVal; } /** * Calls getTextValue and returns a int value * * @param ele * @param tagName * @return */ public static int getIntValue(Element ele, String tagName) { //in production application you would catch the exception return Integer.parseInt(getTextValue(ele, tagName)); } /** * Calls getTextValue and returns a boolean value * * @param ele * @param tagName * @return */ public static boolean getBooleanValue(Element ele, String tagName) { return Boolean.parseBoolean(getTextValue(ele, tagName)) ; } }
2,954
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
UpdateLutsUI.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/UpdateLutsUI.java
package gov.nasa.gsfc.seadas.processing.common; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW; import javax.swing.*; import java.awt.*; import java.io.File; public class UpdateLutsUI extends JPanel implements CloProgramUI { ProcessorModel processorModel; JPanel paramPanel; OCSSW ocssw; public UpdateLutsUI(String programName, String xmlFileName, OCSSW ocssw) { this.ocssw = ocssw; processorModel = ProcessorModel.valueOf(programName, xmlFileName, ocssw); createUserInterface(); } protected void createUserInterface() { paramPanel = getParamPanel(); this.setLayout(new GridBagLayout()); add(paramPanel, new GridBagConstraintsCustom(0, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, 3)); setMinimumSize(getPreferredSize()); setMaximumSize(getPreferredSize()); getProcessorModel().setReadyToRun(true); } @Override public JPanel getParamPanel() { return new ParamUIFactory(processorModel).createParamPanel(); } @Override public ProcessorModel getProcessorModel() { return processorModel; } @Override public File getSelectedSourceProduct() { return null; } @Override public boolean isOpenOutputInApp() { return false; } @Override public String getParamString() { return null; } @Override public void setParamString(String paramString) { } }
1,566
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
EarthBox2.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/EarthBox2.java
package gov.nasa.gsfc.seadas.processing.common; import org.esa.snap.core.datamodel.GeoPos; import ucar.ma2.Array; /** * Created with IntelliJ IDEA. * User: knowles * Date: 10/30/13 * Time: 11:00 AM * To change this template use File | Settings | File Templates. */ public class EarthBox2 { public static final float NULL_COORDINATE = (float) -999; private float minLat = NULL_COORDINATE; private float maxLat = NULL_COORDINATE; private float minLon = NULL_COORDINATE; private float maxLon = NULL_COORDINATE; float deltaLat = NULL_COORDINATE; float deltaLon = NULL_COORDINATE; private int latDimensionLength = 0; private int lonDimensionLength = 0; private short[][] values; public EarthBox2() { } private void setDeltaLon() { if (getMinLon() != NULL_COORDINATE) { deltaLon = (getMaxLon() - getMinLon()) / getLonDimensionLength(); } } private void setDeltaLat() { if (getMinLat() != NULL_COORDINATE) { deltaLat = (getMaxLat() - getMinLat()) / getLatDimensionLength(); } } private float getDeltaLat() { if (deltaLat == NULL_COORDINATE) { setDeltaLat(); } return deltaLat; } private float getDeltaLon() { if (deltaLon == NULL_COORDINATE) { setDeltaLon(); } return deltaLon; } private int getLatIndex(float lat) { int latIndex = (int) Math.round((lat - getMinLat()) / getDeltaLat()); if (latIndex > getLatDimensionLength() - 1) { latIndex = getLatDimensionLength() - 1; } if (latIndex < 0) { latIndex = 0; } return latIndex; } private int getLonIndex(float lon) { int lonIndex = (int) Math.round((lon - getMinLon()) / getDeltaLon()); if (lonIndex > getLonDimensionLength() - 1) { lonIndex = getLonDimensionLength() - 1; } if (lonIndex < 0) { lonIndex = 0; } return lonIndex; } public float getMinLat() { return minLat; } private void setMinLat(float minLat) { this.minLat = minLat; this.deltaLat = NULL_COORDINATE; } public float getMaxLat() { return maxLat; } private void setMaxLat(float maxLat) { this.maxLat = maxLat; this.deltaLat = NULL_COORDINATE; } public float getMinLon() { return minLon; } private void setMinLon(float minLon) { this.minLon = minLon; this.deltaLon = NULL_COORDINATE; } public float getMaxLon() { return maxLon; } private void setMaxLon(float maxLon) { this.maxLon = maxLon; this.deltaLon = NULL_COORDINATE; } public int getLatDimensionLength() { return latDimensionLength; } private void setLatDimensionLength(int latDimensionLength) { this.latDimensionLength = latDimensionLength; } public int getLonDimensionLength() { return lonDimensionLength; } private void setLonDimensionLength(int lonDimensionLength) { this.lonDimensionLength = lonDimensionLength; } public void add(GeoPos geoPos) { float lat = (float) geoPos.lat; float lon = (float) geoPos.lon; add(lat, lon); } public void add(float lat, float lon) { if (lat > getMaxLat() || getMaxLat() == NULL_COORDINATE) { setMaxLat(lat); } if (lat < getMinLat() || getMinLat() == NULL_COORDINATE) { setMinLat(lat); } if (lon > getMaxLon() || getMaxLon() == NULL_COORDINATE) { setMaxLon(lon); } if (lon < getMinLon() || getMinLon() == NULL_COORDINATE) { setMinLon(lon); } } public short getValue(GeoPos geoPos) { return getValue((float)geoPos.lat, (float) geoPos.lon); } public short getValue(float lat, float lon) { int latIndex = getLatIndex(lat); int lonIndex = getLonIndex(lon); return getValue(latIndex, lonIndex); } public short getValue(int latIndex, int lonIndex) { return values[latIndex][lonIndex]; } public void setValues(short[][] values) { this.values = values; setLatDimensionLength(values.length); setLonDimensionLength(values[0].length); } public void setValueUcarArray(Array valueUcarArray) { values = (short[][]) valueUcarArray.copyToNDJavaArray(); } }
4,551
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
FileTypeInfo.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/FileTypeInfo.java
package gov.nasa.gsfc.seadas.processing.common; import java.util.HashMap; import java.util.Iterator; /** * Created by IntelliJ IDEA. * User: knowles * Date: 5/17/12 * Time: 2:51 PM * To change this template use File | Settings | File Templates. */ public class FileTypeInfo { public static enum Id { L0, L1EXTRACT, L1, L1A, GEO, L1B, SDR, L1MAP, L1BRS, L2EXTRACT, L2, L2MAP, L2BRS, L2BIN, L2MERGE, L3BINMERGE, GEOREGION_GEN, L3, L3BIN, L3SMI, UNKNOWN } private final static String[] L0_NAMES = {"Level 0", "L0"}; private final static String[] L1EXTRACT_NAMES = null; private final static String[] L1_NAMES = {"Level 1", "L1"}; private final static String[] L1A_NAMES = {"Level 1A", "L1A"}; private final static String[] GEO_NAMES = {"GEO"}; private final static String[] L1B_NAMES = {"Level 1B", "L1B"}; private final static String[] SDR_NAMES = {"SDR"}; private final static String[] L1MAP_NAMES = null; private final static String[] L1BRS_NAMES = {"Level 1 Browse Data"}; private final static String[] L2EXTRACT_NAMES = null; private final static String[] L2_NAMES = {"Level 2", "L2"}; private final static String[] L2MAP_NAMES = null; private final static String[] L2BRS_NAMES = {"Level 2 Browse Data"}; private final static String[] L2BIN_NAMES = null; private final static String[] L2MERGE_NAMES = null; private final static String[] L3BINMERGE_NAMES = null; private final static String[] GEOREGION_GEN_NAMES = null; private final static String[] L3_NAMES = {"Level 3"}; private final static String[] L3BIN_NAMES = {"Level 3 Binned"}; private final static String[] L3SMI_NAMES = {"Level 3 SMI"}; private final static String[] UNKNOWN_NAMES = {"UNKNOWN"}; private final HashMap<Id, String[]> nameLookup = new HashMap<Id, String[]>(); private Id id = null; public FileTypeInfo() { initNamesHashMap(); } public FileTypeInfo(Id id) { this(); this.id = id; } public void clear() { id = null; } private void initNamesHashMap() { nameLookup.put(Id.L0, L0_NAMES); nameLookup.put(Id.L1EXTRACT, L1EXTRACT_NAMES); nameLookup.put(Id.L1, L1_NAMES); nameLookup.put(Id.L1A, L1A_NAMES); nameLookup.put(Id.GEO, GEO_NAMES); nameLookup.put(Id.L1B, L1B_NAMES); nameLookup.put(Id.SDR, SDR_NAMES); nameLookup.put(Id.L1MAP, L1MAP_NAMES); nameLookup.put(Id.L1BRS, L1BRS_NAMES); nameLookup.put(Id.L2EXTRACT, L2EXTRACT_NAMES); nameLookup.put(Id.L2, L2_NAMES); nameLookup.put(Id.L2MAP, L2MAP_NAMES); nameLookup.put(Id.L2BRS, L2BRS_NAMES); nameLookup.put(Id.L2BIN, L2BIN_NAMES); nameLookup.put(Id.L2MERGE, L2MERGE_NAMES); nameLookup.put(Id.L3BINMERGE, L3BINMERGE_NAMES); nameLookup.put(Id.GEOREGION_GEN, GEOREGION_GEN_NAMES); nameLookup.put(Id.L3BIN, L3BIN_NAMES); nameLookup.put(Id.L3, L3_NAMES); nameLookup.put(Id.L3SMI, L3SMI_NAMES); nameLookup.put(Id.UNKNOWN, UNKNOWN_NAMES); } public Id getId() { return id; } public void setId(Id id) { this.id = id; } public boolean isId(Id id) { if (this.id == id) { return true; } else { return false; } } public void setName(String name) { clear(); if (name == null) { return; } Iterator itr = nameLookup.keySet().iterator(); while (itr.hasNext()) { Object key = itr.next(); if (nameLookup.get(key) != null) { for (String typeLookup : nameLookup.get(key)) { if (typeLookup.toLowerCase().equals(name.toLowerCase())) { setId((Id) key); return; } } } } setId(Id.UNKNOWN); return; } public String getName() { if (id == null) { return null; } if (nameLookup.containsKey(id) && nameLookup.get(id) != null) { return nameLookup.get(id)[0]; } return null; } }
4,405
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
FileInfoFinder.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/FileInfoFinder.java
package gov.nasa.gsfc.seadas.processing.common; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo; /** * Created by aabduraz on 8/21/15. */ public class FileInfoFinder { public static final String FILE_TYPE_VAR_NAME = "fileType"; public static final String MISSION_NAME_VAR_NAME = "missionName"; private String fileType; private String missionName; private String missionDirName; public FileInfoFinder(String fileName, OCSSW ocssw){ if (fileName.contains(" ")) { SimpleDialogMessage dialog = new SimpleDialogMessage(null, "<html><br>&nbsp;&nbsp;WARNING!!<br> " + "&nbsp;&nbsp;Directory path and/or filename cannot have a space in it&nbsp;&nbsp;<br>&nbsp;</html>"); dialog.setVisible(true); dialog.setEnabled(true); } else { ocssw.findFileInfo(fileName, this); setMissionDirName(OCSSWInfo.getInstance().getOcsswDataDirPath()); } } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getMissionName() { return missionName; } public void setMissionName(String missionName) { this.missionName = missionName; } public String getMissionDirName() { return missionDirName; } public void setMissionDirName(String missionDirName) { this.missionDirName = missionDirName; } }
1,543
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
ParFileManager.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/ParFileManager.java
package gov.nasa.gsfc.seadas.processing.common; import gov.nasa.gsfc.seadas.processing.core.ParamList; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.logging.Logger; /** * Created by aabduraz on 7/25/16. */ public class ParFileManager{ private String parFileOptionName; public static String tmpParFileToDelString; ProcessorModel processorModel; protected ParamList paramList; private String parFileLocation; public ParFileManager(ProcessorModel processorModel) { this.processorModel = processorModel; paramList = processorModel.getParamList(); parFileOptionName = processorModel.getParFileOptionName(); } public String[] getCmdArrayWithParFile() { String parString; File parFile = computeParFile(); String parFileName = parFile.getAbsolutePath(); tmpParFileToDelString = parFileName; if (parFileOptionName.equals("none")) { parString = parFileName; } else { parString = parFileOptionName + "=" + parFileName; } return new String[]{parString}; } private File computeParFile() { try { final File tempFile = File.createTempFile(processorModel.getProgramName() + "-tmpParFile", ".par", processorModel.getIFileDir()); parFileLocation = tempFile.getAbsolutePath(); //System.out.println(tempFile.getAbsoluteFile()); //tempFile.deleteOnExit(); FileWriter fileWriter = null; try { fileWriter = new FileWriter(tempFile); String parString; if (processorModel.getProgramName().equals("multilevel_processor")) { parString = getParString4mlp(); } else { parString = getParString(); } fileWriter.write(parString + "\n"); } finally { if (fileWriter != null) { fileWriter.close(); } } return tempFile; } catch (IOException e) { Logger.getGlobal().warning("parfile is not created. " + e.getMessage()); return null; } } public String getParString() { return paramList.getParamString("\n"); } public String getParString4mlp() { return paramList.getParamString4mlp("\n"); } public String getParFileOptionName() { return parFileOptionName; } public void setParFileOptionName(String parFileOptionName) { this.parFileOptionName = parFileOptionName; } }
2,736
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
FileInfo.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/FileInfo.java
package gov.nasa.gsfc.seadas.processing.common; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW; import java.io.File; /** * Created by IntelliJ IDEA. * User: knowles * Date: 6/13/12 * Time: 4:26 PM * To change this template use File | Settings | File Templates. */ public class FileInfo { private File file; private static final String FILE_INFO_SYSTEM_CALL = "obpg_file_type"; private static final boolean DEFAULT_MISSION_AND_FILE_TYPE_ENABLED = true; private final MissionInfo missionInfo = new MissionInfo(); private final FileTypeInfo fileTypeInfo = new FileTypeInfo(); private boolean missionAndFileTypeEnabled = DEFAULT_MISSION_AND_FILE_TYPE_ENABLED; OCSSW ocssw; public FileInfo(String defaultParent, String child, OCSSW ocssw) { this(defaultParent, child, DEFAULT_MISSION_AND_FILE_TYPE_ENABLED, ocssw); } public FileInfo(String defaultParent, String child, boolean missionAndFileTypeEnabled, OCSSW ocssw) { this.ocssw = ocssw; this.missionAndFileTypeEnabled = missionAndFileTypeEnabled; file = SeadasFileUtils.createFile(defaultParent, child); if (file != null && file.exists()) { initMissionAndFileTypeInfos(); } } public FileInfo(String filename) { if (filename != null) { file = new File(filename); if (file.exists()) { initMissionAndFileTypeInfos(); } } } public void clear() { file = null; missionInfo.clear(); fileTypeInfo.clear(); } private void initMissionAndFileTypeInfos() { FileInfoFinder fileInfoFinder = new FileInfoFinder(file.getAbsolutePath(), ocssw); fileTypeInfo.setName(fileInfoFinder.getFileType()); missionInfo.setName(fileInfoFinder.getMissionName()); } //-------------------------- Indirect Get Methods ---------------------------- public MissionInfo.Id getMissionId() { return missionInfo.getId(); } public String getMissionName() { return missionInfo.getName(); } public File getMissionDirectory() { return missionInfo.getDirectory(); } public File getSubsensorDirectory() { return missionInfo.getSubsensorDirectory(); } public boolean isMissionDirExist() { return ocssw.isMissionDirExist(getMissionName()); } public boolean isMissionId(MissionInfo.Id missionId) { return missionInfo.isId(missionId); } public boolean isSupportedMission() { return missionInfo.isSupported(); } public FileTypeInfo.Id getTypeId() { return fileTypeInfo.getId(); } public String getFileTypeName() { return fileTypeInfo.getName(); } public boolean isTypeId(FileTypeInfo.Id type) { return fileTypeInfo.isId(type); } public boolean isGeofileRequired() { return missionInfo.isGeofileRequired(); } public File getFile() { return file; } public boolean isMissionAndFileTypeEnabled() { return missionAndFileTypeEnabled; } public void setMissionAndFileTypeEnabled(boolean missionAndFileTypeEnabled) { this.missionAndFileTypeEnabled = missionAndFileTypeEnabled; } }
3,283
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
ParamUIFactory.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/ParamUIFactory.java
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import gov.nasa.gsfc.seadas.processing.core.*; import gov.nasa.gsfc.seadas.processing.preferences.SeadasToolboxDefaults; import org.esa.snap.core.util.PropertyMap; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.ModalDialog; import javax.swing.*; import javax.swing.border.EtchedBorder; import javax.swing.event.SwingPropertyChangeSupport; 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; import java.util.Arrays; import java.util.Iterator; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 6/7/12 * Time: 9:23 AM * To change this template use File | Settings | File Templates. */ public class ParamUIFactory { ProcessorModel processorModel; SwingPropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this); private String emptySpace = " "; protected Boolean flaguseTextfieldIgnore = false; private JTextField field = new JTextField(); private static int controlHandlerIntEnabled = 1; // enabled if value 1 or greater private static int eventHandlerIntEnabled = 1; // enabled if value 1 or greater public ParamUIFactory(ProcessorModel pm) { this.processorModel = pm; } public JPanel createParamPanel() { //final JScrollPane textScrollPane = new JScrollPane(parameterTextArea); final JScrollPane textScrollPane = new JScrollPane(createParamPanel(processorModel)); // textScrollPane.setPreferredSize(new Dimension(700, 400)); final JPanel parameterComponent = new JPanel(new BorderLayout()); parameterComponent.add(textScrollPane, BorderLayout.NORTH); parameterComponent.setPreferredSize(parameterComponent.getPreferredSize()); if (processorModel.getProgramName().indexOf("smigen") != -1) { SMItoPPMUI smItoPPMUI = new SMItoPPMUI(processorModel); JPanel smitoppmPanel = smItoPPMUI.getSMItoPPMPanel(); parameterComponent.add(smitoppmPanel, BorderLayout.SOUTH); smitoppmPanel.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { parameterComponent.validate(); parameterComponent.repaint(); } }); } parameterComponent.setMaximumSize(parameterComponent.getPreferredSize()); parameterComponent.setMinimumSize(parameterComponent.getPreferredSize()); return parameterComponent; } protected JPanel createParamPanel(ProcessorModel processorModel) { ArrayList<ParamInfo> paramList = processorModel.getProgramParamList(); JPanel paramPanel = new JPanel(); paramPanel.setName("param panel"); // JPanel textFieldPanel = new JPanel(); final JPanel textFieldPanel = GridBagUtils.createPanel(); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 1; gbc.weighty = 1; textFieldPanel.setName("text field panel"); JPanel booleanParamPanel = new JPanel(); booleanParamPanel.setName("boolean field panel"); JPanel fileParamPanel = new JPanel(); fileParamPanel.setName("file parameter panel"); JPanel buttonPanel = new JPanel(); buttonPanel.setName("button panel"); TableLayout booleanParamLayout = new TableLayout(3); booleanParamPanel.setLayout(booleanParamLayout); TableLayout fileParamLayout = new TableLayout(1); fileParamLayout.setTableFill(TableLayout.Fill.HORIZONTAL); fileParamPanel.setLayout(fileParamLayout); int numberOfOptionsPerLine = paramList.size() % 4 < paramList.size() % 5 ? 4 : 5; if ("l3mapgen".equals(processorModel.getProgramName())) { numberOfOptionsPerLine = 6; } // TableLayout textFieldPanelLayout = new TableLayout(numberOfOptionsPerLine); // textFieldPanelLayout.setTablePadding(5,5); // textFieldPanel.setLayout(textFieldPanelLayout); gbc.gridy=0; gbc.gridx=0; gbc.insets.top = 5; gbc.insets.bottom = 5; gbc.insets.left = 5; gbc.insets.right = 25; gbc.weighty = 0; gbc.anchor = GridBagConstraints.NORTHWEST; Iterator<ParamInfo> itr = paramList.iterator(); while (itr.hasNext()) { final ParamInfo pi = itr.next(); if (!(pi.getName().equals(processorModel.getPrimaryInputFileOptionName()) || pi.getName().equals(processorModel.getPrimaryOutputFileOptionName()) || pi.getName().equals(L2genData.GEOFILE) || pi.getName().equals("verbose") || pi.getName().equals("--verbose"))) { if (pi.getColSpan() > numberOfOptionsPerLine) { gbc.gridwidth = numberOfOptionsPerLine; } else { gbc.gridwidth = pi.getColSpan(); } if (pi.hasValidValueInfos() && pi.getType() != ParamInfo.Type.FLAGS) { textFieldPanel.add(makeComboBoxOptionPanel(pi, gbc.gridwidth), gbc); gbc = incrementGridxGridy(gbc, numberOfOptionsPerLine); } else { switch (pi.getType()) { case BOOLEAN: booleanParamPanel.add(makeBooleanOptionField(pi)); break; case IFILE: fileParamPanel.add(createIOFileOptionField(pi)); break; case OFILE: fileParamPanel.add(createIOFileOptionField(pi)); break; case DIR: fileParamPanel.add(createIOFileOptionField(pi)); break; case STRING: textFieldPanel.add(makeOptionField(pi, gbc.gridwidth), gbc); gbc = incrementGridxGridy(gbc, numberOfOptionsPerLine); break; case INT: textFieldPanel.add(makeOptionField(pi, gbc.gridwidth), gbc); gbc = incrementGridxGridy(gbc, numberOfOptionsPerLine); break; case FLOAT: textFieldPanel.add(makeOptionField(pi, gbc.gridwidth), gbc); gbc = incrementGridxGridy(gbc, numberOfOptionsPerLine); break; case FLAGS: // gbc.gridwidth=5; gbc.insets.top = 4; textFieldPanel.add(makeButtonOptionPanel(pi), gbc); gbc = incrementGridxGridy(gbc, numberOfOptionsPerLine); gbc.gridwidth=1; gbc.insets.top = 0; break; case BUTTON: buttonPanel.add(makeActionButtonPanel(pi)); break; } //paramPanel.add(makeOptionField(pi)); } gbc.gridwidth = 1; } } TableLayout paramLayout = new TableLayout(1); paramPanel.setLayout(paramLayout); paramPanel.add(fileParamPanel); paramPanel.add(textFieldPanel); paramPanel.add(booleanParamPanel); paramPanel.add(buttonPanel); return paramPanel; } GridBagConstraints incrementGridxGridy(GridBagConstraints gbc, int numColumns) { gbc.gridx += gbc.gridwidth; if (gbc.gridx > (numColumns - 1)) { gbc.gridy += 1; gbc.gridx = 0; gbc.insets.top = 0; } return gbc; } protected JPanel makeOptionField(final ParamInfo pi, int colSpan) { final String optionName = ParamUtils.removePreceedingDashes(pi.getName()); final JPanel optionPanel = new JPanel(); optionPanel.setName(optionName); TableLayout fieldLayout = new TableLayout(1); fieldLayout.setTableFill(TableLayout.Fill.HORIZONTAL); optionPanel.setLayout(fieldLayout); optionPanel.setName(optionName); optionPanel.add(new JLabel(optionName)); if (pi.getDescription() != null) { optionPanel.setToolTipText(pi.getDescription().replaceAll("\\s+", " ")); } if (pi.getValue() == null || pi.getValue().length() == 0) { if (pi.getDefaultValue() != null) { processorModel.updateParamInfo(pi, pi.getDefaultValue()); } } final PropertyContainer vc = new PropertyContainer(); vc.addProperty(Property.create(optionName, pi.getValue())); vc.getDescriptor(optionName).setDisplayName(optionName); final BindingContext ctx = new BindingContext(vc); final JTextField field = new JTextField(); // field.setColumns(optionName.length() > 12 ? 12 : 8); if (colSpan == 2) { field.setColumns(20); } else if (colSpan == 3) { field.setColumns(32); } else if (colSpan == 4) { field.setColumns(44); } else if (colSpan >= 5) { field.setColumns(56); }else { field.setColumns(8); } field.setPreferredSize(field.getPreferredSize()); field.setMaximumSize(field.getPreferredSize()); field.setMinimumSize(field.getPreferredSize()); field.setName(pi.getName()); if (pi.getDescription() != null) { field.setToolTipText(pi.getDescription().replaceAll("\\s+", " ")); } ctx.bind(optionName, field); ctx.addPropertyChangeListener(optionName, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent pce) { if (!field.getText().trim().equals(pi.getValue().trim())) processorModel.updateParamInfo(pi, field.getText()); } }); processorModel.addPropertyChangeListener(pi.getName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (!field.getText().trim().equals(pi.getValue().trim())) field.setText(pi.getValue()); } }); optionPanel.add(field); return optionPanel; } private JPanel makeBooleanOptionField(final ParamInfo pi) { final String optionName = pi.getName(); final boolean optionValue = pi.getValue().equals("true") || pi.getValue().equals("1") ? true : false; final JPanel optionPanel = new JPanel(); optionPanel.setName(optionName); TableLayout booleanLayout = new TableLayout(1); //booleanLayout.setTableFill(TableLayout.Fill.HORIZONTAL); optionPanel.setLayout(booleanLayout); optionPanel.setAlignmentX(Component.CENTER_ALIGNMENT); optionPanel.setAlignmentY(Component.CENTER_ALIGNMENT); optionPanel.add(new JLabel(emptySpace + ParamUtils.removePreceedingDashes(optionName) + emptySpace)); if (pi.getDescription() != null) { optionPanel.setToolTipText(pi.getDescription().replaceAll("\\s+", " ")); } final PropertySet vc = new PropertyContainer(); vc.addProperty(Property.create(optionName, optionValue)); vc.getDescriptor(optionName).setDisplayName(optionName); final BindingContext ctx = new BindingContext(vc); final JCheckBox field = new JCheckBox(); field.setHorizontalAlignment(JFormattedTextField.LEFT); field.setName(pi.getName()); ctx.bind(optionName, field); if (pi.getDescription() != null) { field.setToolTipText(pi.getDescription().replaceAll("\\s+", " ")); } ctx.addPropertyChangeListener(optionName, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent pce) { processorModel.updateParamInfo(pi, (new Boolean(field.isSelected())).toString()); SeadasFileUtils.debug(((new Boolean(field.isSelected())).toString() + " " + field.getText())); } }); processorModel.addPropertyChangeListener(pi.getName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { field.setSelected(pi.getValue().equals("true") || pi.getValue().equals("1") ? true : false); field.validate(); field.repaint(); } }); optionPanel.add(field); return optionPanel; } private JPanel makeComboBoxOptionPanel(final ParamInfo pi, int colSpan) { final JPanel singlePanel = new JPanel(); String optionName = ParamUtils.removePreceedingDashes(pi.getName()); TableLayout comboParamLayout = new TableLayout(1); comboParamLayout.setTableFill(TableLayout.Fill.HORIZONTAL); singlePanel.setLayout(comboParamLayout); final JLabel optionNameLabel = new JLabel(ParamUtils.removePreceedingDashes(pi.getName())); singlePanel.add(optionNameLabel); singlePanel.setName(pi.getName()); if (pi.getDescription() != null) { singlePanel.setToolTipText(pi.getDescription().replaceAll("\\s+", " ")); } String optionDefaultValue = pi.getValue(); final ArrayList<ParamValidValueInfo> validValues = pi.getValidValueInfos(); final String[] values = new String[validValues.size()]; ArrayList<String> toolTips = new ArrayList<String>(); Iterator<ParamValidValueInfo> itr = validValues.iterator(); int i = 0; ParamValidValueInfo paramValidValueInfo; while (itr.hasNext()) { paramValidValueInfo = itr.next(); values[i] = paramValidValueInfo.getValue(); if (paramValidValueInfo.getDescription() != null) { toolTips.add(paramValidValueInfo.getDescription().replaceAll("\\s+", " ")); } i++; } Dimension preferredComboBoxSize; if (colSpan >= 5) { final String[] tmpValues = {"1234567890123456789012345901234567890123456789012345678901234567890123456789"}; JComboBox<String> tmpComboBox = new JComboBox<String>(tmpValues); preferredComboBoxSize = tmpComboBox.getPreferredSize(); } else if (colSpan == 4) { final String[] tmpValues = {"12345678901234567890123459012345678901234567890123456789012"}; JComboBox<String> tmpComboBox = new JComboBox<String>(tmpValues); preferredComboBoxSize = tmpComboBox.getPreferredSize(); } else if (colSpan == 3) { final String[] tmpValues = {"123456789012345678901234590123456789012345"}; JComboBox<String> tmpComboBox = new JComboBox<String>(tmpValues); preferredComboBoxSize = tmpComboBox.getPreferredSize(); } else if (colSpan == 2) { final String[] tmpValues = {"1234567890123456789012345"}; JComboBox<String> tmpComboBox = new JComboBox<String>(tmpValues); preferredComboBoxSize = tmpComboBox.getPreferredSize(); } else { final String[] tmpValues = {"12345678"}; JComboBox<String> tmpComboBox = new JComboBox<String>(tmpValues); preferredComboBoxSize = tmpComboBox.getPreferredSize(); } final JComboBox<String> inputList = new JComboBox<String>(values); ComboboxToolTipRenderer renderer = new ComboboxToolTipRenderer(); inputList.setRenderer(renderer); renderer.setTooltips(toolTips); inputList.setEditable(true); inputList.setName(pi.getName()); // inputList.setPreferredSize(new Dimension(inputList.getPreferredSize().width, // inputList.getPreferredSize().height)); inputList.setPreferredSize(preferredComboBoxSize); if (pi.getDescription() != null) { inputList.setToolTipText(pi.getDescription().replaceAll("\\s+", " ")); } int defaultValuePosition = new ArrayList<String>(Arrays.asList(values)).indexOf(optionDefaultValue); if (defaultValuePosition != -1) { inputList.setSelectedIndex(defaultValuePosition); } final PropertyContainer vc = new PropertyContainer(); vc.addProperty(Property.create(optionName, optionDefaultValue)); vc.getDescriptor(optionName).setDisplayName(optionName); final BindingContext ctx = new BindingContext(vc); ctx.bind(optionName, inputList); ctx.addPropertyChangeListener(optionName, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent pce) { String newValue = (String) inputList.getSelectedItem(); processorModel.updateParamInfo(pi, newValue); } }); processorModel.addPropertyChangeListener(pi.getName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { //values = updateValidValues(pi); int currentChoicePosition = new ArrayList<String>(Arrays.asList(values)).indexOf(pi.getValue()); if (currentChoicePosition != -1) { inputList.setSelectedIndex(currentChoicePosition); } } }); singlePanel.add(inputList); return singlePanel; } private JPanel makeButtonOptionPanel(final ParamInfo pi) { final JPanel singlePanel = new JPanel(); final JTextField field = new JTextField(); TableLayout comboParamLayout = new TableLayout(8); comboParamLayout.setTableFill(TableLayout.Fill.HORIZONTAL); singlePanel.setLayout(comboParamLayout); final JButton optionNameButton = new JButton(ParamUtils.removePreceedingDashes(pi.getName())); optionNameButton.setName("optionButton"); optionNameButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { String flaguseTextfield = field.getText(); processorModel.updateParamInfo(pi, field.getText()); String value = pi.getValue(); String selectedFlags = chooseValidValues(pi); if (!"-1".equals(selectedFlags)) { processorModel.updateParamInfo(pi, selectedFlags); String value2 = pi.getValue(); } } }); singlePanel.add(optionNameButton); singlePanel.setName(pi.getName()); if (pi.getDescription() != null) { singlePanel.setToolTipText(pi.getDescription().replaceAll("\\s+", " ")); } field.setText(pi.getValue()); field.setColumns(50); if (pi.getDescription() != null) { field.setToolTipText(pi.getDescription().replaceAll("\\s+", " ")); } field.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { flaguseTextfieldIgnore = true; String flaguse = field.getText(); processorModel.updateParamInfo(pi, field.getText()); String value = pi.getValue(); flaguseTextfieldIgnore = false; } }); processorModel.addPropertyChangeListener(pi.getName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (!flaguseTextfieldIgnore) { String flaguse = field.getText(); field.setText(pi.getValue()); String value = pi.getValue(); } } }); singlePanel.add(field); return singlePanel; } private JPanel makeActionButtonPanel(final ParamInfo pi) { final JPanel singlePanel = new JPanel(); TableLayout comboParamLayout = new TableLayout(8); comboParamLayout.setTableFill(TableLayout.Fill.HORIZONTAL); singlePanel.setLayout(comboParamLayout); final JButton actionButton = new JButton(ParamUtils.removePreceedingDashes(pi.getName())); actionButton.setName("actionButton"); actionButton.setEnabled(false); if (pi.getDescription() != null) { actionButton.setToolTipText(pi.getDescription().replaceAll("\\s+", " ")); } singlePanel.add(actionButton); return singlePanel; } public void addPropertyChangeListener(String name, PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(name, listener); } public void removePropertyChangeListener(String name, PropertyChangeListener listener) { propertyChangeSupport.removePropertyChangeListener(name, listener); } 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); } private String chooseValidValues(ParamInfo pi) { JPanel validValuesPanel = new JPanel(); validValuesPanel.setLayout(new TableLayout(3)); String choosenValues = ""; final ArrayList<ParamValidValueInfo> validValues = pi.getValidValueInfos(); Iterator<ParamValidValueInfo> itr = validValues.iterator(); ParamValidValueInfo paramValidValueInfo; while (itr.hasNext()) { paramValidValueInfo = itr.next(); if (!paramValidValueInfo.getValue().trim().equals("SPARE")) { // todo set this based on textfield if (pi.getValue() != null && pi.getValue().length() > 0) { paramValidValueInfo.setSelected(false); String[] values = pi.getValue().split("[,\\s]"); for (String value : values) { // if (pi.getValue().contains(paramValidValueInfo.getValue().trim())) { if (value.trim().toUpperCase().equals(paramValidValueInfo.getValue().trim().toUpperCase())) { paramValidValueInfo.setSelected(true); } } } validValuesPanel.add(makeValidValueCheckbox(paramValidValueInfo)); } } validValuesPanel.repaint(); validValuesPanel.validate(); final Window parent = SnapApp.getDefault().getMainFrame(); String dialogTitle = null; String origChosenValues = ""; itr = validValues.iterator(); while (itr.hasNext()) { paramValidValueInfo = itr.next(); if (paramValidValueInfo.isSelected()) { origChosenValues = origChosenValues + paramValidValueInfo.getValue() + ","; } } if (choosenValues.indexOf(",") != -1) { origChosenValues = origChosenValues.substring(0, origChosenValues.lastIndexOf(",")); } final ModalDialog modalDialog = new ModalDialog(parent, dialogTitle, validValuesPanel, ModalDialog.ID_OK, "test"); final int dialogResult = modalDialog.show(); if (dialogResult != ModalDialog.ID_OK) { } itr = validValues.iterator(); while (itr.hasNext()) { paramValidValueInfo = itr.next(); if (paramValidValueInfo.isSelected()) { choosenValues = choosenValues + paramValidValueInfo.getValue() + ","; } } if (choosenValues.indexOf(",") != -1) { choosenValues = choosenValues.substring(0, choosenValues.lastIndexOf(",")); } return choosenValues; } private JPanel makeValidValueCheckbox(final ParamValidValueInfo paramValidValueInfo) { final String optionName = paramValidValueInfo.getValue(); final boolean optionValue = paramValidValueInfo.isSelected(); final JPanel optionPanel = new JPanel(); optionPanel.setName(optionName); optionPanel.setBorder(new EtchedBorder()); optionPanel.setPreferredSize(new Dimension(100, 40)); TableLayout booleanLayout = new TableLayout(1); //booleanLayout.setTableFill(TableLayout.Fill.HORIZONTAL); optionPanel.setLayout(booleanLayout); optionPanel.setAlignmentX(Component.CENTER_ALIGNMENT); optionPanel.setAlignmentY(Component.CENTER_ALIGNMENT); optionPanel.add(new JLabel(emptySpace + ParamUtils.removePreceedingDashes(optionName) + emptySpace)); if (paramValidValueInfo.getDescription() != null) { optionPanel.setToolTipText(paramValidValueInfo.getDescription().replaceAll("\\s+", " ")); } final PropertySet vc = new PropertyContainer(); vc.addProperty(Property.create(optionName, optionValue)); vc.getDescriptor(optionName).setDisplayName(optionName); final BindingContext ctx = new BindingContext(vc); final JCheckBox field = new JCheckBox(); field.setHorizontalAlignment(JFormattedTextField.LEFT); field.setName(optionName); field.setSelected(paramValidValueInfo.isSelected()); if (paramValidValueInfo.getDescription() != null) { field.setToolTipText(paramValidValueInfo.getDescription().replaceAll("\\s+", " ")); } ctx.bind(optionName, field); ctx.addPropertyChangeListener(optionName, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent pce) { paramValidValueInfo.setSelected(field.isSelected()); } }); processorModel.addPropertyChangeListener(paramValidValueInfo.getValue(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { field.setSelected(paramValidValueInfo.isSelected()); } }); optionPanel.add(field); return optionPanel; } private String[] updateValidValues(ParamInfo pi) { final ArrayList<ParamValidValueInfo> validValues = pi.getValidValueInfos(); final String[] values = new String[validValues.size()]; ArrayList<String> toolTips = new ArrayList<String>(); Iterator<ParamValidValueInfo> itr = validValues.iterator(); int i = 0; ParamValidValueInfo paramValidValueInfo; while (itr.hasNext()) { paramValidValueInfo = itr.next(); values[i] = paramValidValueInfo.getValue(); if (paramValidValueInfo.getDescription() != null) { toolTips.add(paramValidValueInfo.getDescription().replaceAll("\\s+", " ")); } i++; } return values; } private boolean isControlHandlerEnabled() { if (controlHandlerIntEnabled >= 1) { return true; } else { return false; } } private void enableControlHandler() { controlHandlerIntEnabled++; } private void disableControlHandler() { controlHandlerIntEnabled--; } private boolean isEventHandlerEnabled() { if (eventHandlerIntEnabled >= 1) { return true; } else { return false; } } private void enableEventHandler() { eventHandlerIntEnabled++; } private void disableEventHandler() { eventHandlerIntEnabled--; } private JPanel createIOFileOptionField(final ParamInfo pi) { final FileSelector ioFileSelector = new FileSelector(SnapApp.getDefault().getAppContext(), pi.getType(), ParamUtils.removePreceedingDashes(pi.getName())); ioFileSelector.getFileTextField().setColumns(40); ioFileSelector.setFilename(pi.getValue()); if (pi.getDescription() != null) { ioFileSelector.getNameLabel().setToolTipText(pi.getDescription().replaceAll("\\s+", " ")); } processorModel.addPropertyChangeListener(pi.getName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (isEventHandlerEnabled()) { disableControlHandler(); // if (isEventHandlerEnabled() || pi.getName().isEmpty()) { ioFileSelector.setFilename(pi.getValue()); // } enableControlHandler(); } } }); ioFileSelector.addPropertyChangeListener(ioFileSelector.getPropertyName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (isControlHandlerEnabled()) { disableEventHandler(); String iofileName; if (ioFileSelector.getFileName() != null) { iofileName = ioFileSelector.getFileName(); processorModel.updateParamInfo(pi, iofileName); } enableEventHandler(); } } }); ioFileSelector.getjPanel().setName(pi.getName()); return ioFileSelector.getjPanel(); } private class ComboboxToolTipRenderer extends DefaultListCellRenderer { ArrayList<String> tooltips; @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JComponent comp = (JComponent) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (-1 < index && null != value && null != tooltips && !tooltips.isEmpty()) { list.setToolTipText(tooltips.get(index)); } return comp; } public void setTooltips(ArrayList<String> tooltips) { this.tooltips = tooltips; } } private class ValidValueChooser extends JPanel { String selectedBoxes; JPanel valuesPanel; ValidValueChooser(ParamInfo paramInfo) { } } private class ValidValuesButtonAction implements ActionListener { final JPanel valuesPanel; String selectedValues; ValidValuesButtonAction(JPanel panel) { valuesPanel = panel; } public void actionPerformed(ActionEvent actionEvent) { final Window parent = SnapApp.getDefault().getMainFrame(); String dialogTitle = null; final ModalDialog modalDialog = new ModalDialog(parent, dialogTitle, valuesPanel, ModalDialog.ID_OK, "test"); final int dialogResult = modalDialog.show(); if (dialogResult != ModalDialog.ID_OK) { } } void setSelectedValued(String selectedValues) { this.selectedValues = selectedValues; } String getSelectedValues() { return selectedValues; } } }
32,608
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SeadasPrint.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/SeadasPrint.java
package gov.nasa.gsfc.seadas.processing.common; /** * A ... * * @author Danny Knowles * @since SeaDAS 7.0 */ public class SeadasPrint { private static boolean debug = false; private static boolean admin = false; private static boolean user = true; private static boolean danny = false; private static boolean aynur = false; public SeadasPrint() { } public static enum DebugType { DANNY, AYNUR } public static void debug(String message) { if (isDebug()) { System.out.println(message); } } public static void debug(DebugType dt, String message) { if (dt == DebugType.DANNY && danny) { System.out.println(message); } else if (dt ==DebugType.AYNUR && aynur) { System.out.println(message);; } } public static void userlog(String message) { if (isUser()) { System.out.println(message); } } public static void adminlog(String message) { if (isAdmin()) { System.out.println(message); } } public static boolean isDebug() { return debug; } public static void setDebug(boolean debug) { SeadasPrint.debug = debug; } public static boolean isAdmin() { return admin; } public static void setAdmin(boolean admin) { SeadasPrint.admin = admin; } public static boolean isUser() { return user; } public static void setUser(boolean user) { SeadasPrint.user = user; } }
1,575
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
EventInfo.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/EventInfo.java
package gov.nasa.gsfc.seadas.processing.common; import javax.swing.event.SwingPropertyChangeSupport; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * A ... * * @author Danny Knowles * @since SeaDAS 7.0 */ public class EventInfo { private String name; private int enabledCount = 0; private boolean pending = false; Object sourceObject; private SwingPropertyChangeSupport propertyChangeSupport; public EventInfo(String name, Object sourceObject) { this.name = name; this.sourceObject = sourceObject; propertyChangeSupport = new SwingPropertyChangeSupport(sourceObject); } public void setEnabled(boolean enabled) { if (enabled) { enabledCount--; } else { enabledCount++; } if (pending) { fireEvent(); } } public boolean isEnabled() { if (enabledCount == 0) { return true; } else { return false; } } public String getName() { return name; } public void addPropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.removePropertyChangeListener(listener); } public void fireEvent(Object oldValue, Object newValue) { if (!isEnabled()) { // System.out.println("Setting pending event fire - " + name); pending = true; } else { pending = false; // System.out.println("Actually Firing event - " + name); propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(sourceObject, name, oldValue, newValue)); } } public void fireEvent() { fireEvent(null, null); } public String toString() { return name; } public int getEnabledCount() { return enabledCount; } }
2,057
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
TypeAheadSelector.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/TypeAheadSelector.java
package gov.nasa.gsfc.seadas.processing.common; import javax.swing.*; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import javax.swing.plaf.basic.BasicDirectoryModel; import javax.swing.plaf.basic.BasicFileChooserUI; import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.util.Vector; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 9/6/12 * Time: 12:05 PM * This code is taken from http://www.javaworld.com/jw-02-2001/jw-0216-jfile.html */ public class TypeAheadSelector extends KeyAdapter implements PropertyChangeListener { private JFileChooser chooser; private StringBuffer partialName = new StringBuffer(); private Vector files; private boolean resetPartialName = true; public TypeAheadSelector(JFileChooser chooser) { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } this.chooser = chooser; //Component comp = findJList(chooser); Component comp = findJTextField(chooser); comp.addKeyListener(this); setListDataListener(); chooser.addPropertyChangeListener(this); } public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if (prop.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) { if (resetPartialName) partialName.setLength(0); resetPartialName = true; } } private void setListDataListener() { final BasicDirectoryModel model = ((BasicFileChooserUI)chooser.getUI()).getModel(); model.addListDataListener(new ListDataListener() { public void contentsChanged(ListDataEvent lde) { Vector buffer = model.getFiles(); if (buffer.size() > 0) { files = buffer; } } public void intervalAdded(ListDataEvent lde) {} public void intervalRemoved(ListDataEvent lde) {} }); } public void keyTyped(KeyEvent ke) { if (ke.getKeyChar() == KeyEvent.VK_ENTER) { if (chooser.getSelectedFile().isFile()) chooser.approveSelection(); } partialName.append(ke.getKeyChar()); String upperCasePartialName = partialName.toString().toUpperCase(); for(int i = 0; i < files.size(); i++) { File item = (File)files.get(i); String name = item.getName().toUpperCase(); if (name.startsWith(upperCasePartialName)) { resetPartialName = false; chooser.setSelectedFile(item); return; } } } private Component findJList(Component comp) { //System.out.println(comp.getClass()); if (comp.getClass() == JList.class) return comp; if (comp instanceof Container) { Component[] components = ((Container) comp).getComponents(); for (int i = 0; i < components.length; i++) { Component child = findJList(components[i]); if (child != null) return child; } } return null; } private Component findJTextField(Component comp) { //System.out.println(comp.getClass() + " " + JTextField.class); if (comp.getClass().equals(JTextField.class)) return comp; if (comp instanceof Container) { Component[] components = ((Container) comp).getComponents(); for (int i = 0; i < components.length; i++) { Component child = findJTextField(components[i]); if (child != null) return child; } } return null; } }
4,007
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
CloProgramUI.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/CloProgramUI.java
package gov.nasa.gsfc.seadas.processing.common; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import javax.swing.*; import java.io.File; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 4/10/12 * Time: 3:06 PM * To change this template use File | Settings | File Templates. */ public interface CloProgramUI{ public JPanel getParamPanel(); public ProcessorModel getProcessorModel(); public File getSelectedSourceProduct(); public boolean isOpenOutputInApp(); public String getParamString(); public void setParamString(String paramString); }
613
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
LUTManager.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/LUTManager.java
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.swing.TableLayout; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo; import org.esa.snap.rcp.util.Dialogs; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.logging.Logger; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 10/4/12 * Time: 3:33 PM * To change this template use File | Settings | File Templates. */ public class LUTManager { private final String UPDATE_LUTS_PROCESSOR_NAME = "update_luts"; private String missionName; private JButton lutButton; OCSSW ocssw; boolean enableUpdateLuts; public LUTManager(OCSSW ocssw) { this.ocssw = ocssw; lutButton = new JButton(); lutButton.setEnabled(false); lutButton.setName("update luts"); lutButton.setText("Update LUTS"); lutButton.setToolTipText("Click to update Look Up Tables"); lutButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { updateLUT(); } }); enableUpdateLuts = false; } protected JButton getLUTButton() { return lutButton; } private void updateLUT() { String[] lutCmdArray = {OCSSWInfo.getInstance().getOcsswRunnerScriptPath(), UPDATE_LUTS_PROCESSOR_NAME, missionName}; String[] lutCmdArrayParams = {missionName}; Process process = ocssw.execute(lutCmdArray); process = ocssw.execute(UPDATE_LUTS_PROCESSOR_NAME, lutCmdArrayParams); try { int exitValue = process.waitFor(); } catch (Exception e) { Logger.getGlobal().severe("Execution exception 0 : " + e.getMessage()); Dialogs.showError("WARNING: LUTs update failed"); } } protected void enableLUTButton(String missionName) { this.missionName = missionName; enableUpdateLuts = true; lutButton.setEnabled(true); } protected void disableLUTButton() { enableUpdateLuts = false; lutButton.setEnabled(false); } public String getMissionName() { return missionName; } public void setMissionName(String missionName) { this.missionName = missionName; //enableLUTButton(); } protected JPanel getLUTPanel() { JPanel lutPanel = new JPanel(); lutPanel.setLayout(new TableLayout(1)); lutButton.setEnabled(enableUpdateLuts); lutPanel.add(lutButton); return lutPanel; } }
2,677
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
ExtractorParamUI.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/ExtractorParamUI.java
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import gov.nasa.gsfc.seadas.processing.core.ParamInfo; import gov.nasa.gsfc.seadas.processing.core.ParamUtils; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import javax.swing.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import org.esa.snap.rcp.util.Dialogs; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 4/9/15 * Time: 2:50 PM * To change this template use File | Settings | File Templates. */ public class ExtractorParamUI extends ParamUIFactory { private final String NON_INTERGER_VARS = "prod_list"; private final String PRODUCT_VARS = "product"; private final String WAVE_LIST_VARS = "wavelist"; private final String SUITE_VARS = "suite"; public ExtractorParamUI(ProcessorModel pm) { super(pm); } @Override protected JPanel makeOptionField(final ParamInfo pi, int colSpan) { final String optionName = pi.getName(); final JPanel optionPanel = new JPanel(); optionPanel.setName(optionName); TableLayout fieldLayout = new TableLayout(1); fieldLayout.setTableFill(TableLayout.Fill.HORIZONTAL); optionPanel.setLayout(fieldLayout); optionPanel.setName(optionName); optionPanel.add(new JLabel(ParamUtils.removePreceedingDashes(optionName))); if (pi.getDescription() != null) { optionPanel.setToolTipText(pi.getDescription().replaceAll("\\s+", " ")); } if (pi.getValue() == null || pi.getValue().length() == 0) { if (pi.getDefaultValue() != null) { processorModel.updateParamInfo(pi, pi.getDefaultValue()); } } final PropertyContainer vc = new PropertyContainer(); vc.addProperty(Property.create(optionName, pi.getValue())); vc.getDescriptor(optionName).setDisplayName(optionName); final BindingContext ctx = new BindingContext(vc); final JTextField field = new JTextField(); field.setColumns(8); field.setPreferredSize(field.getPreferredSize()); field.setMaximumSize(field.getPreferredSize()); field.setMinimumSize(field.getPreferredSize()); field.setName(pi.getName()); if (pi.getDescription() != null) { field.setToolTipText(pi.getDescription().replaceAll("\\s+", " ")); } ctx.bind(optionName, field); ctx.addPropertyChangeListener(optionName, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent pce) { String value = field.getText(); if (!field.getText().trim().equals(pi.getValue().trim())) { if (NON_INTERGER_VARS.contains(pi.getName()) || PRODUCT_VARS.contains(pi.getName()) || WAVE_LIST_VARS.contains(pi.getName()) || SUITE_VARS.contains(pi.getName()) || new Double(field.getText()).doubleValue() > 0 ) { processorModel.updateParamInfo(pi, field.getText()); } else { Dialogs.showError("Please enter a value greater than zero!"); field.setText(" "); } } } }); processorModel.addPropertyChangeListener(pi.getName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (! field.getText().trim().equals(pi.getValue().trim())) field.setText(pi.getValue()); } }); optionPanel.add(field); return optionPanel; } }
4,015
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
FilenamePatterns.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/FilenamePatterns.java
package gov.nasa.gsfc.seadas.processing.common; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWRemote; import java.io.File; import java.util.ArrayList; import java.util.GregorianCalendar; /** * Created by IntelliJ IDEA. * User: knowles * Date: 5/15/12 * Time: 11:44 AM * To change this template use File | Settings | File Templates. */ public class FilenamePatterns { public static final String GEO_LOCATE_PROGRAM_NAME_VIIRS = "geolocate_viirs"; public static final String GEO_LOCATE_PROGRAM_NAME_MODIS = "modis_GEO"; public static final String GEO_LOCATE_PROGRAM_NAME_HAWKEYE = "geolocate_hawkeye"; // static public FileInfo getOFileInfo(FileInfo fileInfo) { // return new FileInfo(fileInfo.getFile().getParent(), getOFile(fileInfo).getAbsolutePath(), false); // } // // static public FileInfo getAquariusOFileInfo(FileInfo fileInfo, String suite) { // return new FileInfo(fileInfo.getFile().getParent(), getAquariusOFile(fileInfo, suite).getAbsolutePath(), false); // } static public File getAquariusOFile(FileInfo iFileInfo, String suite) { if (iFileInfo == null || iFileInfo.getFile() == null || iFileInfo.getFile().getAbsolutePath() == null || iFileInfo.getFile().getAbsolutePath().length() == 0) { return null; } File oFile = getL2genOfile(iFileInfo.getFile()); // add on the suite StringBuilder ofile = new StringBuilder(oFile.getAbsolutePath()); ofile.append("_").append(suite); oFile = new File(ofile.toString()); return oFile; } static public File getOFile(FileInfo fileInfo) { if (fileInfo == null) { return null; } if (fileInfo.getFile().getAbsolutePath().length() == 0) { return null; } File oFile; if (fileInfo.isMissionId(MissionInfo.Id.VIIRSN) || fileInfo.isMissionId(MissionInfo.Id.VIIRSJ1) || fileInfo.isMissionId(MissionInfo.Id.VIIRSJ2)) { oFile = getViirsOfilename(fileInfo.getFile()); } else { if (fileInfo.getTypeId() == FileTypeInfo.Id.L3BIN) { oFile = getL3genOfile(fileInfo.getFile()); } else { oFile = getL2genOfile(fileInfo.getFile()); } } return oFile; } /** * This program is deprecated as of 9/18/2023 * @param fileInfo * @param ocssw * @return */ static public FileInfo getGeoFileInfo(FileInfo fileInfo, OCSSW ocssw) { if (ocssw instanceof OCSSWRemote) { return getGeoFileInfoNew(fileInfo, ocssw); } if (fileInfo == null) { return null; } File geoFile = getGeoFile(fileInfo, ocssw); if (geoFile == null) { return null; } return new FileInfo(fileInfo.getFile().getParent(), getGeoFile(fileInfo, ocssw).getAbsolutePath(), false, ocssw); } static public FileInfo getGeoFileInfoNew(FileInfo iFileInfo, OCSSW ocssw) { String geoProgramName = new String(); if (iFileInfo.isMissionId(MissionInfo.Id.MODISA) || iFileInfo.isMissionId(MissionInfo.Id.MODIST)) { geoProgramName = GEO_LOCATE_PROGRAM_NAME_MODIS; } else if (iFileInfo.isMissionId(MissionInfo.Id.VIIRSJ1) || iFileInfo.isMissionId(MissionInfo.Id.VIIRSJ2) || iFileInfo.isMissionId(MissionInfo.Id.VIIRSN)) { geoProgramName = GEO_LOCATE_PROGRAM_NAME_VIIRS; ; } else if (iFileInfo.isMissionId(MissionInfo.Id.HAWKEYE)) { geoProgramName = GEO_LOCATE_PROGRAM_NAME_HAWKEYE; } File geoFile = new File(ocssw.getOfileName(iFileInfo.getFile().getAbsolutePath(), geoProgramName)); if (geoFile == null) { return null; } else { return new FileInfo(iFileInfo.getFile().getParent(), geoFile.getAbsolutePath(), false, ocssw); } } static public File getGeoFile(FileInfo iFileInfo, OCSSW ocssw) { if (iFileInfo == null) { return null; } if (iFileInfo.getFile().getAbsolutePath().length() == 0) { return null; } String VIIRS_IFILE_PREFIX = "SVM01"; StringBuilder geofileDirectory = new StringBuilder(iFileInfo.getFile().getParent() + File.separator); StringBuilder geofileBasename = new StringBuilder(); StringBuilder geofile = new StringBuilder(); File geoFile = null; if ((iFileInfo.isMissionId(MissionInfo.Id.VIIRSN) || iFileInfo.isMissionId(MissionInfo.Id.VIIRSJ1) || iFileInfo.isMissionId(MissionInfo.Id.VIIRSJ2)) && iFileInfo.isTypeId(FileTypeInfo.Id.SDR)) { String VIIRS_GEOFILE_PREFIX = "GMTCO"; geofileBasename.append(VIIRS_GEOFILE_PREFIX); geofileBasename.append(iFileInfo.getFile().getName().substring(VIIRS_IFILE_PREFIX.length())); geofile.append(geofileDirectory.toString() + geofileBasename.toString()); File possibleGeoFile = new File(geofile.toString()); if (possibleGeoFile.exists()) { geoFile = possibleGeoFile; } } else { ArrayList<File> possibleGeoFiles = new ArrayList<File>(); if (iFileInfo.isMissionId(MissionInfo.Id.MODISA) || iFileInfo.isMissionId(MissionInfo.Id.MODIST)) { String tmpOFile = ocssw.getOfileName(iFileInfo.getFile().getAbsolutePath(), "modis_GEO"); tmpOFile = tmpOFile.lastIndexOf(File.separator) != -1 ? tmpOFile.substring(tmpOFile.lastIndexOf(File.separator) + 1) : tmpOFile; StringBuilder possibleNewGeofile = new StringBuilder(geofileDirectory + tmpOFile); possibleGeoFiles.add(new File(possibleNewGeofile.toString())); } else if (iFileInfo.isMissionId(MissionInfo.Id.VIIRSJ1) || iFileInfo.isMissionId(MissionInfo.Id.VIIRSJ2) || iFileInfo.isMissionId(MissionInfo.Id.VIIRSN)) { String tmpOFile = ocssw.getOfileName(iFileInfo.getFile().getAbsolutePath(), "geolocate_viirs"); StringBuilder possibleNewGeofile = new StringBuilder(geofileDirectory + tmpOFile); possibleGeoFiles.add(new File(possibleNewGeofile.toString())); } else if (iFileInfo.isMissionId(MissionInfo.Id.HAWKEYE)) { String tmpOFile = ocssw.getOfileName(iFileInfo.getFile().getAbsolutePath(), "geolocate_hawkeye"); StringBuilder possibleNewGeofile = new StringBuilder(geofileDirectory + tmpOFile); possibleGeoFiles.add(new File(possibleNewGeofile.toString())); } String STRING_TO_BE_REPLACED[] = {"L1A_LAC", "L1B_LAC", "L1A.LAC", "L1B.LAC", "L1A_SNPP", "L1B-M_SNPP", "L1A_JPSS1", "L1B-M_JPSS1", "L1A", "L1B", "ifile"}; String STRING_TO_INSERT[] = {"GEO", "geo", "GEO-M_SNPP", "GEO-M_JPSS1", "geofile"}; /** * replace last occurrence of instance of STRING_TO_BE_REPLACED[] */ for (String string_to_be_replaced : STRING_TO_BE_REPLACED) { if (iFileInfo.getFile().getName().contains(string_to_be_replaced)) { int index = iFileInfo.getFile().getName().lastIndexOf(string_to_be_replaced); String start = iFileInfo.getFile().getName().substring(0, index); String end = iFileInfo.getFile().getName().substring((index + string_to_be_replaced.length()), iFileInfo.getFile().getName().length()); for (String string_to_insert : STRING_TO_INSERT) { StringBuilder possibleGeofile = new StringBuilder(geofileDirectory + start + string_to_insert + end); possibleGeoFiles.add(new File(possibleGeofile.toString())); } break; } } for (String string_to_insert : STRING_TO_INSERT) { StringBuilder possibleGeofile = new StringBuilder(geofileDirectory + iFileInfo.getFile().getName() + "." + string_to_insert); possibleGeoFiles.add(new File(possibleGeofile.toString())); } for (File possibleGeoFile : possibleGeoFiles) { if (possibleGeoFile.exists()) { geoFile = possibleGeoFile; break; } } if (geoFile == null) { if (iFileInfo.isGeofileRequired() && iFileInfo.getFileTypeName().contains("L1")) { if (possibleGeoFiles.size() > 0) { geoFile = possibleGeoFiles.get(0); } else { geoFile = new File("YourGeoFilename.GEO"); } } } } return geoFile; } static private File getViirsOfilename(File iFile) { if (iFile == null || iFile.getAbsoluteFile().length() == 0) { return null; } StringBuilder ofile = new StringBuilder(iFile.getParent() + File.separator); String yearString = iFile.getName().substring(11, 15); String monthString = iFile.getName().substring(15, 17); String dayOfMonthString = iFile.getName().substring(17, 19); String formattedDateString = getFormattedDateString(yearString, monthString, dayOfMonthString); String timeString = iFile.getName().substring(21, 27); ofile.append("V"); ofile.append(formattedDateString); ofile.append(timeString); ofile.append("."); ofile.append("L2_NPP"); return new File(ofile.toString()); } static private File getL2genOfile(File iFile) { if (iFile == null || iFile.getAbsoluteFile().length() == 0) { return null; } String OFILE_REPLACEMENT_STRING = "L2"; String IFILE_STRING_TO_BE_REPLACED[] = {"L1A", "L1B"}; StringBuilder ofileBasename = new StringBuilder(); /** * replace last occurrence of instance of IFILE_STRING_TO_BE_REPLACED[] */ for (String string_to_be_replaced : IFILE_STRING_TO_BE_REPLACED) { if (iFile.getName().toUpperCase().contains(string_to_be_replaced)) { int index = iFile.getName().toUpperCase().lastIndexOf(string_to_be_replaced); ofileBasename.append(iFile.getName().substring(0, index)); ofileBasename.append(OFILE_REPLACEMENT_STRING); ofileBasename.append(iFile.getName().substring((index + string_to_be_replaced.length()), iFile.getName().length())); break; } } /** * Not found so append it */ if (ofileBasename.toString().length() == 0) { ofileBasename.append(iFile.getName()); ofileBasename.append("." + OFILE_REPLACEMENT_STRING); } StringBuilder ofile = new StringBuilder(iFile.getParent() + File.separator + ofileBasename.toString()); return new File(ofile.toString()); } static private File getL3genOfile(File iFile) { if (iFile == null || iFile.getAbsoluteFile().length() == 0) { return null; } StringBuilder ofileBasename = new StringBuilder(); if (ofileBasename.toString().length() == 0) { ofileBasename.append(iFile.getName()); ofileBasename.append(".out"); } StringBuilder ofile = new StringBuilder(iFile.getParent() + File.separator + ofileBasename.toString()); return new File(ofile.toString()); } /** * Given standard Gregorian date return day of year (Jan 1=1, Feb 1=32, etc) * * @param year * @param month 1-based Jan=1, etc. * @param dayOfMonth * @return */ static private int getDayOfYear(int year, int month, int dayOfMonth) { GregorianCalendar gc = new GregorianCalendar(year, month - 1, dayOfMonth); return gc.get(GregorianCalendar.DAY_OF_YEAR); } static private String getFormattedDateString(String yearString, String monthString, String dayOfMonthString) { int year = Integer.parseInt(yearString); int month = Integer.parseInt(monthString); int dayOfMonth = Integer.parseInt(dayOfMonthString); return getFormattedDateString(year, month, dayOfMonth); } static private String getFormattedDateString(int year, int month, int dayOfMonth) { StringBuilder formattedDateString = new StringBuilder(Integer.toString(year)); int dayOfYear = getDayOfYear(year, month, dayOfMonth); StringBuilder dayOfYearString = new StringBuilder(Integer.toString(dayOfYear)); while (dayOfYearString.toString().length() < 3) { dayOfYearString.insert(0, "0"); } formattedDateString.append(dayOfYearString); return formattedDateString.toString(); } }
13,157
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
StatusInfo.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/StatusInfo.java
package gov.nasa.gsfc.seadas.processing.common; /** * Created with IntelliJ IDEA. * User: knowles * Date: 4/12/13 * Time: 2:27 PM * To change this template use File | Settings | File Templates. */ public class StatusInfo { public static enum Id { SUCCEED, FAIL, WARN } private Id status; private String message; public StatusInfo() { } public StatusInfo(Id id) { this.status = id; } public Id getStatus() { return status; } public void setStatus(Id status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
745
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
ExtractorUI.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/ExtractorUI.java
package gov.nasa.gsfc.seadas.processing.common; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import org.esa.snap.rcp.util.Dialogs; import javax.swing.*; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.util.HashMap; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 5/3/12 * Time: 3:05 PM * To change this template use File | Settings | File Templates. */ public class ExtractorUI extends ProgramUIFactory { public static final String START_LINE_PARAM_NAME = "sline"; public static final String END_LINE_PARAM_NAME = "eline"; public static final String START_PIXEL_PARAM_NAME = "spixl"; public static final String END_PIXEL_PARAM_NAME = "epixl"; public static final String GEO_LOCATE_PROGRAM_NAME_VIIRS = "geolocate_viirs"; public static final String GEO_LOCATE_PROGRAM_NAME_MODIS = "modis_GEO"; private ProcessorModel lonlat2pixline; private JPanel pixelPanel; private JPanel newsPanel; private JPanel paramPanel; private ParamUIFactory paramUIFactory; private boolean initiliazed = false; HashMap<String, Boolean> paramCounter; //OCSSW ocssw; public ExtractorUI(String programName, String xmlFileName, OCSSW ocssw) { super(programName, xmlFileName, ocssw); paramCounter = new HashMap<String, Boolean>(); initiliazed = true; //this.ocssw = ocssw; } private void initLonLatProcessor() { lonlat2pixline = ProcessorModel.valueOf("lonlat2pixline", "lonlat2pixline.xml", ocssw); lonlat2pixline.addPropertyChangeListener(lonlat2pixline.getAllparamInitializedPropertyName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (processorModel.getProgramName().equals(("l2extract"))) { //"l2extract" takes option "spix" and "epix" processorModel.updateParamInfo("spix", lonlat2pixline.getParamValue(START_PIXEL_PARAM_NAME)); processorModel.updateParamInfo("epix", lonlat2pixline.getParamValue(END_PIXEL_PARAM_NAME)); } else { processorModel.updateParamInfo(START_PIXEL_PARAM_NAME, lonlat2pixline.getParamValue(START_PIXEL_PARAM_NAME)); processorModel.updateParamInfo(END_PIXEL_PARAM_NAME, lonlat2pixline.getParamValue(END_PIXEL_PARAM_NAME)); } processorModel.updateParamInfo(START_LINE_PARAM_NAME, lonlat2pixline.getParamValue(START_LINE_PARAM_NAME)); processorModel.updateParamInfo(END_LINE_PARAM_NAME, lonlat2pixline.getParamValue(END_LINE_PARAM_NAME)); } }); processorModel.addPropertyChangeListener(processorModel.getPrimaryInputFileOptionName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (processorModel.getProgramName() != null) { lonlat2pixline.updateIFileInfo(getLonLattoPixelsIFileName(processorModel.getParamInfo(processorModel.getPrimaryInputFileOptionName()).getValue().trim(), processorModel.getProgramName())); } } }); if (processorModel.getParamInfo(processorModel.getPrimaryInputFileOptionName()).getValue().trim().length() > 0) { lonlat2pixline.updateIFileInfo(processorModel.getParamInfo(processorModel.getPrimaryInputFileOptionName()).getValue().trim()); } } private void initStaticPanels() { newsPanel = new ParamUIFactory(lonlat2pixline).createParamPanel(lonlat2pixline); newsPanel.setBorder(BorderFactory.createTitledBorder("Lon/Lat")); newsPanel.setName("newsPanel"); } @Override public JPanel getParamPanel() { if (!initiliazed) { initLonLatProcessor(); initStaticPanels(); } SeadasFileUtils.debug("updating ofile change listener ... processorModel " + processorModel.getPrimaryOutputFileOptionName()); paramUIFactory = new ExtractorParamUI(processorModel); pixelPanel = paramUIFactory.createParamPanel(processorModel); pixelPanel.setBorder(BorderFactory.createTitledBorder("Pixels")); pixelPanel.setName("pixelPanel"); paramPanel = new JPanel(new GridBagLayout()); paramPanel.setBorder(BorderFactory.createTitledBorder("Parameters")); paramPanel.setPreferredSize(new Dimension(700, 400)); paramPanel.add(newsPanel, new GridBagConstraintsCustom(0, 0, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE)); paramPanel.add(Box.createRigidArea(new Dimension(100, 50)), new GridBagConstraintsCustom(0, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE)); paramPanel.add(pixelPanel, new GridBagConstraintsCustom(0, 2, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE)); return paramPanel; } private String getLonLattoPixelsIFileName(String ifileName, String programName) { try { String geoFileName = null; File iFile = new File(ifileName); FileInfo iFileInfo = new FileInfo(iFile.getParent(), iFile.getName(), ocssw); FileInfo geoFileInfo = FilenamePatterns.getGeoFileInfo(iFileInfo, ocssw); if (geoFileInfo != null && geoFileInfo.getFile().exists()) { geoFileName = geoFileInfo.getFile().getAbsolutePath(); return geoFileName; } if (programName.contains("l1aextract_modis")) { String suffix = ".GEO"; geoFileName = (ifileName.substring(0, ifileName.lastIndexOf("."))).concat(suffix); } else if (programName.contains("l1aextract_viirs")) { String suffix = null; if (ifileName.contains("JPSS1")) { suffix = ".GEO-M_JPSS1"; } else if (ifileName.contains("SNPP")) { suffix = ".GEO-M_SNPP"; } if (suffix != null) { geoFileName = (ifileName.substring(0, ifileName.lastIndexOf(".L"))).concat(suffix); } } if (geoFileName != null) { if (new File(geoFileName).exists()) { return geoFileName; } else { geoFileName = geoFileName + ".nc"; if (new File(geoFileName).exists()) { return geoFileName; } else { Dialogs.showError(ifileName + " requires a GEO file to be extracted. " + geoFileName + " does not exist."); return null; } } } } catch (Exception e) { } return ifileName; } }
7,048
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OptionalFileSelector.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/OptionalFileSelector.java
package gov.nasa.gsfc.seadas.processing.common; import javax.swing.*; 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; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 5/9/12 * Time: 9:42 AM * To change this template use File | Settings | File Templates. */ public class OptionalFileSelector extends JPanel { private JFileChooser fileChooser = new JFileChooser(); private String currentFileName; private JTextField jTextField; //private SwingPropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this); public OptionalFileSelector(String optionalFileName) { createFileChooserPanel(optionalFileName); // this.pm = processorModel; } protected File getFileName(File inputFile, String extension) { String fileName = inputFile.getName(); fileName = fileName.substring(0, fileName.indexOf(".")).concat(extension); //System.out.println(" new file Name = " + fileName); return new File(inputFile.getParentFile(), fileName); } protected void setFileName(File optionalFile) { currentFileName = optionalFile.getName(); jTextField.setText(currentFileName); } protected void createFileChooserPanel(String optionName) { //final JLabel jLabel = new JLabel(L2genData.GEOFILE); final JLabel jLabel = new JLabel(optionName); final JButton jButton = new JButton("..."); jButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { fileChooserHandler(fileChooser); } }); jTextField = new JTextField("123456789 123456789 12345"); jTextField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { currentFileName = jTextField.getText(); } }); jTextField.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { currentFileName = jTextField.getText(); } }); jTextField.setPreferredSize(jTextField.getPreferredSize()); jTextField.setMinimumSize(jTextField.getPreferredSize()); jTextField.setMaximumSize(jTextField.getPreferredSize()); jTextField.setText(""); jButton.setMargin(new Insets(0, -7, 0, -7)); final Dimension size = new Dimension(jButton.getPreferredSize().width, jTextField.getPreferredSize().height); jButton.setPreferredSize(size); jButton.setMinimumSize(size); jButton.setMaximumSize(size); add(jLabel, new GridBagConstraintsCustom(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2)); add(jTextField, new GridBagConstraintsCustom(1, 0, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, 2)); add(jButton, new GridBagConstraintsCustom(2, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2)); } private void fileChooserHandler(JFileChooser jFileChooser) { int result = jFileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { //pm.updateParamInfo(L2genData.GEOFILE, jFileChooser.getSelectedFile().toString()); jTextField.setText(jFileChooser.getSelectedFile().toString()); } } public String getCurrentFileName() { return currentFileName; } protected JTextField getFileNameField(){ return jTextField; } // public void addPropertyChangeListener(String propertyName, PropertyChangeListener l) { // //propertyChangeSupport.addPropertyChangeListener(l); // //propertyChangeSupport.addPropertyChangeListener(propertyName, l); // addPropertyChangeListener(propertyName, l); // } // // public void removePropertyChangeListener(PropertyChangeListener l) { // propertyChangeSupport.removePropertyChangeListener(l); // } }
4,282
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
MissionInfo.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/MissionInfo.java
package gov.nasa.gsfc.seadas.processing.common; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo; import java.io.File; import java.util.HashMap; import java.util.Iterator; /** * Created by IntelliJ IDEA. User: knowles Date: 5/16/12 Time: 3:13 PM To change * this template use File | Settings | File Templates. * @author aabduraz */ public class MissionInfo { public static enum Id { AQUARIUS, AVHRR, CZCS, HAWKEYE, HICO, GOCI, MERIS, MSIS2A, MSIS2B, OCI, MODISA, MODIST, MOS, OCTS, OSMI, SEAWIFS, VIIRSN, VIIRSJ1, VIIRSJ2, OCM1, OCM2, OLIL8, OLIL9, OLCIS3A, OLCIS3B, SGLI, UNKNOWN } public final static String[] SEAWIFS_NAMES = {"SeaWiFS"}; public final static String SEAWIFS_DIRECTORY = "seawifs"; public final static String[] MODISA_NAMES = {"MODIS Aqua", "Aqua", "MODISA"}; public final static String MODISA_DIRECTORY = "modis/aqua"; public final static String[] MODIST_NAMES = {"MODIS Terra", "TERRA", "MODIST"}; public final static String MODIST_DIRECTORY = "modis/terra"; public final static String[] VIIRSN_NAMES = {"VIIRS NPP", "VIIRSN", "VIIRS"}; public final static String VIIRSN_DIRECTORY = "viirs/npp"; public final static String[] VIIRSJ1_NAMES = {"VIIRS J1", "VIIRSJ1"}; public final static String VIIRSJ1_DIRECTORY = "viirs/j1"; public final static String[] VIIRSJ2_NAMES = {"VIIRS J2", "VIIRSJ2"}; public final static String VIIRSJ2_DIRECTORY = "viirs/j2"; public final static String[] MERIS_NAMES = {"MERIS"}; public final static String MERIS_DIRECTORY = "meris"; public final static String[] MSIS2A_NAMES = {"MSIS2A", "MSI S2A"}; public final static String MSIS2A_DIRECTORY = "msi/s2a"; public final static String[] MSIS2B_NAMES = {"MSIS2B", "MSI S2B"}; public final static String MSIS2B_DIRECTORY = "msi/s2b"; public final static String[] OCI_NAMES = {"OCI"}; public final static String OCI_DIRECTORY = "oci"; public final static String[] CZCS_NAMES = {"CZCS"}; public final static String CZCS_DIRECTORY = "czcs"; public final static String[] AQUARIUS_NAMES = {"AQUARIUS"}; public final static String AQUARIUS_DIRECTORY = "aquarius"; public final static String[] AVHRR_NAMES = {"AVHRR"}; public final static String AVHRR_DIRECTORY = "avhrr"; public final static String[] OCTS_NAMES = {"OCTS"}; public final static String OCTS_DIRECTORY = "octs"; public final static String[] OSMI_NAMES = {"OSMI"}; public final static String OSMI_DIRECTORY = "osmi"; public final static String[] MOS_NAMES = {"MOS"}; public final static String MOS_DIRECTORY = "mos"; public final static String[] OCM1_NAMES = {"OCM1"}; public final static String OCM1_DIRECTORY = "ocm1"; public final static String[] OCM2_NAMES = {"OCM2"}; public final static String OCM2_DIRECTORY = "ocm2"; public final static String[] HAWKEYE_NAMES = {"HAWKEYE"}; public final static String HAWKEYE_DIRECTORY = "hawkeye"; public final static String[] HICO_NAMES = {"HICO"}; public final static String HICO_DIRECTORY = "hico"; public final static String[] GOCI_NAMES = {"GOCI"}; public final static String GOCI_DIRECTORY = "goci"; public final static String[] OLIL8_NAMES = {"OLIL8", "OLI L8"}; public final static String OLIL8_DIRECTORY = "oli/l8"; public final static String[] OLIL9_NAMES = {"OLIL9", "OLI L9"}; public final static String OLIL9_DIRECTORY = "oli/l9"; public final static String[] OLCIS3A_NAMES = {"OLCIS3A", "OLCI S3A"}; public final static String OLCIS3A_DIRECTORY = "olci/s3a"; public final static String[] OLCIS3B_NAMES = {"OLCIS3B", "OLCI S3B"}; public final static String OLCIS3B_DIRECTORY = "olci/s3b"; public final static String[] SGLI_NAMES = {"SGLI"}; public final static String SGLI_DIRECTORY = "sgli"; private final HashMap<Id, String[]> names = new HashMap<>(); private final HashMap<Id, String> directories = new HashMap<>(); private Id id; private boolean geofileRequired; private File directory; private File subsensorDirectory; public MissionInfo() { initDirectoriesHashMap(); initNamesHashMap(); } public MissionInfo(Id id) { this(); setId(id); } public MissionInfo(String name) { this(); setName(name); } public void clear() { id = null; geofileRequired = false; directory = null; subsensorDirectory = null; } private void initDirectoriesHashMap() { directories.put(Id.SEAWIFS, SEAWIFS_DIRECTORY); directories.put(Id.MODISA, MODISA_DIRECTORY); directories.put(Id.MODIST, MODIST_DIRECTORY); directories.put(Id.VIIRSN, VIIRSN_DIRECTORY); directories.put(Id.VIIRSJ1, VIIRSJ1_DIRECTORY); directories.put(Id.VIIRSJ2, VIIRSJ2_DIRECTORY); directories.put(Id.MERIS, MERIS_DIRECTORY); directories.put(Id.MSIS2A, MSIS2A_DIRECTORY); directories.put(Id.MSIS2B, MSIS2B_DIRECTORY); directories.put(Id.OCI, OCI_DIRECTORY); directories.put(Id.CZCS, CZCS_DIRECTORY); directories.put(Id.AQUARIUS, AQUARIUS_DIRECTORY); directories.put(Id.AVHRR, AVHRR_DIRECTORY); directories.put(Id.OCTS, OCTS_DIRECTORY); directories.put(Id.OSMI, OSMI_DIRECTORY); directories.put(Id.MOS, MOS_DIRECTORY); directories.put(Id.OCM1, OCM1_DIRECTORY); directories.put(Id.OCM2, OCM2_DIRECTORY); directories.put(Id.HICO, HICO_DIRECTORY); directories.put(Id.GOCI, GOCI_DIRECTORY); directories.put(Id.OLIL8, OLIL8_DIRECTORY); directories.put(Id.OLIL9, OLIL9_DIRECTORY); directories.put(Id.OLCIS3A, OLCIS3A_DIRECTORY); directories.put(Id.OLCIS3B, OLCIS3B_DIRECTORY); directories.put(Id.SGLI, SGLI_DIRECTORY); directories.put(Id.HAWKEYE, HAWKEYE_DIRECTORY); } private void initNamesHashMap() { names.put(Id.SEAWIFS, SEAWIFS_NAMES); names.put(Id.MODISA, MODISA_NAMES); names.put(Id.MODIST, MODIST_NAMES); names.put(Id.VIIRSN, VIIRSN_NAMES); names.put(Id.VIIRSJ1, VIIRSJ1_NAMES); names.put(Id.VIIRSJ2, VIIRSJ2_NAMES); names.put(Id.MERIS, MERIS_NAMES); names.put(Id.MSIS2A, MSIS2A_NAMES); names.put(Id.MSIS2B, MSIS2B_NAMES); names.put(Id.OCI, OCI_NAMES); names.put(Id.CZCS, CZCS_NAMES); names.put(Id.AQUARIUS, AQUARIUS_NAMES); names.put(Id.AVHRR, AVHRR_NAMES); names.put(Id.OCTS, OCTS_NAMES); names.put(Id.OSMI, OSMI_NAMES); names.put(Id.MOS, MOS_NAMES); names.put(Id.OCM1, OCM1_NAMES); names.put(Id.OCM2, OCM2_NAMES); names.put(Id.HICO, HICO_NAMES); names.put(Id.GOCI, GOCI_NAMES); names.put(Id.OLIL8, OLIL8_NAMES); names.put(Id.OLIL9, OLIL9_NAMES); names.put(Id.OLCIS3A, OLCIS3A_NAMES); names.put(Id.OLCIS3B, OLCIS3B_NAMES); names.put(Id.SGLI, SGLI_NAMES); names.put(Id.HAWKEYE, HAWKEYE_NAMES); } public Id getId() { return id; } public void setId(Id id) { clear(); this.id = id; if (isSupported()) { setRequiresGeofile(); setMissionDirectoryName(); } } public boolean isId(Id id) { if (id == getId()) { return true; } else { return false; } } public void setName(String nameString) { if (nameString == null) { setId(null); return; } Iterator itr = names.keySet().iterator(); while (itr.hasNext()) { Object key = itr.next(); for (String name : names.get(key)) { if (name.toLowerCase().equals(nameString.toLowerCase())) { setId((Id) key); return; } } } setId(Id.UNKNOWN); return; } public String getName() { if (id == null) { return null; } if (names.containsKey(id)) { return names.get(id)[0]; } else { return null; } } private void setRequiresGeofile() { if (id == null) { return; } if (isId(Id.MODISA) || isId(Id.MODIST) || isId(Id.VIIRSN) || isId(Id.VIIRSJ1) || isId(Id.VIIRSJ2) || isId(Id.HAWKEYE)) { setGeofileRequired(true); } else { setGeofileRequired(false); } } public boolean isGeofileRequired() { return geofileRequired; } private void setGeofileRequired(boolean geofileRequired) { this.geofileRequired = geofileRequired; } private void setMissionDirectoryName() { if (directories.containsKey(id)) { String missionPiece = directories.get(id); String[] words = missionPiece.split("/"); try { if(words.length == 2) { setDirectory(new File(OCSSWInfo.getInstance().getOcsswDataDirPath(), words[0])); setSubsensorDirectory(new File(OCSSWInfo.getInstance().getOcsswDataDirPath(), missionPiece)); return; } else { setDirectory(new File(OCSSWInfo.getInstance().getOcsswDataDirPath(), missionPiece)); setSubsensorDirectory(null); return; } } catch (Exception e) { } } setDirectory(null); setSubsensorDirectory(null); } public File getDirectory() { return directory; } private void setDirectory(File directory) { this.directory = directory; } public File getSubsensorDirectory() { return subsensorDirectory; } private void setSubsensorDirectory(File directory) { this.subsensorDirectory = directory; } public boolean isSupported() { if (id == null) { return false; } if(id == Id.UNKNOWN) { return false; } return true; } }
10,408
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSWInstallerFormLocal.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/OCSSWInstallerFormLocal.java
package gov.nasa.gsfc.seadas.processing.common; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo; import org.esa.snap.ui.AppContext; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo.OCSSW_SRC_DIR_NAME; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 1/20/15 * Time: 12:46 PM * To change this template use File | Settings | File Templates. */ public class OCSSWInstallerFormLocal extends OCSSWInstallerForm { public OCSSWInstallerFormLocal(AppContext appContext, String programName, String xmlFileName, OCSSW ocssw) { super(appContext, programName, xmlFileName, ocssw); } void updateMissionStatus() { missionDataStatus = new HashMap<String, Boolean>(); missionDataStatus.put("SEAWIFS", ocssw.isMissionDirExist("seawifs")); missionDataStatus.put("MODISA", ocssw.isMissionDirExist("modisa")); missionDataStatus.put("MODIST", ocssw.isMissionDirExist("modist")); missionDataStatus.put("VIIRSN", ocssw.isMissionDirExist("viirsn")); missionDataStatus.put("VIIRSJ1", ocssw.isMissionDirExist("viirsj1")); missionDataStatus.put("VIIRSJ2", ocssw.isMissionDirExist("viirsj2")); missionDataStatus.put("MERIS", ocssw.isMissionDirExist("meris")); missionDataStatus.put("MSIS2A", ocssw.isMissionDirExist("msis2a")); missionDataStatus.put("MSIS2B", ocssw.isMissionDirExist("msis2b")); missionDataStatus.put("OCI", ocssw.isMissionDirExist("oci")); missionDataStatus.put("CZCS", ocssw.isMissionDirExist("czcs")); // missionDataStatus.put("AQUARIUS", ocssw.isMissionDirExist("aquarius")); missionDataStatus.put("OCTS", ocssw.isMissionDirExist("octs")); missionDataStatus.put("OLIL8", ocssw.isMissionDirExist("olil8")); missionDataStatus.put("OLIL9", ocssw.isMissionDirExist("olil9")); missionDataStatus.put("OSMI", ocssw.isMissionDirExist("osmi")); missionDataStatus.put("MOS", ocssw.isMissionDirExist("mos")); missionDataStatus.put("OCM2", ocssw.isMissionDirExist("ocm2")); missionDataStatus.put("OCM1", ocssw.isMissionDirExist("ocm1")); missionDataStatus.put("OLCIS3A", ocssw.isMissionDirExist("olcis3a")); missionDataStatus.put("OLCIS3B", ocssw.isMissionDirExist("olcis3b")); missionDataStatus.put("AVHRR", ocssw.isMissionDirExist("avhrr")); missionDataStatus.put("HICO", ocssw.isMissionDirExist("hico")); missionDataStatus.put("GOCI", ocssw.isMissionDirExist("goci")); missionDataStatus.put("HAWKEYE", ocssw.isMissionDirExist("HAWKEYE")); missionDataStatus.put("SGLI", ocssw.isMissionDirExist("SGLI")); } void init(){ updateMissionStatus(); } void updateMissionValues() { for (Map.Entry<String, Boolean> entry : missionDataStatus.entrySet()) { String missionName = entry.getKey(); Boolean missionStatus = entry.getValue(); if (missionStatus) { processorModel.setParamValue("--" + missionName.toLowerCase(), "1"); } else { processorModel.setParamValue("--" + missionName.toLowerCase(), "0"); } } if (new File(OCSSWInfo.getInstance().getOcsswRoot(), OCSSW_SRC_DIR_NAME).exists()) { processorModel.setParamValue("--src", "1"); } if (new File(OCSSWInfo.getInstance().getOcsswRoot(), "share/viirs/dem").exists()) { processorModel.setParamValue("--viirsdem", "1"); } } }
3,835
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
LonLat2PixLineUI.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/LonLat2PixLineUI.java
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import gov.nasa.gsfc.seadas.processing.core.ParamInfo; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import javax.swing.*; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder; import javax.swing.text.NumberFormatter; import java.awt.*; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Iterator; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 5/3/12 * Time: 1:11 PM * To change this template use File | Settings | File Templates. */ public class LonLat2PixLineUI { private String north; private ProcessorModel pm; ArrayList paramList; public LonLat2PixLineUI(ProcessorModel pm) { north = "north"; this.pm = pm; paramList = pm.getProgramParamList(); } private void createUI() { JPanel lonlatPanel = new JPanel(); TableLayout lonlatLayout = new TableLayout(2); lonlatPanel.setLayout(lonlatLayout); lonlatPanel.setBorder(new TitledBorder(new EtchedBorder(), "")); Iterator itr = paramList.iterator(); while (itr.hasNext()) { final ParamInfo pi = (ParamInfo) itr.next(); lonlatPanel.add(makeOptionField(pi)); } } private JPanel makeOptionField(ParamInfo pi) { final JPanel optionPanel = new JPanel(); optionPanel.setLayout(new BoxLayout(optionPanel, BoxLayout.Y_AXIS)); optionPanel.setAlignmentX(Component.LEFT_ALIGNMENT); optionPanel.add(new JLabel(pi.getName())); final PropertyContainer vc = new PropertyContainer(); vc.addProperty(Property.create(pi.getName(), pi.getValue())); vc.getDescriptor(pi.getName()).setDisplayName(pi.getName()); final BindingContext ctx = new BindingContext(vc); final NumberFormatter formatter = new NumberFormatter(new DecimalFormat("#00.00#")); formatter.setValueClass(Double.class); // to ensure that double values are returned final JFormattedTextField field = new JFormattedTextField(formatter); field.setColumns(4); field.setHorizontalAlignment(JFormattedTextField.LEFT); field.setFocusLostBehavior(0); ctx.bind(pi.getName(), field); optionPanel.add(field); return optionPanel; } }
2,538
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SeadasGuiUtils.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/SeadasGuiUtils.java
package gov.nasa.gsfc.seadas.processing.common; import javax.swing.*; import java.awt.*; import java.io.*; import java.util.ArrayList; /** * A ... * * @author Danny Knowles * @since SeaDAS 7.0 */ public class SeadasGuiUtils { public SeadasGuiUtils() { } public static String importFile(JFileChooser jFileChooser) { StringBuilder stringBuilder; int result = jFileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { final ArrayList<String> parfileTextLines = myReadDataFile(jFileChooser.getSelectedFile().toString()); stringBuilder = new StringBuilder(); for (String currLine : parfileTextLines) { stringBuilder.append(currLine); stringBuilder.append("\n"); } return stringBuilder.toString(); } return null; } public static void exportFile(JFileChooser fileChooser, String contents) { int result = fileChooser.showSaveDialog(null); if (result == JFileChooser.APPROVE_OPTION) { try { // Create file FileWriter fstream = new FileWriter(fileChooser.getSelectedFile().toString()); BufferedWriter out = new BufferedWriter(fstream); out.write(contents); //Close the output stream out.close(); } catch (Exception e) {//Catch exception if any System.err.println("Error: " + e.getMessage()); } } } public static ArrayList<String> myReadDataFile (String fileName) { String lineData; ArrayList<String> fileContents = new ArrayList<String>(); BufferedReader moFile = null; try { moFile = new BufferedReader(new FileReader(new File(fileName))); while ((lineData = moFile.readLine()) != null) { fileContents.add(lineData); } } catch (IOException e) { ; } finally { try { moFile.close(); } catch (Exception e) { //Ignore } } return fileContents; } public static JPanel addWrapperPanel(Object myMainPanel) { JPanel myWrapperPanel = new JPanel(); myWrapperPanel.setLayout(new GridBagLayout()); final GridBagConstraints c; c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.fill = GridBagConstraints.NONE; c.weightx = 1; c.weighty = 1; myWrapperPanel.add((Component) myMainPanel, c); return myWrapperPanel; } public static JPanel addPaddedWrapperPanel(Object myMainPanel, int pad, int anchor) { JPanel myWrapperPanel = new JPanel(); // myWrapperPanel.setBorder(BorderFactory.createTitledBorder("")); myWrapperPanel.setLayout(new GridBagLayout()); final GridBagConstraints c; c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.anchor = anchor; c.insets = new Insets(pad, pad, pad, pad); c.fill = GridBagConstraints.NONE; c.weightx = 1; c.weighty = 1; myWrapperPanel.add((Component) myMainPanel, c); return myWrapperPanel; } public static JPanel addPaddedWrapperPanel(Object myMainPanel, int pad, int anchor, int fill) { JPanel myWrapperPanel = new JPanel(); myWrapperPanel.setBorder(BorderFactory.createTitledBorder("")); myWrapperPanel.setLayout(new GridBagLayout()); final GridBagConstraints c; c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.anchor = anchor; c.insets = new Insets(pad, pad, pad, pad); c.fill = fill; c.weightx = 1; c.weighty = 1; myWrapperPanel.add((Component) myMainPanel, c); return myWrapperPanel; } public static void padPanel(Object innerPanel, JPanel outerPanel, int pad) { final GridBagConstraints c; c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.NORTHWEST; c.insets = new Insets(pad, pad, pad, pad); c.fill = GridBagConstraints.BOTH; c.weightx = 1; c.weighty = 1; outerPanel.add((Component) innerPanel, c); } public static JPanel addPaddedWrapperPanel(Object myMainPanel, int pad) { JPanel myWrapperPanel = new JPanel(); myWrapperPanel.setLayout(new GridBagLayout()); final GridBagConstraints c; c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.NORTHWEST; c.insets = new Insets(pad, pad, pad, pad); c.fill = GridBagConstraints.BOTH; c.weightx = 1; c.weighty = 1; myWrapperPanel.add((Component) myMainPanel, c); return myWrapperPanel; } }
5,024
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
ProgramUIFactory.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/ProgramUIFactory.java
package gov.nasa.gsfc.seadas.processing.common; 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.core.ProcessorTypeInfo; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSW; import gov.nasa.gsfc.seadas.processing.l2gen.userInterface.L2genPrimaryIOFilesSelector; import javax.swing.*; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.util.ArrayList; import java.util.Locale; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 6/6/12 * Time: 5:07 PM * To change this template use File | Settings | File Templates. */ public class ProgramUIFactory extends JPanel implements CloProgramUI { private L2genPrimaryIOFilesSelector ioFilesSelector; ProcessorModel processorModel; private ParFileUI parFileUI; JPanel paramPanel; OCSSW ocssw; public ProgramUIFactory(String programName, String xmlFileName, OCSSW ocssw) { this.ocssw = ocssw; processorModel = ProcessorModel.valueOf(programName, xmlFileName, ocssw); parFileUI = new ParFileUI(processorModel); ioFilesSelector = new L2genPrimaryIOFilesSelector(processorModel); createUserInterface(); } public ProcessorModel getProcessorModel() { return processorModel; } public File getSelectedSourceProduct() { return ioFilesSelector.getIfileSelector().getFileSelector().getSelectedFile(); } public boolean isOpenOutputInApp() { return parFileUI.isOpenOutputInApp(); } public String getParamString() { return processorModel.getParamList().getParamString(); } public void setParamString(String paramString) { processorModel.getParamList().setParamString(paramString); } protected void createUserInterface() { final JPanel ioPanel = ioFilesSelector.getjPanel(); processorModel.addPropertyChangeListener("geofile", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (!processorModel.hasGeoFile() && ioPanel.getComponentCount() > 1) { ioPanel.remove(1); } else { ioPanel.add(ioFilesSelector.getGeofileSelector().getJPanel(), new GridBagConstraintsCustom(0, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL), 1); Component[] c = ((JPanel) ioPanel.getComponent(1)).getComponents(); for (Component ci : c) { ci.setEnabled(true); } } ioPanel.repaint(); ioPanel.validate(); } }); int primaryOutputIndex = 2; if (!processorModel.hasGeoFile()) { ioPanel.remove(1); primaryOutputIndex--; } if (!processorModel.hasPrimaryOutputFile()) { ioPanel.remove(primaryOutputIndex); } ioPanel.repaint(); ioPanel.validate(); //update processor model param info if there is an open product. if (ioFilesSelector.getIfileSelector().getFileSelector().getSelectedFile() != null) { processorModel.updateIFileInfo(ioFilesSelector.getIfileSelector().getSelectedIFileName()); processorModel.updateParamValues(ioFilesSelector.getIfileSelector().getSelectedIFile()); } final JPanel parFilePanel = parFileUI.getParStringPanel(); paramPanel = getParamPanel(); ParamList paramList = processorModel.getParamList(); ArrayList<ParamInfo> paramInfos = paramList.getParamArray(); for (ParamInfo pi : paramInfos) { //when ifile or infile changes, the values of some parameters may change. //ofile and geofile should not affect the param values if (!(pi.getType().equals("ifile") || pi.getType().equals("infile") || pi.getType().equals("ofile") || pi.getType().equals("geofile"))) { processorModel.addPropertyChangeListener(pi.getName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { paramPanel = getParamPanel(); paramPanel.repaint(); paramPanel.validate(); remove(1); if( ! processorModel.getProgramName().toLowerCase(Locale.ROOT).equals(ProcessorTypeInfo.ProcessorID.GEOLOCATE_HAWKEYE.name().toLowerCase(Locale.ROOT)) ) { add(paramPanel, new GridBagConstraintsCustom(0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3)); } add(parFilePanel, new GridBagConstraintsCustom(0, 2, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3)); revalidate(); repaint(); } }); } } this.setLayout(new GridBagLayout()); add(ioPanel, new GridBagConstraintsCustom(0, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3)); if( ! processorModel.getProgramName().toLowerCase(Locale.ROOT).equals(ProcessorTypeInfo.ProcessorID.GEOLOCATE_HAWKEYE.name().toLowerCase(Locale.ROOT)) ) { add(paramPanel, new GridBagConstraintsCustom(0, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, 3)); } add(parFilePanel, new GridBagConstraintsCustom(0, 2, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 3)); setMinimumSize(getPreferredSize()); setMaximumSize(getPreferredSize()); } public JPanel getParamPanel() { return new ParamUIFactory(processorModel).createParamPanel(); } protected void disableJPanel(JPanel panel) { Component[] com = panel.getComponents(); for (int a = 0; a < com.length; a++) { com[a].setEnabled(false); } panel.repaint(); panel.validate(); } }
6,431
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
CallL3BinDumpAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/CallL3BinDumpAction.java
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.swing.TableLayout; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import gov.nasa.gsfc.seadas.processing.utilities.SheetCell; import gov.nasa.gsfc.seadas.processing.utilities.SpreadSheet; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.ModalDialog; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.StringTokenizer; import java.util.logging.Logger; /** * Created by IntelliJ IDEA. * @author Aynur Abdurazik (aabduraz) * Date: 4/29/14 * Time: 1:22 PM * To change this template use File | Settings | File Templates. */ public class CallL3BinDumpAction extends CallCloProgramAction { @Override void displayOutput(final ProcessorModel processorModel) { String output = processorModel.getExecutionLogMessage(); StringTokenizer st = new StringTokenizer(output, "\n"); int numRows = st.countTokens(); String line = st.nextToken(); StringTokenizer stLine = new StringTokenizer(line, " "); String prodName = null; boolean skipFirstLine = false; if (stLine.countTokens() < 14) { prodName = stLine.nextToken(); numRows--; skipFirstLine = true; } if (!skipFirstLine) { st = new StringTokenizer(output, "\n"); } final SheetCell[][] cells = new SheetCell[numRows][14]; int i = 0; while (st.hasMoreElements()) { line = st.nextToken(); stLine = new StringTokenizer(line, " "); int j = 0; while (stLine.hasMoreElements()) { cells[i][j] = new SheetCell(i, j, stLine.nextToken(), null); j++; } i++; } if (skipFirstLine) { cells[0][10] = new SheetCell(0, 10, prodName + " " + cells[0][10].getValue(), null); cells[0][11] = new SheetCell(0, 11, prodName + " " + cells[0][11].getValue(), null); } SpreadSheet sp = new SpreadSheet(cells); final JFrame frame = new JFrame("l3bindump Output"); JPanel content = new JPanel(new BorderLayout()); JButton save = new JButton("Save"); JButton cancel = new JButton("Cancel"); TableLayout buttonPanelLayout = new TableLayout(2); JPanel buttonPanel = new JPanel(buttonPanelLayout); /* * Allows the user to exit the application * from the window manager's dressing. */ frame.addWindowListener(new WindowAdapter() { // public void windowClosing(WindowEvent e) { // System.exit(0); // } }); sp.getScrollPane().getVerticalScrollBar().setAutoscrolls(true); content.add(sp.getScrollPane(), BorderLayout.NORTH); buttonPanel.add(save); buttonPanel.add(cancel); save.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { //To change body of implemented methods use File | Settings | File Templates. String outputFileName = processorModel.getParamValue(processorModel.getPrimaryInputFileOptionName()) + "_l3bindump_output.txt"; saveForSpreadsheet(outputFileName, cells); String message = "l3bindump output is saved in file \n" + outputFileName +"\n" + " in spreadsheet format."; final ModalDialog modalDialog = new ModalDialog(SnapApp.getDefault().getMainFrame(), "", message, ModalDialog.ID_OK, "test"); final int dialogResult = modalDialog.show(); if (dialogResult != ModalDialog.ID_OK) { } frame.setVisible(false); } }); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { //To change body of implemented methods use File | Settings | File Templates. frame.setVisible(false); } }); content.add(buttonPanel, BorderLayout.SOUTH); frame.getContentPane().add(content); frame.pack(); frame.setVisible(true); } private void saveForSpreadsheet(String outputFileName, SheetCell[][] cells) { String cell, all = new String(); for (int i = 0; i < cells.length; i++) { cell = new String(); for (int j = 0; j < cells[i].length; j++) { cell = cell + cells[i][j].getValue() + "\t"; } all = all + cell + "\n"; } try { final File excelFile = new File(outputFileName); FileWriter fileWriter = null; try { fileWriter = new FileWriter(excelFile); fileWriter.write(all); } finally { if (fileWriter != null) { fileWriter.close(); } } } catch (IOException e) { Logger.getGlobal().warning(outputFileName + " is not created. " + e.getMessage()); } } }
5,444
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
FileSelector.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/FileSelector.java
package gov.nasa.gsfc.seadas.processing.common; import gov.nasa.gsfc.seadas.processing.core.ParamInfo; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.SnapFileChooser; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.SwingPropertyChangeSupport; import javax.swing.filechooser.FileFilter; 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; import java.io.File; /** * Created by IntelliJ IDEA. * * @author knowles * @author aabduraz Date: 5/25/12 Time: 10:29 AM To change this template use * File | Settings | File Templates. */ public class FileSelector { public static final String PROPERTY_KEY_APP_LAST_OPEN_DIR = "app.file.lastOpenDir"; private JPanel jPanel = new JPanel(new GridBagLayout()); private boolean isDir = false; // public enum Type { // IFILE, // OFILE, // DIR // } private String propertyName = "FILE_SELECTOR_PANEL_CHANGED"; private AppContext appContext; private ParamInfo.Type type; private String name; private JLabel nameLabel; private JTextField fileTextfield; private JButton fileChooserButton; private File currentDirectory; private RegexFileFilter regexFileFilter; private JTextField filterRegexField; private JLabel filterRegexLabel; private String currentFilename = null; boolean fireTextFieldEnabled = true; private final JPanel filterPane = new JPanel(new GridBagLayout()); private final SwingPropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this); public FileSelector(AppContext appContext) { this(appContext, null); } public FileSelector(AppContext appContext, ParamInfo.Type type) { this.appContext = appContext; setType(type); initComponents(); addComponents(); } public FileSelector(AppContext appContext, ParamInfo.Type type, String name) { this(appContext, type); setName(name); } private void initComponents() { fileTextfield = createFileTextfield(); nameLabel = new JLabel(name); fileChooserButton = new JButton(new FileChooserAction()); } private void addComponents() { jPanel.add(nameLabel, new GridBagConstraintsCustom(0, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2)); if (name == null) { nameLabel.setVisible(false); } jPanel.add(fileTextfield, new GridBagConstraintsCustom(1, 0, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 2)); jPanel.add(fileChooserButton, new GridBagConstraintsCustom(2, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2)); jPanel.add(filterPane, new GridBagConstraintsCustom(3, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, 2)); if (type != ParamInfo.Type.IFILE) { filterPane.setVisible(false); } } public void setEnabled(boolean enabled) { nameLabel.setEnabled(enabled); fileChooserButton.setEnabled(enabled); fileTextfield.setEnabled(enabled); if (type == ParamInfo.Type.IFILE) { filterRegexField.setEnabled(enabled); filterRegexLabel.setEnabled(enabled); } } public void setVisible(boolean visible) { jPanel.setVisible(visible); nameLabel.setVisible(visible); fileChooserButton.setVisible(visible); fileTextfield.setVisible(visible); if (type == ParamInfo.Type.IFILE) { filterRegexField.setVisible(visible); filterRegexLabel.setVisible(visible); } } public void setName(String name) { this.name = name; nameLabel.setText(name); if (name != null && name.length() > 0) { nameLabel.setVisible(true); } } public String getFileName() { return fileTextfield.getText(); } public JTextField getFileTextField() { return fileTextfield; } public void setFilename(String filename) { fireTextFieldEnabled = false; currentFilename = filename; fileTextfield.setText(filename); fireTextFieldEnabled = true; } public void setFilenameAndFire(String filename) { String tmpCurrentFilename = currentFilename; setFilename(filename); fireEvent(propertyName, tmpCurrentFilename, filename); } private void handleFileTextfield() { String newFilename = fileTextfield.getText(); boolean filenameChanged = false; if (newFilename != null) { if (!newFilename.equals(currentFilename)) { filenameChanged = true; } } else { if (currentFilename != null) { filenameChanged = true; } } if (filenameChanged) { fileTextfield.setFocusable(true); fileTextfield.validate(); fileTextfield.repaint(); String previousFilename = currentFilename; currentFilename = newFilename; fireEvent(propertyName, previousFilename, newFilename); } } public JTextField createFileTextfield() { final JTextField jTextField = new JTextField(); jTextField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (fireTextFieldEnabled) { handleFileTextfield(); } } }); jTextField.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { } @Override public void focusLost(FocusEvent e) { if (fireTextFieldEnabled) { handleFileTextfield(); } } }); return jTextField; } private void createFilterPane(JPanel mainPanel) { mainPanel.removeAll(); filterRegexField = new JTextField("123456789 "); filterRegexField.setPreferredSize(filterRegexField.getPreferredSize()); filterRegexField.setMinimumSize(filterRegexField.getPreferredSize()); filterRegexField.setMaximumSize(filterRegexField.getPreferredSize()); filterRegexField.setText(""); filterRegexField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent documentEvent) { //To change body of implemented methods use File | Settings | File Templates. regexFileFilter = new RegexFileFilter(filterRegexField.getText()); SeadasFileUtils.debug(regexFileFilter.getDescription()); } @Override public void removeUpdate(DocumentEvent documentEvent) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void changedUpdate(DocumentEvent documentEvent) { //To change body of implemented methods use File | Settings | File Templates. } }); filterRegexLabel = new JLabel("filter:"); filterRegexLabel.setPreferredSize(filterRegexLabel.getPreferredSize()); filterRegexLabel.setMinimumSize(filterRegexLabel.getPreferredSize()); filterRegexLabel.setMaximumSize(filterRegexLabel.getPreferredSize()); filterRegexLabel.setToolTipText("Filter the chooser by regular expression"); mainPanel.add(filterRegexLabel, new GridBagConstraintsCustom(0, 0, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE)); mainPanel.add(filterRegexField, new GridBagConstraintsCustom(1, 0, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE)); } public ParamInfo.Type getType() { return type; } public void setType(ParamInfo.Type type) { this.type = type; if (type == ParamInfo.Type.IFILE) { regexFileFilter = new RegexFileFilter(); createFilterPane(filterPane); filterPane.setVisible(true); } else if (type == ParamInfo.Type.OFILE) { regexFileFilter = null; filterPane.removeAll(); filterPane.setVisible(false); } else if (type == ParamInfo.Type.DIR) { regexFileFilter = null; filterPane.removeAll(); filterPane.setVisible(false); isDir = true; } } public String getPropertyName() { return propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName; } private class FileChooserAction extends AbstractAction { private String APPROVE_BUTTON_TEXT = "Select"; private JFileChooser fileChooser; private FileChooserAction() { super("..."); fileChooser = new SnapFileChooser(); fileChooser.setDialogTitle("Select Input File"); fileChooser.setAcceptAllFileFilterUsed(true); fileChooser.setFileFilter(fileChooser.getAcceptAllFileFilter()); if (isDir) { fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } } // private FileChooserAction(String dialogTitle) { // super("..."); // fileChooser = new SnapFileChooser(); // // fileChooser.setDialogTitle(dialogTitle); // // fileChooser.setAcceptAllFileFilterUsed(true); // fileChooser.setFileFilter(fileChooser.getAcceptAllFileFilter()); // } @Override public void actionPerformed(ActionEvent event) { final Window window = SwingUtilities.getWindowAncestor((JComponent) event.getSource()); String homeDirPath = SystemUtils.getUserHomeDir().getPath(); String openDir = appContext.getPreferences().getPropertyString(PROPERTY_KEY_APP_LAST_OPEN_DIR, homeDirPath); currentDirectory = new File(openDir); fileChooser.setCurrentDirectory(currentDirectory); if (type == ParamInfo.Type.IFILE) { fileChooser.addChoosableFileFilter(regexFileFilter); } if (fileChooser.showDialog(window, APPROVE_BUTTON_TEXT) == JFileChooser.APPROVE_OPTION) { final File file = fileChooser.getSelectedFile(); currentDirectory = fileChooser.getCurrentDirectory(); appContext.getPreferences().setPropertyString(PROPERTY_KEY_APP_LAST_OPEN_DIR, currentDirectory.getAbsolutePath()); String filename = null; if (file != null) { filename = file.getAbsolutePath(); } setFilenameAndFire(filename); } } } private class RegexFileFilter extends FileFilter { private String regex; public RegexFileFilter() { this(null); } public RegexFileFilter(String regex) throws IllegalStateException { if (regex == null || regex.trim().length() == 0) { //throw new IllegalStateException(); return; } this.regex = ".*" + regex + ".*"; } /* (non-Javadoc) * @see java.io.FileFilter#accept(java.io.File) */ public boolean accept(File pathname) { if (regex == null) { return true; } return (pathname.isFile() && pathname.getName().matches(this.regex)); } public String getDescription() { return "Files matching regular expression: '" + regex + "'"; } } public JPanel getjPanel() { return jPanel; } public JLabel getNameLabel() { return nameLabel; } public void addPropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(propertyName, listener); } public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(propertyName, listener); } public void fireEvent(String propertyName, Object oldValue, Object newValue) { propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(this, propertyName, oldValue, newValue)); } }
12,896
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-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/SimpleDialogMessage.java
package gov.nasa.gsfc.seadas.processing.common; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * 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 GridBagConstraintsCustom(0, 0, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE)); jPanel.add(okayButton, new GridBagConstraintsCustom(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,641
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
Interpreter.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/utilities/Interpreter.java
package gov.nasa.gsfc.seadas.processing.utilities; /** * *************************************************************************************** * This class implements an interpreter * that reads the content of a cell and * computes its associated value. * * @author Thierry Manfé * *************************************************************************************** * @version 1.0 July-2002 */ class Interpreter { /** * Set this variable to true to get * some debugging traces. */ static final boolean DEBUG = false; static final String FORMULA = "FORMULA"; static final String TERM = "TERM"; static final String CELLID = "CELLID"; static final String NUMBER = "NUMBER"; static final String PARENTHESES = "PARENTHESES"; static final String OPENPAR = "("; static final String CLOSEPAR = ")"; static final String OPERATION = "OPERATION"; static final String ADD = "+"; static final String SUBSTRACT = "-"; static final String MULTIPLY = "*"; static final String DEVIDE = "/"; static final char SEPARATORS[] = {'+', '-', '/', '*', '(', ')'}; static final String SYNTAX_ERROR = "Error"; static final String MULTIPLY_OR_DEVIDE = "MULTIDIVE"; static final String ADD_OR_SUBSTRACT = "ADDSUB"; class InterpreterEvent extends Throwable { public InterpreterEvent() { super(); } ; public InterpreterEvent(String s) { super(s); } ; } /** * A syntax error terminates the evaluation * of the formula immediatly */ class SyntaxError extends InterpreterEvent { public SyntaxError() { super(); } ; public SyntaxError(String s) { super(s); } ; } class SyntagmaMismatch extends InterpreterEvent { public SyntagmaMismatch() { super(); } ; } class EndFormula extends InterpreterEvent { public EndFormula() { super(); } ; } class EmptyReference extends InterpreterEvent { public EmptyReference() { super(); } } /** * The associated TableModel. */ private SpreadSheetModel _data; private SheetCell _cell; private String _formula; private int _depth; private boolean _noEmptyRef; private boolean _userEdition; private String _leaf; private StringBuffer _buffer; Interpreter(SpreadSheetModel data) { _data = data; } /** * This method actually interprets the * formula and returns the computed value. * <p/> * Following is the grammar description. Expressions * between brackets are optional. A list of characters * between braces represents any single character from that list. * <p/> * FORMULA = TERM [ {*,/} TERM [ {+,-} FORMULA ] ] * FORMULA = TERM {+,-} FORMULA * <p/> * TERM = ( FORMULA ) * TERM = CELLID * TERM = NUMBER * * @param cell The cell to update * @param edition If true, the method has been called by * an edition of the cell by the user * @return Object The computed value */ void interpret(SheetCell cell, boolean edition) { if (DEBUG) { _depth = 0; } _noEmptyRef = true; _userEdition = edition; _formula = cell.formula.trim(); if (_formula.length() == 0) { cell.value = null; cell.formula = null; } else if (_formula.charAt(0) == '=') { _cell = cell; if (_userEdition) { // Convert all characters to // uppercase characters. char[] upper = _formula.toCharArray(); for (int ii = 0; ii < upper.length; ii++) upper[ii] = Character.toUpperCase(upper[ii]); _formula = new String(upper); cell.formula = _formula; } _formula = cell.formula.substring(1, _formula.length()); _buffer = new StringBuffer(_formula); Float value = null; try { value = (Float) accept(FORMULA); } catch (InterpreterEvent evt) { cell.value = SYNTAX_ERROR; return; } if (_noEmptyRef) cell.value = (String) value.toString(); else cell.value = null; } else { cell.value = cell.formula; cell.formula = null; } return; } /** * Retreive words on the left of the expression * and check if it matches a given syntagma. * * @param String The grammatical term looked for * @return Object The evaluated value of the grammatical term * (if computable) */ Object accept(String syntagma) throws InterpreterEvent { if (DEBUG) { _depth++; System.out.println("********** Depth: " + _depth); } Float value = null; if (syntagma.equals(FORMULA)) { if (DEBUG) System.out.println("Looking for a FORMULA"); Float leftTerm = null; Float rightTerm = null; String op = null; float res = 0; // A formula must have a left term. // If not, this is a syntax error. try { leftTerm = (Float) accept(TERM); } catch (SyntagmaMismatch evt) { throw new SyntaxError(); } try { op = (String) accept(MULTIPLY_OR_DEVIDE); try { rightTerm = (Float) accept(TERM); if (_noEmptyRef) { res = computeOperation(op, leftTerm.floatValue(), rightTerm.floatValue()); if (DEBUG) System.out.println("Result MULTIPLY/DEVIDE is: " + res); } try { op = (String) accept(ADD_OR_SUBSTRACT); try { rightTerm = (Float) accept(FORMULA); } catch (EndFormula err) { throw new SyntaxError(); } catch (SyntagmaMismatch err) { throw new SyntaxError(); } if (_noEmptyRef) { res = computeOperation(op, res, rightTerm.floatValue()); if (DEBUG) System.out.println("Result ADD/SUBSTRACT: " + res); } } catch (SyntagmaMismatch evt) { if (DEBUG) _depth--; try { op = (String) accept(MULTIPLY_OR_DEVIDE); try { rightTerm = (Float) accept(FORMULA); } catch (EndFormula err) { throw new SyntaxError(); } catch (SyntagmaMismatch err) { throw new SyntaxError(); } if (_noEmptyRef) { res = computeOperation(op, res, rightTerm.floatValue()); if (DEBUG) System.out.println("Result MULTIPLY/DEVIDE: " + res); } } catch (SyntagmaMismatch evt2) { throw new SyntaxError(); } } catch (EndFormula evt) { if (DEBUG) _depth--; } } catch (EndFormula err) { throw new SyntaxError(); } catch (SyntagmaMismatch evt) { throw new SyntaxError(); } } catch (SyntagmaMismatch evt1) { if (DEBUG) _depth--; try { op = (String) accept(ADD_OR_SUBSTRACT); try { rightTerm = (Float) accept(FORMULA); if (_noEmptyRef) { res = computeOperation(op, leftTerm.floatValue(), rightTerm.floatValue()); if (DEBUG) System.out.println("Result ADD/SUBSTRACT: " + res); } } catch (SyntagmaMismatch evt2) { throw new SyntaxError(); } } catch (SyntagmaMismatch evt3) { throw new SyntaxError(); } catch (EndFormula end) { if (DEBUG) _depth--; if (_noEmptyRef) res = leftTerm.floatValue(); } } catch (EndFormula end2) { if (DEBUG) _depth--; if (_noEmptyRef) res = leftTerm.floatValue(); } if (DEBUG) _depth--; if (_noEmptyRef) return new Float(res); else return null; } if (syntagma.equals(TERM)) { if (DEBUG) System.out.println("Looking for a TERM"); try { String parenthesis = (String) accept(OPENPAR); value = (Float) accept(FORMULA); parenthesis = (String) accept(CLOSEPAR); } catch (SyntagmaMismatch evt) { if (DEBUG) _depth--; try { value = (Float) accept(CELLID); } catch (SyntagmaMismatch ev) { if (DEBUG) _depth--; value = (Float) accept(NUMBER); } catch (EmptyReference ev) { _noEmptyRef = false; value = null; } } if (DEBUG) { System.out.println("TERM is: " + value); _depth--; } return value; } /* * Hereunder the simple words (or leaf words) */ if (syntagma.equals(NUMBER)) { if (DEBUG) System.out.println("Looking for a NUMBER"); readLeaf(); try { value = new Float(_leaf); } catch (NumberFormatException ex) { throw new SyntagmaMismatch(); } updateFormula(); if (DEBUG) System.out.println("Number=" + value); if (DEBUG) _depth--; return value; } if (syntagma.equals(CELLID)) { if (DEBUG) System.out.println("Looking for a CELLID"); readLeaf(); char[] id = _leaf.toCharArray(); int ii = 0; while (ii < id.length && Character.isLetter(id[ii])) { ii++; } if (ii == 0 || ii >= id.length) throw new SyntagmaMismatch(); String column = _leaf.substring(0, ii); int jj = ii; while (jj < id.length && Character.isDigit(id[jj])) { jj++; } if (ii == jj || jj != id.length) throw new SyntagmaMismatch(); String row = _leaf.substring(ii, jj); // Translate row and column string names into // integer indexes. int r = Integer.valueOf(row).intValue() - 1; char[] buf = column.toCharArray(); int c = 0; for (int kk = 0; kk < buf.length; kk++) { c = 26 * c + (Character.digit(buf[kk], 36) - 9); } c = c - 1; // A cell can not reference itself if (_cell.row == r && _cell.column == c) { System.out.println("Self reference not allowed in cells."); throw new SyntaxError(); } String cellVal = _data.getValueAt(r, c).toString(); if (DEBUG) System.out.println("cellVal: " + cellVal); updateFormula(); // If proceeding a user edition... if (_userEdition) { // ... the links to listeners have been cleaned. // Register the current cell has a listener of the pointed cell. // Make sure the current cell is not already registered. if (_data.cells[r][c].listeners.indexOf(_cell) == -1) _data.cells[r][c].listeners.add(_cell); // Register the pointed cell has a listenee // of the current cell. // Make sure the pointed cell is not already registered if (_cell.listenees.indexOf(_data.cells[r][c]) == -1) _cell.listenees.add(_data.cells[r][c]); } if (cellVal == null) throw new EmptyReference(); try { value = Float.valueOf(cellVal); } catch (NumberFormatException ex) { if (DEBUG) System.out.println("Can't read value at: " + row + ", " + column); throw new SyntagmaMismatch(); } if (DEBUG) _depth--; return value; } if (syntagma.equals(MULTIPLY_OR_DEVIDE)) { if (DEBUG) System.out.println("Looking for MULTIPLY or DEVIDE"); String op = null; try { op = readCharLeaf(MULTIPLY); } catch (SyntagmaMismatch evt) { op = readCharLeaf(DEVIDE); } if (DEBUG) _depth--; return op; } if (syntagma.equals(ADD_OR_SUBSTRACT)) { if (DEBUG) System.out.println("Looking for ADD or SUBSTRACT"); String op = null; try { op = readCharLeaf(ADD); } catch (SyntagmaMismatch evt) { op = readCharLeaf(SUBSTRACT); } if (DEBUG) _depth--; return op; } if (syntagma.equals(OPENPAR)) { if (DEBUG) System.out.println("Looking for an OPENPAR"); readCharLeaf(OPENPAR); if (DEBUG) _depth--; return null; } if (syntagma.equals(CLOSEPAR)) { if (DEBUG) System.out.println("Looking for a CLOSEPAR"); readCharLeaf(CLOSEPAR); if (DEBUG) _depth--; return null; } // Should never be reached throw new SyntaxError(); } /** * Read a single word on the left of the * unevaluated part of the formula and stores * it into _leaf */ private void readLeaf() throws SyntagmaMismatch, EndFormula { if (_formula.length() == 0) throw new EndFormula(); boolean searching = true; char[] buf = _formula.toCharArray(); int ii = 0; search: while (searching && ii < buf.length) { for (int jj = 0; jj < SEPARATORS.length; jj++) { if (buf[ii] == SEPARATORS[jj]) { searching = false; _leaf = _formula.substring(0, ii); continue search; } } ii++; } if (searching) _leaf = _formula; } private String readCharLeaf(String c) throws SyntagmaMismatch, EndFormula { if (_formula.length() == 0) { if (DEBUG) System.out.println("readLeaf(): End Of Formula"); throw new EndFormula(); } if (_formula.substring(0, 1).equals(c)) { _leaf = _formula.substring(0, 1); updateFormula(); } else { if (_formula.substring(0, 1).equals(CLOSEPAR)) { if (DEBUG) System.out.println("readLeaf(): End Of Formula"); throw new EndFormula(); } throw new SyntagmaMismatch(); } return c; } /** * Remove _leaf from _formula */ private void updateFormula() { _buffer = _buffer.delete(0, _leaf.length()); _formula = _buffer.toString().trim(); if (DEBUG) System.out.println("_formula: " + _formula); } private float computeOperation(String op, float left, float right) { if (op.equals(MULTIPLY)) return (left * right); if (op.equals(DEVIDE)) return (left / right); if (op.equals(ADD)) return (left + right); if (op.equals(SUBSTRACT)) return (left - right); return Float.NaN; } }
16,932
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SpreadSheet.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/utilities/SpreadSheet.java
package gov.nasa.gsfc.seadas.processing.utilities; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.EventObject; /** * ********************************************************************************************** * <p/> * This class implements a basic spreadsheet * using a JTable. * It also provides a main() method to be run * as an application. * * @author Thierry Manfé * <p/> * ********************************************************************************************** * @version 1.0 July-2002 */ public class SpreadSheet extends JTable { /** * Set this field to true and recompile * to get debug traces */ public static final boolean DEBUG = true; private JScrollPane _scp; private CellMenu _popupMenu; private SpreadSheetModel _model; private int _numRow; private int _numCol; private int _editedModelRow; private int _editedModelCol; /* * GUI components used to tailored * the SpreadSheet. */ private CellRenderer _renderer; private Font _cellFont; //private FontMetrics _metrics; // Cells selected. private Object[] _selection; /** * Start the spreadsheet into a JFrame. * * @param args The options passed on the command * line. Not used. */ public static void main(String[] args) { String vers = System.getProperty("java.version"); if (vers.compareTo("1.3") < 0) { System.out.println("Please use Java 1.3 or above."); //System.exit(1); } try { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch (Exception ex) { System.out.println("Can't set look and feel MetalLookAndFeel"); System.exit(2); } JFrame frame = new JFrame("A Simple Spreadsheet"); /* * Allows the user to exit the application * from the window manager's dressing. */ frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); //SpreadSheet sp = new SpreadSheet(40, 40); SheetCell[][] cells = new SheetCell[3][2]; cells[0][0] = new SheetCell(0 , 0, "1", null); cells[1][0] = new SheetCell(0 , 1, "2", null); cells[2][0] = new SheetCell(0 , 2, "3", null); cells[0][1] = new SheetCell(1 , 0, "1", "=A1"); cells[1][1] = new SheetCell(1 , 1, "3", "=A1+A2"); cells[2][1] = new SheetCell(1 , 2, "6", "=A1+A2+A3"); SpreadSheet sp = new SpreadSheet(cells); frame.getContentPane().add(sp.getScrollPane()); frame.pack(); frame.setVisible(true); } /** * Build SpreadSheet of numCol columns and numRow rows. * * @param cells If not null, the cells to be used in the spreadsheet. * It must be a two dimensional rectangular array. If null, the cells are * automatically created. * @param numRow The number of rows * @param numCol The number of columns */ private SpreadSheet(SheetCell[][] cells, int numRow, int numCol) { super(); SheetCell foo[][]; if (cells != null) foo = cells; else { foo = new SheetCell[numRow][numCol]; for (int ii = 0; ii < numRow; ii++) { for (int jj = 0; jj < numCol; jj++) foo[ii][jj] = new SheetCell(ii, jj); } } _numRow = numRow; _numCol = numCol; _cellFont = new Font("Times", Font.PLAIN, 20); // Create the JScrollPane that includes the Table _scp = new JScrollPane(this); // Create the rendeder for the cells _renderer = new CellRenderer(); try { setDefaultRenderer(Class.forName("java.lang.Object"), _renderer); } catch (ClassNotFoundException ex) { if (DEBUG) System.out.println("SpreadSheet() Can't modify renderer"); } _model = new SpreadSheetModel(foo, this); setModel(_model); /* * Tune the selection mode */ // Allows row and collumn selections to exit at the same time setCellSelectionEnabled(true); setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent ev) { int selRow[] = getSelectedRows(); int selCol[] = getSelectedColumns(); _selection = new Object[selRow.length * selCol.length]; int indice = 0; for (int r = 0; r < selRow.length; r++) { for (int c = 0; c < selCol.length; c++) { _selection[indice] = _model.cells[selRow[r]][convertColumnIndexToModel(selCol[c])]; indice++; } } } }); // Create a row-header to display row numbers. // This row-header is made of labels whose Borders, // Foregrounds, Backgrounds, and Fonts must be // the one used for the table column headers. // Also ensure that the row-header labels and the table // rows have the same height. TableColumn aColumn = getColumnModel().getColumn(0); TableCellRenderer aRenderer = getTableHeader().getDefaultRenderer(); if (aRenderer == null) { System.out.println(" Aouch !"); aColumn = getColumnModel().getColumn(0); aRenderer = aColumn.getHeaderRenderer(); if (aRenderer == null) { System.out.println(" Aouch Aouch !"); System.exit(3); } } Component aComponent = aRenderer.getTableCellRendererComponent(this, aColumn.getHeaderValue(), false, false, -1, 0); Font aFont = aComponent.getFont(); Color aBackground = aComponent.getBackground(); Color aForeground = aComponent.getForeground(); Border border = (Border) UIManager.getDefaults().get("TableHeader.cellBorder"); Insets insets = border.getBorderInsets(tableHeader); FontMetrics metrics = getFontMetrics(_cellFont); rowHeight = insets.bottom + metrics.getHeight() + insets.top; /* * Creating a panel to be used as the row header. * * Since I'm not using any LayoutManager, * a call to setPreferredSize(). */ JPanel pnl = new JPanel((LayoutManager) null); Dimension dim = new Dimension(metrics.stringWidth("999") + insets.right + insets.left, rowHeight * _numRow); pnl.setPreferredSize(dim); // Adding the row header labels dim.height = rowHeight; for (int ii = 0; ii < _numRow; ii++) { JLabel lbl = new JLabel(Integer.toString(ii + 1), SwingConstants.CENTER); lbl.setFont(aFont); lbl.setBackground(aBackground); lbl.setForeground(aForeground); lbl.setBorder(border); lbl.setBounds(0, ii * dim.height, dim.width, dim.height); pnl.add(lbl); } JViewport vp = new JViewport(); dim.height = rowHeight * _numRow; vp.setViewSize(dim); vp.setView(pnl); _scp.setRowHeader(vp); // Set resize policy and make sure // the table's size is tailored // as soon as it gets drawn. setAutoResizeMode(JTable.AUTO_RESIZE_OFF); Dimension dimScpViewport = getPreferredScrollableViewportSize(); if (_numRow > 30) dimScpViewport.height = 30 * rowHeight; else dimScpViewport.height = _numRow * rowHeight; if (_numCol > 15) dimScpViewport.width = 15 * getColumnModel().getTotalColumnWidth() / _numCol; else dimScpViewport.width = getColumnModel().getTotalColumnWidth(); setPreferredScrollableViewportSize(dimScpViewport); resizeAndRepaint(); } /** * Build a numRow by numColumn SpreadSheet included * in a JScrollPane. The associated model and the cells * are automatically created. * * @param numRow The number of row in the spreadsheet * @param numColumn The number of column in the spreadsheet */ public SpreadSheet(int numRow, int numColumn) { this(null, numRow, numColumn); } /** * Build a SpreadSheet included in a JScrollPane * from the cells given as argument. * * @param cells A two dimensional rectangular * array of cells to be used when * creating the spreadsheet. */ public SpreadSheet(SheetCell cells[][]) { this(cells, cells.length, cells[0].length); } /** * Invoked when a cell edition starts. * This method overrides and calls that of its super class. * * @param row The row to be edited * @param column The column to be edited * @param ev The firing event * @return boolean false if for any reason the cell cannot be edited. */ public boolean editCellAt(int row, int column, EventObject ev) { if (_editedModelRow != -1) _model.setDisplayMode(_editedModelRow, _editedModelCol); _editedModelRow = row; _editedModelCol = convertColumnIndexToModel(column); _model.setEditMode(row, convertColumnIndexToModel(column)); return super.editCellAt(row, column, ev); } /** * Invoked by the cell editor when a cell edition stops. * This method override and calls that of its super class. */ public void editingStopped(ChangeEvent ev) { _model.setDisplayMode(_editedModelRow, _editedModelCol); super.editingStopped(ev); } /** * Invoked by the cell editor when a cell edition is cancelled. * This method override and calls that of its super class. */ public void editingCanceled(ChangeEvent ev) { _model.setDisplayMode(_editedModelRow, _editedModelCol); super.editingCanceled(ev); } public JScrollPane getScrollPane() { return _scp; } public void processMouseEvent(MouseEvent ev) { int type = ev.getID(); int modifiers = ev.getModifiers(); if ((type == MouseEvent.MOUSE_RELEASED) && (modifiers == InputEvent.BUTTON3_MASK)) { if (_selection != null) { if (_popupMenu == null) _popupMenu = new CellMenu(this); if (_popupMenu.isVisible()) _popupMenu.setVisible(false); else { _popupMenu.setTargetCells(_selection); Point p = getLocationOnScreen(); _popupMenu.setLocation(p.x + ev.getX() + 1, p.y + ev.getY() + 1); _popupMenu.setVisible(true); } } } super.processMouseEvent(ev); } protected void release() { _model = null; } public void setVisible(boolean flag) { _scp.setVisible(flag); } /* * This class is used to customize the cells rendering. */ public class CellRenderer extends JLabel implements TableCellRenderer { private LineBorder _selectBorder; private EmptyBorder _emptyBorder; private Dimension _dim; public CellRenderer() { super(); _emptyBorder = new EmptyBorder(1, 2, 1, 2); _selectBorder = new LineBorder(Color.red); setOpaque(true); setHorizontalAlignment(SwingConstants.CENTER); _dim = new Dimension(); _dim.height = 22; _dim.width = 100; setSize(_dim); } ; /** * Method defining the renderer to be used * when drawing the cells. */ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { SheetCell sc = (SheetCell) value; setFont(_cellFont); setText(sc.toString()); setForeground(sc.foreground); setBackground(sc.background); if (isSelected) { setBorder(_selectBorder); setToolTipText("Right-click to change the cell's colors."); } else { setBorder(_emptyBorder); setToolTipText("Single-Click to select a cell, " + "double-click to edit."); } return this; } } }
13,423
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SeadasArrayUtils.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/utilities/SeadasArrayUtils.java
package gov.nasa.gsfc.seadas.processing.utilities; import java.util.Arrays; /** * Created by aabduraz on 7/25/16. */ public class SeadasArrayUtils { /** * Concatenating two arrays * * @param first First array to be concatenated * @param second Second array to be concatenated * @param <T> * @return */ public static <T> T[] concat(T[] first, T[] second) { T[] result = Arrays.copyOf(first, first.length + second.length); System.arraycopy(second, 0, result, first.length, second.length); return result; } /** * Concatenating an arbitrary number of arrays * * @param first First array in the list of arrays * @param rest Rest of the arrays in the list to be concatenated * @param <T> * @return */ public static <T> T[] concatAll(T[] first, T[]... rest) { int totalLength = first.length; for (T[] array : rest) { if (array != null) { totalLength += array.length; } } T[] result = Arrays.copyOf(first, totalLength); int offset = first.length; for (T[] array : rest) { if (array != null) { System.arraycopy(array, 0, result, offset, array.length); offset += array.length; } } return result; } }
1,378
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
FileCompare.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/utilities/FileCompare.java
package gov.nasa.gsfc.seadas.processing.utilities; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.util.Arrays; /** * Created by aabduraz on 2/19/18. */ public class FileCompare { public static void main(String args[]) { if(args.length != 2) throw (new RuntimeException("Usage : java FileCompare fileName1 fileName2")); String fileName1=args[0]; String fileName2=args[1]; String hashValue=""; String hashValue1=""; //First Method try { if (CompareFilesbyByte(fileName1,fileName2)==true) System.out.println("No Difference encountered using CompareFilesbyByte method"); else System.out.println("Both Files are not equal using CompareFilesbyByte method"); }catch (IOException e) { System.out.println("Error"); } System.out.println(); //IInd Method try { hashValue =MD5HashFile(fileName1); hashValue1 =MD5HashFile(fileName2); if (hashValue.equals(hashValue1)) System.out.println("No Difference encountered using method MD5Hash"); else System.out.println("Both Files are not equal using MD5Hash"); } catch (Exception e) { System.out.println("Error"); } } //reading bytes and compare public static boolean CompareFilesbyByte(String file1, String file2) throws IOException { File f1=new File(file1); File f2=new File(file2); FileInputStream fis1 = new FileInputStream (f1); FileInputStream fis2 = new FileInputStream (f2); if (f1.length()==f2.length()) { int n=0; byte[] b1; byte[] b2; while ((n = fis1.available()) > 0) { if (n>80) n=80; b1 = new byte[n]; b2 = new byte[n]; fis1.read(b1); fis2.read(b2); if (Arrays.equals(b1,b2)==false) { System.out.println(file1 + " :\n\n " + new String(b1)); System.out.println(); System.out.println(file2 + " : \n\n" + new String(b2)); return false; } } } else return false; // length is not matched. return true; } public static String MD5HashFile(String filename) throws Exception { byte[] buf = ChecksumFile(filename); String res = ""; for (int i = 0; i < buf.length; i++) { res+= Integer.toString((buf[i] & 0xff) + 0x100, 16).substring(1); } return res; } public static byte[] ChecksumFile(String filename) throws Exception { InputStream fis = new FileInputStream(filename); byte[] buf = new byte[1024]; MessageDigest complete = MessageDigest.getInstance("MD5"); int n; do { n= fis.read(buf); if (n > 0) { complete.update(buf, 0, n); } } while (n != -1); fis.close(); return complete.digest(); } }
3,264
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SheetCell.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/utilities/SheetCell.java
package gov.nasa.gsfc.seadas.processing.utilities; import java.awt.*; import java.util.*; /** * This class specifies the * cell format. * * @version 1.0 July-2002 * @author Thierry Manfé */ public class SheetCell { /** * Set this field to true and recompile * to get debug traces */ public static final boolean DEBUG = false; static final int UNDEFINED = 0; static final int EDITED = 1; static final int UPDATED = 2; static final boolean USER_EDITION = true; static final boolean UPDATE_EVENT = false; String value; String formula; int state; Vector<SheetCell> listeners; Vector<SheetCell> listenees; Color background; Color foreground; int row; int column; SheetCell(int r, int c) { row = r; column = c; value = null; formula = null; state = UNDEFINED; listeners = new Vector<>(); listenees = new Vector<>(); background = Color.white; foreground = Color.black; } public SheetCell(int r, int c, String value, String formula) { this(r,c); this.value = value; this.formula = formula; } public String getValue(){ return value; } void userUpdate() { // The user has edited the cell. The dependencies // on other cells may have changed: // clear the links to the listeners. They will be // resseted during interpretation for (int ii=0; ii<listenees.size(); ii++) { SheetCell c = (SheetCell)listenees.get(ii); c.listeners.remove(this); } listenees.clear(); SpreadSheetModel.interpreter.interpret(this, USER_EDITION); updateListeners(); state = UPDATED; } void updateListeners() { for (int ii=0; ii<listeners.size(); ii++) { SheetCell cell = listeners.get(ii); SpreadSheetModel.interpreter.interpret(cell, UPDATE_EVENT); if (DEBUG) System.out.println("Listener updated."); cell.updateListeners(); } } public String toString() { if (state==EDITED && formula!=null) return formula; else if (value!=null) return value.toString(); else return null; } }
2,124
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
CellMenu.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/utilities/CellMenu.java
package gov.nasa.gsfc.seadas.processing.utilities; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * This class implements a popup-menu * used to customize cell appearance. * * @version 1.0 July-2002 * @author Thierry Manfé */ class CellMenu extends JPopupMenu implements ActionListener { /** * Set this field to true and recompile * to get debug traces */ public static final boolean DEBUG = false; static private final String _FOREGROUND = "Foreground"; static private final String _BACKGROUND = "Background"; static private final String _FONT = "Font"; static private final String _EDITABLE = "Editable"; //private SheetCell _targetCells[]; private Object _targetCells[]; private JWindow _colorWindow; private SpreadSheet _sp; CellMenu(SpreadSheet parent) { _sp = parent; setDefaultLightWeightPopupEnabled(true); JMenuItem item = new JMenuItem(_FOREGROUND); item.addActionListener(this); add(item); item = new JMenuItem(_BACKGROUND); item.addActionListener(this); add(item); pack(); } void setTargetCells( Object c[]) { _targetCells = c; } public void actionPerformed(ActionEvent ev) { if (DEBUG) System.out.println("Size of selection: "+_targetCells.length); if (ev.getActionCommand().equals(_FOREGROUND)) { setVisible(false); if (_colorWindow==null) new JWindow(); Color col = JColorChooser.showDialog(_colorWindow,"Foreground Color",null); for (int ii=0; ii<_targetCells.length; ii++) { SheetCell sc = (SheetCell)_targetCells[ii]; sc.foreground = col; } _sp.repaint(); } else if (ev.getActionCommand().equals(_BACKGROUND)) { setVisible(false); if (_colorWindow==null) new JWindow(); Color col = JColorChooser.showDialog(_colorWindow,"Background Color",null); for (int ii=0; ii<_targetCells.length; ii++) { SheetCell sc = (SheetCell)_targetCells[ii]; sc.background = col; } _sp.repaint(); } } }
2,078
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SpreadSheetModel.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/utilities/SpreadSheetModel.java
package gov.nasa.gsfc.seadas.processing.utilities; import javax.swing.table.AbstractTableModel; /** * This class specifies the data format * for the SpreadSheet JTable * * @version 1.0 July-2002 * @author Thierry Manfé */ class SpreadSheetModel extends AbstractTableModel { final private SpreadSheet _dpyTable; static Interpreter interpreter; static final boolean DEBUG = false; private int _nbRow; private int _nbColumn; protected SheetCell[][] cells; /** * Create a nbRow by nbColumn SpreadSheetModel. * * @param cells The cell array * @param table The associated SpreadSheet */ SpreadSheetModel(SheetCell[][] cells, SpreadSheet table) { _dpyTable = table; _nbRow = cells.length; _nbColumn = cells[0].length; this.cells = cells; interpreter = new Interpreter(this); } private void clean() { _nbRow = _nbColumn = 0; cells = null; } public int getRowCount() {return _nbRow;} public int getColumnCount() {return _nbColumn;} public boolean isCellEditable(int row, int col) { return true; } public Object getValueAt(int row, int column) { return cells[row][column]; } /** * Mark the corresponding cell * as being edited. Its formula * must be displayed instead of * its result */ void setEditMode(int row, int column) { cells[row][column].state=SheetCell.EDITED; } void setDisplayMode(int row, int column) { cells[row][column].state=SheetCell.UPDATED; } public void setValueAt(Object value, int row, int column) { String input = (String)value; cells[row][column].formula = input; cells[row][column].userUpdate(); _dpyTable.repaint(); } }
1,748
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
ScrolledPane.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/utilities/ScrolledPane.java
package gov.nasa.gsfc.seadas.processing.utilities; import javax.swing.*; import java.awt.*; public class ScrolledPane extends JFrame { private JScrollPane scrollPane; public ScrolledPane(String programName, String message, Window window) { setTitle(programName); setSize(500, 500); setBackground(Color.gray); setLocationRelativeTo(window); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); getContentPane().add(topPanel); JTextArea text = new JTextArea(message); scrollPane = new JScrollPane(); scrollPane.getViewport().add(text); topPanel.add(scrollPane, BorderLayout.CENTER); } public ScrolledPane(String programName, String message) { Window activeWindow = javax.swing.FocusManager.getCurrentManager().getActiveWindow(); setTitle(programName); setSize(500, 500); setBackground(Color.gray); setLocationRelativeTo(activeWindow); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); getContentPane().add(topPanel); JTextArea text = new JTextArea(message); scrollPane = new JScrollPane(); scrollPane.getViewport().add(text); topPanel.add(scrollPane, BorderLayout.CENTER); } }
1,325
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
package-info.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/preferences/package-info.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. */ @OptionsPanelController.ContainerRegistration( id = "SeaDAS", categoryName = "#LBL_SeadasToolboxOptionsCategory_Name", iconBase = "gov/nasa/gsfc/seadas/processing/docs/images/seadas_icon_32x32.png", keywords = "#LBL_SeadasToolboxOptionsCategory_Keywords", keywordsCategory = "SeaDAS_Toolbox", position = 1400 ) @NbBundle.Messages(value = { "LBL_SeadasToolboxOptionsCategory_Name=SeaDAS Toolbox", "LBL_SeadasToolboxOptionsCategory_Keywords=seadas, ocssw, l2gen" }) package gov.nasa.gsfc.seadas.processing.preferences; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.NbBundle;
848
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSW_InstallerController.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/preferences/OCSSW_InstallerController.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.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.*; import static com.bc.ceres.swing.TableLayout.cell; /** * * Panel handling OCSSW-Installer preferences. Sub-panel of the "SeaDAS-Toolbox"-panel. * * @author Daniel Knowles */ @OptionsPanelController.SubRegistration(location = "SeaDAS", displayName = "#Options_DisplayName_OCSSW_Installer", keywords = "#Options_Keywords_OCSSW_Installer", keywordsCategory = "Installer", id = "OCSSW-Installer") @org.openide.util.NbBundle.Messages({ "Options_DisplayName_OCSSW_Installer=OCSSW-Installer", "Options_Keywords_OCSSW_Installer=seadas, ocssw, installer" }) public final class OCSSW_InstallerController extends DefaultConfigController { Property restoreDefaults; boolean propertyValueChangeEventsEnabled = true; // Preferences property prefix private static final String PROPERTY_INSTALLER_ROOT_KEY = SeadasToolboxDefaults.PROPERTY_SEADAS_ROOT_KEY + ".ocssw.installer"; // Property Setting: Restore Defaults private static final String PROPERTY_RESTORE_KEY_SUFFIX = PROPERTY_INSTALLER_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 (OCSSW Installer Preferences)"; public static final String PROPERTY_RESTORE_DEFAULTS_TOOLTIP = "Restore all OCSSW Installer preferences to the original default"; public static final boolean PROPERTY_RESTORE_DEFAULTS_DEFAULT = false; public static final String PROPERTY_ONLY_RELEASE_TAGS_KEY = PROPERTY_INSTALLER_ROOT_KEY + ".include.only.release.tags"; public static final String PROPERTY_ONLY_RELEASE_TAGS_LABEL = "Include only SeaDAS-OCSSW release tags"; public static final String PROPERTY_ONLY_RELEASE_TAGS_TOOLTIP = "Include only official SeaDAS-OCSSW release tags in the GUI installer"; public static final boolean PROPERTY_ONLY_RELEASE_TAGS_DEFAULT = true; 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_ONLY_RELEASE_TAGS_KEY, PROPERTY_ONLY_RELEASE_TAGS_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("OCSSW_InstallerPreferences"); } @SuppressWarnings("UnusedDeclaration") static class SeadasToolboxBean { @Preference(key = PROPERTY_ONLY_RELEASE_TAGS_KEY, label = PROPERTY_ONLY_RELEASE_TAGS_LABEL, description = PROPERTY_ONLY_RELEASE_TAGS_TOOLTIP) boolean miscTags = PROPERTY_ONLY_RELEASE_TAGS_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 boolean getPreferenceUseReleaseTagsOnly() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyBool(PROPERTY_ONLY_RELEASE_TAGS_KEY, PROPERTY_ONLY_RELEASE_TAGS_DEFAULT); } }
10,991
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSW_L3mapgenController.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/preferences/OCSSW_L3mapgenController.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.preferences; import com.bc.ceres.binding.*; 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 l3mapgen preferences. Sub-panel of the "SeaDAS-Toolbox"-panel. * * @author Daniel Knowles */ @OptionsPanelController.SubRegistration(location = "SeaDAS", displayName = "#Options_DisplayName_OCSSW_L3mapgen", keywords = "#Options_Keywords_OCSSW_L3mapgen", keywordsCategory = "Processors", id = "L3mapgen") @org.openide.util.NbBundle.Messages({ "Options_DisplayName_OCSSW_L3mapgen=L3mapgen", "Options_Keywords_OCSSW_L3mapgen=seadas, ocssw, l3mapgen" }) public final class OCSSW_L3mapgenController extends DefaultConfigController { Property restoreDefaults; boolean propertyValueChangeEventsEnabled = true; // Preferences property prefix private static final String PROPERTY_L3MAPGEN_ROOT_KEY = SeadasToolboxDefaults.PROPERTY_SEADAS_ROOT_KEY + ".l3mapgen"; public static final String PROPERTY_L3MAPGEN_PRODUCT_KEY = PROPERTY_L3MAPGEN_ROOT_KEY + ".product"; public static final String PROPERTY_L3MAPGEN_PRODUCT_LABEL = "product"; public static final String PROPERTY_L3MAPGEN_PRODUCT_TOOLTIP = "Product(s)"; public static final String PROPERTY_L3MAPGEN_PRODUCT_DEFAULT = ""; public static final String PROPERTY_L3MAPGEN_PROJECTION_KEY = PROPERTY_L3MAPGEN_ROOT_KEY + ".projection"; public static final String PROPERTY_L3MAPGEN_PROJECTION_LABEL = "projection"; public static final String PROPERTY_L3MAPGEN_PROJECTION_TOOLTIP = "Projection"; public static final String PROPERTY_L3MAPGEN_PROJECTION_DEFAULT = "platecarree"; public static final String PROPERTY_L3MAPGEN_RESOLUTION_KEY = PROPERTY_L3MAPGEN_ROOT_KEY + ".resolution"; public static final String PROPERTY_L3MAPGEN_RESOLUTION_LABEL = "resolution"; public static final String PROPERTY_L3MAPGEN_RESOLUTION_TOOLTIP = "Resolution"; public static final String PROPERTY_L3MAPGEN_RESOLUTION_DEFAULT = ""; public static final String PROPERTY_L3MAPGEN_INTERP_KEY = PROPERTY_L3MAPGEN_ROOT_KEY + ".interp"; public static final String PROPERTY_L3MAPGEN_INTERP_LABEL = "interp"; public static final String PROPERTY_L3MAPGEN_INTERP_TOOLTIP = "Interpolation type"; public static final String PROPERTY_L3MAPGEN_INTERP_DEFAULT = "nearest"; public static final String PROPERTY_L3MAPGEN_NORTH_KEY = PROPERTY_L3MAPGEN_ROOT_KEY + ".north"; public static final String PROPERTY_L3MAPGEN_NORTH_LABEL = "north"; public static final String PROPERTY_L3MAPGEN_NORTH_TOOLTIP = "Northernmost boundary"; public static final String PROPERTY_L3MAPGEN_NORTH_DEFAULT = ""; public static final String PROPERTY_L3MAPGEN_SOUTH_KEY = PROPERTY_L3MAPGEN_ROOT_KEY + ".south"; public static final String PROPERTY_L3MAPGEN_SOUTH_LABEL = "south"; public static final String PROPERTY_L3MAPGEN_SOUTH_TOOLTIP = "Southernmost boundary"; public static final String PROPERTY_L3MAPGEN_SOUTH_DEFAULT = ""; public static final String PROPERTY_L3MAPGEN_WEST_KEY = PROPERTY_L3MAPGEN_ROOT_KEY + ".west"; public static final String PROPERTY_L3MAPGEN_WEST_LABEL = "west"; public static final String PROPERTY_L3MAPGEN_WEST_TOOLTIP = "Westernmost boundary"; public static final String PROPERTY_L3MAPGEN_WEST_DEFAULT = ""; public static final String PROPERTY_L3MAPGEN_EAST_KEY = PROPERTY_L3MAPGEN_ROOT_KEY + ".east"; public static final String PROPERTY_L3MAPGEN_EAST_LABEL = "east"; public static final String PROPERTY_L3MAPGEN_EAST_TOOLTIP = "Easternmost boundary"; public static final String PROPERTY_L3MAPGEN_EAST_DEFAULT = ""; // Property Setting: Restore Defaults private static final String PROPERTY_RESTORE_KEY_SUFFIX = PROPERTY_L3MAPGEN_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) { String[] interpOptionsArray = {" ", "nearest", "bin", "area"}; // // Initialize the default value contained within each property descriptor // This is done so subsequently the restoreDefaults actions can be performed // initPropertyDefaults(context, PROPERTY_L3MAPGEN_PRODUCT_KEY, PROPERTY_L3MAPGEN_PRODUCT_DEFAULT); initPropertyDefaults(context, PROPERTY_L3MAPGEN_PROJECTION_KEY, PROPERTY_L3MAPGEN_PROJECTION_DEFAULT); initPropertyDefaults(context, PROPERTY_L3MAPGEN_RESOLUTION_KEY, PROPERTY_L3MAPGEN_RESOLUTION_DEFAULT); initPropertyDefaults(context, PROPERTY_L3MAPGEN_INTERP_KEY, PROPERTY_L3MAPGEN_INTERP_DEFAULT); initPropertyDefaults(context, PROPERTY_L3MAPGEN_NORTH_KEY, PROPERTY_L3MAPGEN_NORTH_DEFAULT); initPropertyDefaults(context, PROPERTY_L3MAPGEN_SOUTH_KEY, PROPERTY_L3MAPGEN_SOUTH_DEFAULT); initPropertyDefaults(context, PROPERTY_L3MAPGEN_WEST_KEY, PROPERTY_L3MAPGEN_WEST_DEFAULT); initPropertyDefaults(context, PROPERTY_L3MAPGEN_EAST_KEY, PROPERTY_L3MAPGEN_EAST_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("OCSSW_L3mapgenPreferences"); } @SuppressWarnings("UnusedDeclaration") static class SeadasToolboxBean { @Preference(label = PROPERTY_L3MAPGEN_PRODUCT_LABEL, key = PROPERTY_L3MAPGEN_PRODUCT_KEY, description = PROPERTY_L3MAPGEN_PRODUCT_TOOLTIP) String l3mapgenProductDefault = PROPERTY_L3MAPGEN_PRODUCT_DEFAULT; @Preference(label = PROPERTY_L3MAPGEN_PROJECTION_LABEL, key = PROPERTY_L3MAPGEN_PROJECTION_KEY, description = PROPERTY_L3MAPGEN_PROJECTION_TOOLTIP) String l3mapgenProjectionDefault = PROPERTY_L3MAPGEN_PROJECTION_DEFAULT; @Preference(label = PROPERTY_L3MAPGEN_RESOLUTION_LABEL, key = PROPERTY_L3MAPGEN_RESOLUTION_KEY, description = PROPERTY_L3MAPGEN_RESOLUTION_TOOLTIP) String l3mapgenResolutionDefault = PROPERTY_L3MAPGEN_RESOLUTION_DEFAULT; @Preference(label = PROPERTY_L3MAPGEN_INTERP_LABEL, key = PROPERTY_L3MAPGEN_INTERP_KEY, valueSet = {" ", "nearest", "bin", "area"}, description = PROPERTY_L3MAPGEN_INTERP_TOOLTIP) String l3mapgenInterpDefault = PROPERTY_L3MAPGEN_INTERP_DEFAULT; @Preference(label = PROPERTY_L3MAPGEN_NORTH_LABEL, key = PROPERTY_L3MAPGEN_NORTH_KEY, description = PROPERTY_L3MAPGEN_NORTH_TOOLTIP) String l3mapgenNorthDefault = PROPERTY_L3MAPGEN_NORTH_DEFAULT; @Preference(label = PROPERTY_L3MAPGEN_SOUTH_LABEL, key = PROPERTY_L3MAPGEN_SOUTH_KEY, description = PROPERTY_L3MAPGEN_SOUTH_TOOLTIP) String l3mapgenSouthDefault = PROPERTY_L3MAPGEN_SOUTH_DEFAULT; @Preference(label = PROPERTY_L3MAPGEN_WEST_LABEL, key = PROPERTY_L3MAPGEN_WEST_KEY, description = PROPERTY_L3MAPGEN_WEST_TOOLTIP) String l3mapgenWestDefault = PROPERTY_L3MAPGEN_WEST_DEFAULT; @Preference(label = PROPERTY_L3MAPGEN_EAST_LABEL, key = PROPERTY_L3MAPGEN_EAST_KEY, description = PROPERTY_L3MAPGEN_EAST_TOOLTIP) String l3mapgenEastDefault = PROPERTY_L3MAPGEN_EAST_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 getPreferenceProduct() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_PRODUCT_KEY, OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_PRODUCT_DEFAULT); } public static String getPreferenceProjection() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_PROJECTION_KEY, OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_PROJECTION_DEFAULT); } public static String getPreferenceResolution() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_RESOLUTION_KEY, OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_RESOLUTION_DEFAULT); } public static String getPreferenceInterp() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_INTERP_KEY, OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_INTERP_DEFAULT); } public static String getPreferenceNorth() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_NORTH_KEY, OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_NORTH_DEFAULT); } public static String getPreferenceSouth() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_SOUTH_KEY, OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_SOUTH_DEFAULT); } public static String getPreferenceWest() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_WEST_KEY, OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_WEST_DEFAULT); } public static String getPreferenceEast() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_EAST_KEY, OCSSW_L3mapgenController.PROPERTY_L3MAPGEN_EAST_DEFAULT); } }
17,915
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSW_L2binController.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/preferences/OCSSW_L2binController.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.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.*; import static com.bc.ceres.swing.TableLayout.cell; /** * * Panel handling l2bin preferences. Sub-panel of the "SeaDAS-Toolbox"-panel. * * @author Daniel Knowles */ @OptionsPanelController.SubRegistration(location = "SeaDAS/OCSSW", displayName = "#Options_DisplayName_OCSSW_L2bin", keywords = "#Options_Keywords_OCSSW_L2bin", keywordsCategory = "OCSSW", id = "L2bin") @org.openide.util.NbBundle.Messages({ "Options_DisplayName_OCSSW_L2bin=L2bin", "Options_Keywords_OCSSW_L2bin=seadas, ocssw, l2bin" }) public final class OCSSW_L2binController extends DefaultConfigController { Property restoreDefaults; boolean propertyValueChangeEventsEnabled = true; // Preferences property prefix private static final String PROPERTY_L2BIN_ROOT_KEY = SeadasToolboxDefaults.PROPERTY_SEADAS_ROOT_KEY + ".l2bin"; public static final String PROPERTY_L2BIN_L3BPROD_KEY = PROPERTY_L2BIN_ROOT_KEY + ".l3bprod"; public static final String PROPERTY_L2BIN_L3BPROD_LABEL = "l3bprod"; public static final String PROPERTY_L2BIN_L3BPROD_TOOLTIP = "Product (or product list)"; public static final String PROPERTY_L2BIN_L3BPROD_DEFAULT = ""; public static final String PROPERTY_L2BIN_PRODTYPE_KEY = PROPERTY_L2BIN_ROOT_KEY + ".prodtype"; public static final String PROPERTY_L2BIN_PRODTYPE_LABEL = "prodtype"; public static final String PROPERTY_L2BIN_PRODTYPE_TOOLTIP = "Product type"; public static final String PROPERTY_L2BIN_PRODTYPE_DEFAULT = "regional"; public static final String PROPERTY_L2BIN_RESOLUTION_KEY = PROPERTY_L2BIN_ROOT_KEY + ".resolution"; public static final String PROPERTY_L2BIN_RESOLUTION_LABEL = "resolution"; public static final String PROPERTY_L2BIN_RESOLUTION_TOOLTIP = "Bin resolution"; public static final String PROPERTY_L2BIN_RESOLUTION_DEFAULT = ""; public static final String PROPERTY_L2BIN_AREA_WEIGHTING_KEY = PROPERTY_L2BIN_ROOT_KEY + ".area_weighting"; public static final String PROPERTY_L2BIN_AREA_WEIGHTING_LABEL = "area_weighting"; public static final String PROPERTY_L2BIN_AREA_WEIGHTING_TOOLTIP = "Area Weighting"; public static final String PROPERTY_L2BIN_AREA_WEIGHTING_DEFAULT = "0"; public static final String PROPERTY_L2BIN_FLAGUSE_KEY = PROPERTY_L2BIN_ROOT_KEY + ".flaguse"; public static final String PROPERTY_L2BIN_FLAGUSE_LABEL = "flaguse"; public static final String PROPERTY_L2BIN_FLAGUSE_TOOLTIP = "Flags to use for binning"; public static final String PROPERTY_L2BIN_FLAGUSE_DEFAULT = ""; public static final String PROPERTY_L2BIN_LATNORTH_KEY = PROPERTY_L2BIN_ROOT_KEY + ".latnorth"; public static final String PROPERTY_L2BIN_LATNORTH_LABEL = "latnorth"; public static final String PROPERTY_L2BIN_LATNORTH_TOOLTIP = "Northernmost latitude"; public static final String PROPERTY_L2BIN_LATNORTH_DEFAULT = ""; public static final String PROPERTY_L2BIN_LATSOUTH_KEY = PROPERTY_L2BIN_ROOT_KEY + ".latsouth"; public static final String PROPERTY_L2BIN_LATSOUTH_LABEL = "latsouth"; public static final String PROPERTY_L2BIN_LATSOUTH_TOOLTIP = "Southernmost latitude"; public static final String PROPERTY_L2BIN_LATSOUTH_DEFAULT = ""; public static final String PROPERTY_L2BIN_LONWEST_KEY = PROPERTY_L2BIN_ROOT_KEY + ".lonwest"; public static final String PROPERTY_L2BIN_LONWEST_LABEL = "lonwest"; public static final String PROPERTY_L2BIN_LONWEST_TOOLTIP = "Westernmost longitude"; public static final String PROPERTY_L2BIN_LONWEST_DEFAULT = ""; public static final String PROPERTY_L2BIN_LONEAST_KEY = PROPERTY_L2BIN_ROOT_KEY + ".loneast"; public static final String PROPERTY_L2BIN_LONEAST_LABEL = "loneast"; public static final String PROPERTY_L2BIN_LONEAST_TOOLTIP = "Easternmost longitude"; public static final String PROPERTY_L2BIN_LONEAST_DEFAULT = ""; // Property Setting: Restore Defaults private static final String PROPERTY_RESTORE_KEY_SUFFIX = PROPERTY_L2BIN_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 (L2bin Preferences)"; public static final String PROPERTY_RESTORE_DEFAULTS_TOOLTIP = "Restore all l2bin 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_L2BIN_L3BPROD_KEY, PROPERTY_L2BIN_L3BPROD_DEFAULT); initPropertyDefaults(context, PROPERTY_L2BIN_PRODTYPE_KEY, PROPERTY_L2BIN_PRODTYPE_DEFAULT); initPropertyDefaults(context, PROPERTY_L2BIN_RESOLUTION_KEY, PROPERTY_L2BIN_RESOLUTION_DEFAULT); initPropertyDefaults(context, PROPERTY_L2BIN_AREA_WEIGHTING_KEY, PROPERTY_L2BIN_AREA_WEIGHTING_DEFAULT); initPropertyDefaults(context, PROPERTY_L2BIN_FLAGUSE_KEY, PROPERTY_L2BIN_FLAGUSE_DEFAULT); initPropertyDefaults(context, PROPERTY_L2BIN_LATNORTH_KEY, PROPERTY_L2BIN_LATNORTH_DEFAULT); initPropertyDefaults(context, PROPERTY_L2BIN_LATSOUTH_KEY, PROPERTY_L2BIN_LATSOUTH_DEFAULT); initPropertyDefaults(context, PROPERTY_L2BIN_LONWEST_KEY, PROPERTY_L2BIN_LONWEST_DEFAULT); initPropertyDefaults(context, PROPERTY_L2BIN_LONEAST_KEY, PROPERTY_L2BIN_LONEAST_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("OCSSW_L2binPreferences"); } @SuppressWarnings("UnusedDeclaration") static class SeadasToolboxBean { @Preference(key = PROPERTY_L2BIN_L3BPROD_KEY, label = PROPERTY_L2BIN_L3BPROD_LABEL, description = PROPERTY_L2BIN_L3BPROD_TOOLTIP) String l2binL3bprodDefault = PROPERTY_L2BIN_L3BPROD_DEFAULT; @Preference(key = PROPERTY_L2BIN_PRODTYPE_KEY, label = PROPERTY_L2BIN_PRODTYPE_LABEL, description = PROPERTY_L2BIN_PRODTYPE_TOOLTIP) String l2binProdtypeDefault = PROPERTY_L2BIN_PRODTYPE_DEFAULT; @Preference(key = PROPERTY_L2BIN_RESOLUTION_KEY, label = PROPERTY_L2BIN_RESOLUTION_LABEL, description = PROPERTY_L2BIN_RESOLUTION_TOOLTIP) String l2binResolutionDefault = PROPERTY_L2BIN_RESOLUTION_DEFAULT; @Preference(key = PROPERTY_L2BIN_AREA_WEIGHTING_KEY, label = PROPERTY_L2BIN_AREA_WEIGHTING_LABEL, description = PROPERTY_L2BIN_AREA_WEIGHTING_TOOLTIP) String l2binAreaWeightingDefault = PROPERTY_L2BIN_AREA_WEIGHTING_DEFAULT; @Preference(key = PROPERTY_L2BIN_FLAGUSE_KEY, label = PROPERTY_L2BIN_FLAGUSE_LABEL, description = PROPERTY_L2BIN_FLAGUSE_TOOLTIP) String l2binFlaguseDefault = PROPERTY_L2BIN_FLAGUSE_DEFAULT; @Preference(key = PROPERTY_L2BIN_LATNORTH_KEY, label = PROPERTY_L2BIN_LATNORTH_LABEL, description = PROPERTY_L2BIN_LATNORTH_TOOLTIP) String l2binLatnorthDefault = PROPERTY_L2BIN_LATNORTH_DEFAULT; @Preference(key = PROPERTY_L2BIN_LATSOUTH_KEY, label = PROPERTY_L2BIN_LATSOUTH_LABEL, description = PROPERTY_L2BIN_LATSOUTH_TOOLTIP) String l2binLatsouthDefault = PROPERTY_L2BIN_LATSOUTH_DEFAULT; @Preference(key = PROPERTY_L2BIN_LONWEST_KEY, label = PROPERTY_L2BIN_LONWEST_LABEL, description = PROPERTY_L2BIN_LONWEST_TOOLTIP) String l2binLonwestDefault = PROPERTY_L2BIN_LONWEST_DEFAULT; @Preference(key = PROPERTY_L2BIN_LONEAST_KEY, label = PROPERTY_L2BIN_LONEAST_LABEL, description = PROPERTY_L2BIN_LONEAST_TOOLTIP) String l2binLoneastDefault = PROPERTY_L2BIN_LONEAST_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 getPreferenceL3bprod() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(PROPERTY_L2BIN_L3BPROD_KEY, PROPERTY_L2BIN_L3BPROD_DEFAULT); } public static String getPreferenceProdtype() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(PROPERTY_L2BIN_PRODTYPE_KEY, PROPERTY_L2BIN_PRODTYPE_DEFAULT); } public static String getPreferenceResolution() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(PROPERTY_L2BIN_RESOLUTION_KEY, PROPERTY_L2BIN_RESOLUTION_DEFAULT); } public static String getPreferenceAreaWeighting() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(PROPERTY_L2BIN_AREA_WEIGHTING_KEY, PROPERTY_L2BIN_AREA_WEIGHTING_DEFAULT); } public static String getPreferenceFlaguse() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(PROPERTY_L2BIN_FLAGUSE_KEY, PROPERTY_L2BIN_FLAGUSE_DEFAULT); } public static String getPreferenceLatnorth() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(PROPERTY_L2BIN_LATNORTH_KEY, PROPERTY_L2BIN_LATNORTH_DEFAULT); } public static String getPreferenceLatsouth() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(PROPERTY_L2BIN_LATSOUTH_KEY, PROPERTY_L2BIN_LATSOUTH_DEFAULT); } public static String getPreferenceLonwest() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(PROPERTY_L2BIN_LONWEST_KEY, PROPERTY_L2BIN_LONWEST_DEFAULT); } public static String getPreferenceLoneast() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyString(PROPERTY_L2BIN_LONEAST_KEY, PROPERTY_L2BIN_LONEAST_DEFAULT); } }
18,357
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSW_L2genController.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/preferences/OCSSW_L2genController.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.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 l2gen preferences. Sub-panel of the "SeaDAS-Toolbox"-panel. * * @author Daniel Knowles */ @OptionsPanelController.SubRegistration(location = "SeaDAS", displayName = "#Options_DisplayName_OCSSW_L2gen", keywords = "#Options_Keywords_OCSSW_L2gen", keywordsCategory = "Processors", id = "L2gen") @org.openide.util.NbBundle.Messages({ "Options_DisplayName_OCSSW_L2gen=L2gen", "Options_Keywords_OCSSW_L2gen=seadas, ocssw, l2gen" }) public final class OCSSW_L2genController extends DefaultConfigController { Property restoreDefaults; boolean propertyValueChangeEventsEnabled = true; protected PropertySet createPropertySet() { return createPropertySet(new SeadasToolboxBean()); } // Preferences property prefix private static final String PROPERTY_L2GEN_ROOT_KEY = SeadasToolboxDefaults.PROPERTY_SEADAS_ROOT_KEY + ".l2gen"; // Property Setting: Restore Defaults private static final String PROPERTY_RESTORE_KEY_SUFFIX = PROPERTY_L2GEN_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 (L2gen Preferences)"; public static final String PROPERTY_RESTORE_DEFAULTS_TOOLTIP = "Restore all l2gen preferences to the original default"; public static final boolean PROPERTY_RESTORE_DEFAULTS_DEFAULT = false; public static final String PROPERTY_L2GEN_SHORTCUTS_KEY = PROPERTY_L2GEN_ROOT_KEY + ".shortcuts"; public static final String PROPERTY_L2GEN_SHORTCUTS_LABEL = "L2prod Wavelength Shortcuts"; public static final String PROPERTY_L2GEN_SHORTCUTS_TOOLTIP = "Use wavelength shortcuts (i.e. Rrs_vvv, Rrs_iii) in l2prod"; public static final boolean PROPERTY_L2GEN_SHORTCUTS_DEFAULT = true; @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_L2GEN_SHORTCUTS_KEY, PROPERTY_L2GEN_SHORTCUTS_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("OCSSW_L2gen_preferences"); } @SuppressWarnings("UnusedDeclaration") static class SeadasToolboxBean { @Preference(key = PROPERTY_L2GEN_SHORTCUTS_KEY, label = PROPERTY_L2GEN_SHORTCUTS_LABEL, description = PROPERTY_L2GEN_SHORTCUTS_TOOLTIP) boolean l2genL2prodWavelengthShortcuts = PROPERTY_L2GEN_SHORTCUTS_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 boolean getPreferenceUseWavelengthShortcuts() { final PropertyMap preferences = SnapApp.getDefault().getAppContext().getPreferences(); return preferences.getPropertyBool(PROPERTY_L2GEN_SHORTCUTS_KEY, PROPERTY_L2GEN_SHORTCUTS_DEFAULT); } }
10,800
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SeadasToolboxDefaults.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/preferences/SeadasToolboxDefaults.java
package gov.nasa.gsfc.seadas.processing.preferences; public class SeadasToolboxDefaults { // Preferences property prefix public static final String PROPERTY_SEADAS_ROOT_KEY = "seadas.toolbox"; }
208
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
GetSysInfoGUI.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ocssw/GetSysInfoGUI.java
package gov.nasa.gsfc.seadas.processing.ocssw; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.about.SnapAboutBox; import org.esa.snap.runtime.Config; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.ModalDialog; import org.esa.snap.core.datamodel.Product; //import org.jsoup.Connection; //import org.jsoup.Jsoup; //import org.jsoup.nodes.Document; //import org.jsoup.nodes.Element; import javax.swing.*; import javax.swing.filechooser.FileSystemView; import java.awt.*; import javax.swing.text.AttributeSet; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.prefs.Preferences; import org.openide.modules.ModuleInfo; import org.openide.modules.Modules; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWConfigData.*; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo.*; /** * @author Aynur Abdurazik * @author Bing Yang */ // May 2020 - Yang - print out relevant system info for SeaDAS or OCSSW troubleshooting public class GetSysInfoGUI { final String PANEL_NAME = "Seadas/System Information"; final String HELP_ID = "getSysInfo"; String sysInfoText; String currentInfoLine; ModalDialog modalDialog; // PropertyContainer pc = new PropertyContainer(); boolean windowsOS; private String ocsswScriptsDirPath; private String ocsswSeadasInfoPath; private String ocsswRunnerScriptPath; private String ocsswBinDirPath; private String ocsswRootEnv = System.getenv(SEADAS_OCSSW_ROOT_ENV); String ocsswRootDocker = SystemUtils.getUserHomeDir().toString() + File.separator + "ocssw"; private String DASHES = "-----------------------------------------------------------"; private String INDENT = " "; public static void main(String args[]) { final AppContext appContext = SnapApp.getDefault().getAppContext(); final Window parent = appContext.getApplicationWindow(); GetSysInfoGUI getSysInfoGUI = new GetSysInfoGUI(); getSysInfoGUI.init(parent); } public void init(Window parent) { String operatingSystem = System.getProperty("os.name"); if (operatingSystem.toLowerCase().contains("windows")) { windowsOS = true; ocsswRootEnv = ocsswRootDocker; } else { windowsOS = false; } JPanel mainPanel = GridBagUtils.createPanel(); modalDialog = new ModalDialog(parent, PANEL_NAME, mainPanel, ModalDialog.ID_OK_CANCEL_HELP, HELP_ID) { @Override protected void onOK() { SystemUtils.copyToClipboard(sysInfoText); } }; modalDialog.getButton(ModalDialog.ID_OK).setText("Copy To Clipboard"); modalDialog.getButton(ModalDialog.ID_CANCEL).setText("Close"); modalDialog.getButton(ModalDialog.ID_HELP).setText("Help"); GridBagConstraints gbc = createConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.weighty = 1; gbc.weightx = 1; JPanel sysInfoPanel = sysInfoPanel(); mainPanel.add(sysInfoPanel, gbc); // Add filler panel at bottom which expands as needed to force all components within this panel to the top gbc.gridy += 1; gbc.weighty = 0; gbc.weightx = 1; gbc.fill = GridBagConstraints.VERTICAL; JPanel fillerPanel = new JPanel(); fillerPanel.setMinimumSize(fillerPanel.getPreferredSize()); mainPanel.add(fillerPanel, gbc); mainPanel.setMinimumSize(mainPanel.getMinimumSize()); modalDialog.getButton(ModalDialog.ID_OK).setMinimumSize(modalDialog.getButton(ModalDialog.ID_OK).getPreferredSize()); // Specifically set sizes for dialog here Dimension minimumSizeAdjusted = adjustDimension(modalDialog.getJDialog().getMinimumSize(), 25, 25); Dimension preferredSizeAdjusted = adjustDimension(modalDialog.getJDialog().getPreferredSize(), 25, 25); modalDialog.getJDialog().setMinimumSize(minimumSizeAdjusted); modalDialog.getJDialog().setPreferredSize(preferredSizeAdjusted); modalDialog.getJDialog().pack(); int dialogResult; boolean finish = false; while (!finish) { dialogResult = modalDialog.show(); if (dialogResult == ModalDialog.ID_CANCEL) { finish = true; } else { finish = true; } // finish = true; } return; } protected JPanel sysInfoPanel() { JPanel panel = GridBagUtils.createPanel(); GridBagConstraints gbc = createConstraints(); // JTextArea sysInfoTextarea = new JTextArea(45,66); // sysInfoTextarea.setLineWrap(true); // sysInfoTextarea.setEditable(false); JTextPane sysInfoTextpane = new JTextPane(); // JScrollPane scroll = new JScrollPane(sysInfoTextarea); JScrollPane scroll = new JScrollPane(sysInfoTextpane); scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); // panel.add(scroll, gbc); // final Preferences preferences = Config.instance("seadas").load().preferences(); // String lastOcsswLocation = preferences.get(SEADAS_OCSSW_LOCATION_PROPERTY, SEADAS_OCSSW_LOCATION_DEFAULT_VALUE); SnapApp snapapp = SnapApp.getDefault(); String appNameVersion = snapapp.getInstanceName() + " " + SystemUtils.getReleaseVersion(); String appName = SystemUtils.getApplicationName(); String appReleaseVersionFromPOM = SystemUtils.getReleaseVersion(); File appHomeDir = SystemUtils.getApplicationHomeDir(); File appDataDir = SystemUtils.getApplicationDataDir(); Path appBinDir = appHomeDir.toPath().resolve("bin"); Path appEtcDir = appHomeDir.toPath().resolve("etc"); Path appHomeSnapProperties = appEtcDir.resolve("snap.properties"); ; Path appHomeSnapConf = appEtcDir.resolve("snap.conf"); Path appHomeSeadasConf = appEtcDir.resolve("seadas.conf"); boolean isSeadasPlatform = (appNameVersion != null && appNameVersion.toLowerCase().contains("seadas")) ? true : false; Path dataDirPath = appDataDir.toPath(); Path dataEtcPath = dataDirPath.resolve("etc"); Path runtimeSnapProperties = dataEtcPath.resolve("snap.properties"); Path runtimeSeadasProperties = dataEtcPath.resolve("seadas.properties"); Path vmOptions = appBinDir.resolve("pconvert.vmoptions"); Path vmOptionsGpt = appBinDir.resolve("gpt.vmoptions"); String jre = System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version"); String jvm = System.getProperty("java.vm.name") + " by " + System.getProperty("java.vendor"); String memory = Math.round(Runtime.getRuntime().maxMemory() / 1024. / 1024.) + " MiB"; ModuleInfo seadasProcessingModuleInfo = Modules.getDefault().ownerOf(OCSSWInfoGUI.class); ModuleInfo desktopModuleInfo = Modules.getDefault().ownerOf(SnapAboutBox.class); ModuleInfo engineModuleInfo = Modules.getDefault().ownerOf(Product.class); // System.out.println("\nMain Application Platform:"); // System.out.println("Application Name Version: " + appNameVersion); // System.out.println("Application Home Directory: " + appHomeDir.toString()); // System.out.println("Application Data Directory: " + appDataDir.toString()); // System.out.println("Application Configuration: " + appConfig.toString()); // System.out.println("Virtual Memory Configuration: " + vmOptions.toString()); // System.out.println("Virtual Memory Configuration (gpt): " + vmOptionsGpt.toString()); // System.out.println("Desktop Specification Version: " + desktopModuleInfo.getSpecificationVersion()); // System.out.println("Desktop Implementation Version: " + desktopModuleInfo.getImplementationVersion()); // System.out.println("Engine Specification Version: " + engineModuleInfo.getSpecificationVersion()); // System.out.println("Engine Implementation Version: " + engineModuleInfo.getImplementationVersion()); // System.out.println("JRE: " + jre); // System.out.println("JVM: " + jvm); // System.out.println("Memory: " + memory); // // System.out.println("SeaDAS Toolbox Specification Version: " + seadasProcessingModuleInfo.getSpecificationVersion()); // System.out.println("SeaDAS Toolbox Implementation Version: " + seadasProcessingModuleInfo.getImplementationVersion()); // // String test =Config.instance().preferences().get("seadas.version", null); // System.out.println("seadas.version=" + test); OCSSWInfo ocsswInfo = OCSSWInfo.getInstance(); String ocsswRootOcsswInfo = ocsswInfo.getOcsswRoot(); String ocsswLogDir = ocsswInfo.getLogDirPath(); String ocsswLocation = ocsswInfo.getOcsswLocation(); String ocsswDebugInfo = ocsswInfo.getOcsswDebugInfo(); Boolean ocsswDebug; if (ocsswDebugInfo.equals("true")) { ocsswDebug = true; } else { ocsswDebug = false; } // System.out.println("appDir = " + installDir); // System.out.println("ocsswRootOcsswInfo = " + ocsswRootOcsswInfo); // System.out.println("OCSSW Log Directory = " + ocsswLogDir); // System.out.println("OCSSW Location = " + lastOcsswLocation); sysInfoText = ""; currentInfoLine = DASHES + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = INDENT + "Main Application Platform: " + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = DASHES + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = "Application Version: " + appNameVersion + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); String brandingSuffix = ""; if (isSeadasPlatform) { brandingSuffix = "* (SeaDAS Platform modified)"; } currentInfoLine = "SNAP Engine Version: " + engineModuleInfo.getSpecificationVersion() + brandingSuffix + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (ocsswDebug) { currentInfoLine = "Snap Engine Implementation Version: " + engineModuleInfo.getImplementationVersion() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); } currentInfoLine = "SNAP Desktop Version: " + desktopModuleInfo.getSpecificationVersion() + brandingSuffix + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (ocsswDebug) { currentInfoLine = "SNAP Desktop Implementation Version: " + desktopModuleInfo.getImplementationVersion() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); } currentInfoLine = "SNAP Engine Build Date: " + engineModuleInfo.getBuildVersion() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = "SNAP Desktop Build Date: " + desktopModuleInfo.getBuildVersion() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = "Installation Directory: " + appHomeDir.toString() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (!appHomeDir.isDirectory()) { currentInfoLine = " WARNING!! Directory '" + appHomeDir.toString() + "' does not exist" + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } currentInfoLine = "Data Directory: " + appDataDir.toString() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (!appDataDir.isDirectory()) { currentInfoLine = " WARNING!! Directory '" + appDataDir.toString() + "' does not exist" + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } currentInfoLine = "Configuration: " + appHomeSnapProperties.toString() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (!Files.exists(appHomeSnapProperties)) { currentInfoLine = " WARNING!! File '" + appHomeSnapProperties.toString() + "' does not exist" + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } if (isSeadasPlatform) { currentInfoLine = "VM Configuration: " + appHomeSeadasConf.toString() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (!Files.exists(appHomeSeadasConf)) { currentInfoLine = " WARNING!! File '" + appHomeSeadasConf.toString() + "' does not exist" + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } currentInfoLine = "VM Configuration: " + appHomeSnapConf.toString() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (!Files.exists(appHomeSnapConf)) { currentInfoLine = " WARNING!! File '" + appHomeSnapConf.toString() + "' does not exist" + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } } else { currentInfoLine = "VM Configuration: " + appHomeSnapConf.toString() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (!Files.exists(appHomeSnapConf)) { currentInfoLine = " WARNING!! File '" + appHomeSnapConf.toString() + "' does not exist" + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } } currentInfoLine = "VM Configuration (gpt): " + vmOptionsGpt.toString() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (!Files.exists(vmOptionsGpt)) { currentInfoLine = " WARNING!! File '" + vmOptionsGpt.toString() + "' does not exist" + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } currentInfoLine = "VM Configuration (pconvert): " + vmOptions.toString() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (!Files.exists(vmOptions)) { currentInfoLine = " WARNING!! File '" + vmOptions.toString() + "' does not exist" + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } if (!Files.exists(runtimeSnapProperties)) { currentInfoLine = "Runtime Configuration: null" + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); } else { currentInfoLine = "Runtime Configuration: " + runtimeSnapProperties.toString() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); } if (!Files.exists(runtimeSeadasProperties)) { currentInfoLine = "Runtime Configuration (SeaDAS Toolbox): null" + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); } else { currentInfoLine = "Runtime Configuration (SeaDAS Toolbox): " + runtimeSeadasProperties.toString() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); } currentInfoLine = "JRE: " + jre + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = "JVM: " + jvm + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = "Memory: " + memory + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (ocsswInfo.getOcsswLocation() == OCSSW_LOCATION_LOCAL) { currentInfoLine = "OCSSWROOT (Java Env): " + ocsswRootEnv + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = ""; // todo temporary nulling this as later lines need editing try { ProcessBuilder processBuilder = new ProcessBuilder(new String[]{"/bin/bash", "-c", "-l", "which python3"}); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream())); String line; Integer numOfLines = 0; currentInfoLine = "Python3 Directory: "; while ((line = reader.readLine()) != null) { currentInfoLine += line + "\n"; if (line.trim().length() > 1) { numOfLines++; } } if (numOfLines == 0) { currentInfoLine += "\n"; } sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (numOfLines > 1) { currentInfoLine = "NOTE: the extraneous output lines displayed were detected in your login configuration output" + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } reader.close(); process.destroy(); try { Thread.sleep(10); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } if (process.exitValue() != 0) { System.out.println(" WARNING!: Non zero exit code returned for 'which python3' "); } } catch (IOException e) { String warning = " WARNING!! Could not retrieve system parameters because 'which python3' failed"; currentInfoLine = warning + "\n"; sysInfoText += currentInfoLine; currentInfoLine = e.toString() + "\n"; sysInfoText += currentInfoLine; e.printStackTrace(); } } currentInfoLine = "\n\n" + DASHES + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = INDENT + "SeaDAS Toolbox: " + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = DASHES + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = "SeaDAS Toolbox Version: " + seadasProcessingModuleInfo.getSpecificationVersion() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = "SeaDAS Toolbox Build Date: " + seadasProcessingModuleInfo.getBuildVersion() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (ocsswDebug) { currentInfoLine = "SeaDAS Toolbox Implementation Version: " + seadasProcessingModuleInfo.getImplementationVersion() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); } if (!Files.exists(runtimeSeadasProperties)) { currentInfoLine = "Configuration: null" + "\n"; sysInfoText += currentInfoLine; } else { currentInfoLine = "Configuration: " + runtimeSeadasProperties.toString() + "\n"; sysInfoText += currentInfoLine; } appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (ocsswDebug) { final Preferences preferences = Config.instance("seadas").load().preferences(); String ocsswRootSeadasProperties = preferences.get(SEADAS_OCSSW_ROOT_PROPERTY, null); currentInfoLine = "seadas.ocssw.root (seadas.properties): " + ocsswRootSeadasProperties + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); } if ("docker".equals(ocsswLocation)) { currentInfoLine = "OCSSW Docker Root Directory: " + ocsswRootDocker + "\n"; } else { currentInfoLine = "OCSSW Root Directory: " + ocsswRootOcsswInfo + "\n"; } sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if (ocsswRootOcsswInfo != null) { if (ocsswInfo.getOcsswLocation() != OCSSW_LOCATION_LOCAL) { // if (!Files.exists(Paths.get(ocsswRootDocker))) { // currentInfoLine = "WARNING!! Directory '" + ocsswRootDocker + "' does not exist" + "\n"; // sysInfoText += currentInfoLine; // appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); // } } else { if (!Files.exists(Paths.get(ocsswRootOcsswInfo))) { currentInfoLine = "WARNING!! Directory '" + ocsswRootOcsswInfo + "' does not exist" + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } } } currentInfoLine = "OCSSW Docker Log Directory: " + ocsswLogDir + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); if ((ocsswLogDir != null) && !Files.exists(Paths.get(ocsswLogDir))) { currentInfoLine = "WARNING!! Directory '" + ocsswLogDir + "' does not exist" + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } currentInfoLine = "OCSSW Location: " + ocsswLocation + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); //need to consider "docker" condition if (ocsswInfo.getOcsswLocation() == OCSSW_LOCATION_LOCAL) { currentInfoLine = "Environment {$OCSSWROOT} (external): " + ocsswRootEnv + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); } if ((ocsswRootOcsswInfo != null) && ocsswRootEnv != null && !ocsswRootOcsswInfo.equals(ocsswRootEnv) && "local".equals(ocsswLocation)) { currentInfoLine = " WARNING!: An environment variable for OCSSWROOT exists which does not match the GUI configuration. " + "The GUI will use '" + ocsswRootOcsswInfo + "' as the ocssw root inside the GUI." + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } currentInfoLine = "\n\n" + DASHES + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = INDENT + "NASA Science Processing (OCSSW): " + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); currentInfoLine = DASHES + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); ocsswScriptsDirPath = ocsswRootOcsswInfo + File.separator + OCSSW_SCRIPTS_DIR_SUFFIX; ocsswRunnerScriptPath = ocsswScriptsDirPath + System.getProperty("file.separator") + OCSSW_RUNNER_SCRIPT; ocsswBinDirPath = ocsswRootOcsswInfo + System.getProperty("file.separator") + OCSSW_BIN_DIR_SUFFIX; String[] command = {"/bin/bash", ocsswRunnerScriptPath, " --ocsswroot ", ocsswRootOcsswInfo, OCSSW_SEADAS_INFO_PROGRAM_NAME}; ocsswSeadasInfoPath = ocsswBinDirPath + System.getProperty("file.separator") + OCSSW_SEADAS_INFO_PROGRAM_NAME; if (ocsswInfo.getOcsswLocation() != OCSSW_LOCATION_LOCAL) { currentInfoLine = ocsswInfo.getRemoteSeaDASInfo(); sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); } else { if ((ocsswRootOcsswInfo == null) || (!Files.exists(Paths.get(ocsswRootOcsswInfo))) && "local".equals(ocsswLocation)) { if ((ocsswRootEnv != null) && Files.exists(Paths.get(ocsswRootEnv))) { currentInfoLine = "WARNING! Processing not configured in the GUI but an installation currently exists in the directory '" + ocsswRootEnv + "'. To configure the GUI to use this installation then update the 'OCSSW ROOT' directory in Menu > SeaDAS-Toolbox > SeaDAS Processors Location"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } else { currentInfoLine = " Warning! Processers not installed " + "\n\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); printGeneralSystemInfo(ocsswDebug); appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); } } else if ((!Files.exists(Paths.get(ocsswRootDocker))) && "docker".equals(ocsswLocation)) { currentInfoLine = " Warning (for docker)! Processers not installed " + "\n\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); printGeneralSystemInfo(ocsswDebug); appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); } else { if ("docker".equals(ocsswLocation)) { currentInfoLine = " WARNING! Cannot find 'seadas_info' in the OCSSW Docker bin directory" + "\n\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); printGeneralSystemInfo(ocsswDebug); appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } else if (!Files.isExecutable(Paths.get(ocsswSeadasInfoPath)) && "local".equals(ocsswLocation)) { currentInfoLine = " WARNING! Cannot find 'seadas_info' in the OCSSW bin directory" + "\n\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); printGeneralSystemInfo(ocsswDebug); appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); } else { currentInfoLine = ""; try { ProcessBuilder processBuilder = new ProcessBuilder(command); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { if (!line.contains("NASA Science Processing (OCSSW)")) { if (line.contains("General System and Software")) { currentInfoLine += "\n" + DASHES + "\n"; currentInfoLine += INDENT + "General System and Software: " + "\n"; currentInfoLine += DASHES + "\n"; } else { currentInfoLine += line + "\n"; } } } sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.BLACK); reader.close(); process.destroy(); try { Thread.sleep(10); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } if (process.exitValue() != 0) { System.out.println(" WARNING!: Non zero exit code returned for \'" + command + "\' "); } } catch (IOException e) { String warning = " WARNING!! Could not retrieve system parameters because command \'" + command.toString() + "\' failed"; currentInfoLine = warning + "\n"; currentInfoLine += e.toString() + "\n"; sysInfoText += currentInfoLine; appendToPane(sysInfoTextpane, currentInfoLine, Color.RED); e.printStackTrace(); } } } } sysInfoTextpane.setEditable(false); sysInfoTextpane.setCaretPosition(0); gbc.gridx = 0; gbc.weightx = 1; gbc.weighty = 1; gbc.fill = GridBagConstraints.BOTH; sysInfoTextpane.setPreferredSize(new Dimension(750, 750)); panel.add(scroll, gbc); return panel; } private void printGeneralSystemInfo(Boolean ocsswDebug) { currentInfoLine = "\n\n" + DASHES + "\n"; currentInfoLine += INDENT + "General System and Software (from GUI): " + "\n"; currentInfoLine += DASHES + "\n\n"; currentInfoLine += "Operating System: " + System.getProperty("os.name"); currentInfoLine += " " + System.getProperty("os.version") + "\n"; currentInfoLine += "Java Version: " + System.getProperty("java.version") + "\n"; if (ocsswDebug) { try { Process process = Runtime.getRuntime().exec("python --version"); BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { currentInfoLine += line + "\n"; } reader.close(); process.destroy(); if (process.exitValue() != 0) { System.out.println("WARNING!: Non zero exit code returned for 'python --version' "); } } catch (IOException e) { String warning = "WARNING!! Could not retrieve system parameters because 'pyhton --version' failed"; currentInfoLine += warning + "\n"; currentInfoLine += e.toString() + "\n"; e.printStackTrace(); } } sysInfoText += currentInfoLine; } private void appendToPane(JTextPane tp, String msg, Color c) { StyleContext sc = StyleContext.getDefaultStyleContext(); AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c); aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console"); aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED); int len = tp.getDocument().getLength(); tp.setCaretPosition(len); tp.setCharacterAttributes(aset, false); tp.replaceSelection(msg); } public File getDir() { File selectedFile = null; JFileChooser jFileChooser = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnValue = jFileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { selectedFile = jFileChooser.getSelectedFile(); //System.out.println(selectedFile.getAbsolutePath()); } return selectedFile; } public static GridBagConstraints createConstraints() { GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 1; gbc.weighty = 1; return gbc; } private Dimension adjustDimension(Dimension dimension, int widthAdjustment, int heightAdjustment) { if (dimension == null) { return null; } int width = dimension.width + widthAdjustment; int height = dimension.height + heightAdjustment; return new Dimension(width, height); } }
34,546
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OsUtils.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ocssw/OsUtils.java
package gov.nasa.gsfc.seadas.processing.ocssw; import java.util.Locale; /** * Created by aabduraz on 3/27/17. */ public final class OsUtils { /** * types of Operating Systems */ public enum OSType { Windows, MacOS, Linux, Other } ; // cached result of OS detection protected static OSType detectedOS; /** * detect the operating system from the os.name System property and cache * the result * * @returns - the operating system detected */ public static OSType getOperatingSystemType() { if (detectedOS == null) { String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); if ((OS.indexOf("mac") >= 0) || (OS.indexOf("darwin") >= 0)) { detectedOS = OSType.MacOS; } else if (OS.indexOf("win") >= 0) { detectedOS = OSType.Windows; } else if (OS.indexOf("nux") >= 0) { detectedOS = OSType.Linux; } else { detectedOS = OSType.Other; } } return detectedOS; } public static String[] getCopyCommandSyntax(){ String[] copyCommandSyntaxArray = {"cp"}; String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); if (OS.indexOf("win") >= 0) { copyCommandSyntaxArray = new String[3]; copyCommandSyntaxArray[0] = "cmd.exe"; copyCommandSyntaxArray[1] = "/C"; copyCommandSyntaxArray[2] = "copy"; } return copyCommandSyntaxArray; } }
1,606
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSWConfigData.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ocssw/OCSSWConfigData.java
package gov.nasa.gsfc.seadas.processing.ocssw; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import gov.nasa.gsfc.seadas.processing.common.SeadasFileUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.runtime.Config; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; public class OCSSWConfigData { /** seadas.log.dir = /accounts/aabduraz/SeaDAS/log #seadas.ocssw.root = /accounts/aabduraz/SeaDAS/ocssw #seadas.ocssw.root = /accounts/aabduraz/SeaDAS/ocsswserver/ocssw seadas.ocssw.root = /accounts/aabduraz/SeaDAS/dev/seadas-7.4/seadas/ocssw # set physical location of OCSSW package # the seadas.ocssw.location property should be assigned one of these three values: "local", "virtualMachine", # or the remote server IP address. seadas.ocssw.location = virtualMachine seadas.ocssw.port=6400 seadas.ocssw.sharedDir=/accounts/aabduraz/clientServerSharedDir seadas.client.id=seadas seadas.ocssw.keepFilesOnServer=false seadas.ocssw.processInputStreamPort=6402 seadas.ocssw.processErrorStreamPort=6403 */ final static String SEADAS_LOG_DIR_PROPERTY = "seadas.log.dir"; public final static String SEADAS_OCSSW_TAG_PROPERTY = "seadas.ocssw.tag"; final static String SEADAS_OCSSW_ROOT_PROPERTY = "seadas.ocssw.root"; final static String SEADAS_OCSSW_ROOT_ENV = "OCSSWROOT"; final static String SEADAS_OCSSW_LOCATION_PROPERTY = "seadas.ocssw.location"; final static String SEADAS_OCSSW_PORT_PROPERTY = "seadas.ocssw.port"; // final static String SEADAS_OCSSW_KEEPFILEONSERVER_PROPERTY = "seadas.ocssw.keepFilesOnServer"; final static String SEADAS_OCSSW_DELETEFILEONSERVER_PROPERTY = "seadas.ocssw.deleteFilesOnServer"; final static String SEADAS_OCSSW_PROCESSINPUTSTREAMPORT_PROPERTY = "seadas.ocssw.processInputStreamPort"; final static String SEADAS_OCSSW_PROCESSERRORSTREAMPORT_PROPERTY = "seadas.ocssw.processErrorStreamPort"; final static String SEADAS_OCSSW_SERVER_ADDRESS_PROPERTY = "seadas.ocssw.serverAddress"; final static String SEADAS_CLIENT_ID_PROPERTY = "seadas.client.id"; public final static String SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY = "seadas.ocssw.sharedDir"; final static String SEADAS_OCSSW_VERSION_NUMBER_PROEPRETY ="seadas.ocssw.version"; final static String SEADAS_OCSSW_DEBUG ="seadas.ocssw.debug"; final static String SEADAS_LOG_DIR_DEFAULT_VALUE = System.getProperty("user.home") + File.separator + ".seadas" + File.separator +"log"; final static String SEADAS_OCSSW_ROOT_DEFAULT_VALUE = System.getProperty("user.home") + File.separator + "ocssw"; final static String SEADAS_OCSSW_LOCATION_DEFAULT_VALUE = "local"; final static String SEADAS_OCSSW_PORT_DEFAULT_VALUE = "6400"; final static String SEADAS_OCSSW_KEEPFILEONSERVER_DEFAULT_VALUE = "false"; final static String SEADAS_OCSSW_PROCESSINPUTSTREAMPORT_DEFAULT_VALUE = "6402"; final static String SEADAS_OCSSW_PROCESSERRORSTREAMPORT_DEFAULT_VALUE = "6403"; final static String SEADAS_OCSSW_SERVER_ADDRESS_DEFAULT_VALUE = ""; final static String SEADAS_CLIENT_ID_DEFAULT_VALUE = System.getProperty("user.name"); //public final static String SEADAS_CLIENT_SERVER_SHARED_DIR_DEFAULT_VALUE = System.getProperty("user.home") + File.separator + "seadasClientServerShared"; final static String SEADAS_CLIENT_SERVER_SHARED_DIR_NAME = "seadasClientServerShared"; final static String SEADAS_OCSSW_DEBUG_DEFAULT_VALUE = "false"; public final static String SEADAS_OCSSW_TAG_DEFAULT_VALUE = "V2024.0"; public final static String SEADAS_OCSSW_TAG_DEFAULT_VALUE_ALT = ""; public final static String SEADAS_OCSSW_TAG_DEFAULT_VALUE_ALT2 = ""; final static String OCSSW_TAG_LABEL = "Valid OCSSW Tags"; final static String OCSSW_LOCATION_LABEL = "OCSSW Location"; final static String OCSSW_SHARED_DIR_LABEL = "OCSSW Shared Dir"; final static String OCSSW_ROOT_LABEL = "OCSSW ROOT"; final static String OCSSW_SERVER_ADDRESS_LABEL = "OCSSW Server Address"; final static String SERVER_PORT_LABEL = "Server Port"; final static String SERVER_INPUT_STREAM_PORT_LABEL = "Server Input Stream Port"; final static String SERVER_ERROR_STREAM_PORT_LABEL = "Server Error Stream Port"; public static Properties properties = new Properties(System.getProperties()); public OCSSWConfigData(){ //initConfigDefauls(); } private void initConfigDefauls(){ final Preferences preferences = Config.instance("seadas").load().preferences(); preferences.put(SEADAS_LOG_DIR_PROPERTY, SEADAS_LOG_DIR_DEFAULT_VALUE); preferences.put(SEADAS_OCSSW_ROOT_PROPERTY, SEADAS_OCSSW_ROOT_DEFAULT_VALUE); preferences.put(SEADAS_OCSSW_LOCATION_PROPERTY, SEADAS_OCSSW_LOCATION_DEFAULT_VALUE); preferences.put(SEADAS_OCSSW_PORT_PROPERTY, SEADAS_OCSSW_PORT_DEFAULT_VALUE); preferences.put(SEADAS_OCSSW_DELETEFILEONSERVER_PROPERTY, SEADAS_OCSSW_KEEPFILEONSERVER_DEFAULT_VALUE); preferences.put(SEADAS_OCSSW_PROCESSINPUTSTREAMPORT_PROPERTY, SEADAS_OCSSW_PROCESSINPUTSTREAMPORT_DEFAULT_VALUE); preferences.put(SEADAS_OCSSW_PROCESSERRORSTREAMPORT_PROPERTY, SEADAS_OCSSW_PROCESSERRORSTREAMPORT_DEFAULT_VALUE); preferences.put(SEADAS_CLIENT_ID_PROPERTY, SEADAS_CLIENT_ID_DEFAULT_VALUE); preferences.put(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY, getSeadasClientServerSharedDirDefaultValue()); try { preferences.flush(); } catch (BackingStoreException e) { SnapApp.getDefault().getLogger().severe(e.getMessage()); } } public static String getSeadasClientServerSharedDirDefaultValue(){ Path path = Paths.get(System.getProperty("user.home"), SEADAS_CLIENT_SERVER_SHARED_DIR_NAME); SeadasFileUtils.debug("seadasClientServerDIR path: " + path.toString()); return path.toString(); } public void updateconfigData(PropertyContainer pc) { final Preferences preferences = Config.instance("seadas").load().preferences(); Property[] newProperties = pc.getProperties(); String key, value; for (int i = 0; i < newProperties.length; i++) { key = newProperties[i].getName(); value = newProperties[i].getValue(); preferences.put(key, value); } try { preferences.flush(); } catch (BackingStoreException e) { SnapApp.getDefault().getLogger().severe(e.getMessage()); } OCSSWInfo.updateOCSSWInfo(); } }
6,752
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OcsswCommandArrayManager.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ocssw/OcsswCommandArrayManager.java
package gov.nasa.gsfc.seadas.processing.ocssw; import gov.nasa.gsfc.seadas.processing.core.ParamList; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import java.io.File; /** * Created by aabduraz on 6/12/16. */ public abstract class OcsswCommandArrayManager { ProcessorModel processorModel; public String[] cmdArray; protected ParamList paramList; private File ifileDir; OcsswCommandArrayManager(ProcessorModel processorModel) { this.processorModel = processorModel; paramList = processorModel.getParamList(); ifileDir = processorModel.getIFileDir(); } public abstract String[] getProgramCommandArray(); public File getIfileDir() { return ifileDir; } public void setIfileDir(File ifileDir) { this.ifileDir = ifileDir; } }
829
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSW.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ocssw/OCSSW.java
package gov.nasa.gsfc.seadas.processing.ocssw; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.core.runtime.RuntimeContext; import com.bc.ceres.core.runtime.Version; import gov.nasa.gsfc.seadas.processing.common.FileInfoFinder; import gov.nasa.gsfc.seadas.processing.core.*; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.core.util.VersionChecker; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.runtime.Config; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import javax.swing.*; import java.awt.*; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import static gov.nasa.gsfc.seadas.processing.core.L2genData.OPER_DIR; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWConfigData.SEADAS_LOG_DIR_PROPERTY; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWConfigData.SEADAS_OCSSW_ROOT_PROPERTY; /** * Created by aabduraz on 3/27/17. * To install ocssw run: /tmp/install_ocssw --tag $TAG -i $OCSSWROOT --seadas --$MISSIONNAME * To get valid ocssw tags: /tmp/install_ocssw --list_tags */ public abstract class OCSSW { public static final String SEADAS_OCSSW_VERSIONS_JSON_NAME = "seadasVersions.json"; public static final String OCSSW_CLIENT_SHARED_DIR_NAME_PROPERTY = "ocssw.sharedDir"; public static final String MLP_PAR_FILE_NAME = "mlp_par_file"; public static final String OCSSW_INSTALLER_URL = "https://oceandata.sci.gsfc.nasa.gov/manifest/install_ocssw"; public static final String OCSSW_BOOTSTRAP_URL = "https://oceandata.sci.gsfc.nasa.gov/manifest/ocssw_bootstrap"; public static final String OCSSW_MANIFEST_URL = "https://oceandata.sci.gsfc.nasa.gov/manifest/manifest.py"; public static final String OCSSW_SEADAS_VERSIONS_URL = "https://oceandata.sci.gsfc.nasa.gov/manifest/seadasVersions.json"; public static final File TMP_OCSSW_INSTALLER_DIR = new File(System.getProperty("java.io.tmpdir") + File.separator + System.getProperty("user.name")); // public static final String TMP_OCSSW_INSTALLER = (new File(System.getProperty("java.io.tmpdir"), "install_ocssw")).getPath(); public static final String TMP_OCSSW_INSTALLER = (new File(TMP_OCSSW_INSTALLER_DIR, "install_ocssw")).getPath(); // public static final String TMP_OCSSW_BOOTSTRAP = (new File(System.getProperty("java.io.tmpdir"), "ocssw_bootstrap")).getPath(); public static final String TMP_OCSSW_BOOTSTRAP = (new File(TMP_OCSSW_INSTALLER_DIR, "ocssw_bootstrap")).getPath(); // public static final String TMP_OCSSW_MANIFEST = (new File(System.getProperty("java.io.tmpdir"), "manifest.py")).getPath(); public static final String TMP_OCSSW_MANIFEST = (new File(TMP_OCSSW_INSTALLER_DIR, "manifest.py")).getPath(); // public static final String TMP_SEADAS_OCSSW_VERSIONS_FILE = (new File(System.getProperty("java.io.tmpdir"), SEADAS_OCSSW_VERSIONS_JSON_NAME)).getPath(); public static final String TMP_SEADAS_OCSSW_VERSIONS_FILE = (new File(TMP_OCSSW_INSTALLER_DIR, SEADAS_OCSSW_VERSIONS_JSON_NAME)).getPath(); // public static String NEXT_LEVEL_NAME_FINDER_PROGRAM_NAME = "next_level_name"; public static String GET_OUTPUT_NAME_PROGRAM_NAME = "get_output_name"; public static String GET_OUTPUT_NAME_TOKEN = "Output Name:"; public static final String OBPG_FILE_TYPE_PROGRAM_NAME = "obpg_file_type"; public static final String UPDATE_LUTS_PROGRAM_NAME = "update_luts"; private static boolean monitorProgress = false; private ArrayList<String> ocsswTags; private String seadasVersion; private String seadasToolboxVersion; private ArrayList<String> ocsswTagsValid4CurrentSeaDAS; String programName; private String xmlFileName; String ifileName; //File ifileDir; private String missionName; private String fileType; String[] commandArrayPrefix; String[] commandArraySuffix; String[] commandArray; //HashMap<String, Mission> missions; OCSSWInfo ocsswInfo = OCSSWInfo.getInstance(); private int processExitValue; private boolean ofileNameFound; String ofileName; String ofileDir; String ifileDir; private String serverSharedDirName = null; private boolean ocsswInstalScriptDownloadSuccessful = false; public static OCSSW getOCSSWInstance() { OCSSWInfo ocsswInfo = OCSSWInfo.getInstance(); if (ocsswInfo == null) { return null; } String ocsswLocation = ocsswInfo.getOcsswLocation(); if ( ocsswLocation == null) { return null; } if (ocsswLocation.equals(OCSSWInfo.OCSSW_LOCATION_LOCAL)) { return new OCSSWLocal(); } else if (ocsswLocation.equals(OCSSWInfo.OCSSW_LOCATION_VIRTUAL_MACHINE)) { return new OCSSWVM(); } else if (ocsswLocation.equals(OCSSWInfo.OCSSW_LOCATION_DOCKER)) { return new OCSSWVM(); } else if (ocsswLocation.equals(OCSSWInfo.OCSSW_LOCATION_REMOTE_SERVER)) { return new OCSSWRemote(); } return new OCSSWLocal(); } public abstract ProcessObserver getOCSSWProcessObserver(Process process, String processName, ProgressMonitor progressMonitor); public boolean isOCSSWExist() { return ocsswInfo.isOCSSWExist(); } public boolean isProgramValid() { return true; } public String getOCSSWLogDirPath(){ Preferences preferences; String appContextId = SystemUtils.getApplicationContextId(); String logDirPath = ifileDir; preferences = Config.instance("seadas").load().preferences(); if (preferences != null ) { logDirPath = preferences.get(SEADAS_LOG_DIR_PROPERTY, ifileDir); if (logDirPath == null) { logDirPath = SystemUtils.getApplicationDataDir() + File.separator + "seadas_logs"; } File logDir = new File(logDirPath); if (!logDir.exists()) { try { Files.createDirectories(Paths.get(logDirPath)); } catch (IOException e) { e.printStackTrace(); } } } return logDirPath; } public abstract boolean isMissionDirExist(String missionName); public abstract String[] getMissionSuites(String missionName, String programName); public abstract ArrayList<String> readSensorFileIntoArrayList(File file); public abstract Process execute(ProcessorModel processorModel); public abstract String executeUpdateLuts(ProcessorModel processorModel); public abstract Process executeSimple(ProcessorModel processorModel); public abstract InputStream executeAndGetStdout(ProcessorModel processorModel); public abstract Process execute(ParamList paramList); public abstract Process execute(String[] commandArray); public abstract Process execute(String programName, String[] commandArrayParams); public abstract void getOutputFiles(ProcessorModel processorModel); public abstract boolean getIntermediateOutputFiles(ProcessorModel processorModel); public abstract void findFileInfo(String fileName, FileInfoFinder fileInfoFinder); public abstract String getOfileDir(); public abstract String getOfileName(String ifileName); public abstract String getOfileName(String ifileName, String programName); public abstract String getOfileName(String ifileName, String[] options); public abstract String getOfileName(String ifileName, String programName, String suiteValue); public String getProgramName() { return programName; } public void setProgramName(String programName) { this.programName = programName; setCommandArrayPrefix(); setCommandArraySuffix(); } public abstract void setCommandArrayPrefix(); public abstract void setCommandArraySuffix(); public String getMissionName() { return missionName; } public void setMissionName(String missionName) { this.missionName = missionName; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String[] getCommandArraySuffix() { return commandArraySuffix; } public void setCommandArraySuffix(String[] commandArraySuffix) { this.commandArraySuffix = commandArraySuffix; } public void updateOCSSWRoot(String installDir) { FileWriter fileWriter = null; try { final FileReader reader = new FileReader(new File(RuntimeContext.getConfig().getConfigFilePath())); final BufferedReader br = new BufferedReader(reader); StringBuilder text = new StringBuilder(); String line; boolean isOCSSWRootSpecified = false; while ((line = br.readLine()) != null) { if (line.startsWith("seadas.ocssw.root")) { line = "seadas.ocssw.root = " + installDir; isOCSSWRootSpecified = true; } text.append(line); text.append("\n"); } //Append "seadas.ocssw.root = " + installDir + "\n" to the runtime config file if it is not exist if (!isOCSSWRootSpecified) { text.append("seadas.ocssw.root = " + installDir + "\n"); } fileWriter = new FileWriter(new File(RuntimeContext.getConfig().getConfigFilePath())); fileWriter.write(text.toString()); if (fileWriter != null) { fileWriter.close(); } ocsswInfo.setOcsswRoot(installDir); } catch (IOException ioe) { ioe.printStackTrace(); } } public void updateOCSSWRootProperty(String installDir) { final Preferences preferences = Config.instance("seadas").load().preferences(); preferences.put(SEADAS_OCSSW_ROOT_PROPERTY, installDir); try { preferences.flush(); } catch (BackingStoreException e) { SnapApp.getDefault().getLogger().severe(e.getMessage()); } } public String[] getCommandArray() { return commandArray; } public void setCommandArray(String[] commandArray) { this.commandArray = commandArray; } public String getIfileName() { return ifileName; } public void setIfileName(String ifileName) { this.ifileName = ifileName; if (ifileName != null) { ifileDir = new File(ifileName).getParent(); } setOfileNameFound(false); ofileName = null; } public String getXmlFileName() { return xmlFileName; } public void setXmlFileName(String xmlFileName) { this.xmlFileName = xmlFileName; } public static boolean isMonitorProgress() { return monitorProgress; } public static void setMonitorProgress(boolean mProgress) { monitorProgress = mProgress; } public abstract HashMap<String, String> computePixelsFromLonLat(ProcessorModel processorModel); public int getProcessExitValue() { return processExitValue; } public void setProcessExitValue(int processExitValue) { this.processExitValue = processExitValue; } public void waitForProcess() { } public boolean isOfileNameFound() { return ofileNameFound; } public void setOfileNameFound(boolean ofileNameFound) { this.ofileNameFound = ofileNameFound; } public String getOCSSWClientSharedDirName() { return RuntimeContext.getConfig().getContextProperty(OCSSW_CLIENT_SHARED_DIR_NAME_PROPERTY); } public void setServerSharedDirName(String name) { serverSharedDirName = name; } public String getServerSharedDirName() { return serverSharedDirName; } private static void handleException(String errorMessage) { Dialogs.showError(errorMessage); } public boolean isOcsswInstalScriptDownloadSuccessful() { return ocsswInstalScriptDownloadSuccessful; } /** * This method downloads the ocssw installer program ocssw_install to a tmp directory * @return */ public boolean downloadOCSSWInstaller() { if (isOcsswInstalScriptDownloadSuccessful()) { return ocsswInstalScriptDownloadSuccessful; } try { //download install_ocssw URL website = new URL(OCSSW_INSTALLER_URL); if(!TMP_OCSSW_INSTALLER_DIR.exists()){ TMP_OCSSW_INSTALLER_DIR.mkdir(); } ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(TMP_OCSSW_INSTALLER); fos.getChannel().transferFrom(rbc, 0, 1 << 24); fos.close(); (new File(TMP_OCSSW_INSTALLER)).setExecutable(true); ocsswInstalScriptDownloadSuccessful = true; //download install_ocssw website = new URL(OCSSW_BOOTSTRAP_URL); rbc = Channels.newChannel(website.openStream()); fos = new FileOutputStream(TMP_OCSSW_BOOTSTRAP); fos.getChannel().transferFrom(rbc, 0, 1 << 24); fos.close(); (new File(TMP_OCSSW_BOOTSTRAP)).setExecutable(true); //download manifest.py website = new URL(OCSSW_MANIFEST_URL); rbc = Channels.newChannel(website.openStream()); fos = new FileOutputStream(TMP_OCSSW_MANIFEST); fos.getChannel().transferFrom(rbc, 0, 1 << 24); fos.close(); (new File(TMP_OCSSW_MANIFEST)).setExecutable(true); //download seadasVersion.json website = new URL(OCSSW_SEADAS_VERSIONS_URL); rbc = Channels.newChannel(website.openStream()); fos = new FileOutputStream(TMP_SEADAS_OCSSW_VERSIONS_FILE); fos.getChannel().transferFrom(rbc, 0, 1 << 24); fos.close(); //update ocssw tags updateOCSSWTags(); } catch (MalformedURLException malformedURLException) { handleException("URL for downloading install_ocssw is not correct!"); } catch (FileNotFoundException fileNotFoundException) { handleException("ocssw installation script failed to download. \n" + "Please check network connection or 'seadas.ocssw.root' variable in the 'seadas.config' file. \n" + "possible cause of error: " + fileNotFoundException.getMessage()); } catch (IOException ioe) { handleException("ocssw installation script failed to download. \n" + "Please check network connection or 'seadas.ocssw.root' variable in the \"seadas.config\" file. \n" + "possible cause of error: " + ioe.getLocalizedMessage()); } finally { return ocsswInstalScriptDownloadSuccessful; } } public abstract void updateOCSSWTags(); public void getValidOCSSWTags4SeaDASVersion(){ //JSON parser object to parse read file setOcsswTagsValid4CurrentSeaDAS(new ArrayList<String>()); 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 void parseValidSeaDASTagObject(JSONObject tagObject) { Version currentVersion = VersionChecker.getInstance().getLocalVersion(); this.seadasVersion = currentVersion.toString(); seadasToolboxVersion = getClass().getPackage().getImplementationVersion(); String seadasVersionString = (String)tagObject.get("seadas"); if (seadasVersionString.equals(seadasToolboxVersion)) { //Get corresponding ocssw tags for seadas JSONArray ocsswTags = (JSONArray) tagObject.get("ocssw"); if (ocsswTags != null) { for (int i=0;i<ocsswTags.size();i++){ try { getOcsswTagsValid4CurrentSeaDAS().add((String) ocsswTags.get(i)); } catch (Exception e) { e.printStackTrace(); } } } } } public ArrayList<String> getOcsswTags() { return ocsswTags; } public void setOcsswTags(ArrayList<String> ocsswTags) { this.ocsswTags = ocsswTags; } public String getSeadasVersion() { return seadasVersion; } public void setSeadasVersion(String seadasVersion) { this.seadasVersion = seadasVersion; } public ArrayList<String> getOcsswTagsValid4CurrentSeaDAS() { return ocsswTagsValid4CurrentSeaDAS; } public void setOcsswTagsValid4CurrentSeaDAS(ArrayList<String> ocsswTagsValid4CurrentSeaDAS) { this.ocsswTagsValid4CurrentSeaDAS = ocsswTagsValid4CurrentSeaDAS; } public abstract InputStream getProductXMLFile(L2genData.Source source) throws IOException; }
18,213
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSWClient.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ocssw/OCSSWClient.java
package gov.nasa.gsfc.seadas.processing.ocssw; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.jsonp.JsonProcessingFeature; import org.glassfish.jersey.media.multipart.MultiPartFeature; import javax.json.stream.JsonGenerator; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 12/9/14 * Time: 12:24 PM * To change this template use File | Settings | File Templates. */ public class OCSSWClient { public static final String defaultServer ="localhost"; public static final String defaultPort = "6400"; final static String OCSSW_REST_SERVICES_CONTEXT_PATH = "ocsswws"; private WebTarget target; private String resourceBaseUri; public OCSSWClient(String serverIPAddress, String portNumber) { resourceBaseUri = getResourceBaseUri(serverIPAddress, portNumber); final ClientConfig clientConfig = new ClientConfig(); clientConfig.register(MultiPartFeature.class); clientConfig.register(JsonProcessingFeature.class).property(JsonGenerator.PRETTY_PRINTING, true); Client c = ClientBuilder.newClient(clientConfig); target = c.target(resourceBaseUri); } public OCSSWClient(String resourceBaseUri) { this.resourceBaseUri = resourceBaseUri; final ClientConfig clientConfig = new ClientConfig(); clientConfig.register(MultiPartFeature.class); clientConfig.register(JsonProcessingFeature.class).property(JsonGenerator.PRETTY_PRINTING, true); Client c = ClientBuilder.newClient(clientConfig); target = c.target(resourceBaseUri); } public OCSSWClient(){ this(defaultServer, defaultPort); } public WebTarget getOcsswWebTarget() { return target; } public WebTarget getServicePathForFileVerification(String jobId){ return target.path("fileServices").path("fileVerification").path(jobId); } public WebTarget getServicePathForFileCharSet(String jobId){ return target.path("ocssw").path("getFileCharSet").path(jobId); } private String getResourceBaseUri(String serverIPAddress, String portNumber){ resourceBaseUri = "http://" + serverIPAddress + ":" + portNumber + "/" + OCSSW_REST_SERVICES_CONTEXT_PATH + "/"; return resourceBaseUri; } }
2,419
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSWRemote.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ocssw/OCSSWRemote.java
package gov.nasa.gsfc.seadas.processing.ocssw; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import gov.nasa.gsfc.seadas.processing.common.FileInfoFinder; import gov.nasa.gsfc.seadas.processing.common.ParFileManager; import gov.nasa.gsfc.seadas.processing.common.SeadasFileUtils; import gov.nasa.gsfc.seadas.processing.common.SeadasProcess; import gov.nasa.gsfc.seadas.processing.core.*; import gov.nasa.gsfc.seadas.processing.utilities.ScrolledPane; import gov.nasa.gsfc.seadas.processing.utilities.SeadasArrayUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.runtime.Config; import org.glassfish.jersey.media.multipart.FormDataMultiPart; import org.glassfish.jersey.media.multipart.MultiPart; import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; import javax.json.*; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.prefs.Preferences; import static gov.nasa.gsfc.seadas.processing.core.L2genData.PRODUCT_XML; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWConfigData.SEADAS_CLIENT_SERVER_SHARED_DIR_NAME; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWConfigData.SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo.OCSSW_INSTALLER_PROGRAM_NAME; /** * Created by aabduraz on 3/27/17. */ public class OCSSWRemote extends OCSSW { public static final String MLP_PROGRAM_NAME = "multilevel_processor"; public static final String MLP_PAR_FILE_ODIR_KEY_NAME = "odir"; public static String MLP_OUTPUT_DIR_NAME = "mlpOutputDir"; public static final String PROCESS_STATUS_NONEXIST = "-100"; public static final String PROCESS_STATUS_STARTED = "-1"; public static final String PROCESS_STATUS_COMPLETED = "0"; public static final String PROCESS_STATUS_FAILED = "1"; public static final String US_ASCII_CHAR_SET = "us-ascii"; public static final String PROGRAM_NAMES_FOR_TEXT_INPUT_FILES = "l2bin, l3bin, multilevel_processor"; public static final String PROGRAMS_NEED_ADDITIONAL_FILES = "l2gen,l3gen,l2gen_aquarius"; public static final String ADDITIONAL_FILE_EXTENSIONS = "L1B_HKM, L1B_QKM, L1B_LAC.anc"; OCSSWClient ocsswClient; WebTarget target; String jobId; String clientId; boolean ifileUploadSuccess; ProcessorModel processorModel; boolean serverProcessCompleted; public OCSSWRemote() { if (!OCSSWInfo.getInstance().isOcsswServerUp()) { OCSSWInfo.displayRemoteServerDownMessage(); return; } ocsswClient = new OCSSWClient(ocsswInfo.getResourceBaseUri()); target = ocsswClient.getOcsswWebTarget(); jobId = target.path("jobs").path("newJobId").request(MediaType.TEXT_PLAIN_TYPE).get(String.class); clientId = ocsswInfo.getClientId(); target.path("ocssw").path("ocsswSetClientId").path(jobId).request().put(Entity.entity(clientId, MediaType.TEXT_PLAIN_TYPE)); setOfileNameFound(false); } @Override public void setProgramName(String programName) { if (this.programName == null || !this.programName.equals(programName)) { this.programName = programName; Response response = target.path("ocssw").path("ocsswSetProgramName").path(jobId).request().put(Entity.entity(programName, MediaType.TEXT_PLAIN_TYPE)); } } @Override public void setIfileName(String ifileName) { this.ifileName = ifileName; setOfileNameFound(false); ofileName = null; if (uploadClientFile(ifileName)) { ifileUploadSuccess = true; } else { ifileUploadSuccess = false; } } @Override public HashMap<String, String> computePixelsFromLonLat(ProcessorModel processorModel) { HashMap<String, String> pixels = new HashMap<String, String>(); JsonObject commandArrayJsonObject = getJsonFromParamList(processorModel.getParamList()); Response response = target.path("ocssw").path("convertLonLat2Pixels").path(jobId).path(processorModel.getProgramName()).request().put(Entity.entity(commandArrayJsonObject, MediaType.APPLICATION_JSON_TYPE)); if (response.getStatus() == Response.Status.OK.getStatusCode()) { JsonObject jsonObject = target.path("ocssw").path("getConvertedPixels").path(jobId).request(MediaType.APPLICATION_JSON_TYPE).get(JsonObject.class); if (jsonObject != null) { pixels.put(ParamUtils.SLINE, jsonObject.getString(ParamUtils.SLINE)); pixels.put(ParamUtils.ELINE, jsonObject.getString(ParamUtils.ELINE)); pixels.put(ParamUtils.SPIXL, jsonObject.getString(ParamUtils.SPIXL)); pixels.put(ParamUtils.EPIXL, jsonObject.getString(ParamUtils.EPIXL)); } } return pixels; } private void updateProgramName(String programName) { this.programName = programName; setXmlFileName(programName + ".xml"); } public boolean uploadClientFile(String fileName) { if (fileExistsOnServer(fileName) && !needToUplaodFileContent(programName, fileName)) { return ifileUploadSuccess = true; } ifileUploadSuccess = false; SnapApp snapApp = SnapApp.getDefault(); ProgressMonitorSwingWorker pmSwingWorker = new ProgressMonitorSwingWorker(snapApp.getMainFrame(), "OCSSW Remote Server File Upload") { @Override protected Void doInBackground(ProgressMonitor pm) throws Exception { pm.beginTask("Uploading file '" + fileName + "' to the remote server ", 10); pm.worked(1); try { if (needToUplaodFileContent(programName, fileName)) { uploadListedFiles(pm, fileName); updateFileListFileContent(fileName); } } catch (Exception e) { e.printStackTrace(); pm.done(); } finally { pm.done(); } final FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file", new File(fileName)); final MultiPart multiPart = new FormDataMultiPart() //.field("ifileName", ifileName) .bodyPart(fileDataBodyPart); Response response = target.path("fileServices").path("uploadClientFile").path(jobId).request().post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE)); if (response.getStatus() == Response.ok().build().getStatus()) { ifileUploadSuccess = true; } return null; } }; pmSwingWorker.executeWithBlocking(); //System.out.println("upload process is done: " + pmSwingWorker.isDone()); return ifileUploadSuccess; } public boolean uploadParFile(File parFile) { String parFileName = parFile.getName(); ifileUploadSuccess = false; SnapApp snapApp = SnapApp.getDefault(); ProgressMonitorSwingWorker pmSwingWorker = new ProgressMonitorSwingWorker(snapApp.getMainFrame(), "OCSSW Remote Server File Upload") { @Override protected Void doInBackground(ProgressMonitor pm) throws Exception { pm.beginTask("Uploading par file '" + parFileName + "' to the remote server ", 10); pm.worked(1); final FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file", parFile); final MultiPart multiPart = new FormDataMultiPart() //.field("ifileName", ifileName) .bodyPart(fileDataBodyPart); Response response = target.path("fileServices").path("uploadParFile").path(jobId).request().post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE)); if (response.getStatus() == Response.ok().build().getStatus()) { ifileUploadSuccess = true; } return null; } }; pmSwingWorker.executeWithBlocking(); //System.out.println("par file upload process is done: " + pmSwingWorker.isDone()); return ifileUploadSuccess; } public boolean isTextFile(String fileName) { if (!fileExistsOnServer(fileName)) { SnapApp snapApp = SnapApp.getDefault(); ProgressMonitorSwingWorker pmSwingWorker = new ProgressMonitorSwingWorker(snapApp.getMainFrame(), "OCSSW Remote Server File Upload") { @Override protected Void doInBackground(ProgressMonitor pm) throws Exception { pm.beginTask("Uploading file '" + fileName + "' to the remote server ", 10); pm.worked(1); final FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file", new File(fileName)); final MultiPart multiPart = new FormDataMultiPart() //.field("ifileName", ifileName) .bodyPart(fileDataBodyPart); Response response = target.path("fileServices").path("uploadClientFile").path(jobId).request().post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE)); if (response.getStatus() == Response.ok().build().getStatus()) { ifileUploadSuccess = true; } return null; } }; pmSwingWorker.executeWithBlocking(); //System.out.println("upload process is done: " + pmSwingWorker.isDone()); } String fileNameWithoutPath = fileName.substring(fileName.lastIndexOf(File.separator) + 1); String charSet = ocsswClient.getServicePathForFileCharSet(jobId).path(fileNameWithoutPath).request().get(String.class); if (charSet.trim().equals(US_ASCII_CHAR_SET)) { return true; } else { return false; } } public boolean isTextFileValidInput(String programName) { StringTokenizer st = new StringTokenizer(PROGRAM_NAMES_FOR_TEXT_INPUT_FILES, ","); while (st.hasMoreTokens()) { if (programName.trim().equals(st.nextToken().trim())) { return true; } } return false; } public boolean needToUplaodFileContent(String programName, String fileName) { return isTextFileValidInput(programName) && isTextFile(fileName); } public boolean fileExistsOnServer(String fileName) { String fileNameWithoutPath = fileName.substring(fileName.lastIndexOf(File.separator) + 1); Response response = ocsswClient.getServicePathForFileVerification(jobId).queryParam("fileName", fileNameWithoutPath).request().get(); int responseCode = response.getStatus(); int responseFound = Response.Status.FOUND.getStatusCode(); if (response.getStatus() != Response.Status.FOUND.getStatusCode()) { return false; } else { return true; } } /** * This method uploads list of files provided in the text file. * * @param fileName is the name of the text file that contains list of input files. * @return true if all files uploaded successfully. */ public String uploadListedFiles(ProgressMonitor pm, String fileName) { File file = new File(fileName); StringBuilder sb = new StringBuilder(); Scanner scanner = null; ArrayList<String> fileList = new ArrayList<>(); try { scanner = new Scanner(file); } catch (FileNotFoundException e) { e.printStackTrace(); } int fileCount = 0; while (scanner.hasNextLine()) { fileCount++; fileList.add(scanner.nextLine()); } scanner.close(); pm.beginTask("Uploading " + fileCount + " files to the remote server ...", fileCount); FileDataBodyPart fileDataBodyPart; MultiPart multiPart; Response response; boolean fileUploadSuccess = true; int numberOfTasksWorked = 1; for (String nextFileName : fileList) { if (!fileExistsOnServer(nextFileName)) { pm.setSubTaskName("Uploading " + nextFileName + " to the remote server ..."); fileDataBodyPart = new FileDataBodyPart("file", new File(nextFileName)); multiPart = new FormDataMultiPart() //.field("ifileName", ifileName) .bodyPart(fileDataBodyPart); response = target.path("fileServices").path("uploadClientFile").path(jobId).request().post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE)); if (response.getStatus() == Response.ok().build().getStatus()) { fileUploadSuccess = fileUploadSuccess & true; sb.append(nextFileName.substring(nextFileName.lastIndexOf(File.separator) + 1) + "\n"); } else { fileUploadSuccess = fileUploadSuccess & false; } pm.worked(numberOfTasksWorked++); } } String fileNames = sb.toString(); if (fileUploadSuccess) { return fileNames; } else { return null; } } public void updateFileListFileContent(String fileListFileName) { StringBuilder stringBuilder = new StringBuilder(); try { List<String> lines = Files.readAllLines(Paths.get(fileListFileName), StandardCharsets.UTF_8); Iterator<String> itr = lines.iterator(); String fileName; while (itr.hasNext()) { fileName = itr.next(); if (fileName.trim().length() > 0) { //System.out.println("file name in the file list: " + fileName); fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1); stringBuilder.append(fileName + "\n"); } } String fileContent = stringBuilder.toString(); //System.out.println(fileContent); SeadasFileUtils.writeStringToFile(fileContent, fileListFileName); } catch (IOException ioe) { ioe.printStackTrace(); } } @Override public String getOfileName(String ifileName) { if (programName.equals("l3bindump")) { return ifileName + ".xml"; } if (!fileExistsOnServer(ifileName)) { uploadClientFile(ifileName); }else { ifileUploadSuccess = true; } if (ifileUploadSuccess) { ofileName = getFindOfileJsonObject(ifileName.substring(ifileName.lastIndexOf(File.separator) + 1), programName); ofileName = ifileName.substring(0, ifileName.lastIndexOf(File.separator) + 1) + ofileName; if (ofileName != null) { setOfileNameFound(true); return ofileName; } } setOfileNameFound(false); return null; } @Override public String getOfileName(String ifileName, String programName) { if (programName.equals("l3bindump")) { return ifileName + ".xml"; } if(programName.equals("l1bgen_generic")){ programName = "l1bgen"; } if (!fileExistsOnServer(ifileName)) { uploadClientFile(ifileName); } else { ifileUploadSuccess = true; } String ifileNameWithoutFullPath = ifileName.substring(ifileName.lastIndexOf(File.separator) + 1); if (ifileUploadSuccess) { ofileName = getFindOfileJsonObject(ifileNameWithoutFullPath, programName); ofileName = ifileName.substring(0, ifileName.lastIndexOf(File.separator) + 1) + ofileName; if (ofileName != null) { setOfileNameFound(true); return ofileName; } } setOfileNameFound(false); return null; } public String getFindOfileJsonObject(String ifileName, String programName) { return target.path("ocssw").path("getOfileName").path(jobId).path(ifileName).path(programName).request().get(String.class); } public JsonObject getFindFileInfoJsonObject(String ifileName) { return target.path("ocssw").path("getFileInfo").path(jobId).path(ifileName).request(MediaType.APPLICATION_JSON_TYPE).get(JsonObject.class); } @Override public String getOfileName(String ifileName, String[] options) { if (programName.equals("l3bindump")) { return ifileName + ".xml"; } if (ifileUploadSuccess) { JsonObject jsonObjectForUpload = getNextLevelNameJsonObject(ifileName, options); Response response = target.path("ocssw").path("uploadNextLevelNameParams").path(jobId).request().post(Entity.entity(jsonObjectForUpload, MediaType.APPLICATION_JSON_TYPE)); if (response.getStatus() == Response.Status.OK.getStatusCode()) { ofileName = target.path("ocssw").path("getOfileName").path(jobId).request(MediaType.APPLICATION_JSON_TYPE).get(String.class); } if (ofileName != null) { ofileName = ifileName.substring(0, ifileName.lastIndexOf(File.separator) + 1) + ofileName; } } return ofileName; } @Override public String getOfileName(String ifileName, String programName, String suiteValue) { if (isOfileNameFound()) { return ofileName; } this.programName = programName; String[] additionalOptions = {"--suite=" + suiteValue}; return getOfileName(ifileName, additionalOptions); } private JsonObject getNextLevelNameJsonObject(String ifileName, String[] additionalOptions) { String ifileNameWithoutFullPath = ifileName.substring(ifileName.lastIndexOf(File.separator) + 1); String additionalOptionsString = ""; for (String s : additionalOptions) { additionalOptionsString = additionalOptionsString + s + " ; "; } JsonObject jsonObject = Json.createObjectBuilder().add("ifileName", ifileNameWithoutFullPath) .add("programName", programName) .add("additionalOptions", additionalOptionsString) .build(); return jsonObject; } private JsonArray transformToJsonArray(String[] commandArray) { JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder(); for (String option : commandArray) { jsonArrayBuilder.add(option); } return jsonArrayBuilder.build(); } @Override public ProcessObserver getOCSSWProcessObserver(Process process, String processName, ProgressMonitor progressMonitor) { RemoteProcessObserver remoteProcessObserver = new RemoteProcessObserver(process, processName, progressMonitor); remoteProcessObserver.setJobId(jobId); return remoteProcessObserver; } @Override public boolean isMissionDirExist(String missionName) { Boolean isMissionExist = target.path("ocssw").path("isMissionDirExist").path(missionName).request().get(Boolean.class); return isMissionExist.booleanValue(); } @Override public String[] getMissionSuites(String missionName, String programName) { if (missionName == null) { return null; } this.missionName = missionName; missionName.replaceAll(" ", "_"); return target.path("ocssw").path("missionSuites").path(missionName).path(programName).request(MediaType.APPLICATION_JSON_TYPE).get(String[].class); } /** * * @return */ public Process executeP(ProcessorModel processorModel) { this.processorModel = processorModel; Process seadasProcess; JsonObject commandArrayJsonObject = null; programName = processorModel.getProgramName(); if (programName.equals(MLP_PROGRAM_NAME)) { return executeMLP(processorModel); } else { if (processorModel.acceptsParFile() ) { String parString = processorModel.getParamList().getParamString("\n"); File parFile = writeParFile(convertParStringForRemoteServer(parString)); uploadParFile(parFile); Response response = target.path("ocssw").path("executeParFile").path(jobId).path(processorModel.getProgramName()).request().put(Entity.entity(parFile.getName(), MediaType.TEXT_PLAIN)); seadasProcess = waitForServerExecution(response); } else { commandArrayJsonObject = getJsonFromParamList(processorModel.getParamList()); //this is to make sure that all necessary files are uploaded to the server before execution prepareToRemoteExecute(processorModel.getParamValue(processorModel.getPrimaryInputFileOptionName())); Response response = target.path("ocssw").path("executeOcsswProgramOnDemand").path(jobId).path(programName).request().put(Entity.entity(commandArrayJsonObject, MediaType.APPLICATION_JSON_TYPE)); seadasProcess = waitForServerExecution(response); } return seadasProcess; } } public Process executeSimilartoLocal(ProcessorModel processorModel) { setProgramName(processorModel.getProgramName()); setIfileName(processorModel.getParamValue(processorModel.getPrimaryInputFileOptionName())); return execute(getProgramCommandArray(processorModel)); } public Process execute(ProcessorModel processorModel) { this.processorModel = processorModel; Process seadasProcess; JsonObject commandArrayJsonObject = null; programName = processorModel.getProgramName(); if (programName.equals(MLP_PROGRAM_NAME)) { return executeMLP(processorModel); } else { //todo implement par file uploading for programs other than mlp if (processorModel.acceptsParFile() ) { String parString = processorModel.getParamList().getParamString("\n"); File parFile = writeParFile(convertParStringForRemoteServerSpecialMissions(parString)); uploadParFile(parFile); Response response = target.path("ocssw").path("executeParFile").path(jobId).path(processorModel.getProgramName()).request().put(Entity.entity(parFile.getName(), MediaType.TEXT_PLAIN)); seadasProcess = waitForServerExecution(response); } else { commandArrayJsonObject = getJsonFromParamList(processorModel.getParamList()); //this is to make sure that all necessary files are uploaded to the server before execution prepareToRemoteExecute(processorModel.getParamValue(processorModel.getPrimaryInputFileOptionName())); Response response = target.path("ocssw").path("executeOcsswProgramOnDemand").path(jobId).path(programName).request().put(Entity.entity(commandArrayJsonObject, MediaType.APPLICATION_JSON_TYPE)); seadasProcess = waitForServerExecution(response); } return seadasProcess; } } public Process waitForServerExecution(Response response) { Process seadasProcess = new SeadasProcess(ocsswInfo, jobId); if (response.getStatus() == Response.Status.OK.getStatusCode()) { boolean serverProcessStarted = false; serverProcessCompleted = false; String processStatus = "-100"; while (!serverProcessStarted) { processStatus = target.path("ocssw").path("processStatus").path(jobId).request().get(String.class); switch (processStatus) { case PROCESS_STATUS_NONEXIST: serverProcessStarted = false; break; case PROCESS_STATUS_STARTED: serverProcessStarted = true; break; case PROCESS_STATUS_COMPLETED: serverProcessStarted = true; serverProcessCompleted = true; setProcessExitValue(0); break; case PROCESS_STATUS_FAILED: setProcessExitValue(1); serverProcessStarted = true; break; } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } else { setProcessExitValue(1); } return seadasProcess; } @Override public Process executeSimple(ProcessorModel processorModel) { Process seadasProcess = new SeadasProcess(ocsswInfo, jobId); JsonObject commandArrayJsonObject = getJsonFromParamList(processorModel.getParamList()); Response response = target.path("ocssw").path("executeOcsswProgramSimple").path(jobId).path(processorModel.getProgramName()).request().put(Entity.entity(commandArrayJsonObject, MediaType.APPLICATION_JSON_TYPE)); if (response.getStatus() == Response.Status.OK.getStatusCode()) { setProcessExitValue(0); } serverProcessCompleted = false; String processStatus = "-100"; while (!serverProcessCompleted) { processStatus = target.path("ocssw").path("processStatus").path(jobId).request().get(String.class); switch (processStatus) { case PROCESS_STATUS_NONEXIST: serverProcessCompleted = false; break; case PROCESS_STATUS_STARTED: serverProcessCompleted = false; break; case PROCESS_STATUS_COMPLETED: serverProcessCompleted = true; setProcessExitValue(0); break; case PROCESS_STATUS_FAILED: setProcessExitValue(1); serverProcessCompleted = true; break; } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } return seadasProcess; } @Override public InputStream executeAndGetStdout(ProcessorModel processorModel) { InputStream responceStream = null; JsonObject commandArrayJsonObject = getJsonFromParamList(processorModel.getParamList()); Response response = target.path("ocssw").path("executeOcsswProgramAndGetStdout").path(jobId).path(processorModel.getProgramName()).request().put(Entity.entity(commandArrayJsonObject, MediaType.APPLICATION_JSON_TYPE)); if (response.getStatus() == Response.Status.OK.getStatusCode()) { response = target.path("fileServices").path("downloadAncFileList").path(jobId).request().get(Response.class); responceStream = (InputStream) response.getEntity(); } return responceStream; } @Override public void waitForProcess() { String processStatus = PROCESS_STATUS_NONEXIST; while (!serverProcessCompleted) { processStatus = target.path("ocssw").path("processStatus").path(jobId).request().get(String.class); switch (processStatus) { case PROCESS_STATUS_NONEXIST: serverProcessCompleted = false; break; case PROCESS_STATUS_STARTED: serverProcessCompleted = false; break; case PROCESS_STATUS_COMPLETED: serverProcessCompleted = true; setProcessExitValue(0); break; case PROCESS_STATUS_FAILED: serverProcessCompleted = true; setProcessExitValue(1); break; default: serverProcessCompleted = false; } try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } } @Override public void updateOCSSWTags() { ArrayList<String> tagsList = getRemoteOcsswTags(); setOcsswTags(tagsList); getValidOCSSWTags4SeaDASVersion(); } public ArrayList<String> getRemoteOcsswTags() { //System.out.println("getting remote tag list!"); JsonObject response; JsonArray jsonArray; ArrayList<String> tags = new ArrayList<String>(); try { response = target.path("ocssw").path("ocsswTags").request(MediaType.APPLICATION_JSON_TYPE).get(JsonObject.class); jsonArray = response.getJsonArray("tags"); for(int i = 0; i < jsonArray.size(); i++) { tags.add(jsonArray.getString(i)); } } catch (Exception e) { e.printStackTrace(); } return tags; } @Override public InputStream getProductXMLFile(L2genData.Source source) throws IOException { Response response = target.path("fileServices").path("downloadFile").path("productXmlFile").request().get(Response.class); InputStream responseStream = (InputStream) response.getEntity(); final Preferences preferences = Config.instance("seadas").load().preferences(); File productXMLFile = new File(preferences.get(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY, OCSSWConfigData.getSeadasClientServerSharedDirDefaultValue() ), PRODUCT_XML); SeadasFileUtils.debug("product xml file path:" + productXMLFile.getAbsolutePath()); SeadasFileUtils.writeToFile(responseStream, productXMLFile.getAbsolutePath()); try { return new FileInputStream(productXMLFile); } catch (IOException e) { throw new IOException("problem creating product XML file: " + e.getMessage()); } } @Override public String executeUpdateLuts(ProcessorModel processorModel) { this.processorModel = processorModel; Process seadasProcess = new SeadasProcess(ocsswInfo, jobId); JsonObject commandArrayJsonObject = getJsonFromParamList(processorModel.getParamList()); Response response = target.path("ocssw").path("executeUpdateLutsProgram").path(jobId).request().put(Entity.entity(commandArrayJsonObject, MediaType.APPLICATION_JSON_TYPE)); if (response.getStatus() == 200) { return "Update Luts successful"; } else { return "Update Luts failed on server"; } } @Override public void getOutputFiles(ProcessorModel processorModel) { if (processorModel.getProgramName() == MLP_PROGRAM_NAME) { downloadMLPOutputFiles(processorModel); } else { getOutputFiles(processorModel.getOfileName()); } } public boolean getIntermediateOutputFiles(ProcessorModel processorModel) { boolean downloadSuccessful = false; JsonObject commandArrayJsonObject = null; commandArrayJsonObject = getJsonFromParamList(processorModel.getParamList()); downloadSuccessful = downloadCommonFiles(commandArrayJsonObject); return downloadSuccessful; } //todo: implement download files using output file names from processModel object public void getOutputFiles(String outputFileNames) { SnapApp snapApp = SnapApp.getDefault(); ProgressMonitorSwingWorker pmSwingWorker = new ProgressMonitorSwingWorker(snapApp.getMainFrame(), "OCSSW Remote Server File Download") { @Override protected Void doInBackground(ProgressMonitor pm) throws Exception { JsonObject commandArrayJsonObject = null; StringTokenizer st = new StringTokenizer(outputFileNames, "\n"); String fileNameWithFullPath, fileNameWithoutPath; while (st.hasMoreTokens()) { fileNameWithFullPath = st.nextToken(); fileNameWithoutPath = fileNameWithFullPath.substring(fileNameWithFullPath.lastIndexOf(File.separator) + 1); Response response = target.path("fileServices").path("downloadFile").path(jobId).path(fileNameWithoutPath).request().get(Response.class); InputStream responseStream = (InputStream) response.getEntity(); SeadasFileUtils.writeToFile(responseStream, fileNameWithFullPath); } return null; } }; pmSwingWorker.execute(); } @Override public void findFileInfo(String fileName, FileInfoFinder fileInfoFinder) { if (!fileExistsOnServer(fileName)) { uploadClientFile(fileName); } JsonObject jsonObject = getFindFileInfoJsonObject(fileName.substring(fileName.lastIndexOf(File.separator) + 1)); fileInfoFinder.setFileType(jsonObject.getString(FileInfoFinder.FILE_TYPE_VAR_NAME)); String mission = jsonObject.getString(FileInfoFinder.MISSION_NAME_VAR_NAME); fileInfoFinder.setMissionName(mission); setMissionName(mission); } @Override public String getOfileDir() { return ofileDir; } public boolean downloadCommonFiles(JsonObject paramJsonObject) { Set<String> commandArrayKeys = paramJsonObject.keySet(); String param; String ofileFullPathName, ofileName; try { Object[] array = (Object[]) commandArrayKeys.toArray(); int i = 0; String[] commandArray = new String[commandArrayKeys.size() + 1]; commandArray[i++] = programName; for (Object element : array) { String elementName = (String) element; param = paramJsonObject.getString((String) element); if (elementName.contains("OFILE")) { if (param.indexOf("=") != -1) { StringTokenizer st = new StringTokenizer(param, "="); String paramName = st.nextToken(); String paramValue = st.nextToken(); ofileFullPathName = paramValue; } else { ofileFullPathName = param; } ofileName = ofileFullPathName.substring(ofileFullPathName.lastIndexOf(File.separator) + 1); Response response = target.path("fileServices").path("downloadFile").path(jobId).path(ofileName).request().get(Response.class); InputStream responceStream = (InputStream) response.getEntity(); SeadasFileUtils.writeToFile(responceStream, ofileDir + File.separator + ofileFullPathName); } } return true; } catch (Exception e) { e.printStackTrace(); return false; } } private Process executeMLP(ProcessorModel processorModel) { Process seadasProcess = new SeadasProcess(ocsswInfo, jobId); String parString = processorModel.getParamList().getParamString("\n"); programName = processorModel.getProgramName(); ifileName = processorModel.getParamValue(processorModel.getPrimaryInputFileOptionName()); ifileDir = new File(ifileName).getParent(); File parFile = writeMLPParFile(convertParStringForRemoteServer(parString)); target.path("ocssw").path("uploadMLPParFile").path(jobId).request().put(Entity.entity(parFile, MediaType.APPLICATION_OCTET_STREAM_TYPE)); boolean serverProcessStarted = false; String processStatus = "-100"; while (!serverProcessStarted) { processStatus = target.path("ocssw").path("processStatus").path(jobId).request().get(String.class); switch (processStatus) { case PROCESS_STATUS_NONEXIST: serverProcessStarted = false; break; case PROCESS_STATUS_STARTED: serverProcessStarted = true; setProcessExitValue(1); break; case PROCESS_STATUS_COMPLETED: serverProcessStarted = true; setProcessExitValue(1); break; case PROCESS_STATUS_FAILED: setProcessExitValue(1); serverProcessStarted = true; break; default: serverProcessStarted = false; } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } return seadasProcess; } protected boolean isMLPOdirValid(String mlpOdir) { if (mlpOdir == null || mlpOdir.trim().isEmpty()) { return false; } else { return true; } } protected void downloadMLPOutputFiles(ProcessorModel processorModel) { String mlpOdir = processorModel.getParamValue(MLP_PAR_FILE_ODIR_KEY_NAME); final String ofileDir = isMLPOdirValid(mlpOdir) ? mlpOdir : ifileDir; SnapApp snapApp = SnapApp.getDefault(); ProgressMonitorSwingWorker pmSwingWorker = new ProgressMonitorSwingWorker(snapApp.getMainFrame(), "OCSSW Remote Server File Download") { @Override protected Void doInBackground(ProgressMonitor pm) throws Exception { JsonObject mlpOfilesJsonObject = target.path("fileServices").path("getMLPOutputFilesList").path(jobId).request(MediaType.APPLICATION_JSON_TYPE).get(JsonObject.class); Set<String> fileSetKeys = mlpOfilesJsonObject.keySet(); Object[] fileArray = (Object[]) fileSetKeys.toArray(); pm.beginTask("Downloading output files from the remote server to " + ofileDir, fileArray.length); pm.worked(1); String ofileName, ofileFullPathName; int numberOfTasksWorked = 1; for (Object fileNameKey : fileArray) { ofileName = mlpOfilesJsonObject.getString((String) fileNameKey); pm.setSubTaskName("Downloading file '" + ofileName + " to " + ofileDir); Response response = target.path("fileServices").path("downloadMLPOutputFile").path(jobId).path(ofileName).request().get(Response.class); InputStream responceStream = (InputStream) response.getEntity(); ofileFullPathName = ofileDir + File.separator + ofileName; SeadasFileUtils.writeToFile(responceStream, ofileFullPathName); pm.worked(numberOfTasksWorked++); } return null; } }; pmSwingWorker.executeWithBlocking(); } @Override public Process execute(ParamList paramListl) { JsonObject commandArrayJsonObject = getJsonFromParamList(paramListl); setCommandArray((String[]) commandArrayJsonObject.asJsonArray().toArray()); Response response = target.path("ocssw").path("executeOcsswProgram").path(jobId).request().put(Entity.entity(commandArrayJsonObject, MediaType.APPLICATION_JSON_TYPE)); if (response.getStatus() == Response.Status.OK.getStatusCode()) { Response output = target.path("fileServices").path("downloadFile").path(jobId).request().get(Response.class); final InputStream responseStream = (InputStream) output.getEntity(); SeadasFileUtils.writeToFile(responseStream, ofileName); } Process Process = new SeadasProcess(ocsswInfo, jobId); return Process; } protected JsonObject getJsonFromParamList(ParamList paramList) { JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder(); Iterator<ParamInfo> itr = paramList.getParamArray().iterator(); Response response; ParamInfo option; String commandItem; String fileName; while (itr.hasNext()) { option = itr.next(); commandItem = null; if (option.getType() != ParamInfo.Type.HELP) { if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_ARGUMENT)) { if (option.getType().equals(ParamInfo.Type.IFILE) || option.getType().equals(ParamInfo.Type.OFILE)) { commandItem = option.getValue().substring(option.getValue().lastIndexOf(File.separator) + 1); } else if (option.getValue() != null && option.getValue().length() > 0) { commandItem = option.getValue(); } } else if ((option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_OPTION) || option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_OPTION_MINUSMINUS)) && !option.getDefaultValue().equals(option.getValue()) && !option.getValue().trim().isEmpty()) { if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_OPTION_MINUSMINUS)) { if ((option.getType().equals(ParamInfo.Type.IFILE) && !isAncFile(option.getValue())) || option.getType().equals(ParamInfo.Type.OFILE)) { commandItem = "--" + option.getName() + " " + option.getValue().substring(option.getValue().lastIndexOf(File.separator) + 1); } else { commandItem = "--" + option.getName() + " " + option.getValue(); } } else { if ((option.getType().equals(ParamInfo.Type.IFILE) && !isAncFile(option.getValue())) || option.getType().equals(ParamInfo.Type.OFILE)) { commandItem = option.getName() + "=" + option.getValue().substring(option.getValue().lastIndexOf(File.separator) + 1); } else { commandItem = option.getName() + "=" + option.getValue(); } } if (option.getType().equals(ParamInfo.Type.OFILE)) { ofileDir = option.getValue().substring(0, option.getValue().lastIndexOf(File.separator)); } if (option.getType().equals(ParamInfo.Type.IFILE) && !isAncFile(option.getValue())) { fileName = option.getValue().substring(option.getValue().lastIndexOf(File.separator) + 1); if (fileName.length() > 0) { ifileDir = option.getValue().substring(0, option.getValue().lastIndexOf(File.separator)); response = ocsswClient.getServicePathForFileVerification(jobId).queryParam("fileName", fileName).request().get(); if (response.getStatus() != Response.Status.FOUND.getStatusCode()) { uploadClientFile(option.getValue()); } else { ifileUploadSuccess = true; } } } } else if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_FLAG) && (option.getValue().equals("true") || option.getValue().equals("1"))) { if (option.getName() != null && option.getName().length() > 0) { commandItem = option.getName(); } } else if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_FLAG_MINUSMINUS) && (option.getValue().equals("true") || option.getValue().equals("1"))) { if (option.getName() != null && option.getName().length() > 0) { commandItem = "--" + option.getName(); } } } //need to send both item name and its type to accurately construct the command array on the server if (commandItem != null) { jsonObjectBuilder.add(option.getName() + "_" + option.getType(), commandItem); } } return jsonObjectBuilder.build(); } boolean isAncFile(String fileName) { boolean isAncFile = fileName.contains("/var/anc/"); return isAncFile; } /** * this method returns a command array for execution. * the array is constructed using the paramList data and input/output files. * the command array structure is: full pathname of the program to be executed, input file name, params in the required order and finally the output file name. * assumption: order starts with 1 * * @return */ public String[] getProgramCommandArray(ProcessorModel processorModel) { String[] cmdArray; String[] programNameArray = {processorModel.getProgramName()}; String[] cmdArrayForParams; ParFileManager parFileManager = new ParFileManager(processorModel); if (processorModel.acceptsParFile()) { cmdArrayForParams = parFileManager.getCmdArrayWithParFile(); } else { cmdArrayForParams = getCommandArrayParam(processorModel.getParamList()); } commandArraySuffix = processorModel.getCmdArraySuffix(); //The final command array is the concatination of commandArrayPrefix, cmdArrayForParams, and commandArraySuffix //TODO: for ocssw_install commandArrayPrefix has the program name with the file path, so it can't include programNameArray again if (!processorModel.getProgramName().equals(OCSSW_INSTALLER_PROGRAM_NAME)) { cmdArray = SeadasArrayUtils.concatAll(commandArrayPrefix, programNameArray, cmdArrayForParams, commandArraySuffix); } else { cmdArray = SeadasArrayUtils.concatAll(commandArrayPrefix, cmdArrayForParams, commandArraySuffix); } // get rid of the null strings ArrayList<String> cmdList = new ArrayList<String>(); for (String s : cmdArray) { if (s != null) { cmdList.add(s); } } cmdArray = cmdList.toArray(new String[cmdList.size()]); return cmdArray; } private String[] getCommandArrayParam(ParamList paramList) { ArrayList<String> commandArrayList = new ArrayList<>(); Iterator<ParamInfo> itr = paramList.getParamArray().iterator(); ParamInfo option; int optionOrder; String optionValue; int i = 0; while (itr.hasNext()) { option = itr.next(); optionOrder = option.getOrder(); optionValue = option.getValue(); if (option.getType() != ParamInfo.Type.HELP) { if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_ARGUMENT)) { if (option.getValue() != null && option.getValue().length() > 0) { commandArrayList.add(optionValue); } } else if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_OPTION_MINUSMINUS) && !option.getDefaultValue().equals(option.getValue())) { commandArrayList.add("--" + option.getName() + " " + optionValue); } else if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_FLAG_MINUSMINUS) && (option.getValue().equals("true") || option.getValue().equals("1"))) { if (option.getName() != null && option.getName().length() > 0) { commandArrayList.add("--" + option.getName()); } } else if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_OPTION) && !option.getDefaultValue().equals(option.getValue())) { commandArrayList.add(option.getName() + "=" + optionValue); } else if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_FLAG) && (option.getValue().equals("true") || option.getValue().equals("1"))) { if (option.getName() != null && option.getName().length() > 0) { commandArrayList.add(option.getName()); } } } } String[] commandArrayParam = new String[commandArrayList.size()]; commandArrayParam = commandArrayList.toArray(commandArrayParam); return commandArrayParam; } private void prepareToRemoteExecute(String ifileName) { Response response; String fileExtensions = processorModel.getImplicitInputFileExtensions(); if (fileExtensions != null) { StringTokenizer st = new StringTokenizer(fileExtensions, ","); String fileExtension; String fileNameBase = ifileName.substring(ifileName.lastIndexOf(File.separator) + 1, ifileName.lastIndexOf(".")); String fileNameToUpload; while (st.hasMoreTokens()) { fileExtension = st.nextToken().trim(); fileNameToUpload = ifileDir + File.separator + fileNameBase + "." + fileExtension; response = ocsswClient.getServicePathForFileVerification(jobId).queryParam("fileName", fileNameBase).request().get(); if (response.getStatus() != Response.Status.FOUND.getStatusCode()) { uploadClientFile(fileNameToUpload); } } } } protected String convertParStringForRemoteServer(String parString) { setCommandArray(new String[]{parString}); StringTokenizer st1 = new StringTokenizer(parString, "\n"); StringTokenizer st2; StringBuilder stringBuilder = new StringBuilder(); String token; String key, value; String fileTypeString; while (st1.hasMoreTokens()) { token = st1.nextToken(); if (token.contains("=")) { st2 = new StringTokenizer(token, "="); key = st2.nextToken(); value = st2.nextToken(); if (new File(value).exists() && !new File(value).isDirectory() && !key.equals(processorModel.getPrimaryOutputFileOptionName())) { //if item is ifile if (key.equals(processorModel.getPrimaryInputFileOptionName())) { ifileDir = value.substring(0, value.lastIndexOf(File.separator)); } uploadClientFile(value); value = value.substring(value.lastIndexOf(File.separator) + 1); } else if (key.equals(MLP_PAR_FILE_ODIR_KEY_NAME) && new File(value).isDirectory()) { ofileDir = value; //if item is ofile } else if (key.equals(processorModel.getPrimaryOutputFileOptionName())) { ofileDir = value.substring(0, value.lastIndexOf(File.separator)); value = value.substring(value.lastIndexOf(File.separator) + 1); } token = key + "=" + value; } stringBuilder.append(token); stringBuilder.append("\n"); } String newParString = stringBuilder.toString(); //remove empty lines String adjusted = newParString.replaceAll("(?m)^[ \t]*\r?\n", ""); return adjusted; } protected String convertParStringForRemoteServerSpecialMissions(String parString) { setCommandArray(new String[]{parString}); StringTokenizer st1 = new StringTokenizer(parString, "\n"); StringTokenizer st2; StringBuilder stringBuilder = new StringBuilder(); String token; String key, value; String fileTypeString; while (st1.hasMoreTokens()) { token = st1.nextToken(); if (token.contains("=")) { st2 = new StringTokenizer(token, "="); key = st2.nextToken(); value = st2.nextToken(); if (new File(value).exists() && !new File(value).isDirectory() && !key.equals(processorModel.getPrimaryOutputFileOptionName())) { //if item is ifile if (key.equals(processorModel.getPrimaryInputFileOptionName())) { ifileDir = value.substring(0, value.lastIndexOf(File.separator)); } //uploadClientFile(value); value = value.substring(value.indexOf(SEADAS_CLIENT_SERVER_SHARED_DIR_NAME) + SEADAS_CLIENT_SERVER_SHARED_DIR_NAME.length() + 1); } else if (key.equals(MLP_PAR_FILE_ODIR_KEY_NAME) && new File(value).isDirectory()) { ofileDir = value; //if item is ofile } else if (key.equals(processorModel.getPrimaryOutputFileOptionName())) { ofileDir = value.substring(0, value.lastIndexOf(File.separator)); value = value.substring(value.indexOf(SEADAS_CLIENT_SERVER_SHARED_DIR_NAME) + SEADAS_CLIENT_SERVER_SHARED_DIR_NAME.length() + 1); } token = key + "=" + value; } stringBuilder.append(token); stringBuilder.append("\n"); } String newParString = stringBuilder.toString(); //remove empty lines String adjusted = newParString.replaceAll("(?m)^[ \t]*\r?\n", ""); return adjusted; } @Override /** * */ public ArrayList<String> readSensorFileIntoArrayList(File file) { JsonObject jsonObject = target.path("ocssw").path("getSensorInfoFileContent").path(jobId).path(missionName).request(MediaType.APPLICATION_JSON_TYPE).get(JsonObject.class); Iterator<String> keys = jsonObject.keySet().iterator(); ArrayList<String> fileContents = new ArrayList<>(); String sensorFileLine; while (keys.hasNext()) { sensorFileLine = String.valueOf(jsonObject.get(keys.next())); sensorFileLine = sensorFileLine.substring(1, sensorFileLine.length() - 1); fileContents.add(sensorFileLine); } return fileContents; } protected File writeMLPParFile(String parString) { try { final File tempFile = File.createTempFile(MLP_PAR_FILE_NAME, ".par", processorModel.getIFileDir()); System.out.println(tempFile.getAbsoluteFile()); //tempFile.deleteOnExit(); FileWriter fileWriter = null; try { fileWriter = new FileWriter(tempFile); fileWriter.write(parString); } finally { if (fileWriter != null) { fileWriter.close(); } } return tempFile; } catch (IOException e) { //SeadasLogger.getLogger().warning("parfile is not created. " + e.getMessage()); ScrolledPane messagePane = new ScrolledPane(programName, e.getMessage()); messagePane.setVisible(true); return null; } } protected File writeParFile(String parString) { try { final File tempFile = File.createTempFile(programName + "_par_file", ".par", processorModel.getIFileDir()); System.out.println(tempFile.getAbsoluteFile()); //tempFile.deleteOnExit(); FileWriter fileWriter = null; try { fileWriter = new FileWriter(tempFile); fileWriter.write(parString); } finally { if (fileWriter != null) { fileWriter.close(); } } return tempFile; } catch (IOException e) { //SeadasLogger.getLogger().warning("parfile is not created. " + e.getMessage()); ScrolledPane messagePane = new ScrolledPane(programName, e.getMessage()); messagePane.setVisible(true); return null; } } @Override public Process execute(String[] commandArray) { Process seadasProcess; JsonObject commandArrayJsonObject = null; programName = processorModel.getProgramName(); if (programName.equals(MLP_PROGRAM_NAME)) { return executeMLP(processorModel); } else { if (processorModel.acceptsParFile() ) { String parString = processorModel.getParamList().getParamString("\n"); File parFile = writeParFile(convertParStringForRemoteServer(parString)); uploadParFile(parFile); Response response = target.path("ocssw").path("executeParFile").path(jobId).path(processorModel.getProgramName()).request().put(Entity.entity(parFile.getName(), MediaType.TEXT_PLAIN)); seadasProcess = waitForServerExecution(response); } else { commandArrayJsonObject = getJsonFromParamList(processorModel.getParamList()); //this is to make sure that all necessary files are uploaded to the server before execution prepareToRemoteExecute(processorModel.getParamValue(processorModel.getPrimaryInputFileOptionName())); Response response = target.path("ocssw").path("executeOcsswProgramOnDemand").path(jobId).path(programName).request().put(Entity.entity(commandArrayJsonObject, MediaType.APPLICATION_JSON_TYPE)); seadasProcess = waitForServerExecution(response); } return seadasProcess; } } @Override public Process execute(String programName, String[] commandArrayParams) { String[] programNameArray = {programName}; commandArray = SeadasArrayUtils.concatAll(commandArrayPrefix, programNameArray, commandArrayParams, commandArraySuffix); return execute(commandArray); } @Override public void setCommandArrayPrefix() { } @Override public void setCommandArraySuffix() { } @Override public void setMissionName(String missionName) { this.missionName = missionName; } @Override public void setFileType(String fileType) { } public static void retrieveServerSharedDirName() { OCSSWClient ocsswClient = new OCSSWClient(); WebTarget target = ocsswClient.getOcsswWebTarget(); OCSSW.getOCSSWInstance().setServerSharedDirName(target.path("file").path("test").request(MediaType.TEXT_PLAIN).get(String.class)); } String missionName; }
59,223
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSWExecutionMonitor.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ocssw/OCSSWExecutionMonitor.java
package gov.nasa.gsfc.seadas.processing.ocssw; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import gov.nasa.gsfc.seadas.processing.common.SeadasFileUtils; import gov.nasa.gsfc.seadas.processing.core.ProcessObserver; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import org.esa.snap.rcp.SnapApp; import java.io.IOException; import java.util.Arrays; /** * Created by aabduraz on 1/17/18. */ public class OCSSWExecutionMonitor { public void executeWithProgressMonitor(ProcessorModel processorModel, OCSSW ocssw, String programName){ SnapApp snapApp = SnapApp.getDefault(); ProgressMonitorSwingWorker swingWorker = new ProgressMonitorSwingWorker<String, Object>(snapApp.getMainFrame(), "Running " + programName + " ...") { protected String doInBackground(ProgressMonitor pm) throws Exception { ocssw.setMonitorProgress(true); ocssw.setIfileName(processorModel.getParamValue(processorModel.getPrimaryInputFileOptionName())); final Process process = ocssw.execute(processorModel.getParamList());//ocssw.execute(processorModel.getParamList()); //OCSSWRunnerOld.execute(processorModel); if (process == null) { throw new IOException(programName + " failed to create process."); } final ProcessObserver processObserver = ocssw.getOCSSWProcessObserver(process, programName, pm); final CallCloProgramAction.ConsoleHandler ch = new CallCloProgramAction.ConsoleHandler(programName); // todo Danny replaced commented out block with following lines. This block replicates new logic in CallCloProgramAction // if (programName.equals(OCSSWInfo.getInstance().OCSSW_INSTALLER_PROGRAM_NAME)) { // processObserver.addHandler(new CallCloProgramAction.InstallerHandler(programName, processorModel.getProgressPattern())); // } else { // processObserver.addHandler(new CallCloProgramAction.ProgressHandler(programName, processorModel.getProgressPattern())); // } pm.beginTask(programName, CallCloProgramAction.TOTAL_WORK_DEFAULT); processObserver.addHandler(new CallCloProgramAction.ProgressHandler(programName, processorModel.getProgressPattern())); // end of todo processObserver.addHandler(ch); processObserver.startAndWait(); processorModel.setExecutionLogMessage(ch.getExecutionErrorLog()); int exitCode = processObserver.getProcessExitValue(); if (exitCode == 0) { pm.done(); SeadasFileUtils.writeToDisk(processorModel.getIFileDir() + System.getProperty("file.separator") + "OCSSW_LOG_" + programName + ".txt", "Execution log for " + "\n" + Arrays.toString(ocssw.getCommandArray()) + "\n" + processorModel.getExecutionLogMessage()); } else { throw new IOException(programName + " failed with exit code " + exitCode + ".\nCheck log for more details."); } ocssw.setMonitorProgress(false); return processorModel.getOfileName(); } }; swingWorker.execute(); } }
3,494
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSWInfoGUI.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ocssw/OCSSWInfoGUI.java
package gov.nasa.gsfc.seadas.processing.ocssw; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.swing.binding.BindingContext; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.runtime.Config; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.ModalDialog; import org.esa.snap.ui.UIUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.openide.modules.ModuleInfo; import org.openide.modules.Modules; import javax.swing.*; import javax.swing.filechooser.FileSystemView; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWConfigData.*; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo.*; /** * @author Aynur Abdurazik * @author Daniel Knowles */ // DEC 2018 - Daniel Knowles - Applied formatting logic for GUI component alignment and arrangement // Added listeners to set Apply button based on textfield values // Minor variable renaming // MAY 2019 - Knowles - Added OCSSW branch field public class OCSSWInfoGUI { final String PANEL_NAME = "Configure OCSSW Location"; final String HELP_ID = "ocsswInfoConfig"; //todo the wording needs to be updated. final String BRANCH_TOOLTIP = "<html>The OCSSW installation tag<br>" + "This by default will match the SeaDAS version (first two decimal fields)<br> " + "For instance SeaDAS 8.0.0 by default will use OCSSW tag 8.0<br>" + "If OCSSW was manually updated to a different tag then this parameter needs to be set to match</html>"; JPanel paramPanel = GridBagUtils.createPanel(); JPanel paramSubPanel; ModalDialog modalDialog; JTextField ocsswTagTextfield; JComboBox ocsswLocationComboBox; JTextField ocsswSharedDir; JTextField ocsswRootTextfield; JTextField ocsswserverAddressTextfield; JTextField serverPortTextfield; JTextField serverInputStreamPortTextfield; JTextField serverErrorStreamPortTextfield; PropertyContainer pc = new PropertyContainer(); OCSSWConfigData ocsswConfigData = new OCSSWConfigData(); boolean windowsOS; String[] ocsswLocations; ArrayList<String> validOCSSWTagList = new ArrayList<>(); public static void main(String args[]) { final AppContext appContext = SnapApp.getDefault().getAppContext(); final Window parent = appContext.getApplicationWindow(); OCSSWInfoGUI ocsswInfoGUI = new OCSSWInfoGUI(); ocsswInfoGUI.init(parent); } public void init(Window parent) { String operatingSystem = System.getProperty("os.name"); if (operatingSystem.toLowerCase().contains("windows")) { windowsOS = true; } else { windowsOS = false; } JPanel mainPanel = GridBagUtils.createPanel(); modalDialog = new ModalDialog(parent, PANEL_NAME, mainPanel, ModalDialog.ID_OK_CANCEL_HELP, HELP_ID); modalDialog.getButton(ModalDialog.ID_OK).setText("OK"); modalDialog.getButton(ModalDialog.ID_CANCEL).setText("Cancel"); modalDialog.getButton(ModalDialog.ID_HELP).setText("Help"); GridBagConstraints gbc = createConstraints(); gbc.fill = GridBagConstraints.NONE; gbc.weighty = 0; gbc.weightx = 0; // JPanel ocsswTagPanel = ocsswTagPanel(); // ocsswTagPanel.setToolTipText(BRANCH_TOOLTIP); // mainPanel.add(ocsswTagPanel, gbc); // // gbc.gridy += 1; // gbc.weighty = 0; // gbc.weightx = 0; gbc.fill = GridBagConstraints.HORIZONTAL; mainPanel.add(makeParamPanel(), gbc); // Add filler panel at bottom which expands as needed to force all components within this panel to the top gbc.gridy += 1; gbc.weighty = 1; gbc.weightx = 1; gbc.fill = GridBagConstraints.VERTICAL; JPanel fillerPanel = new JPanel(); fillerPanel.setMinimumSize(fillerPanel.getPreferredSize()); mainPanel.add(fillerPanel, gbc); mainPanel.setMinimumSize(mainPanel.getMinimumSize()); modalDialog.getButton(ModalDialog.ID_OK).setMinimumSize(modalDialog.getButton(ModalDialog.ID_OK).getPreferredSize()); // Specifically set sizes for dialog here Dimension minimumSizeAdjusted = adjustDimension(modalDialog.getJDialog().getMinimumSize(), 25, 25); Dimension preferredSizeAdjusted = adjustDimension(modalDialog.getJDialog().getPreferredSize(), 25, 25); modalDialog.getJDialog().setMinimumSize(minimumSizeAdjusted); modalDialog.getJDialog().setPreferredSize(preferredSizeAdjusted); modalDialog.getJDialog().pack(); int dialogResult; boolean finish = false; while (!finish) { dialogResult = modalDialog.show(); if (dialogResult == ModalDialog.ID_OK) { if (checkParameters()) { ocsswConfigData.updateconfigData(pc); finish = true; } } else { finish = true; } } return; } private JPanel makeParamPanel() { final Preferences preferences = Config.instance("seadas").load().preferences(); String lastOcsswLocation = preferences.get(SEADAS_OCSSW_LOCATION_PROPERTY, SEADAS_OCSSW_LOCATION_DEFAULT_VALUE); GridBagConstraints gbc = createConstraints(); JLabel ocsswLocationLabel = new JLabel(OCSSW_LOCATION_LABEL + ": "); ArrayList<String> ocsswLocationArrayList = new ArrayList<String>(); if (!windowsOS) { ocsswLocationArrayList.add(OCSSW_LOCATION_LOCAL); ocsswLocationLabel.setToolTipText("Note: Windows operating system detected so no local directory option"); } ocsswLocationArrayList.add(OCSSW_LOCATION_VIRTUAL_MACHINE); ocsswLocationArrayList.add(OCSSW_LOCATION_REMOTE_SERVER); ocsswLocationArrayList.add(OCSSW_LOCATION_DOCKER); ocsswLocations = ocsswLocationArrayList.toArray(new String[ocsswLocationArrayList.size()]); // String[] ocsswLocations = {OCSSW_LOCATION_LOCAL, OCSSW_LOCATION_VIRTUAL_MACHINE, OCSSW_LOCATION_REMOTE_SERVER}; int lastOcsswLocationIndex = 0; for (int i = 0; i < ocsswLocations.length; i++) { if (lastOcsswLocation.equals(ocsswLocations[i])) { lastOcsswLocationIndex = i; break; } } ocsswLocationComboBox = new JComboBox(ocsswLocations); ocsswLocationComboBox.setSelectedIndex(lastOcsswLocationIndex); ocsswLocationComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Remove previous selection of paramSubPanel if (paramSubPanel != null) { paramPanel.remove(paramSubPanel); } // Create new paramSubPanel String ocssLocationString = (String) ocsswLocationComboBox.getSelectedItem(); switch (ocssLocationString) { case OCSSW_LOCATION_LOCAL: paramSubPanel = getLocalOCSSWPanel(); break; case OCSSW_LOCATION_VIRTUAL_MACHINE: paramSubPanel = getVirtualMachinePanel(); break; case OCSSW_LOCATION_DOCKER: paramSubPanel = getDockerPanel(); break; case OCSSW_LOCATION_REMOTE_SERVER: paramSubPanel = getRemoteServerPanel(); break; } updateParamPanel(paramSubPanel); preferences.put(SEADAS_OCSSW_LOCATION_PROPERTY, ocssLocationString); try { preferences.flush(); } catch (BackingStoreException bse) { SnapApp.getDefault().getLogger().severe(bse.getMessage()); } } }); gbc.weighty = 0; gbc.insets.top = 10; gbc.fill = GridBagConstraints.HORIZONTAL; paramPanel.add(getLocationPanel(ocsswLocationLabel, ocsswLocationComboBox), gbc); // Determine ideal preferred size and minimum size of the param panel by invoking each selection to obtain // the respective values and then use the largest values. ocsswLocationComboBox.setSelectedIndex(0); Dimension preferredSize0 = paramPanel.getPreferredSize(); Dimension minimumSize0 = paramPanel.getMinimumSize(); Dimension preferredSize1 = paramPanel.getPreferredSize(); Dimension minimumSize1 = paramPanel.getMinimumSize(); if (ocsswLocations.length > 1) { ocsswLocationComboBox.setSelectedIndex(1); preferredSize1 = paramPanel.getPreferredSize(); minimumSize1 = paramPanel.getMinimumSize(); } Dimension preferredSize2 = paramPanel.getPreferredSize(); Dimension minimumSize2 = paramPanel.getMinimumSize(); if (ocsswLocations.length > 2) { ocsswLocationComboBox.setSelectedIndex(2); preferredSize2 = paramPanel.getPreferredSize(); minimumSize2 = paramPanel.getMinimumSize(); } Integer preferredWidths[] = {preferredSize0.width, preferredSize1.width, preferredSize2.width}; Integer preferredHeights[] = {preferredSize0.height, preferredSize1.height, preferredSize2.height}; Integer minimumWidths[] = {minimumSize0.width, minimumSize1.width, minimumSize2.width}; Integer minimumHeights[] = {minimumSize0.height, minimumSize1.height, minimumSize2.height}; int preferredWidth = Collections.max(Arrays.asList(preferredWidths)); int preferredHeight = Collections.max(Arrays.asList(preferredHeights)); int minimumWidth = Collections.max(Arrays.asList(minimumWidths)); int minimumHeight = Collections.max(Arrays.asList(minimumHeights)); Dimension preferredParamPanelSize = new Dimension(preferredWidth, preferredHeight); Dimension minimumParamPanelSize = new Dimension(minimumWidth, minimumHeight); ocsswLocationComboBox.setSelectedIndex(lastOcsswLocationIndex); // Specifically set preferred and minimum size paramPanel.setPreferredSize(preferredParamPanelSize); paramPanel.setMinimumSize(minimumParamPanelSize); return paramPanel; } private JPanel getLocationPanel(JLabel ocsswLocationLabel, JComboBox ocsswLocationComboBox) { JPanel panel = GridBagUtils.createPanel(); GridBagConstraints gbc = createConstraints(); gbc.weightx = 0; gbc.fill = GridBagConstraints.NONE; panel.add(ocsswLocationLabel, gbc); gbc.gridx += 1; gbc.weightx = 1; gbc.fill = GridBagConstraints.NONE; panel.add(ocsswLocationComboBox, gbc); ocsswLocationLabel.setMinimumSize(ocsswLocationLabel.getPreferredSize()); ocsswLocationComboBox.setMinimumSize(ocsswLocationComboBox.getPreferredSize()); panel.setMinimumSize(panel.getPreferredSize()); return panel; } private void updateParamPanel(JPanel newSubParamPanel) { paramPanel.validate(); GridBagConstraints gbc = createConstraints(); gbc.gridy = 1; gbc.weighty = 0; gbc.insets.top = 5; gbc.fill = GridBagConstraints.HORIZONTAL; newSubParamPanel.setMinimumSize(newSubParamPanel.getMinimumSize()); paramPanel.add(newSubParamPanel, gbc); // Add filler panel at bottom which expands as needed to force all components within this panel to the top gbc.insets.top = 0; gbc.gridy = 2; gbc.weighty = 1; gbc.fill = GridBagConstraints.VERTICAL; JPanel fillerPanel = new JPanel(); fillerPanel.setMinimumSize(fillerPanel.getPreferredSize()); paramPanel.add(fillerPanel, gbc); paramPanel.repaint(); paramPanel.validate(); } private JPanel getDockerPanel() { final Preferences preferences = Config.instance("seadas").load().preferences(); JPanel panel = GridBagUtils.createPanel(); GridBagConstraints gbc = createConstraints(); panel.setBorder(UIUtils.createGroupBorder("Docker")); JLabel ocsswSharedDirLabel = new JLabel(OCSSW_SHARED_DIR_LABEL + ": "); ocsswSharedDir = new JTextField(20); ocsswSharedDirLabel.setMinimumSize(ocsswSharedDirLabel.getPreferredSize()); ocsswSharedDir.setMinimumSize(new JTextField(10).getPreferredSize()); pc.addProperty(Property.create(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY, preferences.get(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY, OCSSWConfigData.getSeadasClientServerSharedDirDefaultValue()))); pc.getDescriptor(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY).setDisplayName(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY); final BindingContext ctx = new BindingContext(pc); ctx.bind(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY, ocsswSharedDir); JButton ocsswSharedDirButton = new JButton("..."); ocsswSharedDirButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File newDir = getDir(); if (newDir != null) { ocsswSharedDir.setText(newDir.getAbsolutePath()); pc.setValue(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY, ocsswSharedDir.getText()); } } }); ocsswSharedDirButton.setMinimumSize(ocsswSharedDirButton.getPreferredSize()); gbc.gridx = 0; gbc.weightx = 0; gbc.fill = GridBagConstraints.NONE; panel.add(ocsswSharedDirLabel, gbc); gbc.gridx = 1; gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; panel.add(ocsswSharedDir, gbc); gbc.gridx = 2; gbc.weightx = 0; gbc.fill = GridBagConstraints.NONE; panel.add(ocsswSharedDirButton, gbc); panel.setMinimumSize(panel.getMinimumSize()); return panel; } private JPanel getVirtualMachinePanel() { final Preferences preferences = Config.instance("seadas").load().preferences(); JPanel panel = GridBagUtils.createPanel(); GridBagConstraints gbc = createConstraints(); panel.setBorder(UIUtils.createGroupBorder("Virtual Machine")); JLabel ocsswSharedDirLabel = new JLabel(OCSSW_SHARED_DIR_LABEL + ": "); ocsswSharedDir = new JTextField(20); ocsswSharedDirLabel.setMinimumSize(ocsswSharedDirLabel.getPreferredSize()); ocsswSharedDir.setMinimumSize(new JTextField(10).getPreferredSize()); pc.addProperty(Property.create(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY, preferences.get(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY, OCSSWConfigData.getSeadasClientServerSharedDirDefaultValue()))); pc.getDescriptor(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY).setDisplayName(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY); final BindingContext ctx = new BindingContext(pc); ctx.bind(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY, ocsswSharedDir); JButton ocsswSharedDirButton = new JButton("..."); ocsswSharedDirButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File newDir = getDir(); if (newDir != null) { ocsswSharedDir.setText(newDir.getAbsolutePath()); pc.setValue(SEADAS_CLIENT_SERVER_SHARED_DIR_PROPERTY, ocsswSharedDir.getText()); } } }); ocsswSharedDirButton.setMinimumSize(ocsswSharedDirButton.getPreferredSize()); gbc.gridx = 0; gbc.weightx = 0; gbc.fill = GridBagConstraints.NONE; panel.add(ocsswSharedDirLabel, gbc); gbc.gridx = 1; gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; panel.add(ocsswSharedDir, gbc); gbc.gridx = 2; gbc.weightx = 0; gbc.fill = GridBagConstraints.NONE; panel.add(ocsswSharedDirButton, gbc); panel.setMinimumSize(panel.getMinimumSize()); return panel; } private JPanel getRemoteServerPanel() { final Preferences preferences = Config.instance("seadas").load().preferences(); JPanel panel = GridBagUtils.createPanel(); GridBagConstraints gbc = createConstraints(); panel.setBorder(UIUtils.createGroupBorder("Remote Server")); JLabel ocsswServerAddressLabel = new JLabel(OCSSW_SERVER_ADDRESS_LABEL + ": "); JLabel serverPortLabel = new JLabel(SERVER_PORT_LABEL + ": "); JLabel serverInputStreamPortLabel = new JLabel(SERVER_INPUT_STREAM_PORT_LABEL + ": "); JLabel serverErrorStreamPortLabel = new JLabel(SERVER_ERROR_STREAM_PORT_LABEL + ": "); ocsswserverAddressTextfield = new JTextField(20); serverPortTextfield = new JTextField(4); serverInputStreamPortTextfield = new JTextField(4); serverErrorStreamPortTextfield = new JTextField(4); // Set minimum size for each component ocsswServerAddressLabel.setMinimumSize(ocsswServerAddressLabel.getPreferredSize()); serverPortLabel.setMinimumSize(serverPortLabel.getPreferredSize()); serverInputStreamPortLabel.setMinimumSize(serverInputStreamPortLabel.getPreferredSize()); serverErrorStreamPortLabel.setMinimumSize(serverErrorStreamPortLabel.getPreferredSize()); ocsswserverAddressTextfield.setMinimumSize(new JTextField(10).getPreferredSize()); serverPortTextfield.setMinimumSize(serverPortTextfield.getPreferredSize()); serverInputStreamPortTextfield.setMinimumSize(serverInputStreamPortTextfield.getPreferredSize()); serverErrorStreamPortTextfield.setMinimumSize(serverErrorStreamPortTextfield.getPreferredSize()); pc.addProperty(Property.create(SEADAS_OCSSW_SERVER_ADDRESS_PROPERTY, preferences.get(SEADAS_OCSSW_SERVER_ADDRESS_PROPERTY, SEADAS_OCSSW_SERVER_ADDRESS_DEFAULT_VALUE))); pc.getDescriptor(SEADAS_OCSSW_SERVER_ADDRESS_PROPERTY).setDisplayName(SEADAS_OCSSW_SERVER_ADDRESS_PROPERTY); pc.addProperty(Property.create(SEADAS_OCSSW_PORT_PROPERTY, preferences.get(SEADAS_OCSSW_PORT_PROPERTY, SEADAS_OCSSW_PORT_DEFAULT_VALUE))); pc.getDescriptor(SEADAS_OCSSW_PORT_PROPERTY).setDisplayName(SEADAS_OCSSW_PORT_PROPERTY); pc.addProperty(Property.create(SEADAS_OCSSW_PROCESSINPUTSTREAMPORT_PROPERTY, preferences.get(SEADAS_OCSSW_PROCESSINPUTSTREAMPORT_PROPERTY, SEADAS_OCSSW_PROCESSINPUTSTREAMPORT_DEFAULT_VALUE))); pc.getDescriptor(SEADAS_OCSSW_PROCESSINPUTSTREAMPORT_PROPERTY).setDisplayName(SEADAS_OCSSW_PROCESSINPUTSTREAMPORT_PROPERTY); pc.addProperty(Property.create(SEADAS_OCSSW_PROCESSERRORSTREAMPORT_PROPERTY, preferences.get(SEADAS_OCSSW_PROCESSERRORSTREAMPORT_PROPERTY, SEADAS_OCSSW_PROCESSERRORSTREAMPORT_DEFAULT_VALUE))); pc.getDescriptor(SEADAS_OCSSW_PROCESSERRORSTREAMPORT_PROPERTY).setDisplayName(SEADAS_OCSSW_PROCESSERRORSTREAMPORT_PROPERTY); final BindingContext ctx = new BindingContext(pc); ctx.bind(SEADAS_OCSSW_PORT_PROPERTY, serverPortTextfield); ctx.bind(SEADAS_OCSSW_PROCESSINPUTSTREAMPORT_PROPERTY, serverInputStreamPortTextfield); ctx.bind(SEADAS_OCSSW_PROCESSERRORSTREAMPORT_PROPERTY, serverErrorStreamPortTextfield); ctx.bind(SEADAS_OCSSW_SERVER_ADDRESS_PROPERTY, ocsswserverAddressTextfield); gbc.gridx = 0; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0; panel.add(ocsswServerAddressLabel, gbc); gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1; panel.add(ocsswserverAddressTextfield, gbc); gbc.gridy += 1; gbc.gridx = 0; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0; panel.add(serverPortLabel, gbc); gbc.gridx = 1; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 1; panel.add(serverPortTextfield, gbc); gbc.gridy += 1; gbc.gridx = 0; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0; panel.add(serverInputStreamPortLabel, gbc); gbc.gridx = 1; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 1; panel.add(serverInputStreamPortTextfield, gbc); gbc.gridy += 1; gbc.gridx = 0; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0; panel.add(serverErrorStreamPortLabel, gbc); gbc.gridx = 1; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 1; panel.add(serverErrorStreamPortTextfield, gbc); panel.setMinimumSize(panel.getMinimumSize()); return panel; } private JPanel getLocalOCSSWPanel() { final Preferences preferences = Config.instance("seadas").load().preferences(); String ocsswRootString = preferences.get(SEADAS_OCSSW_ROOT_PROPERTY, null); if (ocsswRootString == null) { final Preferences preferencesSnap = Config.instance().load().preferences(); ocsswRootString = preferencesSnap.get(SEADAS_OCSSW_ROOT_PROPERTY, null); } String ocsswRoot1 = "$" + SEADAS_OCSSW_ROOT_ENV; String ocsswRoot2 = "${" + SEADAS_OCSSW_ROOT_ENV + "}"; if (ocsswRootString != null && (ocsswRootString.equals(ocsswRoot1) || ocsswRootString.equals(ocsswRoot2))) { ocsswRootString = System.getenv(SEADAS_OCSSW_ROOT_ENV); if (ocsswRootString == null) { ocsswRootString = " "; // todo open a popup warning } } else if (ocsswRootString == null) { ocsswRootString = System.getenv(SEADAS_OCSSW_ROOT_ENV); } // todo This appears to remove this pattern at beginning of string, why is this check needed? // if (ocsswRootString != null && ocsswRootString.startsWith("$")) { // ocsswRootString = System.getProperty(ocsswRootString.substring(ocsswRootString.indexOf("{") + 1, ocsswRootString.indexOf("}"))) + ocsswRootString.substring(ocsswRootString.indexOf("}") + 1); // } if (ocsswRootString == null || ocsswRootString.length() == 0) { File ocsswRootDir = new File(SystemUtils.getApplicationHomeDir(), "ocssw"); ocsswRootString = ocsswRootDir.getAbsolutePath(); } JPanel panel = GridBagUtils.createPanel(); GridBagConstraints gbc = createConstraints(); panel.setBorder(UIUtils.createGroupBorder("Local Server")); JLabel ocsswRootLabel = new JLabel(OCSSW_ROOT_LABEL + ": "); ocsswRootLabel.setMinimumSize(ocsswRootLabel.getPreferredSize()); ocsswRootTextfield = new JTextField(20); ocsswRootTextfield.setMinimumSize(new JTextField(10).getPreferredSize()); pc.addProperty(Property.create(SEADAS_OCSSW_ROOT_PROPERTY, ocsswRootString)); pc.getDescriptor(SEADAS_OCSSW_ROOT_PROPERTY).setDisplayName(SEADAS_OCSSW_ROOT_PROPERTY); final BindingContext ctx = new BindingContext(pc); ctx.bind(SEADAS_OCSSW_ROOT_PROPERTY, ocsswRootTextfield); JButton ocsswRootButton = new JButton("..."); ocsswRootButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File newDir = getDir(); if (newDir != null) { ocsswRootTextfield.setText(newDir.getAbsolutePath()); pc.setValue(SEADAS_OCSSW_ROOT_PROPERTY, ocsswRootTextfield.getText()); } } }); ocsswRootButton.setMinimumSize(ocsswRootButton.getPreferredSize()); gbc.gridx = 0; gbc.weightx = 0; gbc.fill = GridBagConstraints.NONE; panel.add(ocsswRootLabel, gbc); gbc.gridx = 1; gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; panel.add(ocsswRootTextfield, gbc); gbc.gridx = 2; gbc.weightx = 0; gbc.fill = GridBagConstraints.NONE; panel.add(ocsswRootButton, gbc); panel.setMinimumSize(panel.getMinimumSize()); return panel; } public File getDir() { File selectedFile = null; JFileChooser jFileChooser = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnValue = jFileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { selectedFile = jFileChooser.getSelectedFile(); } return selectedFile; } public static GridBagConstraints createConstraints() { GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 1; gbc.weighty = 1; return gbc; } private void getTagsforConfig() { 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 void parseValidSeaDASTagObject(JSONObject tagObject) { ModuleInfo seadasProcessingModuleInfo = Modules.getDefault().ownerOf(OCSSWInfoGUI.class); String seadasToolboxVersion = String.valueOf(seadasProcessingModuleInfo.getSpecificationVersion()); String seadasToolboxVersionJson = (String) tagObject.get("seadas"); if (seadasToolboxVersionJson.equals(seadasToolboxVersion)) { //Get corresponding ocssw tags for seadas JSONArray ocsswTags = (JSONArray) tagObject.get("ocssw"); if (ocsswTags != null) { for (int i = 0; i < ocsswTags.size(); i++) { try { validOCSSWTagList.add((String) ocsswTags.get(i)); } catch (Exception e) { e.printStackTrace(); } } } } } // todo call to this method was removed as it is broken and unneeded. This method can be deleted in future if desired. private JPanel ocsswTagPanel() { final Preferences preferences = Config.instance("seadas").load().preferences(); getTagsforConfig(); JPanel panel = GridBagUtils.createPanel(); GridBagConstraints gbc = createConstraints(); JLabel ocsswTagLabel = new JLabel(OCSSW_TAG_LABEL + ": "); JComboBox validOCSSWTagsComboBox = new JComboBox(validOCSSWTagList.toArray()); Font f1 = validOCSSWTagsComboBox.getFont(); Font f2 = new Font("Tahoma", 0, 14); validOCSSWTagsComboBox.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value instanceof JComponent) return (JComponent) value; boolean itemEnabled = validOCSSWTagList.contains((String) value); super.getListCellRendererComponent(list, value, index, isSelected && itemEnabled, cellHasFocus); // Render item as disabled and with different font: setEnabled(itemEnabled); setFont(itemEnabled ? f1 : f2); return this; } }); ocsswTagTextfield = new JTextField(10); ocsswTagLabel.setMinimumSize(ocsswTagLabel.getPreferredSize()); validOCSSWTagsComboBox.setMinimumSize(new JComboBox().getPreferredSize()); ocsswTagLabel.setToolTipText(BRANCH_TOOLTIP); if (validOCSSWTagList.size() != 0) { pc.addProperty(Property.create(SEADAS_OCSSW_TAG_PROPERTY, preferences.get(SEADAS_OCSSW_TAG_PROPERTY, validOCSSWTagList.get(0)))); } else { pc.addProperty(Property.create(SEADAS_OCSSW_TAG_PROPERTY, preferences.get(SEADAS_OCSSW_TAG_PROPERTY, SEADAS_OCSSW_TAG_DEFAULT_VALUE))); } // // pc.addProperty(Property.create(SEADAS_OCSSW_TAG_PROPERTY, preferences.get(SEADAS_OCSSW_TAG_PROPERTY, SEADAS_OCSSW_TAG_DEFAULT_VALUE))); // pc.addProperty(Property.create(SEADAS_OCSSW_TAG_PROPERTY, preferences.get(SEADAS_OCSSW_TAG_PROPERTY, validOCSSWTagList.get(0)))); pc.getDescriptor(SEADAS_OCSSW_TAG_PROPERTY).setDisplayName(SEADAS_OCSSW_TAG_PROPERTY); final BindingContext ctx = new BindingContext(pc); ctx.bind(SEADAS_OCSSW_TAG_PROPERTY, validOCSSWTagsComboBox); gbc.fill = GridBagConstraints.NONE; gbc.weighty = 0; gbc.weightx = 0; panel.add(ocsswTagLabel, gbc); gbc.gridx = 1; gbc.weightx = 1; //panel.add(ocsswTagTextfield, gbc); panel.add(validOCSSWTagsComboBox, gbc); return panel; } private Dimension adjustDimension(Dimension dimension, int widthAdjustment, int heightAdjustment) { if (dimension == null) { return null; } int width = dimension.width + widthAdjustment; int height = dimension.height + heightAdjustment; return new Dimension(width, height); } /** * If there is a conflict between the String ocsswroot and the environment variable OCSSWROOT * a GUI prompts the users whether this conflict is okay. If there is no conflict or if there * is a conflict and the user approves then 'true' is returned. * * @param field * @param ocsswroot * @return */ private Boolean checkIfEnvironmentVariableConflict(String field, String ocsswroot) { Map<String, String> env = System.getenv(); String ocsswroot_env = env.get("OCSSWROOT"); if (ocsswroot_env == null || ocsswroot_env.trim().length() == 0) { return true; } if (ocsswroot_env.equals(ocsswroot)) { return true; } String msg = "<html>" + "WARNING!: You are defining OCSSW ROOT to be '" + ocsswroot + "'<br>" + "but on your system the environment variable OCSSWROOT points to '" + ocsswroot_env + "'<br>" + "This mismatch could cause problems or conflict between GUI and command line operations<br>" + "</html>"; final int dialogResult = getUserResponse(msg, "Continue", "Back"); if (dialogResult == ModalDialog.ID_OK) { return true; } else { return false; } } private Boolean checkParameters() { // if (!isTextFieldValidTag(OCSSW_TAG_LABEL, ocsswTagTextfield)) { // return false; // } String ocssLocationString = (String) ocsswLocationComboBox.getSelectedItem(); switch (ocssLocationString) { case OCSSW_LOCATION_LOCAL: if (!directoryCheck(OCSSW_ROOT_LABEL, ocsswRootTextfield.getText())) { return false; } if (!checkIfEnvironmentVariableConflict(OCSSW_ROOT_LABEL, ocsswRootTextfield.getText())) { return false; } break; case OCSSW_LOCATION_VIRTUAL_MACHINE: case OCSSW_LOCATION_DOCKER: if (!directoryCheck(OCSSW_SHARED_DIR_LABEL, ocsswSharedDir.getText())) { return false; } break; case OCSSW_LOCATION_REMOTE_SERVER: if (!isTextFieldValidIP(OCSSW_SERVER_ADDRESS_LABEL, ocsswserverAddressTextfield)) { return false; } if (!isTextFieldValidPort(SERVER_PORT_LABEL, serverPortTextfield)) { return false; } if (!isTextFieldValidPort(SERVER_INPUT_STREAM_PORT_LABEL, serverInputStreamPortTextfield)) { return false; } if (!isTextFieldValidPort(SERVER_ERROR_STREAM_PORT_LABEL, serverErrorStreamPortTextfield)) { return false; } break; } return true; } public boolean isTextFieldValidTag(String field, JTextField textfield) { boolean valid = true; if (textfield != null) { if (textfieldHasValue(textfield)) { String branch = textfield.getText().trim(); if (!isValidBranch(branch)) { notifyError("<html>" + field + "='" + branch + "' is not a valid OCSSW branch. <br>" + "The OCSSW branch must contain 2 fields of the form X.X where X is an integer</html>"); return false; } // if (!isDefaultBranch(branch)) { // return false; // } } else { notifyError("'" + field + "' must contain an OCSSW Branch"); valid = false; } } else { notifyError("'" + field + "' not defined"); valid = false; } return valid; } // public boolean isDefaultBranch(String branch) { // // if (branch == null) { // return false; // } // // branch.trim(); // //// if (SEADAS_OCSSW_BRANCH_DEFAULT_VALUE.equals(branch)) { //// return true; //// } // // String msg = "<html>" + // "WARNING!: Your current SeaDAS version has default branch='" + SEADAS_OCSSW_BRANCH_DEFAULT_VALUE + "'<br>"+ // "You have selected to use branch='" + branch + "'<br>" + // "This version mismatch could cause possible problems when running from the SeaDAS GUI" + // "</html>"; // // final int dialogResult = getUserResponse(msg, "Continue", "Back"); // // if (dialogResult == ModalDialog.ID_OK) { // return true; // } else { // return false; // } // } public static boolean isValidBranch(final String branch) { String[] arrOfBranch = branch.split("\\."); if (arrOfBranch.length == 2) { if (isNumeric(arrOfBranch[0]) && isNumeric(arrOfBranch[1])) { return true; } } else { return false; } return false; } public boolean isTextFieldValidIP(String label, JTextField textfield) { if (textfield != null) { if (textfieldHasValue(textfield)) { if (isValidIP(textfield.getText())) { return true; } else { notifyError("<html>" + label + "='" + textfield.getText() + "' is not a valid IP address</html>"); } } else { notifyError("'" + label + "' must contain an IP address"); } } else { notifyError("'" + label + "' not defined"); } return false; } public boolean isTextFieldValidPort(String label, JTextField textfield) { if (textfield != null) { if (textfieldHasValue(textfield)) { if (isValidPort(textfield.getText())) { return true; } else { notifyError("'" + label + "=" + textfield.getText() + "' is not a valid port"); } } else { notifyError("'" + label + "' must contain a port number"); } } else { notifyError("'" + label + "' not defined"); } return false; } public static boolean textfieldHasValue(JTextField textfield) { if (textfield.getText() != null && textfield.getText().length() > 0) { return true; } else { return false; } } public static boolean isValidPort(String str) { int port; try { port = Integer.parseInt(str); } catch (NumberFormatException e) { return false; } if (port >= 1 && port <= 65535) { return true; } else { return false; } } public static boolean isValidIP(final String ip) { String PATTERN = "^((0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)\\.){3}(0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)$"; return ip.matches(PATTERN); } public static boolean isNumeric(String str) { try { Integer.parseInt(str); return true; } catch (NumberFormatException e) { return false; } } private int getUserResponse(String msg, String okText, String cancelText) { JPanel panel = GridBagUtils.createPanel(); JLabel label = new JLabel(msg); GridBagConstraints gbc = createConstraints(); gbc.anchor = GridBagConstraints.NORTH; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weighty = 1; gbc.weightx = 1; panel.add(label, gbc); ModalDialog dialog = new ModalDialog(modalDialog.getParent(), PANEL_NAME, panel, ModalDialog.ID_OK_CANCEL, HELP_ID); dialog.getButton(ModalDialog.ID_OK).setText(okText); dialog.getButton(ModalDialog.ID_CANCEL).setText(cancelText); dialog.getButton(ModalDialog.ID_OK).setMinimumSize(dialog.getButton(ModalDialog.ID_OK).getPreferredSize()); // Specifically set sizes for dialog here Dimension minimumSizeAdjusted = adjustDimension(dialog.getJDialog().getMinimumSize(), 25, 50); Dimension preferredSizeAdjusted = adjustDimension(dialog.getJDialog().getPreferredSize(), 25, 50); dialog.getJDialog().setMinimumSize(minimumSizeAdjusted); dialog.getJDialog().setPreferredSize(preferredSizeAdjusted); dialog.getJDialog().pack(); return dialog.show(); } private Boolean directoryCheck(String field, String filename) { File dir = new File(filename); if (dir.exists()) { return true; } String msg = "<html>" + field + " directory: '" + filename + "' does not exist" + "</html>"; final int dialogResult = getUserResponse(msg, "Create Directory", "Back"); if (dialogResult == ModalDialog.ID_OK) { try { dir.mkdirs(); if (dir.exists()) { return true; } else { msg = "<html>Failed to create directory '" + filename + "'<br></html>"; } } catch (Exception e) { msg = "<html>Failed to create directory '" + filename + "'<br>" + e.toString() + "</html>"; } notifyError(msg); } return false; } private void notifyError(String msg) { JOptionPane.showMessageDialog(null, msg, PANEL_NAME, JOptionPane.WARNING_MESSAGE); } }
40,722
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSWLocal.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ocssw/OCSSWLocal.java
package gov.nasa.gsfc.seadas.processing.ocssw; import com.bc.ceres.core.ProgressMonitor; import gov.nasa.gsfc.seadas.processing.common.FileInfoFinder; import gov.nasa.gsfc.seadas.processing.common.MissionInfo; import gov.nasa.gsfc.seadas.processing.common.ParFileManager; import gov.nasa.gsfc.seadas.processing.core.*; import gov.nasa.gsfc.seadas.processing.utilities.SeadasArrayUtils; import org.apache.commons.lang3.ArrayUtils; import org.esa.snap.core.util.Debug; import org.esa.snap.rcp.util.Dialogs; import java.io.*; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import static gov.nasa.gsfc.seadas.processing.common.SeadasFileUtils.debug; import static gov.nasa.gsfc.seadas.processing.core.L2genData.*; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo.OCSSW_INSTALLER_PROGRAM_NAME; /** * Created by aabduraz on 3/27/17. */ public class OCSSWLocal extends OCSSW { public static String TMP_OCSSW_INSTALLER_PROGRAM_PATH = (new File(System.getProperty("java.io.tmpdir"), OCSSW_INSTALLER_PROGRAM_NAME)).getPath(); private static final String DEFAULTS_FILE_PREFIX = "msl12_defaults_", AQUARIUS_DEFAULTS_FILE_PREFIX = "l2gen_aquarius_defaults_", L3GEN_DEFAULTS_FILE_PREFIX = "msl12_defaults_"; private String defaultsFilePrefix; private final static String L2GEN_PROGRAM_NAME = "l2gen", AQUARIUS_PROGRAM_NAME = "l2gen_aquarius", L3GEN_PROGRAM_NAME = "l3gen"; Process process; public OCSSWLocal() { initialize(); } private void initialize() { //missionInfo = new MissionInfo(); } @Override public ProcessObserver getOCSSWProcessObserver(Process process, String processName, ProgressMonitor progressMonitor) { return new ProcessObserver(process, processName, progressMonitor); } @Override public boolean isMissionDirExist(String missionName) { MissionInfo missionInfo = new MissionInfo(missionName); File dir = missionInfo.getSubsensorDirectory(); if (dir == null) { dir = missionInfo.getDirectory(); } if (dir != null) { return dir.isDirectory(); } return false; } @Override public int getProcessExitValue() { return process.exitValue(); } @Override public void waitForProcess() { try { process.waitFor(); } catch (InterruptedException ie) { ie.printStackTrace(); } } @Override public InputStream getProductXMLFile(L2genData.Source source) throws IOException { File ocsswShareDir = new File(OCSSWInfo.getInstance().getOcsswRoot(), SHARE_DIR); File ocsswCommonDir = new File(ocsswShareDir, COMMON_DIR); //todo File xmlFile = new File(ocsswCommonDir, PRODUCT_XML); if (source == L2genData.Source.RESOURCES) { try { return new FileInputStream(xmlFile); } catch (IOException e) { throw new IOException("problem creating product XML file: " + e.getMessage()); } } else if (source == Source.L2GEN) { try { return new FileInputStream(xmlFile); } catch (IOException e) { throw new IOException("problem creating product XML file: " + e.getMessage()); } } return null; } @Override public Process execute(ProcessorModel processorModel) { setProgramName(processorModel.getProgramName()); setIfileName(processorModel.getParamValue(processorModel.getPrimaryInputFileOptionName())); return execute(getProgramCommandArray(processorModel)); } @Override public Process executeSimple(ProcessorModel processorModel) { return execute(processorModel); } @Override public InputStream executeAndGetStdout(ProcessorModel processorModel) { Process process = execute(processorModel); try { process.waitFor(); } catch (InterruptedException ie) { ie.printStackTrace(); } return process.getInputStream(); } @Override public Process execute(ParamList paramListl) { String[] programNameArray = {programName}; commandArray = SeadasArrayUtils.concatAll(commandArrayPrefix, programNameArray, getCommandArrayParam(paramListl), commandArraySuffix); return execute(commandArray); } /** * this method returns a command array for execution. * the array is constructed using the paramList data and input/output files. * the command array structure is: full pathname of the program to be executed, input file name, params in the required order and finally the output file name. * assumption: order starts with 1 * * @return */ public String[] getProgramCommandArray(ProcessorModel processorModel) { String[] cmdArray; String[] programNameArray = {processorModel.getProgramName()}; String[] cmdArrayForParams; ParFileManager parFileManager = new ParFileManager(processorModel); if (processorModel.acceptsParFile()) { cmdArrayForParams = parFileManager.getCmdArrayWithParFile(); } else { cmdArrayForParams = getCommandArrayParam(processorModel.getParamList()); } commandArraySuffix = processorModel.getCmdArraySuffix(); //The final command array is the concatination of commandArrayPrefix, cmdArrayForParams, and commandArraySuffix //TODO: for ocssw_install commandArrayPrefix has the program name with the file path, so it can't include programNameArray again if (!processorModel.getProgramName().equals(OCSSW_INSTALLER_PROGRAM_NAME)) { cmdArray = SeadasArrayUtils.concatAll(commandArrayPrefix, programNameArray, cmdArrayForParams, commandArraySuffix); } else { cmdArray = SeadasArrayUtils.concatAll(commandArrayPrefix, cmdArrayForParams, commandArraySuffix); } // get rid of the null strings ArrayList<String> cmdList = new ArrayList<String>(); for (String s : cmdArray) { if (s != null) { cmdList.add(s); } } cmdArray = cmdList.toArray(new String[cmdList.size()]); return cmdArray; } @Override public Process execute(String[] commandArray) { StringBuilder sb = new StringBuilder(); for (String item : commandArray) { sb.append(item + " "); } debug("command array content: " + sb.toString()); ProcessBuilder processBuilder = new ProcessBuilder(commandArray); Map<String, String> env = processBuilder.environment(); if (ifileDir != null) { env.put("PWD", ifileDir); processBuilder.directory(new File(ifileDir)); } process = null; try { process = processBuilder.start(); if (process != null) { debug("Running the program " + commandArray.toString()); } } catch (Exception e) { e.printStackTrace(); } return process; } @Override public Process execute(String programName, String[] commandArrayParams) { String[] programNameArray = {programName}; commandArray = SeadasArrayUtils.concatAll(commandArrayPrefix, programNameArray, commandArrayParams, commandArraySuffix); return execute(commandArray); } @Override public String executeUpdateLuts(ProcessorModel processorModel) { String[] programNameArray = {programName}; String[] commandArrayParams = getCommandArrayParam(processorModel.getParamList()); Process process = null; for (String param : commandArrayParams) { commandArray = SeadasArrayUtils.concatAll(commandArrayPrefix, programNameArray, new String[]{param}, commandArraySuffix); process = execute(commandArray); } try { process.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } return process.exitValue() == 0 ? "Update Luts successful." : "Update Luts failed."; } @Override public void getOutputFiles(ProcessorModel processorModel) { //todo implement this method. } @Override public boolean getIntermediateOutputFiles(ProcessorModel processorModel) { return true; } @Override public void findFileInfo(String fileName, FileInfoFinder fileInfoFinder) { String[] fileTypeCommandArrayParams = {OBPG_FILE_TYPE_PROGRAM_NAME, fileName}; process = execute((String[]) ArrayUtils.addAll(commandArrayPrefix, fileTypeCommandArrayParams)); try { BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); File f = new File(fileName); String line = stdInput.readLine(); while (line != null) { if (line.startsWith(f.getName())) { String splitLine[] = line.split(":"); if (splitLine.length == 3) { String missionName = splitLine[1].toString().trim(); String fileType = splitLine[2].toString().trim(); if (fileType.length() > 0) { fileInfoFinder.setFileType(fileType); } if (missionName.length() > 0) { fileInfoFinder.setMissionName(missionName); setMissionName(missionName); } break; } } line = stdInput.readLine(); } // while lines } catch (IOException ioe) { Dialogs.showError(ioe.getMessage()); } } @Override public String getOfileDir() { return ofileDir; } @Override public String getOfileName(String ifileName) { if (isOfileNameFound() && this.ifileName.equals(ifileName)) { return ofileName; } if (ifileName == null || programName == null) { return null; } if (programName.equals("l3bindump")) { return ifileName + ".xml"; } String[] commandArrayParams = {GET_OUTPUT_NAME_PROGRAM_NAME, ifileName, programName}; ofileName = findOfileName(ifileName, SeadasArrayUtils.concat(commandArrayPrefix, commandArrayParams)); setOfileNameFound(true); return ofileName; } @Override public String getOfileName(String ifileName, String programName) { if(programName.equals("l1bgen_generic")){ programName = "l1bgen"; } if (programName.equals("l2merge")) { return "l2merge_output.nc"; } if (programName.equals("l3binmerge")) { return "l3binmerge_output.nc"; } if (programName.equals("georegion_gen")) { return "georegion_output.nc"; } String[] commandArrayParams = {GET_OUTPUT_NAME_PROGRAM_NAME, ifileName, programName}; ofileName = findOfileName(ifileName, SeadasArrayUtils.concat(commandArrayPrefix, commandArrayParams)); return ofileName; } private void addSuites(ArrayList<String> suites, File dir, String prefix) { if (dir != null && dir.isDirectory()) { for (File file : dir.listFiles()) { String filename = file.getName(); if (filename.startsWith(prefix) && filename.endsWith(".par")) { String suiteName = filename.substring(prefix.length(), filename.length() - 4); if (!suites.contains(suiteName)) { suites.add(suiteName); } } } } } public String[] getMissionSuites(String missionName, String programName) { ArrayList<String> suitesArrayList = new ArrayList<String>(); MissionInfo missionInfo = new MissionInfo(missionName); String prefix = getDefaultsFilePrefix(programName); // first look in the common directory File dir = new File(ocsswInfo.getOcsswDataDirPath(), "common"); addSuites(suitesArrayList, dir, prefix); // look in sensor dir addSuites(suitesArrayList, missionInfo.getDirectory(), prefix); // look in subsensor dir addSuites(suitesArrayList, missionInfo.getSubsensorDirectory(), prefix); if (suitesArrayList.size() > 0) { final String[] suitesArray = new String[suitesArrayList.size()]; int i = 0; for (String suite : suitesArrayList) { suitesArray[i] = suite; i++; } java.util.Arrays.sort(suitesArray); return suitesArray; } else { return null; } } public String getDefaultsFilePrefix(String programName) { defaultsFilePrefix = DEFAULTS_FILE_PREFIX; if (programName.equals(L3GEN_PROGRAM_NAME)) { defaultsFilePrefix = L3GEN_DEFAULTS_FILE_PREFIX; } else if (programName.equals(AQUARIUS_PROGRAM_NAME)) { defaultsFilePrefix = AQUARIUS_DEFAULTS_FILE_PREFIX; } return defaultsFilePrefix; } @Override public String getOfileName(String ifileName, String[] options) { if (ifileName == null || programName == null) { return null; } if (programName.equals("l3bindump")) { return ifileName + ".xml"; } String[] commandArrayParams = {GET_OUTPUT_NAME_PROGRAM_NAME, ifileName, programName}; return findOfileName(ifileName, SeadasArrayUtils.concatAll(commandArrayPrefix, commandArrayParams, options)); } @Override public String getOfileName(String ifileName, String programName, String suiteValue) { this.programName = programName; String[] additionalOptions = {"--suite=" + suiteValue}; return getOfileName(ifileName, additionalOptions); } private String findOfileName(String ifileName, String[] commandArray) { setIfileName(ifileName); process = execute(commandArray); if (process == null) { return null; } //wait for process to exit try { Field field = process.getClass().getDeclaredField("hasExited"); field.setAccessible(true); while (!(Boolean) field.get(process)) { } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } int exitCode = process.exitValue(); InputStream is; if (exitCode == 0) { is = process.getInputStream(); } else { is = process.getErrorStream(); } InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); try { if (exitCode == 0) { String line = br.readLine(); while (line != null) { if (line.startsWith(GET_OUTPUT_NAME_TOKEN)) { return (line.substring(GET_OUTPUT_NAME_TOKEN.length())).trim(); } line = br.readLine(); } } else { String line = br.readLine(); while (line != null) { debug("error stream: " + line); line = br.readLine(); } Debug.trace("Failed exit code on program '" + GET_OUTPUT_NAME_PROGRAM_NAME + "'"); } } catch (IOException ioe) { Dialogs.showError(ioe.getMessage()); } return null; } public void setCommandArrayPrefix() { if (programName.equals(OCSSW_INSTALLER_PROGRAM_NAME) ) { //&& !isOCSSWExist() commandArrayPrefix = new String[2]; commandArrayPrefix[0] = TMP_OCSSW_BOOTSTRAP; commandArrayPrefix[1] = TMP_OCSSW_INSTALLER; } else { // if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME)) { // commandArrayPrefix = new String[1]; // commandArrayPrefix[0] = programName; // if (!isOCSSWExist()) { // commandArrayPrefix[0] = TMP_OCSSW_INSTALLER_PROGRAM_PATH; // } else { // commandArrayPrefix[0] = ocsswInfo.getOcsswInstallerScriptPath(); // } // } else { commandArrayPrefix = new String[3]; commandArrayPrefix[0] = ocsswInfo.getOcsswRunnerScriptPath(); commandArrayPrefix[1] = "--ocsswroot"; commandArrayPrefix[2] = ocsswInfo.getOcsswRoot(); } } private String[] getCommandArrayParam(ParamList paramList) { ArrayList<String> commandArrayList = new ArrayList<>(); Iterator<ParamInfo> itr = paramList.getParamArray().iterator(); ParamInfo option; int optionOrder; String optionValue; int i = 0; while (itr.hasNext()) { option = itr.next(); optionOrder = option.getOrder(); optionValue = option.getValue(); if (option.getType() != ParamInfo.Type.HELP) { if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_ARGUMENT)) { if (option.getValue() != null && option.getValue().length() > 0) { commandArrayList.add(optionValue); } } else if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_OPTION_MINUSMINUS) && !option.getDefaultValue().equals(option.getValue())) { commandArrayList.add("--" + option.getName() + " " + optionValue); } else if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_FLAG_MINUSMINUS) && (option.getValue().equals("true") || option.getValue().equals("1"))) { if (option.getName() != null && option.getName().length() > 0) { commandArrayList.add("--" + option.getName()); } } else if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_OPTION) && !option.getDefaultValue().equals(option.getValue())) { commandArrayList.add(option.getName() + "=" + optionValue); } else if (option.getUsedAs().equals(ParamInfo.USED_IN_COMMAND_AS_FLAG) && (option.getValue().equals("true") || option.getValue().equals("1"))) { if (option.getName() != null && option.getName().length() > 0) { commandArrayList.add(option.getName()); } } } } String[] commandArrayParam = new String[commandArrayList.size()]; commandArrayParam = commandArrayList.toArray(commandArrayParam); return commandArrayParam; } /** * /tmp/install_ocssw --tag initial -i ocssw-new --seadas --modist * * @return */ @Override public void setCommandArraySuffix() { String[] cmdArraySuffix = new String[2]; cmdArraySuffix[0] = "--tag=R2020.1"; cmdArraySuffix[1] = "--seadas"; } @Override public HashMap<String, String> computePixelsFromLonLat(ProcessorModel processorModel) { String[] commandArray = getProgramCommandArray(processorModel); HashMap<String, String> pixels = new HashMap<String, String>(); try { Process process = execute(commandArray); BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; String[] tmp; while ((line = stdInput.readLine()) != null) { if (line.indexOf("=") != -1) { tmp = line.split("="); pixels.put(tmp[0], tmp[1]); } } } catch (IOException ioe) { ioe.printStackTrace(); } return pixels; } @Override public ArrayList<String> readSensorFileIntoArrayList(File file) { String lineData; ArrayList<String> fileContents = new ArrayList<String>(); BufferedReader moFile = null; try { moFile = new BufferedReader(new FileReader(file)); while ((lineData = moFile.readLine()) != null) { fileContents.add(lineData); } } catch (IOException e) { ; } finally { try { moFile.close(); } catch (Exception e) { //Ignore } } return fileContents; } public void updateOCSSWTags(){ String[] commands = {"/bin/bash", TMP_OCSSW_BOOTSTRAP, TMP_OCSSW_INSTALLER, "--list_tags"}; ProcessBuilder processBuilder = new ProcessBuilder(commands); Process proc = null; try { proc = processBuilder.start(); } catch (IOException e) { e.printStackTrace(); } BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); // Read the output from the command //System.out.println("Here is the standard output of the command:\n"); String s = null; ArrayList<String> tagsList = new ArrayList<>(); while (true) { try { if (!((s = stdInput.readLine()) != null)) break; } catch (IOException e) { e.printStackTrace(); } //System.out.println(s); tagsList.add(s); } getValidOCSSWTags4SeaDASVersion(); if (tagsList == null || tagsList.size() == 0) { tagsList = getOcsswTagsValid4CurrentSeaDAS(); if (tagsList == null || tagsList.size() == 0) { tagsList.add(OCSSWConfigData.SEADAS_OCSSW_TAG_DEFAULT_VALUE); if (OCSSWConfigData.SEADAS_OCSSW_TAG_DEFAULT_VALUE_ALT != null && OCSSWConfigData.SEADAS_OCSSW_TAG_DEFAULT_VALUE_ALT.length() > 0) { tagsList.add(OCSSWConfigData.SEADAS_OCSSW_TAG_DEFAULT_VALUE_ALT); } if (OCSSWConfigData.SEADAS_OCSSW_TAG_DEFAULT_VALUE_ALT2 != null && OCSSWConfigData.SEADAS_OCSSW_TAG_DEFAULT_VALUE_ALT2.length() > 0) { tagsList.add(OCSSWConfigData.SEADAS_OCSSW_TAG_DEFAULT_VALUE_ALT2); } } } setOcsswTags(tagsList); } }
22,813
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSWInfo.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ocssw/OCSSWInfo.java
package gov.nasa.gsfc.seadas.processing.ocssw; import gov.nasa.gsfc.seadas.processing.common.SeadasToolboxVersion; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.runtime.Config; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.jsonp.JsonProcessingFeature; import org.glassfish.jersey.media.multipart.MultiPartFeature; import javax.json.JsonObject; import javax.json.stream.JsonGenerator; import javax.swing.*; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Date; import java.util.prefs.Preferences; import java.util.regex.Pattern; import static gov.nasa.gsfc.seadas.processing.ocssw.OCSSWConfigData.*; /** * Created by aabduraz on 5/25/17. */ /** * OCSSWInfo is an Singleton class. */ public class OCSSWInfo { public final static String OCSSW_VM_SERVER_SHARED_DIR_PROPERTY = "seadas.ocssw.sharedDir"; public static final String SEADAS_CLIENT_ID_PROPERTY = "seadas.client.id"; // public static final String OCSSW_KEEP_FILES_ON_SERVER_PROPERTY = "seadas.ocssw.keepFilesOnServer"; public static final String OCSSW_DELETE_FILES_ON_SERVER_PROPERTY = "seadas.ocssw.deleteFilesOnServer"; public static final String OS_64BIT_ARCHITECTURE = "_64"; public static final String OS_32BIT_ARCHITECTURE = "_32"; public static final String SEADAS_VERSION_PROPERTY = "seadas.version"; public static final String SEADAS_LOG_DIR_PROPERTY = "seadas.log.dir"; public static final String OCSSW_LOCATION_PROPERTY = "seadas.ocssw.location"; public static final String OCSSW_LOCATION_LOCAL = "local"; public static final String OCSSW_LOCATION_VIRTUAL_MACHINE = "virtualMachine"; public static final String OCSSW_LOCATION_REMOTE_SERVER = "remoteServer"; public static final String OCSSW_LOCATION_DOCKER = "docker"; public static final String OCSSW_PROCESS_INPUT_STREAM_PORT = "seadas.ocssw.processInputStreamPort"; public static final String OCSSW_PROCESS_ERROR_STREAM_PORT = "seadas.ocssw.processErrorStreamPort"; private static final Pattern PATTERN = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); public static final String OCSSW_SCRIPTS_DIR_SUFFIX = "bin"; public static final String OCSSW_DATA_DIR_SUFFIX = "share"; public static final String OCSSW_BIN_DIR_SUFFIX = "bin"; public static final String OCSSW_SRC_DIR_NAME = "ocssw_src"; public static final String OCSSW_INSTALLER_PROGRAM_NAME = "install_ocssw"; public static final String OCSSW_RUNNER_SCRIPT = "ocssw_runner"; public static final String OCSSW_SEADAS_INFO_PROGRAM_NAME = "seadas_info"; public static final String VIRTUAL_MACHINE_SERVER_API = "localhost"; public static final String DOCKER_SERVER_API = "localhost"; private static OCSSWInfo ocsswInfo = null; private static String sessionId = null; private int processInputStreamPort; private int processErrorStreamPort; private static boolean ocsswServerUp; private static boolean ocsswExist; private String ocsswRoot; private String ocsswDataDirPath; private String ocsswScriptsDirPath; private String ocsswInstallerScriptPath; private String ocsswRunnerScriptPath; private String ocsswBinDirPath; private String ocsswLocation; private String logDirPath; private String resourceBaseUri; private String ocsswTag; private String remoteSeaDASInfo; private static String seadasVersion; public static String getSessionId() { return sessionId; } public static void setSessionId(String sessionId) { OCSSWInfo.sessionId = sessionId; } public static String getSeadasVersion() { return seadasVersion; } public static void setSeadasVersion(String seadasVersion) { OCSSWInfo.seadasVersion = seadasVersion; } public boolean isOcsswServerUp() { return ocsswServerUp; } public void setOcsswServerUp(boolean ocsswServerUp) { OCSSWInfo.ocsswServerUp = ocsswServerUp; } public String getOcsswLocation() { return ocsswLocation; } private void setOcsswLocation(String location) { ocsswLocation = location; } private String clientId; String sharedDirPath; final Preferences preferences; private OCSSWInfo() { preferences = Config.instance("seadas").load().preferences(); if (preferences != null ) { logDirPath = preferences.get(SEADAS_LOG_DIR_PROPERTY, System.getProperty("user.dir")); File logDir = new File(getLogDirPath()); if (!logDir.exists()) { try { Files.createDirectory(Paths.get(logDirPath)); } catch (IOException e) { e.printStackTrace(); } } seadasVersion = preferences.get(SEADAS_VERSION_PROPERTY, null); } } public static OCSSWInfo getInstance() { if (ocsswInfo == null) { ocsswInfo = new OCSSWInfo(); ocsswInfo.detectOcssw(); } return ocsswInfo; } public static OCSSWInfo updateOCSSWInfo() { ocsswInfo = new OCSSWInfo(); ocsswInfo.detectOcssw(); return ocsswInfo; } public int getProcessInputStreamPort() { return processInputStreamPort; } public int getProcessErrorStreamPort() { return processErrorStreamPort; } public boolean isOCSSWExist() { return ocsswExist; } public void detectOcssw() { Date date = new Date(); //System.out.println(sdf.format(date)); sessionId = date.toString(); String ocsswLocationPropertyValue = preferences.get(OCSSW_LOCATION_PROPERTY, null); if (ocsswLocationPropertyValue == null) { return; } if(ocsswLocationPropertyValue.equals(OCSSW_LOCATION_REMOTE_SERVER)) { ocsswLocationPropertyValue = preferences.get(SEADAS_OCSSW_SERVER_ADDRESS_PROPERTY, null); } setOcsswLocation(null); boolean isValidOcsswPropertyValue = isValidOcsswLocationProperty(ocsswLocationPropertyValue); if ((ocsswLocationPropertyValue.equalsIgnoreCase(OCSSW_LOCATION_LOCAL) && OsUtils.getOperatingSystemType() != OsUtils.OSType.Windows) || (!isValidOcsswPropertyValue && (OsUtils.getOperatingSystemType() == OsUtils.OSType.Linux || OsUtils.getOperatingSystemType() == OsUtils.OSType.MacOS))) { setOcsswLocation(OCSSW_LOCATION_LOCAL); initializeLocalOCSSW(); } else { if (ocsswLocationPropertyValue.equalsIgnoreCase(OCSSW_LOCATION_VIRTUAL_MACHINE)) { setOcsswLocation(OCSSW_LOCATION_VIRTUAL_MACHINE); initializeRemoteOCSSW(VIRTUAL_MACHINE_SERVER_API); } else if (ocsswLocationPropertyValue.equalsIgnoreCase(OCSSW_LOCATION_DOCKER)) { setOcsswLocation(OCSSW_LOCATION_DOCKER); initializeRemoteOCSSW(DOCKER_SERVER_API); } else if (validate(ocsswLocationPropertyValue)) { setOcsswLocation(OCSSW_LOCATION_REMOTE_SERVER); initializeRemoteOCSSW(ocsswLocationPropertyValue); } } if (ocsswLocationPropertyValue == null) { Dialogs.showError("Remote OCSSW Initialization", "Please provide OCSSW server location in $HOME/.seadas/etc/seadas.properties"); return; } } public static void displayRemoteServerDownMessage(){ JOptionPane.showMessageDialog(new JOptionPane(), "Remote server is down. OCSSW is not accessible. Please start OCSSW remote server.", "OCSSW Initialization Warning", JOptionPane.WARNING_MESSAGE); } /** * OCSSW_LOCATION_PROPERTY takes only one of the following three values: local, virtualMachine, IP address of a remote server * * @return */ private boolean isValidOcsswLocationProperty(String ocsswLocationPropertyValue) { if (ocsswLocationPropertyValue.equalsIgnoreCase(OCSSW_LOCATION_LOCAL) || ocsswLocationPropertyValue.equalsIgnoreCase(OCSSW_LOCATION_VIRTUAL_MACHINE) || ocsswLocationPropertyValue.equalsIgnoreCase(OCSSW_LOCATION_DOCKER) || validate(ocsswLocationPropertyValue)) { return true; } return false; } public boolean validate(final String ip) { return PATTERN.matcher(ip).matches(); } public void initializeLocalOCSSW() { ocsswServerUp = true; final Preferences preferences = Config.instance("seadas").load().preferences(); String ocsswRootString = preferences.get(SEADAS_OCSSW_ROOT_PROPERTY, null); if (ocsswRootString == null) { final Preferences preferencesSnap = Config.instance().load().preferences(); ocsswRootString = preferencesSnap.get(SEADAS_OCSSW_ROOT_PROPERTY, null); } String ocsswRoot1 = "$" + SEADAS_OCSSW_ROOT_ENV; String ocsswRoot2 = "${" + SEADAS_OCSSW_ROOT_ENV + "}"; if (ocsswRootString != null && (ocsswRootString.equals(ocsswRoot1) || ocsswRootString.equals(ocsswRoot2))) { ocsswRootString = System.getenv(SEADAS_OCSSW_ROOT_ENV); if (ocsswRootString == null) { ocsswRootString = " "; // todo open a popup warning } } else if (ocsswRootString == null ) { ocsswRootString = System.getenv(SEADAS_OCSSW_ROOT_ENV); } // todo This appears to remove this pattern at beginning of string, why is this check needed? // if (ocsswRootString != null && ocsswRootString.startsWith("$")) { // ocsswRootString = System.getProperty(ocsswRootString.substring(ocsswRootString.indexOf("{") + 1, ocsswRootString.indexOf("}"))) + ocsswRootString.substring(ocsswRootString.indexOf("}") + 1); // } if (ocsswRootString == null || ocsswRootString.length() == 0) { // File ocsswRootDir = new File(SystemUtils.getApplicationHomeDir() + File.separator + "ocssw"); File ocsswRootDir = new File(SystemUtils.getApplicationHomeDir(), "ocssw"); ocsswRootString = ocsswRootDir.getAbsolutePath(); } if (ocsswRootString != null && ocsswRootString.length() > 0) { // final File dir = new File(ocsswRootString + File.separator + OCSSW_SCRIPTS_DIR_SUFFIX); final File dir = new File(ocsswRootString, OCSSW_SCRIPTS_DIR_SUFFIX); //SeadasLogger.getLogger().info("server ocssw root path: " + dir.getAbsoluteFile()); if (dir.isDirectory()) { ocsswExist = true; } } ocsswRoot = ocsswRootString; ocsswScriptsDirPath = ocsswRoot + File.separator + OCSSW_SCRIPTS_DIR_SUFFIX; ocsswDataDirPath = ocsswRoot + File.separator + OCSSW_DATA_DIR_SUFFIX; ocsswInstallerScriptPath = ocsswScriptsDirPath + System.getProperty("file.separator") + OCSSW_INSTALLER_PROGRAM_NAME; ocsswRunnerScriptPath = ocsswScriptsDirPath + System.getProperty("file.separator") + OCSSW_RUNNER_SCRIPT; ocsswBinDirPath = ocsswRoot + System.getProperty("file.separator") + OCSSW_BIN_DIR_SUFFIX; } private boolean initializeRemoteOCSSW(String serverAPI) { ocsswServerUp = false; ocsswExist = false; final String BASE_URI_PORT_NUMBER_PROPERTY = "seadas.ocssw.port"; final String OCSSW_REST_SERVICES_CONTEXT_PATH = "ocsswws"; String baseUriPortNumber = preferences.get(BASE_URI_PORT_NUMBER_PROPERTY, "6400"); resourceBaseUri = "http://" + serverAPI + ":" + baseUriPortNumber + "/" + OCSSW_REST_SERVICES_CONTEXT_PATH + "/"; //System.out.println("server URL:" + resourceBaseUri); final ClientConfig clientConfig = new ClientConfig(); clientConfig.register(MultiPartFeature.class); clientConfig.register(JsonProcessingFeature.class).property(JsonGenerator.PRETTY_PRINTING, true); Client c = ClientBuilder.newClient(clientConfig); WebTarget target = c.target(resourceBaseUri); JsonObject jsonObject = null; SeadasToolboxVersion seadasToolboxVersion = new SeadasToolboxVersion(); ocsswTag = seadasToolboxVersion.getLatestOCSSWTagForInstalledRelease(); if (ocsswTag == null) { ocsswTag = SEADAS_OCSSW_TAG_DEFAULT_VALUE; } //System.out.println("ocssw tag = " + ocsswTag); try { jsonObject = target.path("ocssw").path("ocsswInfo").path(ocsswTag).request(MediaType.APPLICATION_JSON_TYPE).get(JsonObject.class); } catch (Exception e) { e.printStackTrace(); writeException(e); return false; } if (jsonObject != null) { ocsswServerUp = true; ocsswExist = jsonObject.getBoolean("ocsswExists"); ocsswRoot = jsonObject.getString("ocsswRoot"); ocsswDataDirPath = jsonObject.getString("ocsswDataDirPath"); ocsswInstallerScriptPath = jsonObject.getString("ocsswInstallerScriptPath"); ocsswRunnerScriptPath = jsonObject.getString("ocsswRunnerScriptPath"); ocsswScriptsDirPath = jsonObject.getString("ocsswScriptsDirPath"); //todo decide what will happen when sharedDirPath is null sharedDirPath = preferences.get(OCSSW_VM_SERVER_SHARED_DIR_PROPERTY, null); //if ( sharedDirPath == null ) { clientId = preferences.get(SEADAS_CLIENT_ID_PROPERTY, System.getProperty("user.name")); String deleteFilesOnServer = preferences.get(OCSSW_DELETE_FILES_ON_SERVER_PROPERTY, "true"); Response response = target.path("ocssw").path("manageClientWorkingDirectory").path(clientId).request().put(Entity.entity(deleteFilesOnServer, MediaType.TEXT_PLAIN_TYPE)); // } processInputStreamPort = new Integer(preferences.get(OCSSW_PROCESS_INPUT_STREAM_PORT, "6402")).intValue(); processErrorStreamPort = new Integer(preferences.get(OCSSW_PROCESS_ERROR_STREAM_PORT, "6403")).intValue(); remoteSeaDASInfo = target.path("ocssw").path("getSystemInfo").request().get(String.class); } //System.out.println("ocsswExist = " + ocsswExist); return ocsswExist; } private void writeException(Exception e) { FileWriter fileWriter = null; try { fileWriter = new FileWriter(new File(logDirPath + File.separator + this.getClass().getName() + "_" + e.getClass().getName() + ".log")); fileWriter.write(e.getMessage()); if (fileWriter != null) { fileWriter.close(); } } catch (Exception exc) { JOptionPane.showMessageDialog(new JOptionPane(), "Log file directory is not accessible to write.", "OCSSW Initialization Warning", JOptionPane.WARNING_MESSAGE); } } public static String getOSName() { String osName = System.getProperty("os.name").toLowerCase(); if (System.getProperty("os.arch").indexOf("64") != -1) { return osName + OS_64BIT_ARCHITECTURE; } else { return osName + OS_32BIT_ARCHITECTURE; } } public String getResourceBaseUri() { return resourceBaseUri; } public String getOcsswRoot() { return ocsswRoot; } public void setOcsswRoot(String ocsswRootNewValue) { ocsswRoot = ocsswRootNewValue; } public String getOcsswDataDirPath() { return ocsswDataDirPath; } public String getOcsswScriptsDirPath() { return ocsswScriptsDirPath; } public String getOcsswInstallerScriptPath() { return ocsswInstallerScriptPath; } public String getOcsswRunnerScriptPath() { return ocsswRunnerScriptPath; } public String getOcsswBinDirPath() { return ocsswBinDirPath; } public String getLogDirPath() { return logDirPath; } public void setLogDirPath(String logDirPath) { this.logDirPath = logDirPath; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getContextProperty(String key, String defaultValue) { return preferences.get(key, defaultValue); } public String getOcsswDebugInfo(){ return preferences.get(SEADAS_OCSSW_DEBUG, SEADAS_OCSSW_DEBUG_DEFAULT_VALUE); } public String getRemoteSeaDASInfo() { return remoteSeaDASInfo; } public void setRemoteSeaDASInfo(String remoteSeaDASInfo) { this.remoteSeaDASInfo = remoteSeaDASInfo; } }
17,184
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSWVM.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ocssw/OCSSWVM.java
package gov.nasa.gsfc.seadas.processing.ocssw; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import gov.nasa.gsfc.seadas.processing.common.SeadasFileUtils; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import gov.nasa.gsfc.seadas.processing.utilities.FileCompare; import org.esa.snap.rcp.SnapApp; import javax.json.JsonObject; import javax.ws.rs.core.MediaType; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; /** * Created by aabduraz on 3/27/17. */ public class OCSSWVM extends OCSSWRemote { public final static String OCSSW_VM_SERVER_SHARED_DIR_PROPERTY = "seadas.ocssw.sharedDir"; public final static String OCSSW_VM_SERVER_SHARED_DIR_PROPERTY_DEFAULT_VALUE = System.getProperty("user.home") + File.separator + "ocsswVMServerSharedDir"; String workingDir; public OCSSWVM() { super(); workingDir = ocsswInfo.getContextProperty(OCSSW_VM_SERVER_SHARED_DIR_PROPERTY, OCSSW_VM_SERVER_SHARED_DIR_PROPERTY_DEFAULT_VALUE); } /** * This method copies the client file into the shared directory between the host and the virtual machine. * The shared directory is specified in the seadas.config file. * * @param sourceFilePathName * @return */ @Override public boolean uploadClientFile(String sourceFilePathName) { ifileUploadSuccess = false; if (!isAncFile(sourceFilePathName) && !fileExistsOnServer(sourceFilePathName)) { if (needToUplaodFileContent(programName, sourceFilePathName)) { uploadListedFiles(null, sourceFilePathName); updateFileListFileContent(sourceFilePathName); } copyFileC2S(sourceFilePathName); } ifileUploadSuccess = true; return ifileUploadSuccess; } /** * This method uploads list of files provided in the text file. * * @param fileName is the name of the text file that contains list of input files. * @return true if all files uploaded successfully. */ @Override public String uploadListedFiles(ProgressMonitor pm, String fileName) { File file = new File(fileName); StringBuilder sb = new StringBuilder(); Scanner input = null; try { input = new Scanner(file); } catch (FileNotFoundException e) { e.printStackTrace(); } String nextFileName; boolean fileUploadSuccess = true; while (input.hasNext()) { nextFileName = input.nextLine(); if (!fileExistsOnServer(nextFileName)) { copyFileC2S(nextFileName); } } String fileNames = sb.toString(); input.close(); if (fileUploadSuccess) { return fileNames; } else { return null; } } @Override public void updateFileListFileContent(String fileListFileName) { StringBuilder stringBuilder = new StringBuilder(); try { List<String> lines = Files.readAllLines(Paths.get(fileListFileName), StandardCharsets.UTF_8); Iterator<String> itr = lines.iterator(); String fileName; while (itr.hasNext()) { fileName = itr.next(); if (fileName.trim().length() > 0) { //System.out.println("file name in the file list: " + fileName); fileName = workingDir + File.separator + fileName.substring(fileName.lastIndexOf(File.separator) + 1); stringBuilder.append(fileName + "\n"); } } String fileContent = stringBuilder.toString(); //System.out.println(fileContent); SeadasFileUtils.writeStringToFile(fileContent, fileListFileName); } catch (IOException ioe) { ioe.printStackTrace(); } } private void copyFileC2S(String sourceFilePathName) { String targetFilePathName = workingDir + File.separator + sourceFilePathName.substring(sourceFilePathName.lastIndexOf(File.separator) + 1); try { //SeadasFileUtils.copyFile(sourceFilePathName, targetFilePathName); SeadasFileUtils.cloFileCopy(sourceFilePathName, targetFilePathName); ifileUploadSuccess = true; } catch (Exception e) { e.printStackTrace(); } } @Override public boolean fileExistsOnServer(String fileName) { String sourceFileDir = fileName.substring(0, fileName.lastIndexOf(File.separator)); String fileNameOnServer = workingDir + File.separator + fileName.substring(fileName.lastIndexOf(File.separator) + 1); if (sourceFileDir.equals(workingDir) || new File(fileNameOnServer).exists()) { ifileUploadSuccess = true; return true; } else { return false; } } private boolean compareFileContents(String file1Path, String file2Path) { String file1HashValue; String file2HashValue; boolean isTwoEqual = false; try { //System.out.println("two file is equal: " + isTwoEqual); file1HashValue = FileCompare.MD5HashFile(file1Path); file2HashValue = FileCompare.MD5HashFile(file2Path); isTwoEqual = file1HashValue.equals(file2HashValue); } catch (Exception ioe) { //System.out.println("exception in comparing two files"); ioe.printStackTrace(); } return isTwoEqual; } private void copyFileS2C(String fileName) { String sourceFilePathName = workingDir + File.separator + fileName.substring(fileName.lastIndexOf(File.separator) + 1); try { SeadasFileUtils.cloFileCopy(sourceFilePathName, fileName); } catch (Exception e) { e.printStackTrace(); } } private void copyMLPFiles(String sourceFilePath) { File sourceFile = new File(sourceFilePath); String targetFilePathName = workingDir + File.separator + sourceFilePath.substring(sourceFilePath.lastIndexOf(File.separator) + 1); File targetFile = new File(targetFilePathName); targetFile.getParentFile().mkdirs(); try { SeadasFileUtils.copyFileUsingStream(sourceFile, targetFile); } catch (IOException e) { e.printStackTrace(); } } private void copyFileFromServerToClient(String sourceFilePathName, String targetFilePathName) { File sourceFile = new File(sourceFilePathName); File targetFile = new File(targetFilePathName); targetFile.getParentFile().mkdirs(); try { SeadasFileUtils.copyFileUsingStream(sourceFile, targetFile); } catch (IOException e) { e.printStackTrace(); } } @Override public void getOutputFiles(String outputFileNames) { SnapApp snapApp = SnapApp.getDefault(); ProgressMonitorSwingWorker pmSwingWorker = new ProgressMonitorSwingWorker(snapApp.getMainFrame(), "OCSSW Remote Server File Download") { @Override protected Void doInBackground(ProgressMonitor pm) throws Exception { JsonObject commandArrayJsonObject = null; StringTokenizer st = new StringTokenizer(outputFileNames, "\n"); String fileName; while (st.hasMoreTokens()) { fileName = st.nextToken(); copyFileS2C(fileName); } return null; } }; pmSwingWorker.execute(); } @Override public boolean downloadCommonFiles(JsonObject paramJsonObject) { Set commandArrayKeys = paramJsonObject.keySet(); String param; String ofileFullPathName, ofileName; try { Object[] array = (Object[]) commandArrayKeys.toArray(); int i = 0; String[] commandArray = new String[commandArrayKeys.size() + 1]; commandArray[i++] = programName; for (Object element : array) { String elementName = (String) element; param = paramJsonObject.getString((String) element); if (elementName.contains("OFILE")) { if (param.indexOf("=") != -1) { StringTokenizer st = new StringTokenizer(param, "="); String paramName = st.nextToken(); String paramValue = st.nextToken(); ofileFullPathName = paramValue; } else { ofileFullPathName = param; } ofileName = ofileFullPathName.substring(ofileFullPathName.lastIndexOf(File.separator) + 1); if (!workingDir.equals(ofileDir)) { String sourceFilePathName = workingDir + File.separator + ofileName; String targetFilePathName = ofileDir + File.separator + ofileName; SeadasFileUtils.cloFileCopy(sourceFilePathName, targetFilePathName); } } } return true; } catch (Exception e) { e.printStackTrace(); return false; } } @Override protected void downloadMLPOutputFiles(ProcessorModel processorModel) { String mlpWorkingDir = workingDir + File.separator + MLP_OUTPUT_DIR_NAME; String mlpOdir = processorModel.getParamValue(MLP_PAR_FILE_ODIR_KEY_NAME); final String ofileDir = isMLPOdirValid(mlpOdir) ? mlpOdir : ifileDir; if (!mlpWorkingDir.equals(ofileDir)) { SnapApp snapApp = SnapApp.getDefault(); ProgressMonitorSwingWorker pmSwingWorker = new ProgressMonitorSwingWorker(snapApp.getMainFrame(), "OCSSW Remote Server File Upload") { @Override protected Void doInBackground(ProgressMonitor pm) throws Exception { JsonObject mlpOfilesJsonObject = target.path("fileServices").path("getMLPOutputFilesList").path(jobId).request(MediaType.APPLICATION_JSON_TYPE).get(JsonObject.class); Set fileSetKeys = mlpOfilesJsonObject.keySet(); Object[] fileArray = (Object[]) fileSetKeys.toArray(); pm.beginTask("Copying output files from the shared folder " + workingDir + " to " + ofileDir, fileArray.length); pm.worked(1); String ofileName, ofileFullPathName; int numberOfTasksWorked = 1; String sourceFilePathName, targetFilePathName; for (Object fileNameKey : fileArray) { ofileName = mlpOfilesJsonObject.getString((String) fileNameKey); pm.setSubTaskName("Copying file '" + ofileName + " to " + ofileDir); sourceFilePathName = mlpWorkingDir + File.separator + ofileName; targetFilePathName = ofileDir + File.separator + ofileName; SeadasFileUtils.cloFileCopy(sourceFilePathName, targetFilePathName); pm.worked(numberOfTasksWorked++); } return null; } }; pmSwingWorker.executeWithBlocking(); } } }
11,629
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
package-info.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/docs/package-info.java
@HelpSetRegistration(helpSet = "help.hs", position = 4410) package gov.nasa.gsfc.seadas.processing.docs; import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration;
168
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L2BrsGenAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/L2BrsGenAction.java
//package gov.nasa.gsfc.seadas.processing.ui; // //import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; //import org.esa.snap.core.datamodel.ProductNode; //import org.openide.awt.ActionID; //import org.openide.awt.ActionReference; //import org.openide.awt.ActionRegistration; //import org.openide.util.*; // //import javax.swing.*; // ///** // * @author Aynur Abdurazik // * @since SeaDAS 8.0 // * @see // */ //@ActionID( // category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L2BrsGenAction" //) //@ActionRegistration( // displayName = "#CTL_ L2BrsGenAction_Name", // popupText = "#CTL_ L2BrsGenAction_Name" //) //@ActionReference( // path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/Tools", // position = 410 //) //@NbBundle.Messages({ // "CTL_L2BrsGenAction_Name=l2brsgen...", // "CTL_L2BrsGenAction_ProgramName=l2brsgen", // "CTL_L2BrsGenAction_DialogTitle=l2brsgen", // "CTL_L2BrsGenAction_XMLFileName=l2brsgen.xml", // "CTL_L2BrsGenAction_Description=Creates a Level 2 Browse file" //}) // //public class L2BrsGenAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { // // private final Lookup lkp; // // public L2BrsGenAction() { // this(Utilities.actionsGlobalContext()); // } // // public L2BrsGenAction(Lookup lkp) { // this.lkp = lkp; // Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); // lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); // putValue(Action.NAME, Bundle.CTL_L2BrsGenAction_Name()); // putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L2BrsGenAction_Description()); // setProgramName(Bundle.CTL_L2BrsGenAction_ProgramName()); // setDialogTitle(Bundle.CTL_L2BrsGenAction_DialogTitle()); // setXmlFileName(Bundle.CTL_L2BrsGenAction_XMLFileName()); // } //// //// @Override //// public void actionPerformed(ActionEvent e) { //// //// } // // @Override // public void resultChanged(LookupEvent lookupEvent) { // // } // // @Override // public Action createContextAwareInstance(Lookup actionContext) { // return new L2BrsGenAction(actionContext); // } //}
2,286
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
GeoLocateVIIRSAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/GeoLocateVIIRSAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.GeoLocateVIIRSAction" ) @ActionRegistration( displayName = "#CTL_ GeoLocateVIIRSAction_Name", popupText = "#CTL_ GeoLocateVIIRSAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/VIIRS", position = 60 ) @NbBundle.Messages({ "CTL_GeoLocateVIIRSAction_Name=geolocate_viirs...", "CTL_GeoLocateVIIRSAction_ProgramName=geolocate_viirs", "CTL_GeoLocateVIIRSAction_DialogTitle=geolocate_viirs", "CTL_GeoLocateVIIRSAction_XMLFileName=geolocate_viirs.xml", "CTL_GeoLocateVIIRSAction_Description=Creates a VIIRS GEO file from a VIIRS L1A input file" }) public class GeoLocateVIIRSAction extends CallCloProgramAction implements ContextAwareAction, LookupListener{ private final Lookup lkp; public GeoLocateVIIRSAction() { this(Utilities.actionsGlobalContext()); } public GeoLocateVIIRSAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<OCSSWInfo> lkpContext = lkp.lookupResult(OCSSWInfo.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_GeoLocateVIIRSAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_GeoLocateVIIRSAction_Description()); setProgramName(Bundle.CTL_GeoLocateVIIRSAction_ProgramName()); setDialogTitle(Bundle.CTL_GeoLocateVIIRSAction_DialogTitle()); setXmlFileName(Bundle.CTL_GeoLocateVIIRSAction_XMLFileName()); //setEnableState(); } @Override public void resultChanged(LookupEvent lookupEvent) { //setEnableState(); } public void setEnableState() { boolean state = false; // OCSSWInfo ocsswInfo = lkp.lookup(OCSSWInfo.class); if (ocsswInfo != null) { state = ocsswInfo.isOCSSWExist(); } setEnabled(state); } @Override public Action createContextAwareInstance(Lookup actionContext) { return new GeoLocateVIIRSAction(actionContext); } }
2,527
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSWConfigAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/OCSSWConfigAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfoGUI; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.rcp.actions.AbstractSnapAction; import org.esa.snap.ui.AppContext; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import org.openide.util.actions.Presenter; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.OCSSWConfigAction" ) @ActionRegistration( displayName = "#CTL_OCSSWConfigAction_Name", popupText = "#CTL_OCSSWConfigAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox", position = 1101, separatorBefore = 1100 ) @NbBundle.Messages({ "CTL_OCSSWConfigAction_Name=SeaDAS Processor Location...", "CTL_OCSSWConfigAction_DialogTitle=Configure SeaDAS Processor Location (OCSSW)", "CTL_OCSSWConfigAction_Description= Set values for seadas.config properties (variables)." }) public class OCSSWConfigAction extends AbstractSnapAction implements ContextAwareAction, LookupListener, Presenter.Menu { private final Lookup lkp; public OCSSWConfigAction() { this(Utilities.actionsGlobalContext()); } public OCSSWConfigAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_OCSSWConfigAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_OCSSWConfigAction_Description()); } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new OCSSWConfigAction(actionContext); } @Override public void actionPerformed(ActionEvent e) { final AppContext appContext = getAppContext(); final Window parent = appContext.getApplicationWindow(); OCSSWInfoGUI ocsswInfoGUI = new OCSSWInfoGUI(); ocsswInfoGUI.init(parent); } @Override public JMenuItem getMenuPresenter() { JMenuItem menuItem = new JMenuItem(this); menuItem.setIcon(null); menuItem.setName((String) getValue(Action.NAME)); menuItem.setToolTipText((String) getValue(Action.SHORT_DESCRIPTION)); return menuItem; } }
2,598
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L1BGenAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/L1BGenAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L1BGenAction" ) @ActionRegistration( displayName = "#CTL_L1BGenAction_Name", popupText = "#CTL_L1BGenAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors", position = 80 ) @NbBundle.Messages({ "CTL_L1BGenAction_Name=l1bgen_generic...", "CTL_L1BGenAction_ProgramName=l1bgen_generic", "CTL_L1BGenAction_DialogTitle=l1bgen_generic", "CTL_L1BGenAction_XMLFileName=l1bgen_generic.xml", "CTL_L1BGenAction_Description=Creates a Level 1B file from an input Level 1A file" }) public class L1BGenAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public L1BGenAction() { this(Utilities.actionsGlobalContext()); } public L1BGenAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_L1BGenAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L1BGenAction_Description()); setProgramName(Bundle.CTL_L1BGenAction_ProgramName()); setDialogTitle(Bundle.CTL_L1BGenAction_DialogTitle()); setXmlFileName(Bundle.CTL_L1BGenAction_XMLFileName()); } // // @Override // public void actionPerformed(ActionEvent e) { // // } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new L1BGenAction(actionContext); } }
2,152
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
UpdateLutsAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/UpdateLutsAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.UpdateLutsAction" ) @ActionRegistration( displayName = "#CTL_UpdateLutsAction_Name", popupText = "#CTL_UpdateLutsAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox", position = 1200 ) @NbBundle.Messages({ "CTL_UpdateLutsAction_Name=Update LUTs...", "CTL_UpdateLutsAction_ProgramName=update_luts", "CTL_UpdateLutsAction_DialogTitle=update_luts", "CTL_UpdateLutsAction_XMLFileName=update_luts.xml", "CTL_UpdateLutsAction_Description=Retrieve latest lookup tables for specified sensor." }) public class UpdateLutsAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public static final String HELP_ID = "update_luts"; private HelpCtx helpCtx; public UpdateLutsAction() { this(Utilities.actionsGlobalContext()); helpCtx = new HelpCtx(HELP_ID); } public UpdateLutsAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_UpdateLutsAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_UpdateLutsAction_Description()); setProgramName(Bundle.CTL_UpdateLutsAction_ProgramName()); setDialogTitle(Bundle.CTL_UpdateLutsAction_DialogTitle()); setXmlFileName(Bundle.CTL_UpdateLutsAction_XMLFileName()); } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new UpdateLutsAction(actionContext); } }
2,234
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L3BinMergeAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/L3BinMergeAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Daniel Knowles * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L3BinMergeAction" ) @ActionRegistration( displayName = "#CTL_L3BinMergeAction_Name", popupText = "#CTL_L3BinMergeAction_Description" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/Tools", position = 150 ) @NbBundle.Messages({ "CTL_L3BinMergeAction_Name=l3binmerge...", "CTL_L3BinMergeAction_ProgramName=l3binmerge", "CTL_L3BinMergeAction_DialogTitle=l3binmerge", "CTL_L3BinMergeAction_XMLFileName=l3binmerge.xml", "CTL_L3BinMergeAction_Description=Merges multiple input L3 binned files into a single L3 binned output file" }) public class L3BinMergeAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public L3BinMergeAction() { this(Utilities.actionsGlobalContext()); } public L3BinMergeAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_L3BinMergeAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L3BinMergeAction_Description()); setProgramName(Bundle.CTL_L3BinMergeAction_ProgramName()); setDialogTitle(Bundle.CTL_L3BinMergeAction_DialogTitle()); setXmlFileName(Bundle.CTL_L3BinMergeAction_XMLFileName()); } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new L3BinMergeAction(actionContext); } }
2,155
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
CalibrateVIIRSAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/CalibrateVIIRSAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.CalibrateVIIRSAction" ) @ActionRegistration( displayName = "#CTL_ CalibrateVIIRSAction_Name", popupText = "#CTL_ CalibrateVIIRSAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/VIIRS", position = 70 ) @NbBundle.Messages({ "CTL_CalibrateVIIRSAction_Name=calibrate_viirs...", "CTL_CalibrateVIIRSAction_ProgramName=calibrate_viirs", "CTL_CalibrateVIIRSAction_DialogTitle=calibrate_viirs", "CTL_CalibrateVIIRSAction_XMLFileName=calibrate_viirs.xml", "CTL_CalibrateVIIRSAction_Description=Creates a VIIRS L1B file from a VIIRS L1A input file" }) public class CalibrateVIIRSAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private static final String OPERATOR_ALIAS = "CalibrateVIIRS"; private static final String HELP_ID = "calibrate_viirs"; private final Lookup lkp; public CalibrateVIIRSAction() { this(Utilities.actionsGlobalContext()); } public CalibrateVIIRSAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<OCSSWInfo> lkpContext = lkp.lookupResult(OCSSWInfo.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_CalibrateVIIRSAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_CalibrateVIIRSAction_Description()); setProgramName(Bundle.CTL_CalibrateVIIRSAction_ProgramName()); setDialogTitle(Bundle.CTL_CalibrateVIIRSAction_DialogTitle()); setXmlFileName(Bundle.CTL_CalibrateVIIRSAction_XMLFileName()); } @Override public void resultChanged(LookupEvent lookupEvent) { setEnabled(true); } @Override public Action createContextAwareInstance(Lookup actionContext) { return new CalibrateVIIRSAction(actionContext); } }
2,382
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
MapGenAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/MapGenAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.MapGenAction" ) @ActionRegistration( displayName = "#CTL_ MapGenAction_Name", popupText = "#CTL_ MapGenAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors", position = 351, separatorBefore = 350 ) @NbBundle.Messages({ "CTL_MapGenAction_Name=mapgen...", "CTL_MapGenAction_ProgramName=mapgen", "CTL_MapGenAction_DialogTitle=mapgen", "CTL_MapGenAction_XMLFileName=mapgen.xml", "CTL_MapGenAction_Description=Create a mapped file from various choices of input file levels" }) public class MapGenAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public MapGenAction() { this(Utilities.actionsGlobalContext()); } public MapGenAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_MapGenAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_MapGenAction_Description()); setProgramName(Bundle.CTL_MapGenAction_ProgramName()); setDialogTitle(Bundle.CTL_MapGenAction_DialogTitle()); setXmlFileName(Bundle.CTL_MapGenAction_XMLFileName()); } // // @Override // public void actionPerformed(ActionEvent e) { // // } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new MapGenAction(actionContext); } }
2,163
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L3BinDumpAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/L3BinDumpAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallL3BinDumpAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L3BinDumpAction" ) @ActionRegistration( displayName = "#CTL_ L3BinDumpAction_Name", popupText = "#CTL_ L3BinDumpAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/Tools", position = 451 // separatorBefore = 450 ) @NbBundle.Messages({ "CTL_L3BinDumpAction_Name=l3bindump...", "CTL_L3BinDumpAction_ProgramName=l3bindump", "CTL_L3BinDumpAction_DialogTitle=l3bindump", "CTL_L3BinDumpAction_XMLFileName=l3bindump.xml", "CTL_L3BinDumpAction_Description=Creates a text file dump of a L3 binned file" }) public class L3BinDumpAction extends CallL3BinDumpAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public L3BinDumpAction() { this(Utilities.actionsGlobalContext()); } public L3BinDumpAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_L3BinDumpAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L3BinDumpAction_Description()); setProgramName(Bundle.CTL_L3BinDumpAction_ProgramName()); setDialogTitle(Bundle.CTL_L3BinDumpAction_DialogTitle()); setXmlFileName(Bundle.CTL_L3BinDumpAction_XMLFileName()); } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new L3BinDumpAction(actionContext); } }
2,131
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
GetSysInfoAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/GetSysInfoAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.ocssw.GetSysInfoGUI; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.rcp.actions.AbstractSnapAction; import org.esa.snap.ui.AppContext; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import org.openide.util.actions.Presenter; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; /** * @author Bing Yang * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.GetSysInfoAction" ) @ActionRegistration( displayName = "#CTL_GetSysInfoAction_Name", popupText = "#CTL_GetSysInfoAction_Description" ) @ActionReference( path = "Menu/SeaDAS-Toolbox", position = 1500, separatorAfter = 1501) @NbBundle.Messages({ "CTL_GetSysInfoAction_Name=Software & System Info...", "CTL_GetSysInfoAction_DialogTitle=Software & System Information", "CTL_GetSysInfoAction_Description=Print SeaDAS and system info for trouble shooting." }) public class GetSysInfoAction extends AbstractSnapAction implements ContextAwareAction, LookupListener, Presenter.Menu { private final Lookup lkp; public GetSysInfoAction() { this(Utilities.actionsGlobalContext()); } public GetSysInfoAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_GetSysInfoAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_GetSysInfoAction_Description()); } // // @Override // public void actionPerformed(ActionEvent e) { // // } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new GetSysInfoAction(actionContext); } @Override public void actionPerformed(ActionEvent e) { final AppContext appContext = getAppContext(); final Window parent = appContext.getApplicationWindow(); GetSysInfoGUI getSysInfoGUI = new GetSysInfoGUI(); getSysInfoGUI.init(parent); } @Override public JMenuItem getMenuPresenter() { JMenuItem menuItem = new JMenuItem(this); menuItem.setIcon(null); menuItem.setName((String) getValue(Action.NAME)); menuItem.setToolTipText((String) getValue(Action.SHORT_DESCRIPTION)); return menuItem; } }
2,712
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
GeoLocateHAWKEYEAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/GeoLocateHAWKEYEAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.GeoLocateHAWKEYEAction" ) @ActionRegistration( displayName = "#CTL_ GeoLocateHAWKEYEAction_Name", popupText = "#CTL_ GeoLocateHAWKEYEAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/HawkEye", position = 60 ) @NbBundle.Messages({ "CTL_GeoLocateHAWKEYEAction_Name=geolocate_hawkeye...", "CTL_GeoLocateHAWKEYEAction_ProgramName=geolocate_hawkeye", "CTL_GeoLocateHAWKEYEAction_DialogTitle=geolocate_hawkeye", "CTL_GeoLocateHAWKEYEAction_XMLFileName=geolocate_hawkeye.xml", "CTL_GeoLocateHAWKEYEAction_Description=Creates a HawkEye GEO file from a HawkEye L1A input file" }) public class GeoLocateHAWKEYEAction extends CallCloProgramAction implements ContextAwareAction, LookupListener{ private final Lookup lkp; public GeoLocateHAWKEYEAction() { this(Utilities.actionsGlobalContext()); } public GeoLocateHAWKEYEAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<OCSSWInfo> lkpContext = lkp.lookupResult(OCSSWInfo.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_GeoLocateHAWKEYEAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_GeoLocateHAWKEYEAction_Description()); setProgramName(Bundle.CTL_GeoLocateHAWKEYEAction_ProgramName()); setDialogTitle(Bundle.CTL_GeoLocateHAWKEYEAction_DialogTitle()); setXmlFileName(Bundle.CTL_GeoLocateHAWKEYEAction_XMLFileName()); //setEnableState(); } @Override public void resultChanged(LookupEvent lookupEvent) { //setEnableState(); } public void setEnableState() { boolean state = false; // OCSSWInfo ocsswInfo = lkp.lookup(OCSSWInfo.class); if (ocsswInfo != null) { state = ocsswInfo.isOCSSWExist(); } setEnabled(state); } @Override public Action createContextAwareInstance(Lookup actionContext) { return new GeoLocateHAWKEYEAction(actionContext); } }
2,575
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L3BinAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/L3BinAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L3BinAction" ) @ActionRegistration( displayName = "#CTL_ L3BinAction_Name", popupText = "#CTL_ L3BinAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors", position = 170 ) @NbBundle.Messages({ "CTL_L3BinAction_Name=l3bin...", "CTL_L3BinAction_ProgramName=l3bin", "CTL_L3BinAction_DialogTitle=l3bin", "CTL_L3BinAction_XMLFileName=l3bin.xml", "CTL_L3BinAction_Description=Create a L3 bin file from L3 input file(s)." }) public class L3BinAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; private HelpCtx helpCtx; public L3BinAction() { this(Utilities.actionsGlobalContext()); helpCtx = new HelpCtx(getProgramName()); } public L3BinAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_L3BinAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L3BinAction_Description()); setProgramName(Bundle.CTL_L3BinAction_ProgramName()); setDialogTitle(Bundle.CTL_L3BinAction_DialogTitle()); setXmlFileName(Bundle.CTL_L3BinAction_XMLFileName()); setHelpId(getProgramName()); } // // @Override // public void actionPerformed(ActionEvent e) { // // } @Override public HelpCtx getHelpCtx() { return helpCtx; } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new L3BinAction(actionContext); } }
2,290
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
GeoRegionGenAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/GeoRegionGenAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Daniel Knowles * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.GeoRegionGenAction" ) @ActionRegistration( displayName = "#CTL_GeoRegionGenAction_Name", popupText = "#CTL_GeoRegionGenAction_Description" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/Tools", position = 150 ) @NbBundle.Messages({ "CTL_GeoRegionGenAction_Name=georegion_gen...", "CTL_GeoRegionGenAction_ProgramName=georegion_gen", "CTL_GeoRegionGenAction_DialogTitle=georegion_gen", "CTL_GeoRegionGenAction_XMLFileName=georegion_gen.xml", "CTL_GeoRegionGenAction_Description=Generates a mask file from input WKT or Shapefiles" }) public class GeoRegionGenAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public GeoRegionGenAction() { this(Utilities.actionsGlobalContext()); } public GeoRegionGenAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_GeoRegionGenAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_GeoRegionGenAction_Description()); setProgramName(Bundle.CTL_GeoRegionGenAction_ProgramName()); setDialogTitle(Bundle.CTL_GeoRegionGenAction_DialogTitle()); setXmlFileName(Bundle.CTL_GeoRegionGenAction_XMLFileName()); } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new GeoRegionGenAction(actionContext); } }
2,178
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L3MapGenAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/L3MapGenAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L3MapGenAction" ) @ActionRegistration( displayName = "#CTL_ L3MapGenAction_Name", popupText = "#CTL_ L3MapGenAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors", position = 360) @NbBundle.Messages({ "CTL_L3MapGenAction_Name=l3mapgen...", "CTL_L3MapGenAction_ProgramName=l3mapgen", "CTL_L3MapGenAction_DialogTitle=l3mapgen", "CTL_L3MapGenAction_XMLFileName=l3mapgen.xml", "CTL_L3MapGenAction_Description=Creates a L3 mapped file from an input L3 bin file" }) public class L3MapGenAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public L3MapGenAction() { this(Utilities.actionsGlobalContext()); } public L3MapGenAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_L3MapGenAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L3MapGenAction_Description()); setProgramName(Bundle.CTL_L3MapGenAction_ProgramName()); setDialogTitle(Bundle.CTL_L3MapGenAction_DialogTitle()); setXmlFileName(Bundle.CTL_L3MapGenAction_XMLFileName()); } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new L3MapGenAction(actionContext); } }
2,083
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/ui/L2GenAquariusAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.l2gen.userInterface.L2genAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L2GenAquariusAction" ) @ActionRegistration( displayName = "#CTL_ L2GenAquariusAction_Name", popupText = "#CTL_ L2GenAquariusAction_Name" ) //@ActionReference( // path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/Aquarius", // position = 120 //) @NbBundle.Messages({ "CTL_L2GenAquariusAction_Name=l2gen_aquarius...", "CTL_L2GenAquariusAction_ProgramName=l2gen_aquarius", "CTL_L2GenAquariusAction_DialogTitle=l2gen_aquarius", "CTL_L2GenAquariusAction_XMLFileName=l2gen_aquarius.xml", "CTL_L2GenAquariusAction_Description=Creates a L2 file from an input Aquarius L1 file" }) public class L2GenAquariusAction extends L2genAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public L2GenAquariusAction() { this(Utilities.actionsGlobalContext()); } public L2GenAquariusAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_L2GenAquariusAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L2GenAquariusAction_Description()); setProgramName(Bundle.CTL_L2GenAquariusAction_ProgramName()); setDialogTitle(Bundle.CTL_L2GenAquariusAction_DialogTitle()); setXmlFileName(Bundle.CTL_L2GenAquariusAction_XMLFileName()); } // // @Override // public void actionPerformed(ActionEvent e) { // // } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new L2GenAquariusAction(actionContext); } }
2,282
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L2GenSnapAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/L2GenSnapAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.l2gen.userInterface.L2genAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ // @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L2GenSnapAction" ) @ActionRegistration( displayName = "#CTL_ L2GenAction_Name", popupText = "#CTL_ L2GenAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors", position = 111, separatorBefore = 110 ) @NbBundle.Messages({ "CTL_L2GenAction_Name=l2gen...", "CTL_L2GenAction_ProgramName=l2gen", "CTL_L2GenAction_DialogTitle=l2gen", "CTL_L2GenAction_XMLFileName=l2gen.xml", "CTL_L2GenAction_Description=Creates a L2 file from an input L1 file (and input GEO file depending on mission)" }) public class L2GenSnapAction extends L2genAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public L2GenSnapAction() { this(Utilities.actionsGlobalContext()); } /** * * @param lkp */ public L2GenSnapAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_L2GenAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L2GenAction_Description()); setProgramName(Bundle.CTL_L2GenAction_ProgramName()); setDialogTitle(Bundle.CTL_L2GenAction_DialogTitle()); setXmlFileName(Bundle.CTL_L2GenAction_XMLFileName()); } /** * @param lookupEvent * @ */ @Override public void resultChanged(LookupEvent lookupEvent) { } /** * * @param actionContext * @return */ @Override public Action createContextAwareInstance(Lookup actionContext) { return new L2GenSnapAction(actionContext); } }
2,253
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
ModisL1AAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/ModisL1AAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @see * @since SeaDAS 8.0 */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.ModisL1AAction" ) @ActionRegistration( displayName = "#CTL_ModisL1AAction_Name", popupText = "#CTL_ModisL1AAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/MODIS", position = 30 ) @NbBundle.Messages({ "CTL_ModisL1AAction_Name=modis_L1A...", "CTL_ModisL1AAction_ProgramName=modis_L1A", "CTL_ModisL1AAction_DialogTitle=modis_L1A", "CTL_ModisL1AAction_XMLFileName=modis_L1A.xml", "CTL_ModisL1AAction_Description=Creates a MODIS L1A file from a MODIS L0 input file" }) public class ModisL1AAction extends CallCloProgramAction implements LookupListener { private final Lookup lkp; private HelpCtx helpCtx; public ModisL1AAction() { this(Utilities.actionsGlobalContext()); helpCtx = new HelpCtx(getProgramName()); } public ModisL1AAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_ModisL1AAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_ModisL1AAction_Description()); setProgramName(Bundle.CTL_ModisL1AAction_ProgramName()); setDialogTitle(Bundle.CTL_ModisL1AAction_DialogTitle()); setXmlFileName(Bundle.CTL_ModisL1AAction_XMLFileName()); setHelpId(getProgramName()); } // // @Override // public void actionPerformed(ActionEvent e) { // // } @Override public HelpCtx getHelpCtx() { return helpCtx; } @Override public void resultChanged(LookupEvent lookupEvent) { } // // @Override // /** // * for ContextAwareAction interface // */ // public Action createContextAwareInstance(Lookup actionContext) { // return new ModisL1AAction(actionContext); // } }
2,417
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
ExtractorAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/ExtractorAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import gov.nasa.gsfc.seadas.processing.ocssw.OCSSWInfo; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.ExtractorAction" ) @ActionRegistration( displayName = "#CTL_ ExtractorAction_Name", popupText = "#CTL_ ExtractorAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors", position = 10, separatorAfter = 11) @NbBundle.Messages({ "CTL_ExtractorAction_Name=extractors...", "CTL_ExtractorAction_ProgramName=extractor", "CTL_ExtractorAction_DialogTitle=extractor", "CTL_ExtractorAction_XMLFileName=extractor.xml", "CTL_ExtractorAction_Description=Creates L1 extract from L1 input file or creates L2 extract from L2 input file" }) public class ExtractorAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public ExtractorAction() { this(Utilities.actionsGlobalContext()); } public ExtractorAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<OCSSWInfo> lkpContext = lkp.lookupResult(OCSSWInfo.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_ExtractorAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_ExtractorAction_Description()); setProgramName(Bundle.CTL_ExtractorAction_ProgramName()); setDialogTitle(Bundle.CTL_ExtractorAction_DialogTitle()); setXmlFileName(Bundle.CTL_ExtractorAction_XMLFileName()); //setEnableState(); } @Override public void resultChanged(LookupEvent lookupEvent) { //setEnableState(); } public void setEnableState() { boolean state = false; // OCSSWInfo ocsswInfo = lkp.lookup(OCSSWInfo.class); if (ocsswInfo != null) { state = ocsswInfo.isOCSSWExist(); } setEnabled(state); } @Override public Action createContextAwareInstance(Lookup actionContext) { return new ExtractorAction(actionContext); } }
2,467
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L2MapGenAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/L2MapGenAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L2MapGenAction" ) @ActionRegistration( displayName = "#CTL_ L2MapGenAction_Name", popupText = "#CTL_ L2MapGenAction_Name" ) //@ActionReference( // path = "Menu/SeaDAS-OCSSW", // position = 140 //) @NbBundle.Messages({ "CTL_L2MapGenAction_Name=l2mapgen...", "CTL_L2MapGenAction_ProgramName=l2mapgen", "CTL_L2MapGenAction_DialogTitle=l2mapgen", "CTL_L2MapGenAction_XMLFileName=l2mapgen.xml", "CTL_L2MapGenAction_Description=Process MODIS L0 to L1A." }) public class L2MapGenAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public L2MapGenAction() { this(Utilities.actionsGlobalContext()); } public L2MapGenAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_L2MapGenAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L2MapGenAction_Description()); setProgramName(Bundle.CTL_L2MapGenAction_ProgramName()); setDialogTitle(Bundle.CTL_L2MapGenAction_DialogTitle()); setXmlFileName(Bundle.CTL_L2MapGenAction_XMLFileName()); } // // @Override // public void actionPerformed(ActionEvent e) { // // } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new L2MapGenAction(actionContext); } }
2,123
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L2BinAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/L2BinAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L2BinAction" ) @ActionRegistration( displayName = "#CTL_ L2BinAction_Name", popupText = "#CTL_ L2BinAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors", position = 150 ) @NbBundle.Messages({ "CTL_L2BinAction_Name=l2bin...", "CTL_L2BinAction_ProgramName=l2bin", "CTL_L2BinAction_DialogTitle=l2bin", "CTL_L2BinAction_XMLFileName=l2bin.xml", "CTL_L2BinAction_Description=Creates a L3 bin file from input L2 file(s)" }) public class L2BinAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public L2BinAction() { this(Utilities.actionsGlobalContext()); } public L2BinAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_L2BinAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L2BinAction_Description()); setProgramName(Bundle.CTL_L2BinAction_ProgramName()); setDialogTitle(Bundle.CTL_L2BinAction_DialogTitle()); setXmlFileName(Bundle.CTL_L2BinAction_XMLFileName()); } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new L2BinAction(actionContext); } }
2,013
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L2BinAquariusAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/L2BinAquariusAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L2BinAquariusAction" ) @ActionRegistration( displayName = "#CTL_ L2BinAquariusAction_Name", popupText = "#CTL_ L2BinAquariusAction_Name" ) //@ActionReference( // path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/Aquarius", // position = 160 //) @NbBundle.Messages({ "CTL_L2BinAquariusAction_Name=l2bin_aquarius...", "CTL_L2BinAquariusAction_ProgramName=l2bin_aquarius", "CTL_L2BinAquariusAction_DialogTitle=l2bin_aquarius", "CTL_L2BinAquariusAction_XMLFileName=l2bin_aquarius.xml", "CTL_L2BinAquariusAction_Description=Create a L3 bin file from input Aquarius L2 file(s)." }) public class L2BinAquariusAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public L2BinAquariusAction() { this(Utilities.actionsGlobalContext()); } public L2BinAquariusAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_L2BinAquariusAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L2BinAquariusAction_Description()); setProgramName(Bundle.CTL_L2BinAquariusAction_ProgramName()); setDialogTitle(Bundle.CTL_L2BinAquariusAction_DialogTitle()); setXmlFileName(Bundle.CTL_L2BinAquariusAction_XMLFileName()); } // // @Override // public void actionPerformed(ActionEvent e) { // // } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new L2BinAquariusAction(actionContext); } }
2,293
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L1MapGenAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/L1MapGenAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L1MapGenAction" ) @ActionRegistration( displayName = "#CTL_ L1MapGenAction_Name", popupText = "#CTL_ L1MapGenAction_Name" ) //@ActionReference( // path = "Menu/SeaDAS-OCSSW", // position = 100 //) @NbBundle.Messages({ "CTL_L1MapGenAction_Name=l1mapgen...", "CTL_L1MapGenAction_ProgramName=l1mapgen", "CTL_L1MapGenAction_DialogTitle=l1mapgen", "CTL_L1MapGenAction_XMLFileName=l1mapgen.xml", "CTL_L1MapGenAction_Description=Process MODIS L0 to L1A." }) public class L1MapGenAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public L1MapGenAction() { this(Utilities.actionsGlobalContext()); } public L1MapGenAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_L1MapGenAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L1MapGenAction_Description()); setProgramName(Bundle.CTL_L1MapGenAction_ProgramName()); setDialogTitle(Bundle.CTL_L1MapGenAction_DialogTitle()); setXmlFileName(Bundle.CTL_L1MapGenAction_XMLFileName()); } // // @Override // public void actionPerformed(ActionEvent e) { // // } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new L1MapGenAction(actionContext); } }
2,085
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
ModisGeoAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/ModisGeoAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.ModisGeoAction" ) @ActionRegistration( displayName = "#CTL_ ModisGeoAction_Name", popupText = "#CTL_ ModisGeoAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/MODIS", position = 40 ) @NbBundle.Messages({ "CTL_ModisGeoAction_Name=modis_GEO...", "CTL_ModisGeoAction_ProgramName=modis_GEO", "CTL_ModisGeoAction_DialogTitle=modis_GEO", "CTL_ModisGeoAction_XMLFileName=modis_GEO.xml", "CTL_ModisGeoAction_Description=Creates a MODIS GEO file from a MODIS L1A input file" }) public class ModisGeoAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public ModisGeoAction() { this(Utilities.actionsGlobalContext()); } public ModisGeoAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_ModisGeoAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_ModisGeoAction_Description()); setProgramName(Bundle.CTL_ModisGeoAction_ProgramName()); setDialogTitle(Bundle.CTL_ModisGeoAction_DialogTitle()); setXmlFileName(Bundle.CTL_ModisGeoAction_XMLFileName()); } // // @Override // public void actionPerformed(ActionEvent e) { // // } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new ModisGeoAction(actionContext); } }
2,173
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
ModisL1BAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/ModisL1BAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.ModisL1BAction" ) @ActionRegistration( displayName = "#CTL_ ModisL1BAction_Name", popupText = "#CTL_ ModisL1BAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/MODIS", position = 50 ) @NbBundle.Messages({ "CTL_ModisL1BAction_Name=modis_L1B...", "CTL_ModisL1BAction_ProgramName=modis_L1B", "CTL_ModisL1BAction_DialogTitle=modis_L1B", "CTL_ModisL1BAction_XMLFileName=modis_L1B.xml", "CTL_ModisL1BAction_Description=Creates a MODIS L1B file from a MODIS L1A input file" }) public class ModisL1BAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public ModisL1BAction() { this(Utilities.actionsGlobalContext()); } public ModisL1BAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_ModisL1BAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_ModisL1BAction_Description()); setProgramName(Bundle.CTL_ModisL1BAction_ProgramName()); setDialogTitle(Bundle.CTL_ModisL1BAction_DialogTitle()); setXmlFileName(Bundle.CTL_ModisL1BAction_XMLFileName()); } // // @Override // public void actionPerformed(ActionEvent e) { // // } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new ModisL1BAction(actionContext); } }
2,173
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/ui/L3GenAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.l2gen.userInterface.L2genAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L3GenAction" ) @ActionRegistration( displayName = "#CTL_ L3GenAction_Name", popupText = "#CTL_ L3GenAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors", position = 180 ) @NbBundle.Messages({ "CTL_L3GenAction_Name=l3gen...", "CTL_L3GenAction_ProgramName=l3gen", "CTL_L3GenAction_DialogTitle=l3gen", "CTL_L3GenAction_XMLFileName=l3gen.xml", "CTL_L3GenAction_Description=Creates a level 3 bin from an input RRS level 3 input file" }) public class L3GenAction extends L2genAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public L3GenAction() { this(Utilities.actionsGlobalContext()); } public L3GenAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_L3GenAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L3GenAction_Description()); setProgramName(Bundle.CTL_L3GenAction_ProgramName()); setDialogTitle(Bundle.CTL_L3GenAction_DialogTitle()); setXmlFileName(Bundle.CTL_L3GenAction_XMLFileName()); } // // @Override // public void actionPerformed(ActionEvent e) { // // } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new L3GenAction(actionContext); } }
2,106
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L1BrsGenAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/L1BrsGenAction.java
//package gov.nasa.gsfc.seadas.processing.ui; // //import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; //import org.esa.snap.core.datamodel.ProductNode; //import org.openide.awt.ActionID; //import org.openide.awt.ActionReference; //import org.openide.awt.ActionRegistration; //import org.openide.util.*; // //import javax.swing.*; // ///** // * @author Aynur Abdurazik // * @since SeaDAS 8.0 // * @see // */ //@ActionID( // category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L1BrsGenAction" //) //@ActionRegistration( // displayName = "#CTL_ L1BrsGenAction_Name", // popupText = "#CTL_ L1BrsGenAction_Name" //) //@ActionReference( // path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/Tools", // position = 401, // separatorBefore = 400 //) //@NbBundle.Messages({ // "CTL_L1BrsGenAction_Name=l1brsgen...", // "CTL_L1BrsGenAction_ProgramName=l1brsgen", // "CTL_L1BrsGenAction_DialogTitle=l1brsgen", // "CTL_L1BrsGenAction_XMLFileName=l1brsgen.xml", // "CTL_L1BrsGenAction_Description=Creates a Level 1 browse (pseudo true color - RGB) file" //}) // //public class L1BrsGenAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { // // private final Lookup lkp; // // public L1BrsGenAction() { // this(Utilities.actionsGlobalContext()); // } // // public L1BrsGenAction(Lookup lkp) { // this.lkp = lkp; // Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); // lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); // putValue(Action.NAME, Bundle.CTL_L1BrsGenAction_Name()); // putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L1BrsGenAction_Description()); // setProgramName(Bundle.CTL_L1BrsGenAction_ProgramName()); // setDialogTitle(Bundle.CTL_L1BrsGenAction_DialogTitle()); // setXmlFileName(Bundle.CTL_L1BrsGenAction_XMLFileName()); // } //// //// @Override //// public void actionPerformed(ActionEvent e) { //// //// } // // @Override // public void resultChanged(LookupEvent lookupEvent) { // // } // // @Override // public Action createContextAwareInstance(Lookup actionContext) { // return new L1BrsGenAction(actionContext); // } //}
2,346
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L2MergeAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/L2MergeAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Daniel Knowles * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.L2MergeAction" ) @ActionRegistration( displayName = "#CTL_L2MergeAction_Name", popupText = "#CTL_L2MergeAction_Description" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors/Tools", position = 150 ) @NbBundle.Messages({ "CTL_L2MergeAction_Name=l2merge...", "CTL_L2MergeAction_ProgramName=l2merge", "CTL_L2MergeAction_DialogTitle=l2merge", "CTL_L2MergeAction_XMLFileName=l2merge.xml", "CTL_L2MergeAction_Description=Merges multiple L2 input files into a single L2 output file" }) public class L2MergeAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public L2MergeAction() { this(Utilities.actionsGlobalContext()); } public L2MergeAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_L2MergeAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_L2MergeAction_Description()); setProgramName(Bundle.CTL_L2MergeAction_ProgramName()); setDialogTitle(Bundle.CTL_L2MergeAction_DialogTitle()); setXmlFileName(Bundle.CTL_L2MergeAction_XMLFileName()); } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new L2MergeAction(actionContext); } }
2,078
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
SmiGenAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/SmiGenAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.SmiGenAction" ) @ActionRegistration( displayName = "#CTL_ SmiGenAction_Name", popupText = "#CTL_ SmiGenAction_Name" ) //@ActionReference( // path = "Menu/SeaDAS-OCSSW", // position = 200 //) @NbBundle.Messages({ "CTL_SmiGenAction_Name=smigen...", "CTL_SmiGenAction_ProgramName=smigen", "CTL_SmiGenAction_DialogTitle=smigen", "CTL_SmiGenAction_XMLFileName=smigen.xml", "CTL_SmiGenAction_Description=Create a L3 map file." }) public class SmiGenAction extends CallCloProgramAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public SmiGenAction() { this(Utilities.actionsGlobalContext()); } public SmiGenAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_SmiGenAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_SmiGenAction_Description()); setProgramName(Bundle.CTL_SmiGenAction_ProgramName()); setDialogTitle(Bundle.CTL_SmiGenAction_DialogTitle()); setXmlFileName(Bundle.CTL_SmiGenAction_XMLFileName()); } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new SmiGenAction(actionContext); } }
1,959
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/ui/MultiLevelProcessorAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.processor.MultilevelProcessorAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID( category = "Processing", id = "gov.nasa.gsfc.seadas.processing.ui.MultiLevelProcessorAction" ) @ActionRegistration( displayName = "#CTL_ MultiLevelProcessorAction_Name", popupText = "#CTL_ MultiLevelProcessorAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox/SeaDAS Processors", position = 501, separatorBefore = 500 ) @NbBundle.Messages({ "CTL_MultiLevelProcessorAction_Name=multilevel_processor...", "CTL_MultiLevelProcessorAction_ProgramName=multilevel_processor", "CTL_MultiLevelProcessorAction_DialogTitle=multilevel_processor", "CTL_MultiLevelProcessorAction_XMLFileName=multilevel_processor.xml", "CTL_MultiLevelProcessorAction_Description=Process SeaDAS files through many levels" }) public class MultiLevelProcessorAction extends MultilevelProcessorAction implements ContextAwareAction, LookupListener { private final Lookup lkp; public MultiLevelProcessorAction() { this(Utilities.actionsGlobalContext()); } public MultiLevelProcessorAction(Lookup lkp) { this.lkp = lkp; Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_MultiLevelProcessorAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_MultiLevelProcessorAction_Description()); setProgramName(Bundle.CTL_MultiLevelProcessorAction_ProgramName()); setDialogTitle(Bundle.CTL_MultiLevelProcessorAction_DialogTitle()); setXmlFileName(Bundle.CTL_MultiLevelProcessorAction_XMLFileName()); } @Override public void resultChanged(LookupEvent lookupEvent) { } @Override public Action createContextAwareInstance(Lookup actionContext) { return new MultiLevelProcessorAction(actionContext); } }
2,353
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
OCSSWInstallerAction.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/ui/OCSSWInstallerAction.java
package gov.nasa.gsfc.seadas.processing.ui; import gov.nasa.gsfc.seadas.processing.common.CallCloProgramAction; import org.esa.snap.core.datamodel.ProductNode; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.*; import javax.swing.*; /** * @author Aynur Abdurazik * @since SeaDAS 8.0 * @see */ @ActionID(category = "Processing", id = "gov.nasa.gsfc.seadas.processing.OCSSWInstallerAction") @ActionRegistration( displayName = "#CTL_OCSSWInstallerAction_Name", popupText = "#CTL_OCSSWInstallerAction_Name" ) @ActionReference( path = "Menu/SeaDAS-Toolbox", position = 10, separatorAfter = 11 ) @NbBundle.Messages({ "CTL_OCSSWInstallerAction_Name=Install/Update SeaDAS Processors...", "CTL_OCSSWInstallerAction_ProgramName=install_ocssw", "CTL_OCSSWInstallerAction_DialogTitle=Install/Update SeaDAS Processors", "CTL_OCSSWInstallerAction_XMLFileName=ocssw_installer.xml", "CTL_OCSSWInstallerAction_Description=Install/Update SeaDAS processors and supported missions" }) public class OCSSWInstallerAction extends CallCloProgramAction implements LookupListener { //ContextAwareAction private final Lookup lookup; public static final String HELP_ID = "install_ocssw"; private HelpCtx helpCtx; public OCSSWInstallerAction() { this(Utilities.actionsGlobalContext()); helpCtx = new HelpCtx(getProgramName()); } public OCSSWInstallerAction(Lookup lookup) { this.lookup = lookup != null ? lookup : Utilities.actionsGlobalContext(); Lookup.Result<ProductNode> lkpContext = lookup.lookupResult(ProductNode.class); lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext)); putValue(Action.NAME, Bundle.CTL_OCSSWInstallerAction_Name()); putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_OCSSWInstallerAction_Description()); setProgramName(Bundle.CTL_OCSSWInstallerAction_ProgramName()); setDialogTitle(Bundle.CTL_OCSSWInstallerAction_DialogTitle()); setXmlFileName(Bundle.CTL_OCSSWInstallerAction_XMLFileName()); setHelpId(getProgramName()); } // @Override // public void actionPerformed(ActionEvent e) { // // } @Override public HelpCtx getHelpCtx() { return helpCtx; } @Override public void resultChanged(LookupEvent lookupEvent) { } // @Override /** * for ContextAwareAction interface */ // public Action createContextAwareInstance(Lookup actionContext) { // return new OCSSWInstallerAction(actionContext); // } }
2,718
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L2genAlgorithmInfo.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/productData/L2genAlgorithmInfo.java
package gov.nasa.gsfc.seadas.processing.l2gen.productData; import gov.nasa.gsfc.seadas.processing.preferences.OCSSW_L2genController; import org.esa.snap.core.util.PropertyMap; import org.esa.snap.rcp.SnapApp; import java.util.ArrayList; import java.util.HashSet; /** * A ... * * @author Danny Knowles * @since SeaDAS 7.0 */ public class L2genAlgorithmInfo extends L2genBaseInfo { public static enum ParameterType { VISIBLE, IR, ALL, INT, NONE } public final static String PARAMTYPE_VISIBLE = "VISIBLE", PARAMTYPE_IR = "IR", PARAMTYPE_ALL = "ALL", PARAMTYPE_NONE = "NONE", PARAMTYPE_INT = "INTEGER"; // These fields are populated according to productInfo.xml public ArrayList<L2genWavelengthInfo> waveLimiterInfos; private String dataType = null, prefix = null, suffix = null, units = null; private ParameterType parameterType = null; public L2genAlgorithmInfo(String name, String description, ParameterType parameterType, ArrayList<L2genWavelengthInfo> waveLimiterInfos) { super(name); setDescription(description); this.parameterType = parameterType; this.waveLimiterInfos = waveLimiterInfos; } // public AlgorithmInfo(String name, String description, String waveTypeStr) { // this(name, description, convertWavetype(waveTypeStr)); // } // // public AlgorithmInfo(String name, String description) { // this(name, description, ParameterType.NONE); // } public L2genAlgorithmInfo(ArrayList<L2genWavelengthInfo> waveLimiterInfos) { this("", "", ParameterType.NONE, waveLimiterInfos); } public String getProductName() { if (getParent() == null) { return null; } return getParent().getName(); } public L2genProductInfo getProductInfo() { return (L2genProductInfo) getParent(); } public void setProductInfo(L2genProductInfo productInfo) { setParent(productInfo); } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public String getUnits() { return units; } public void setUnits(String units) { this.units = units; } public ParameterType getParameterType() { return parameterType; } public void setParameterType(String parameterTypeStr) { this.parameterType = convertWavetype(parameterTypeStr); } @Override public String getFullName() { StringBuilder result = new StringBuilder(); if (prefix != null && !prefix.isEmpty()) { result.append(prefix); } if (suffix != null && !suffix.isEmpty()) { result.append(suffix); } return result.toString().replaceAll("[_]+", "_").replaceAll("[_]$", ""); } public static ParameterType convertWavetype(String str) { if (str == null) { return ParameterType.NONE; } if (str.compareToIgnoreCase(PARAMTYPE_VISIBLE) == 0) { return ParameterType.VISIBLE; } else if (str.compareToIgnoreCase(PARAMTYPE_IR) == 0) { return ParameterType.IR; } else if (str.compareToIgnoreCase(PARAMTYPE_ALL) == 0) { return ParameterType.ALL; } else if (str.compareToIgnoreCase(PARAMTYPE_INT) == 0) { return ParameterType.INT; } else if (str.compareToIgnoreCase(PARAMTYPE_NONE) == 0) { return ParameterType.NONE; } else { return ParameterType.NONE; } } private String getShortcutFullname(L2genProductTools.ShortcutType shortcutType) { StringBuilder result = new StringBuilder(); if (prefix != null && !prefix.isEmpty()) { result.append(prefix); } result.append("_"); result.append(L2genProductTools.convertShortcutType(shortcutType)); if (suffix != null && !suffix.isEmpty()) { result.append("_"); result.append(suffix); } return result.toString().replaceAll("[_]+", "_").replaceAll("[_]$", ""); } private boolean isSelectedShortcut(L2genProductTools.ShortcutType shortcutType) { boolean found = false; if (shortcutType == L2genProductTools.ShortcutType.ALL) { for (L2genBaseInfo wInfo : getChildren()) { L2genWavelengthInfo wavelengthInfo = (L2genWavelengthInfo) wInfo; if (wavelengthInfo.isSelected()) { found = true; } else { return false; } } return found; } else if (shortcutType == L2genProductTools.ShortcutType.VISIBLE) { for (L2genBaseInfo wInfo : getChildren()) { L2genWavelengthInfo wavelengthInfo = (L2genWavelengthInfo) wInfo; if (wavelengthInfo.isWaveType(L2genWavelengthInfo.WaveType.VISIBLE)) { if (wavelengthInfo.isSelected()) { found = true; } else { return false; } } } return found; } else if (shortcutType == L2genProductTools.ShortcutType.IR) { for (L2genBaseInfo wInfo : getChildren()) { L2genWavelengthInfo wavelengthInfo = (L2genWavelengthInfo) wInfo; if (wavelengthInfo.isWaveType(L2genWavelengthInfo.WaveType.IR)) { if (wavelengthInfo.isSelected()) { found = true; } else { return false; } } } return found; } return false; } public void setL2prod(HashSet<String> inProducts) { if (getParameterType() == L2genAlgorithmInfo.ParameterType.NONE) { String thisProduct = getFullName(); if (inProducts.contains(thisProduct)) { setState(State.SELECTED); inProducts.remove(thisProduct); } else { setState(State.NOT_SELECTED); } } else { for (L2genBaseInfo wInfo : getChildren()) { L2genWavelengthInfo wavelengthInfo = (L2genWavelengthInfo) wInfo; if (wavelengthInfo.getWavelength() == L2genProductTools.WAVELENGTH_FOR_IFILE_INDEPENDENT_MODE) { String inProductFound = null; for (String inProduct : inProducts) { boolean matchIsStillPossible = true; if (getPrefix() != null && getPrefix().length() > 0) { if (inProduct.startsWith(getPrefix())) { inProduct = inProduct.substring((getPrefix().length())); //trim off prefix } else { matchIsStillPossible = false; } } if (getSuffix() != null && getPrefix().length() > 0) { if (inProduct.endsWith(getSuffix())) { inProduct = inProduct.substring(0, (inProduct.length() - getSuffix().length())); // trim off suffix } else { matchIsStillPossible = false; } } if (matchIsStillPossible) { if (L2genProductTools.isInteger(inProduct) || inProduct.equals(L2genProductTools.SHORTCUT_NAMEPART_IR) || inProduct.equals(L2genProductTools.SHORTCUT_NAMEPART_VISIBLE) || inProduct.equals(L2genProductTools.SHORTCUT_NAMEPART_ALL)) { inProductFound = inProduct; } } } if (inProductFound != null) { wavelengthInfo.setState(State.SELECTED); inProducts.remove(inProductFound); } else { wavelengthInfo.setState(State.NOT_SELECTED); } } else { String wavelengthProduct = wavelengthInfo.getFullName(); if (inProducts.contains(wavelengthProduct)) { wavelengthInfo.setState(State.SELECTED); inProducts.remove(wavelengthProduct); } else { wavelengthInfo.setState(State.NOT_SELECTED); } } } String visibleProduct = getShortcutFullname(L2genProductTools.ShortcutType.VISIBLE); if (inProducts.contains(visibleProduct)) { setStateShortcut(L2genProductTools.ShortcutType.VISIBLE, State.SELECTED); inProducts.remove(visibleProduct); } String irProduct = getShortcutFullname(L2genProductTools.ShortcutType.IR); if (inProducts.contains(irProduct)) { setStateShortcut(L2genProductTools.ShortcutType.IR, State.SELECTED); inProducts.remove(irProduct); } String allProduct = getShortcutFullname(L2genProductTools.ShortcutType.ALL); if (inProducts.contains(allProduct)) { setStateShortcut(L2genProductTools.ShortcutType.ALL, State.SELECTED); inProducts.remove(allProduct); } } } private boolean isUseShortcuts() { return OCSSW_L2genController.getPreferenceUseWavelengthShortcuts(); } public ArrayList<String> getL2prod() { ArrayList<String> l2prod = new ArrayList<String>(); if (hasChildren()) { int count = 0; int selectedCount = 0; int visibleCount = 0; int visibleSelectedCount = 0; int infraredCount = 0; int infraredSelectedCount = 0; for (L2genWavelengthInfo waveLimiterInfo : waveLimiterInfos) { for (L2genBaseInfo wInfo : getChildren()) { L2genWavelengthInfo wavelengthInfo = (L2genWavelengthInfo) wInfo; if (wavelengthInfo.getWavelength() == waveLimiterInfo.getWavelength()) { if (wavelengthInfo.isSelected()) { if (waveLimiterInfo.getWaveType() == L2genWavelengthInfo.WaveType.IR) { infraredSelectedCount++; } else if (waveLimiterInfo.getWaveType() == L2genWavelengthInfo.WaveType.VISIBLE) { visibleSelectedCount++; } selectedCount++; } continue; } } if (waveLimiterInfo.getWaveType() == L2genWavelengthInfo.WaveType.IR) { infraredCount++; } else if (waveLimiterInfo.getWaveType() == L2genWavelengthInfo.WaveType.VISIBLE) { visibleCount++; } count++; } if (isUseShortcuts()) { // System.out.println("IS USE SHORTCUTS"); if (selectedCount == count && selectedCount > 0) { l2prod.add(getShortcutFullname(L2genProductTools.ShortcutType.ALL)); } else { if (visibleSelectedCount == visibleCount && visibleSelectedCount > 0) { l2prod.add(getShortcutFullname(L2genProductTools.ShortcutType.VISIBLE)); } if (infraredSelectedCount == infraredCount && infraredSelectedCount > 0) { l2prod.add(getShortcutFullname(L2genProductTools.ShortcutType.IR)); } for (L2genBaseInfo wInfo : getChildren()) { L2genWavelengthInfo wavelengthInfo = (L2genWavelengthInfo) wInfo; if (wInfo.isSelected()) { if (wavelengthInfo.isWaveType(L2genWavelengthInfo.WaveType.VISIBLE)) { if (visibleSelectedCount != visibleCount) { l2prod.add(wavelengthInfo.getFullName()); } } else if (wavelengthInfo.isWaveType(L2genWavelengthInfo.WaveType.IR)) { if (infraredSelectedCount != infraredCount) { l2prod.add(wavelengthInfo.getFullName()); } } else { l2prod.add(wavelengthInfo.getFullName()); } } } } } else { // System.out.println("IS NOT USE SHORTCUTS"); for (L2genBaseInfo wInfo : getChildren()) { L2genWavelengthInfo wavelengthInfo = (L2genWavelengthInfo) wInfo; if (wInfo.isSelected()) { l2prod.add(wavelengthInfo.getFullName()); } } } } else { if (isSelected()) { l2prod.add(getFullName()); } } return l2prod; } public void reset() { setSelected(false); if (getParameterType() != L2genAlgorithmInfo.ParameterType.NONE) { clearChildren(); for (L2genWavelengthInfo waveLimiterInfo : waveLimiterInfos) { boolean addWavelength = false; // Here is where the xml values are based used to determine which wavelengths get into the algorithmInfo if (getParameterType() == L2genAlgorithmInfo.ParameterType.ALL) { addWavelength = true; } else if (waveLimiterInfo.getWavelength() >= L2genWavelengthInfo.IR_ALLOWED_LOWER_LIMIT && getParameterType() == L2genAlgorithmInfo.ParameterType.IR) { addWavelength = true; } else if (waveLimiterInfo.getWavelength() < L2genWavelengthInfo.IR_ALLOWED_LOWER_LIMIT && getParameterType() == L2genAlgorithmInfo.ParameterType.VISIBLE) { addWavelength = true; } if (addWavelength) { L2genWavelengthInfo newWavelengthInfo = new L2genWavelengthInfo(waveLimiterInfo.getWavelength()); newWavelengthInfo.setParent(this); newWavelengthInfo.setDescription(getDescription() + ", at " + newWavelengthInfo.getWavelengthString()); addChild(newWavelengthInfo); } } } } private void setStateShortcut(L2genProductTools.ShortcutType shortcutType, State state) { for (L2genBaseInfo wInfo : getChildren()) { L2genWavelengthInfo wavelengthInfo = (L2genWavelengthInfo) wInfo; if (wavelengthInfo.isWaveType(L2genWavelengthInfo.WaveType.VISIBLE)) { if (shortcutType == L2genProductTools.ShortcutType.ALL || shortcutType == L2genProductTools.ShortcutType.VISIBLE) { wavelengthInfo.setState(state); } } if (wavelengthInfo.isWaveType(L2genWavelengthInfo.WaveType.IR)) { if (shortcutType == L2genProductTools.ShortcutType.ALL || shortcutType == L2genProductTools.ShortcutType.IR) { wavelengthInfo.setState(state); } } if (wavelengthInfo.isWaveType(L2genWavelengthInfo.WaveType.NIR) || wavelengthInfo.isWaveType(L2genWavelengthInfo.WaveType.SWIR)) { if (shortcutType == L2genProductTools.ShortcutType.ALL) { wavelengthInfo.setState(state); } } } } }
16,599
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L2genProductInfo.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/productData/L2genProductInfo.java
package gov.nasa.gsfc.seadas.processing.l2gen.productData; /** * A ... * * @author Danny Knowles * @since SeaDAS 7.0 */ public class L2genProductInfo extends L2genBaseInfo { public L2genProductInfo(String name) { super(name); } }
256
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L2genWavelengthInfo.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/productData/L2genWavelengthInfo.java
package gov.nasa.gsfc.seadas.processing.l2gen.productData; /** * A ... * * @author Danny Knowles * @since SeaDAS 7.0 */ public class L2genWavelengthInfo extends L2genBaseInfo { public static final double UV_LOWER_LIMIT = 100; public static final double VISIBLE_LOWER_LIMIT = 400; public static final double NIR_LOWER_LIMIT = 725; public static final double SWIR_LOWER_LIMIT = 1400; public static final double INFRARED_LOWER_LIMIT = 3000; public static final double INFRARED_UPPER_LIMIT = 15000; public static final double IR_ALLOWED_LOWER_LIMIT = INFRARED_LOWER_LIMIT; public static final int NULL_WAVELENGTH = -1; private int wavelength = NULL_WAVELENGTH; public static enum WaveType { UV, VISIBLE, NIR, SWIR, IR, NULL } public L2genWavelengthInfo(int wavelength, L2genAlgorithmInfo algorithmInfo) { super(Integer.toString(wavelength), algorithmInfo); this.wavelength = wavelength; // correct the name for the special mode if (wavelength == L2genProductTools.WAVELENGTH_FOR_IFILE_INDEPENDENT_MODE) { setName(L2genProductTools.SHORTCUT_NAMEPART_ALL); } } public L2genWavelengthInfo(int wavelength) { this(wavelength, null); } public L2genWavelengthInfo(String wavelengthStr) { super(wavelengthStr); try { double wavelengthDouble = Double.valueOf(wavelengthStr); long wavelengthRounded = Math.round(wavelengthDouble); String wavelengthRoundedString = String.valueOf(wavelengthRounded); this.wavelength = Integer.parseInt(wavelengthRoundedString); } catch (Exception e) { this.wavelength = NULL_WAVELENGTH; } } public L2genAlgorithmInfo getAlgorithmInfo() { return (L2genAlgorithmInfo) getParent(); } public int getWavelength() { return wavelength; } public void setWavelength(int wavelength) { this.wavelength = wavelength; if (wavelength == L2genProductTools.WAVELENGTH_FOR_IFILE_INDEPENDENT_MODE) { setName(L2genProductTools.SHORTCUT_NAMEPART_ALL); } else { setName(Integer.toString(wavelength)); } } public String getWavelengthString() { return Integer.toString(wavelength); } @Override public String getFullName() { StringBuilder result = new StringBuilder(); L2genBaseInfo aInfo = getParent(); if (aInfo != null) { String prefix = ((L2genAlgorithmInfo) aInfo).getPrefix(); String suffix = ((L2genAlgorithmInfo) aInfo).getSuffix(); if (prefix != null && !prefix.isEmpty()) { result.append(prefix); } if (wavelength != NULL_WAVELENGTH) { result.append('_'); result.append(getName()); } if (suffix != null && !suffix.isEmpty()) { result.append("_"); result.append(suffix); } } return result.toString().replaceAll("[_]+", "_"); } public boolean isWaveType(WaveType waveType) { if (waveType == getWaveType()) { return true; } else { return false; } } public WaveType getWaveType() { if (wavelength >= UV_LOWER_LIMIT && wavelength < VISIBLE_LOWER_LIMIT) { return WaveType.UV; } else if (wavelength >= VISIBLE_LOWER_LIMIT && wavelength < NIR_LOWER_LIMIT) { return WaveType.VISIBLE; } else if (wavelength >= NIR_LOWER_LIMIT && wavelength < SWIR_LOWER_LIMIT) { return WaveType.NIR; } else if (wavelength >= SWIR_LOWER_LIMIT && wavelength < INFRARED_LOWER_LIMIT) { return WaveType.SWIR; } else if (wavelength >= INFRARED_LOWER_LIMIT && wavelength < INFRARED_UPPER_LIMIT) { return WaveType.IR; } else { return WaveType.NULL; } } }
4,027
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z
L2genBaseInfo.java
/FileExtraction/Java_unseen/seadas_seadas-toolbox/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/productData/L2genBaseInfo.java
package gov.nasa.gsfc.seadas.processing.l2gen.productData; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by IntelliJ IDEA. * User: dshea * Date: 1/3/12 * Time: 8:30 AM * To change this template use File | Settings | File Templates. */ public class L2genBaseInfo implements Comparable<L2genBaseInfo> { public enum State { NOT_SELECTED, PARTIAL, SELECTED } private String name; private State state = State.NOT_SELECTED; private String description = null; private L2genBaseInfo parent = null; private ArrayList<L2genBaseInfo> children = new ArrayList<L2genBaseInfo>(); public static final Comparator<L2genProductInfo> CASE_SENSITIVE_ORDER = new CaseSensitiveComparator(); public static final Comparator<L2genProductInfo> CASE_INSENSITIVE_ORDER = new CaseInsensitiveComparator(); private static class CaseSensitiveComparator implements Comparator<L2genProductInfo> { public int compare(L2genProductInfo s1, L2genProductInfo s2) { return s1.getFullName().compareTo(s2.getFullName()); } } private static class CaseInsensitiveComparator implements Comparator<L2genProductInfo> { public int compare(L2genProductInfo s1, L2genProductInfo s2) { return s1.getFullName().compareToIgnoreCase(s2.getFullName()); } } public L2genBaseInfo() { this("", null); } public L2genBaseInfo(String name) { this(name, null); } public L2genBaseInfo(String name, L2genBaseInfo parent) { this.name = name; this.parent = parent; } public void setName(String name) { this.name = name; } public String getName() { return name; } public String getFullName() { return getName(); } public void setSelected(boolean selected) { if (selected) { setState(State.SELECTED); } else { setState(State.NOT_SELECTED); } } public boolean isSelected() { if (state == State.SELECTED || state == State.PARTIAL) { return true; } else { return false; } } public void setState(State state) { this.state = state; } public void nextState() { if (state == State.NOT_SELECTED) { setState(State.PARTIAL); } else if (state == State.PARTIAL) { setState(State.SELECTED); } else { setState(State.NOT_SELECTED); } } public State getState() { return state; } public void setParent(L2genBaseInfo parent) { this.parent = parent; } public L2genBaseInfo getParent() { return parent; } public boolean hasChildren() { return !children.isEmpty(); } public List<L2genBaseInfo> getChildren() { return children; } public void clearChildren() { children.clear(); } public void addChild(L2genBaseInfo child) { children.add(child); } public int compareTo(L2genBaseInfo info) { return getName().compareToIgnoreCase(info.getName()); } public void dump() { System.out.println(getName()); for (L2genBaseInfo info : getChildren()) { info.dump(); } } public void sortChildren() { Collections.sort(children); } // // public boolean isWavelengthDependent() { // // boolean result = false; // // for(BaseInfo info : getChildren()) { // if(info.isWavelengthDependent()) { // return true; // } // } // return false; // } // // public boolean isWavelengthIndependent() { // for(BaseInfo info : getChildren()) { // if(info.isWavelengthIndependent()) { // return true; // } // } // return false; // } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String toString() { return getFullName(); } }
4,287
Java
.java
seadas/seadas-toolbox
17
2
5
2018-06-28T18:46:30Z
2024-05-08T21:01:05Z